Collection resource support in SDK and Plug-in.
authorHarish Kumara Marappa <h.marappa@samsung.com>
Sat, 14 Nov 2015 13:49:08 +0000 (19:19 +0530)
committerMadan Lanka <lanka.madan@samsung.com>
Mon, 16 Nov 2015 00:51:01 +0000 (00:51 +0000)
- Managing life cycle of collection resource.
- Supporting all types of attribute value in SimulatorResourceModel as supported in
  OCRepresentation.
- Updated unit test cases.

JIRA: https://jira.iotivity.org/browse/IOT-836

Change-Id: Iba01f46477155adad64e69dec9cda192405b09ee
Signed-off-by: Harish Kumara Marappa <h.marappa@samsung.com>
Reviewed-on: https://gerrit.iotivity.org/gerrit/4209
Tested-by: jenkins-iotivity <jenkins-iotivity@opendaylight.org>
Reviewed-by: Madan Lanka <lanka.madan@samsung.com>
324 files changed:
service/simulator/SConscript
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_collection_resource.h [new file with mode: 0644]
service/simulator/inc/simulator_manager.h
service/simulator/inc/simulator_remote_resource.h
service/simulator/inc/simulator_resource.h [new file with mode: 0644]
service/simulator/inc/simulator_resource_model.h
service/simulator/inc/simulator_resource_server.h [deleted file]
service/simulator/inc/simulator_server_types.h
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/icons/light_16x16.png [deleted file]
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/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/remoteresource/PutPostAttributeModel.java
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
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/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/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/ResourceManagerView.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/LoadRAMLDialog.java
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/VerificationDialog.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/build.properties
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/collection_resource.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/device.gif [new file with mode: 0644]
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/LogLabelProvider.java
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IAutomationUIListener.java
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IObserverListChangedUIListener.java
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IPropertiesChangedUIListener.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IResourceListChangedUIListener.java
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IResourceModelChangedUIListener.java
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/ISelectionChangedUIListener.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/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/CollectionResource.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/DeleteCategory.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/Device.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/LocalResourceAttribute.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/ModelChangeNotificationType.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/ResourceCategory.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/SRMItem.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/SimulatorPluginException.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/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/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/AddResourceToCollections.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/AddResourceToDevices.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/AddResources.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/AddResourcesToCollectionPage.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/CollectionResourceBasicDetailsPage.java [new file with mode: 0644]
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/DevicePage.java [new file with mode: 0644]
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/MainPage.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/RemoveResourceFromCollections.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/RemoveResourceFromDevices.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/RemoveResources.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/SimpleResourcePage.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/StartStopResourcePage.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/jni/jni_listener_holder.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_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_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/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/AttributeValueValidation.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/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/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/InvalidArgsException.java
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/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/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: 0644]
service/simulator/ramlparser/raml/Utils.h [deleted file]
service/simulator/ramlparser/raml/jsonSchemaParser/Definitions.h
service/simulator/ramlparser/raml/jsonSchemaParser/Items.h
service/simulator/ramlparser/raml/jsonSchemaParser/JsonSchema.cpp
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/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/query_param_generator.cpp [deleted file]
service/simulator/src/client-controller/query_param_generator.h [deleted file]
service/simulator/src/client-controller/request_list.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/attribute_generator.cpp [new file with mode: 0644]
service/simulator/src/client/attribute_generator.h [new file with mode: 0644]
service/simulator/src/client/auto_request_gen.cpp [new file with mode: 0644]
service/simulator/src/client/auto_request_gen.h [new file with mode: 0644]
service/simulator/src/client/auto_request_gen_mngr.cpp [new file with mode: 0644]
service/simulator/src/client/auto_request_gen_mngr.h [new file with mode: 0644]
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 [new file with mode: 0644]
service/simulator/src/client/query_param_generator.h [new file with mode: 0644]
service/simulator/src/client/request_list.h [new file with mode: 0644]
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/common/request_model_builder.cpp
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_utils.cpp
service/simulator/src/common/simulator_utils.h
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: 0644]
service/simulator/src/server/simulator_collection_resource_impl.h [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: 0644]
service/simulator/src/server/simulator_single_resource_impl.cpp [new file with mode: 0644]
service/simulator/src/server/simulator_single_resource_impl.h [new file with mode: 0644]
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/AttributeValueTest.java [new file with mode: 0644]
service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/AttributeValueValidationTest.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/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/utils/ObjectHolder.java [new file with mode: 0644]
service/simulator/unittests/SimulatorTest/src/org/oic/simulator/utils/SampleSingleResource.java [new file with mode: 0644]

index 260cb0bb5fea981faf51191bbc1c5db754235807..b77e5dcfaf8a13351dc3c628893e933edb25bd96 100755 (executable)
@@ -36,7 +36,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',
@@ -86,4 +86,4 @@ simulator_env.InstallTarget(simulatorsdk, 'libSimulator')
 
 #Build sample application
 SConscript('examples/server/SConscript')
-SConscript('examples/client-controller/SConscript')
+SConscript('examples/client/SConscript')
\ No newline at end of file
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..f0f3148
--- /dev/null
@@ -0,0 +1,692 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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";
+}
+
+std::string getPropertyTypeString(SimulatorResourceModel::AttributeProperty::Type type)
+{
+    switch(type)
+    {
+        case SimulatorResourceModel::AttributeProperty::Type::RANGE:
+            return "RANGE";
+        case SimulatorResourceModel::AttributeProperty::Type::VALUE_SET:
+            return "VALUE_SET";
+        default:
+            break;
+    }
+
+    return "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 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->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::cout << "Representation is: " << std::endl;
+                std::cout << rep->toString() << 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 =
+                [](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::cout << rep->toString() << 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 =
+                [](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::cout << rep->toString() << std::endl;
+            };
+
+            try
+            {
+                SimulatorResourceModelSP rep = std::make_shared<SimulatorResourceModel>();
+                std::string value = "off";
+                rep->add("power", value);
+                rep->add("intensity", 5);
+
+                resource->put(std::map <std::string, std::string>(), 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 =
+                [](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::cout << rep->toString() << std::endl;
+            };
+
+            try
+            {
+                SimulatorResourceModelSP rep = std::make_shared<SimulatorResourceModel>();
+                std::string value = "on";
+                rep->add("power", value);
+                rep->add("intensity", 7);
+
+                resource->post(std::map <std::string, std::string>(), 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::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 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::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 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::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 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;
+
+                SimulatorResourceModelSP representation = resource->configure(configPath);
+                if (representation)
+                {
+                    std::cout << "configuration is successful!" << std::endl;
+                    std::map<std::string, SimulatorResourceModel::Attribute> attributes =
+                    representation->getAttributes();
+                    std::cout << "##### Attributes [" << attributes.size() << "]" << std::endl;
+                    for (auto & attribute : attributes)
+                    {
+                        std::cout << (attribute.second).getName() << " :  {" << std::endl;
+                        std::cout << "value: " << (attribute.second).toString() << std::endl;
+                        SimulatorResourceModel::AttributeProperty prop = (attribute.second).getProperty();
+                        std::cout << "Supported values given by : " << getPropertyTypeString(prop.type()) << std::endl;
+                        if (SimulatorResourceModel::AttributeProperty::Type::RANGE == prop.type())
+                        {
+                            std::cout << "Min: " << prop.min() << std::endl;
+                            std::cout << "Max: " << prop.max() << std::endl;
+                        }
+                        else if (SimulatorResourceModel::AttributeProperty::Type::VALUE_SET == prop.type())
+                        {
+                            std::cout << "Value set: " << prop.valueSetToString() << std::endl;
+                        }
+
+                        std::cout << "}" << std::endl << std::endl;
+                    }
+                    std::cout << "#############################" << 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;
+}
index 9a5b38ea5d912407d20bdf189676e1a7b0c3e14a..cb028dd0d9334487c4f4efa5ddb8a2f070dc08d8 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..74f4b15
--- /dev/null
@@ -0,0 +1,446 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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;
+
+std::string getPropertyTypeString(SimulatorResourceModel::AttributeProperty::Type type)
+{
+    switch(type)
+    {
+        case SimulatorResourceModel::AttributeProperty::Type::RANGE:
+            return "RANGE";
+        case SimulatorResourceModel::AttributeProperty::Type::VALUE_SET:
+            return "VALUE_SET";
+        default:
+            break;
+    }
+
+    return "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());
+
+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::ResourceModelChangedCallback modelChangeCB =
+        [](const std::string &uri, 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.toString() << 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;
+            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);
+            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);
+            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
+    SimulatorResourceModel resModel = resource->getResourceModel();
+    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).toString() << std::endl;
+        SimulatorResourceModel::AttributeProperty prop = (attribute.second).getProperty();
+        std::cout << "Supported values given by : " << getPropertyTypeString(prop.type()) << std::endl;
+        if (SimulatorResourceModel::AttributeProperty::Type::RANGE == prop.type())
+        {
+            std::cout << "Min: " << prop.min() << std::endl;
+            std::cout << "Max: " << prop.max() << std::endl;
+        }
+        else if (SimulatorResourceModel::AttributeProperty::Type::VALUE_SET == prop.type())
+        {
+            std::cout << "Value set: " << prop.valueSetToString() << std::endl;
+        }
+
+        std::cout << "}" << std::endl << 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()
+{
+    updateCompleteCallback 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;
+
+    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 = 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()
+{
+    updateCompleteCallback 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];
+    SimulatorResourceModel resModel = resource->getResourceModel();
+    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 <<
+              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->getResourceUpdationIds();
+        std::vector<int> aids = resource->getAttributeUpdationIds();
+        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->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;
+}
+
+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. 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[])
+{
+    printMainMenu();
+    bool cont = true;
+    while (cont == true)
+    {
+        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 : 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: printMainMenu(); break;
+            case 0: cont = false;
+        }
+    }
+
+    std::cout << "Terminating test !!!" << std::endl;
+}
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..88addd0
--- /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.
+ *
+ ******************************************************************/
+
+#ifndef SIMULATOR_COLLECTION_RESOURCE_H_
+#define SIMULATOR_COLLECTION_RESOURCE_H_
+
+#include "simulator_resource.h"
+
+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(SimulatorResourceSP &resource) = 0;
+
+        /**
+         * API to remove a child resource from collection.
+         *
+         * @param resource - SimulatorResource shared object.
+         */
+        virtual void removeChildResource(SimulatorResourceSP &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 662ea3eb8219ee33151d8119928ee29289e34c29..5b3d76ed2e212141bb29ac2f8aaedbc453f558d4 100644 (file)
@@ -32,7 +32,8 @@
 #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"
@@ -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,20 @@ 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);
-
-        /**
-         * 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<std::shared_ptr<SimulatorResourceServer>> getResources(
-                    const std::string &resourceType = "");
+        std::vector<std::shared_ptr<SimulatorResource>> createResource(
+                    const std::string &configPath, unsigned int count);
 
-        /**
-          * 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 = "");
+        std::shared_ptr<SimulatorCollectionResource> createCollectionResource(
+            const std::string &name, const std::string &uri, const std::string &resourceType);
 
         /**
          * API for discovering all type of resources.
index 5388bcc51b2e40fd62bb5966b7fa4e1bc7303a3a..917b6ac4ba0cfc072059c225fd93efd47b12518f 100644 (file)
 
 #include "simulator_client_types.h"
 #include "simulator_resource_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.
  */
-class SimulatorRemoteResource
+class SimulatorRemoteResource : public UnCopyable
 {
     public:
 
@@ -150,7 +152,7 @@ class SimulatorRemoteResource
 
         virtual void stopVerification(int id) = 0;
 
-        virtual void configure(const std::string &path) = 0;
+        virtual SimulatorResourceModelSP configure(const std::string &path) = 0;
 };
 
 typedef std::shared_ptr<SimulatorRemoteResource> SimulatorRemoteResourceSP;
diff --git a/service/simulator/inc/simulator_resource.h b/service/simulator/inc/simulator_resource.h
new file mode 100644 (file)
index 0000000..d5b99ca
--- /dev/null
@@ -0,0 +1,215 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_H_
+#define SIMULATOR_RESOURCE_H_
+
+#include "simulator_server_types.h"
+#include "simulator_resource_model.h"
+#include "simulator_uncopyable.h"
+#include "simulator_exceptions.h"
+
+class SimulatorResource : public 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, SimulatorResourceModel &resModel)>
+        ResourceModelChangedCallback;
+
+        /**
+         * 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 name of the resource.
+         *
+         * @return Resource name.
+         */
+        virtual std::string getName() const = 0;
+
+        /**
+         * API to get the type which indicates whether resource is single or collection resource.
+         *
+         * @return Type of resource.
+         */
+        virtual SimulatorResource::Type getType() const = 0;
+
+        /**
+         * API to get the resource URI.
+         *
+         * @return Resource URI.
+         */
+        virtual std::string getURI() const = 0;
+
+        /**
+         * API to get the resource type.
+         *
+         * @return Resource type.
+         */
+        virtual std::string getResourceType() const = 0;
+
+        /**
+         * API to get the interfaces resource is bound with.
+         *
+         * @return Interface type.
+         */
+        virtual std::vector<std::string> getInterface() const = 0;
+
+        /**
+         * API to get the observable state of resource.
+         *
+         * @return bool - true if resource is observable, otherwise false.
+         */
+        virtual bool isObservable() = 0;
+
+        /**
+         * API to get the start state of resource.
+         *
+         * @return bool - true if resource is started, otherwise false.
+         */
+        virtual bool isStarted() = 0;
+
+        /**
+         * API to get SimulatorResourceModel of resource.
+         *
+         * @return Resource model of the resource.
+         */
+        virtual SimulatorResourceModel getResourceModel() = 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 add interface type for resource.
+         *
+         * @param interfaceType - interface to be added for resource.
+         *
+         * NOTE: API throws @InvalidArgsException, @SimulatorException exceptions.
+         */
+        virtual void addInterface(std::string interfaceType) = 0;
+
+        /**
+         * API to make the resource observable or not.
+         *
+         * @param state - true make the resource observable, otherwise non-observable.
+         *
+         * NOTE: API throws @SimulatorException exceptions.
+         */
+        virtual void setObservable(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 model changes.
+         *
+         * @param callback - Callback to be set for receiving the notifications.
+         */
+        virtual void setModelChangeCallback(ResourceModelChangedCallback 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 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.
+         *
+         * @param id - Observer ID to notify.
+         *
+         * NOTE: API throws @SimulatorException exception.
+         */
+        virtual void notify(int id) = 0;
+
+        /**
+         * API to notify all registered observers.
+         *
+         * NOTE: API throws @SimulatorException exception.
+         */
+        virtual void notifyAll() = 0;
+};
+
+typedef std::shared_ptr<SimulatorResource> SimulatorResourceSP;
+
+#endif
index d596ed9b23c93cad6272ec0e26fc892c8e46320d..40a112b3b30fc27ee88ac53ca0c6ecff241e0123 100644 (file)
 #ifndef SIMULATOR_RESOURCE_MODEL_H_
 #define SIMULATOR_RESOURCE_MODEL_H_
 
-#include <string>
-#include <vector>
 #include "OCPlatform.h"
-#include <climits>
+#include <map>
+
+class OCRepresentationBuilder;
+class ToStringConverter;
 
 /**
  * @class   SimulatorResourceModel
 class SimulatorResourceModel
 {
     public:
-        SimulatorResourceModel() = default;
-        SimulatorResourceModel(const SimulatorResourceModel &) = default;
-        SimulatorResourceModel &operator=(const SimulatorResourceModel &) = default;
-        SimulatorResourceModel(SimulatorResourceModel &&) = default;
-        SimulatorResourceModel &operator=(SimulatorResourceModel && ) = default;
+        friend class OCRepresentationBuilder;
+        friend class ToStringConverter;
+
+        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>>>
+        > ValueVariant;
+
+        enum class ValueType
+        {
+            UNKNOWN,
+            INTEGER,
+            DOUBLE,
+            BOOLEAN,
+            STRING,
+            RESOURCE_MODEL,
+            VECTOR
+        };
 
-        /**
-          * @class   Attribute
-          * @brief   This class represents a resource attribute whose values can be generic.
-          */
-        class Attribute
+        class TypeInfo
         {
             public:
-                typedef boost::variant <
-                int,
-                double,
-                bool,
-                std::string
-                > ValueVariant;
-
-                enum class ValueType
+                TypeInfo(ValueType, ValueType, int);
+                TypeInfo(const TypeInfo &) = default;
+                TypeInfo &operator=(const TypeInfo &) = default;
+                TypeInfo(TypeInfo &&) = default;
+                TypeInfo &operator=(TypeInfo &&) = default;
+
+                ValueType type() const;
+                ValueType baseType() const;
+                int depth() const;
+                bool operator ==(const TypeInfo &) const;
+                bool operator !=(const TypeInfo &) const;
+
+            private:
+                ValueType m_type;
+                ValueType m_baseType;
+                int m_depth;
+        };
+
+        class AttributeProperty
+        {
+            public:
+                enum class Type
                 {
                     UNKNOWN,
-                    INTEGER,
-                    DOUBLE,
-                    BOOLEAN,
-                    STRING
+                    RANGE,
+                    VALUE_SET
                 };
 
-                Attribute()
-                {
-                    m_min = INT_MIN;
-                    m_max = INT_MAX;
-                    m_updateInterval = -1;
-                }
+                AttributeProperty();
+                AttributeProperty(const AttributeProperty &) = default;
+                AttributeProperty &operator=(const AttributeProperty &) = default;
+                AttributeProperty(AttributeProperty &&) = default;
+                AttributeProperty &operator=(AttributeProperty &&) = default;
+
+                explicit AttributeProperty(double min, double max);
+                explicit AttributeProperty(const std::vector<int> &valueSet);
+                explicit AttributeProperty(const std::vector<double> &valueSet);
+                explicit AttributeProperty(const std::vector<bool> &valueSet);
+                explicit AttributeProperty(const std::vector<std::string> &valueSet);
+                explicit AttributeProperty(const std::vector<ValueVariant> &valueSet);
+
+                Type type() const;
+                double min() const;
+                double max() const;
+                int valueSetSize() const;
+                std::vector<ValueVariant> valueSet() const;
+                std::string valueSetToString() const;
+                void setChildProperty(AttributeProperty &childProperty);
+                std::shared_ptr<AttributeProperty> getChildProperty();
 
-                Attribute(const std::string &attrName)
-                {
-                    m_name = attrName;
-                    m_min = INT_MIN;
-                    m_max = INT_MAX;
-                    m_updateInterval = -1;
-                }
+            private:
+                Type m_type;
+                double m_min;
+                double m_max;
+                std::vector<ValueVariant> m_valueSet;
+                std::shared_ptr<AttributeProperty> m_childProperty;
+        };
 
-                /**
-                 * 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);
-                }
+        class Attribute
+        {
+            public:
+                Attribute(const std::string &name) : m_name(name) {}
+                Attribute() = default;
+                Attribute(const Attribute &) = default;
+                Attribute &operator=(const Attribute &) = default;
+                Attribute(Attribute &&) = default;
+                Attribute &operator=(Attribute &&) = default;
 
-                /**
-                 * API to get attribute's value.
-                 *
-                 * @return value of attribute as ValueVariant.
-                 */
-                ValueVariant &getValue()
-                {
-                    return m_value;
-                }
+                std::string getName() const;
+                TypeInfo getType() const;
+                const AttributeProperty &getProperty() const;
+                AttributeProperty &getProperty();
 
-                /**
-                 * 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)
-                {
-                    m_value = value;
-                }
+                void setName(const std::string &);
+                void setProperty(const AttributeProperty &);
 
-                /**
-                 * 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)
+                void setValue(const T &value)
                 {
-                    ValueVariant temp = values.at(0);
-                    if (temp.which() != m_value.which())
-                    {
-                        return false;
-                    }
-
-                    m_allowedValues.addValues(values);
-                    return true;
+                    m_value = std::make_shared<ValueVariant>(value);
                 }
 
-                /**
-                 * API to get the number of values present in allowed values set.
-                 *
-                 * @return Size of the allowed values.
-                 */
-                int getAllowedValuesSize() const;
+                ValueVariant getValue() const { return *m_value; }
 
-                /**
-                 * API to get the string representation of the value.
-                 *
-                 * @return Attribute's value as a string.
-                 */
-                std::string valueToString() 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;
-
-                void addValuetoRepresentation(OC::OCRepresentation &rep,
-                                              const std::string &key) const;
-
-                bool compare(Attribute &attribute);
-
-                std::vector<ValueVariant> getAllowedValues() const;
-
-                int getUpdateFrequencyTime() {return m_updateInterval;}
-                void setUpdateFrequencyTime(int interval) {m_updateInterval = interval;}
+                std::string toString() 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;
+                std::shared_ptr<ValueVariant> m_value;
+                AttributeProperty m_property;
         };
 
-        /**
-         * 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
-         */
+        SimulatorResourceModel() = default;
+        SimulatorResourceModel(const SimulatorResourceModel &) = default;
+        SimulatorResourceModel &operator=(const SimulatorResourceModel &) = default;
+        SimulatorResourceModel(SimulatorResourceModel &&) = default;
+        SimulatorResourceModel &operator=(SimulatorResourceModel && ) = default;
+
         template <typename T>
-        void addAttribute(const std::string &attrName, const T &attrValue)
+        bool add(const std::string &key, T value)
         {
-            if (m_attributes.end() == m_attributes.find(attrName))
-            {
-                m_attributes[attrName] = Attribute(attrName);
-                m_attributes[attrName].setValue(attrValue);
-            }
+            ValueVariant newValue = value;
+            return setAttributeValue(key, newValue, true, false);
         }
 
-        /**
-          * 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);
+        bool add(const Attribute &attribute);
 
         template <typename T>
-        void setAllowedValues(const std::string &attrName, const std::vector<T> &values)
+        T get(const std::string &key) const
         {
-            if (m_attributes.end() != m_attributes.find(attrName))
-                m_attributes[attrName].setAllowedValues(values);
+            T val = T();
+            auto x = m_attributes.find(key);
+            if (x != m_attributes.end())
+            {
+                val = boost::get<T>(x->second);
+            }
+            return val;
         }
 
-        bool update(OC::OCRepresentation &ocRep);
-
-        bool update(std::shared_ptr<SimulatorResourceModel> &repModel);
-
         template <typename T>
-        void updateAttribute(const std::string &attrName, const T &value)
+        bool updateValue(const std::string &key, T value, bool forcewrite = false)
         {
-            if (m_attributes.end() != m_attributes.find(attrName))
-                m_attributes[attrName].setValue(value);
+            ValueVariant newValue = value;
+            return setAttributeValue(key, newValue, false, forcewrite);
         }
 
-        void updateAttributeFromAllowedValues(const std::string &attrName, unsigned int index);
+        bool updateValue(const Attribute &attribute, bool forcewrite = false);
+
+        bool containsAttribute(const std::string &key);
+
+        bool setAttributeProperty(const std::string &key, const AttributeProperty &property);
+
+        bool getAttributeProperty(const std::string &key, AttributeProperty &property);
+
+        int size() const;
+
+        TypeInfo getType(const std::string &key);
+
+        std::map<std::string, Attribute> getAttributes();
+
+        bool getAttribute(const std::string &key, Attribute &attribute);
+
+        bool removeAttribute(const std::string &key);
+
+        bool update(OC::OCRepresentation &ocRep);
+
+        OC::OCRepresentation getOCRepresentation();
+
+        bool match(const SimulatorResourceModel &resModel, bool strict = false);
 
-        void removeAttribute(const std::string &attrName);
+        std::string toString() const;
 
-        void setUpdateInterval(const std::string &attrName, int interval);
+        static SimulatorResourceModel build(const OC::OCRepresentation &ocRep);
 
     private:
-        std::map<std::string, Attribute> m_attributes;
+        TypeInfo getTypeInfo(const ValueVariant &value) const;
+        bool setAttributeValue(const std::string &key, const ValueVariant &newValue,
+                               bool create, bool overwrite);
+        bool match(const std::string &key, const ValueVariant &newValue);
+        bool update(SimulatorResourceModel &resModel);
+        std::map<std::string, ValueVariant> getValues() const;
+
+        std::map<std::string, ValueVariant> m_attributes;
+        std::map<std::string, AttributeProperty> m_attrProperties;
 };
 
 typedef std::shared_ptr<SimulatorResourceModel> SimulatorResourceModelSP;
-typedef std::shared_ptr<SimulatorResourceModel::Attribute> AttributeSP;
 
 #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
index 2449d0a7f3f8e1a3ea13fbcf9fcfc99054f18c23..9d9297705ce9df34faa99adad9a3878400c40760 100644 (file)
 #include <iostream>
 #include <functional>
 
+enum class ObservationStatus
+{
+    REGISTER,
+    UNREGISTER
+};
+
+typedef struct
+{
+    uint8_t id;
+    std::string address;
+    uint16_t port;
+} ObserverInfo;
+
 enum class AutomationType
 {
     NORMAL,
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..3fb7935
--- /dev/null
@@ -0,0 +1,182 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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 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_SINGLE_RESOURCE_H_
+#define SIMULATOR_SINGLE_RESOURCE_H_
+
+#include "simulator_resource.h"
+
+/**
+ * @class   SimulatorSingleResource
+ * @brief   This class provides a set of APIs for handling simulated resource.
+ */
+class SimulatorSingleResource : public SimulatorResource
+{
+    public:
+
+        /**
+         * 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,
+                                  SimulatorResourceModel::Attribute &attribute) = 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 void addAttribute(const SimulatorResourceModel::Attribute &attribute,
+                                  bool notify = true) = 0;
+
+        /**
+         * API to get property of attribute's value.
+         *
+         * @param attrName - Attribute's name.
+         * @param property - Property which was set to attribute's value.
+         *
+         * @return bool - true on success, otherwise false.
+         */
+        virtual bool getAttributeProperty(const std::string &attrName,
+                                          SimulatorResourceModel::AttributeProperty &property) = 0;
+
+        /**
+         * API to set property of attribute's value.
+         *
+         * @param attrName - Attribute's name.
+         * @param property - Property to be set for attribute's value.
+         *
+         * @return bool - true on success, otherwise false.
+         */
+        virtual bool setAttributeProperty(const std::string &attrName,
+                                          const SimulatorResourceModel::AttributeProperty &property) = 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)
+        {
+            SimulatorResourceModel::Attribute 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 SimulatorResourceModel::Attribute &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(AutomationType type, int updateInterval,
+                                          updateCompleteCallback 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, 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> getResourceUpdationIds() = 0;
+
+        /**
+         * API to get the Ids of all ongoing attribute update automation .
+         *
+         * @return vector of attribute automation ids.
+         */
+        virtual std::vector<int> getAttributeUpdationIds() = 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..7d87e38
--- /dev/null
@@ -0,0 +1,33 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_UNCOPYABLE_H_
+#define SIMULATOR_UNCOPYABLE_H_
+
+class UnCopyable
+{
+    public:
+        UnCopyable() = default;
+        UnCopyable(const UnCopyable &) = delete;
+        UnCopyable &operator=(const UnCopyable &) = delete;
+        virtual ~UnCopyable() {};
+};
+
+#endif
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
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 6d752c541b84342f9a17f37dad1b44ee426a8ad1..535d60b8908eb7f0b09170a9aa60d74ee1946b8b 100644 (file)
@@ -23,6 +23,4 @@ import oic.simulator.clientcontroller.remoteresource.RemoteResource;
  */
 public interface IGetUIListener {
     public void onGetCompleted(RemoteResource resource);
-
-    public void onGetFailed(RemoteResource resource);
 }
index ca5f8383f515ceeef8b9078df2030a3720d0fbbb..8294f9c762ca5c47151c9be183d5112c3be81b0d 100644 (file)
@@ -24,6 +24,4 @@ import oic.simulator.clientcontroller.remoteresource.RemoteResource;
  */
 public interface IObserveUIListener {
     public void onObserveCompleted(RemoteResource resource);
-
-    public void onObserveFailed(RemoteResource resource);
 }
index 793eb763193f17326ae9c8049356738c4b02a3c3..9ce67733eacebfc4bf5a976be0e31b1680bfc1f2 100644 (file)
@@ -23,6 +23,4 @@ import oic.simulator.clientcontroller.remoteresource.RemoteResource;
  */
 public interface IPostUIListener {
     public void onPostCompleted(RemoteResource resource);
-
-    public void onPostFailed(RemoteResource resource);
 }
index 28eb3ffaaeb217b634aefd55f729c013deab1099..3b17c43f78ba6ec9e7d1675789d4d6ecaabf7c6e 100644 (file)
@@ -23,6 +23,4 @@ import oic.simulator.clientcontroller.remoteresource.RemoteResource;
  */
 public interface IPutUIListener {
     public void onPutCompleted(RemoteResource resource);
-
-    public void onPutFailed(RemoteResource resource);
 }
index b0b1f6c27fc050a093e0a249ffbb441ad4fc933f..cb7f17e1ccc38dc5d59d32b077a380e01414b351 100644 (file)
@@ -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 03700e46bb95e2790ffd2f68ffdaca4b05f50484..ffdb442c6875daf0e2dd2152dcc657799760ba87 100644 (file)
@@ -24,6 +24,7 @@ import java.util.LinkedList;
 import oic.simulator.clientcontroller.Activator;
 import oic.simulator.clientcontroller.listener.ILogUIListener;
 import oic.simulator.clientcontroller.utils.Constants;
+import oic.simulator.clientcontroller.utils.Utility;
 import oic.simulator.logger.LogEntry;
 import oic.simulator.logger.LoggerCallback;
 
@@ -31,6 +32,7 @@ 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.SimulatorException;
 import org.oic.simulator.SimulatorManager;
 
 /**
@@ -55,7 +57,14 @@ public class LogManager {
 
         // Set the logger callback with the native layer
         logger = new LoggerCallback();
-        SimulatorManager.setLogger(logger);
+        try {
+            SimulatorManager.setLogger(logger);
+        } catch (SimulatorException e) {
+            log(Level.ERROR.ordinal(),
+                    new Date(),
+                    "Failed to register the logger.\n"
+                            + Utility.getSimulatorErrorString(e, null));
+        }
     }
 
     private static class LogManagerSynchronizerThread implements Runnable {
index c7d225fc91055304219aaa1e24a1978726119e4c..bcadd4a7f9aea69115dee3b5e0f78e31f2f4a2f4 100644 (file)
@@ -16,7 +16,6 @@
 
 package oic.simulator.clientcontroller.manager;
 
-import java.net.URL;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.Comparator;
@@ -27,9 +26,11 @@ import java.util.LinkedList;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
+import java.util.Vector;
 
 import oic.simulator.clientcontroller.Activator;
 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;
@@ -41,27 +42,33 @@ 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.AttributeValueBuilder;
 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.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.DeviceInfo;
+import org.oic.simulator.DeviceListener;
 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.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.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;
+import org.oic.simulator.SimulatorResult;
+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.VerificationListener;
+import org.oic.simulator.client.SimulatorRemoteResource.VerificationType;
 
 /**
  * This class acts as an interface between the simulator java SDK and the
@@ -76,12 +83,14 @@ public class ResourceManager {
 
     private RemoteResource                            currentResourceInSelection;
 
-    private IFindResourceListener                     findResourceListener;
-    private IGetListener                              getListener;
-    private IPutListener                              putListener;
-    private IPostListener                             postListener;
-    private IObserveListener                          observeListener;
-    private IVerificationListener                     verifyListener;
+    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 ResponseSynchronizerThread                synchronizerThread;
 
@@ -95,6 +104,7 @@ public class ResourceManager {
     private List<IObserveUIListener>                  observeUIListeners;
     private List<IVerificationUIListener>             verificationUIListeners;
     private List<IConfigurationUpload>                configUploadUIListeners;
+    private List<IDevicePlatformInfoUIListener>       devicePlatformInfoUIListeners;
 
     // Map with Server ID as key and the complete object as the value
     private Map<String, RemoteResource>               resourceMap;
@@ -105,6 +115,9 @@ public class ResourceManager {
     // Maintaining a list of observed resource URIs.
     private List<String>                              observedResourceURIList;
 
+    private DeviceInfo                                devInfo;
+    private PlatformInfo                              platInfo;
+
     public ResourceManager() {
         resourceMap = new HashMap<String, RemoteResource>();
         favoriteResources = new ArrayList<RemoteResource>();
@@ -118,41 +131,41 @@ public class ResourceManager {
         observeUIListeners = new ArrayList<IObserveUIListener>();
         verificationUIListeners = new ArrayList<IVerificationUIListener>();
         configUploadUIListeners = new ArrayList<IConfigurationUpload>();
+        devicePlatformInfoUIListeners = new ArrayList<IDevicePlatformInfoUIListener>();
 
-        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.
+
+                        // 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 + "]");
                             return;
                         }
 
                         // Fetch the resource data
-                        RemoteResource resource = fetchResourceDetails(resourceN);
-                        if (null == resource) {
-                            return;
-                        }
-
-                        resource.setResource(resourceN);
+                        // RemoteResource resource =
+                        // fetchResourceDetails(resourceN);
+                        RemoteResource resource = new RemoteResource();
+                        resource.setRemoteResourceRef(resourceN);
 
-                        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)) {
@@ -161,8 +174,15 @@ public class ResourceManager {
                             // Add resource to observed resources list if it was
                             // in observe list during find/refresh operation.
                             if (observedResourceURIList.contains(uri)) {
-                                resource.setObserved(true);
+                                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
@@ -171,6 +191,14 @@ public class ResourceManager {
                         // Notify the UI listener
                         newResourceFoundNotification(resource);
 
+                        Activator
+                                .getDefault()
+                                .getLogManager()
+                                .log(Level.INFO.ordinal(),
+                                        new Date(),
+                                        "Resource Found [" + resourceN.getURI()
+                                                + "].");
+
                         // Send an initial GET request to get the resource
                         // attributes
                         try {
@@ -181,50 +209,86 @@ public class ResourceManager {
                                     .getLogManager()
                                     .log(Level.ERROR.ordinal(),
                                             new Date(),
-                                            "[" + e.getClass().getSimpleName()
-                                                    + "]" + e.code().toString()
-                                                    + "-" + e.message());
+                                            Utility.getSimulatorErrorString(e,
+                                                    null));
+                        }
+
+                        // Get the device and platform information
+                        try {
+                            SimulatorManager.findDevices(deviceListener);
+                            SimulatorManager
+                                    .getPlatformInformation(platformListener);
+                        } catch (SimulatorException e) {
+                            Activator
+                                    .getDefault()
+                                    .getLogManager()
+                                    .log(Level.ERROR.ordinal(),
+                                            new Date(),
+                                            Utility.getSimulatorErrorString(e,
+                                                    null));
                         }
                     }
                 });
             }
         };
 
-        getListener = new IGetListener() {
+        // TODO: Listeners for device and platform information.
+        deviceListener = new DeviceListener() {
+
             @Override
-            public void onGetCompleted(final String uid,
-                    final SimulatorResourceModel resourceModelN) {
+            public void onDeviceFound(final DeviceInfo deviceInfo) {
+                if (null == deviceInfo) {
+                    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);
-                        }
+                        setDeviceInfo(deviceInfo);
+
+                        // Notify UI listeners
+                        deviceInfoReceivedNotification();
                     }
                 });
             }
+        };
+
+        platformListener = new PlatformListener() {
 
             @Override
-            public void onGetFailed(Throwable th) {
+            public void onPlatformFound(final PlatformInfo platformInfo) {
+                if (null == platformInfo) {
+                    return;
+                }
                 synchronizerThread.addToQueue(new Runnable() {
                     @Override
                     public void run() {
+                        setPlatformInfo(platformInfo);
+
+                        // Notify UI listeners
+                        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() {
+                System.out.println(result);
+                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,26 +297,62 @@ public class ResourceManager {
                                 resourceModelN);
                         if (null != resource) {
                             // Notify the UI listeners
-                            putCompleteNotification(resource);
+                            getCompleteNotification(resource);
                         }
                     }
                 });
             }
+        };
+
+        putListener = new PutResponseListener() {
 
             @Override
-            public void onPutFailed(Throwable th) {
-                synchronizerThread.addToQueue(new Runnable() {
+            public void onPutResponse(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 PUT request.");
+                    return;
+                }
+                synchronizerThread.addToQueue(new Thread() {
                     @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
+                            putCompleteNotification(resource);
+                        }
                     }
                 });
             }
         };
 
-        postListener = new IPostListener() {
+        postListener = new PostResponseListener() {
             @Override
-            public void onPostCompleted(final String uid,
+            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() {
@@ -267,23 +367,13 @@ public class ResourceManager {
                     }
                 });
             }
-
-            @Override
-            public void onPostFailed(Throwable th) {
-                synchronizerThread.addToQueue(new Runnable() {
-                    @Override
-                    public void run() {
-                    }
-                });
-            }
         };
 
-        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() {
@@ -298,18 +388,12 @@ public class ResourceManager {
                     }
                 });
             }
-
-            @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() {
@@ -331,7 +415,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() {
@@ -352,7 +435,6 @@ public class ResourceManager {
 
             @Override
             public void onVerificationAborted(final String uid, final int autoId) {
-                System.out.println("onVefificationAborted: " + autoId);
                 synchronizerThread.addToQueue(new Runnable() {
                     @Override
                     public void run() {
@@ -391,20 +473,75 @@ public class ResourceManager {
             return null;
         }
 
-        resource.setResourceModel(resourceModelN);
+        resource.setResourceModelRef(resourceModelN);
         Map<String, RemoteResourceAttribute> attributeMap = fetchResourceAttributesFromModel(resourceModelN);
-
-        // TODO: For debugging
+        if (resource.isConfigUploaded()) {
+            updateResourceAttributesFromResponse(resource, attributeMap);
+        } else {
+            resource.setResourceAttributesMap(attributeMap);
+        }
+        // TODO: Printing the values for debugging
         if (null != attributeMap) {
             RemoteResourceAttribute.printAttributes(attributeMap);
-            System.out.println("Attributes found: " + (null != attributeMap));
-            System.out.println("No of attributes: " + attributeMap.size());
-
-            resource.setResourceAttributesMap(attributeMap);
         }
         return resource;
     }
 
+    private void updateResourceAttributesFromResponse(RemoteResource res,
+            Map<String, RemoteResourceAttribute> newAttributeMap) {
+        if (null == res || null == newAttributeMap) {
+            return;
+        }
+        Map<String, RemoteResourceAttribute> oldAttributeMap = res
+                .getResourceAttributesMap();
+        if (null == oldAttributeMap) {
+            return;
+        }
+        Iterator<String> itr = oldAttributeMap.keySet().iterator();
+        String attName;
+        RemoteResourceAttribute newAtt;
+        RemoteResourceAttribute oldAtt;
+        while (itr.hasNext()) {
+            attName = itr.next();
+            newAtt = newAttributeMap.get(attName);
+            if (null == newAtt) {
+                // Attribute does not exist in the received model. Hence
+                // removing it from local model.
+                itr.remove();
+            } else {
+                oldAtt = oldAttributeMap.get(attName);
+                if (null != oldAtt) {
+                    oldAtt.setAttributeValue(newAtt.getAttributeValue());
+                } else {
+                    itr.remove();
+                }
+                newAttributeMap.remove(attName);
+            }
+        }
+        // Adding new attributes in the received model.
+        itr = newAttributeMap.keySet().iterator();
+        while (itr.hasNext()) {
+            attName = itr.next();
+            oldAttributeMap.put(attName, newAttributeMap.get(attName));
+        }
+    }
+
+    public synchronized DeviceInfo getDeviceInfo() {
+        return devInfo;
+    }
+
+    public synchronized void setDeviceInfo(DeviceInfo devInfo) {
+        this.devInfo = devInfo;
+    }
+
+    public synchronized PlatformInfo getPlatformInfo() {
+        return platInfo;
+    }
+
+    public synchronized void setPlatformInfo(PlatformInfo platInfo) {
+        this.platInfo = platInfo;
+    }
+
     private static class ResponseSynchronizerThread implements Runnable {
 
         LinkedList<Runnable> responseQueue = new LinkedList<Runnable>();
@@ -491,6 +628,20 @@ public class ResourceManager {
         }
     }
 
+    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) {
@@ -545,7 +696,6 @@ public class ResourceManager {
         resource.setFavorite(true);
         synchronized (favoriteResources) {
             favoriteResources.add(resource);
-            favoriteURIList.add(resource.getResourceURI());
         }
     }
 
@@ -559,12 +709,21 @@ 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());
         }
     }
 
@@ -600,7 +759,8 @@ public class ResourceManager {
     private void addResourceDetails(RemoteResource remoteResource) {
         if (null != remoteResource) {
             synchronized (resourceMap) {
-                resourceMap.put(remoteResource.getuId(), remoteResource);
+                resourceMap.put(remoteResource.getRemoteResourceRef().getId(),
+                        remoteResource);
             }
         }
     }
@@ -623,24 +783,6 @@ public class ResourceManager {
         }
     }
 
-    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) {
@@ -664,27 +806,19 @@ public class ResourceManager {
             SimulatorResourceModel resourceModelN) {
         Map<String, RemoteResourceAttribute> 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;
-            }
+            Map<String, SimulatorResourceAttribute> attributeMapN;
+            attributeMapN = resourceModelN.getAttributes();
             if (null != attributeMapN) {
                 resourceAttributeMap = new HashMap<String, RemoteResourceAttribute>();
 
                 Set<String> attNameSet = attributeMapN.keySet();
                 String attName;
                 Object attValueObj;
-                ResourceAttribute attributeN;
+                AttributeValue attValueN;
+                AttributeProperty attPropN;
+                TypeInfo typeInfo;
+                Type valuesType;
+                SimulatorResourceAttribute attributeN;
                 RemoteResourceAttribute attribute;
                 Iterator<String> attNameItr = attNameSet.iterator();
                 while (attNameItr.hasNext()) {
@@ -692,53 +826,42 @@ public class ResourceManager {
                     attributeN = attributeMapN.get(attName);
                     if (null != attributeN) {
                         attribute = new RemoteResourceAttribute();
-                        attribute.setResourceAttribute(attributeN);
+                        attribute.setResourceAttributeRef(attributeN);
                         attribute.setAttributeName(attName);
 
-                        attValueObj = attributeN.getValue();
-                        if (null != attValueObj) {
-                            attribute.setAttributeValue(attValueObj);
-                        }
+                        attValueN = attributeN.value();
+                        if (null != attValueN) {
+                            attValueObj = attValueN.get();
+                            if (null != attValueObj) {
+                                attribute.setAttributeValue(attValueObj);
+                            }
 
-                        // Set the attribute type
-                        attribute.setAttValBaseType(attributeN.getBaseType());
-                        attribute.setAttValType(attributeN.getType());
+                            // Set the attribute type
+                            typeInfo = attValueN.typeInfo();
+                            if (null != typeInfo) {
+                                attribute.setAttValBaseType(typeInfo.mBaseType);
+                                attribute.setAttValType(typeInfo.mType);
+                                attribute.setDepth(typeInfo.mDepth);
+                            }
+
+                        }
 
                         // 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();
+                        attPropN = attributeN.property();
+                        valuesType = attPropN.type();
+                        attribute.setValuesType(valuesType);
+                        if (valuesType == Type.RANGE) {
+                            attribute.setMinValue(attPropN.min());
+                            attribute.setMaxValue(attPropN.max());
+                        } else if (valuesType == Type.VALUESET) {
+                            Object[] values = attPropN.valueSet();
                             if (null != values && values.length > 0) {
                                 List<Object> valueList = new ArrayList<Object>();
                                 for (Object obj : values) {
-                                    valueList.add(obj);
+                                    valueList.add(((AttributeValue) obj).get());
                                 }
                                 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);
                     }
@@ -911,31 +1034,36 @@ public class ResourceManager {
         }
     }
 
-    // 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);
+    private 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();
+                    }
                 }
             }
+        }
+    }
 
-            // Sort the types
-            Collections.sort(list);
+    private 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();
+                    }
+                }
+            }
         }
-        return list;
     }
 
     public synchronized Set<String> getLastKnownSearchTypes() {
@@ -948,45 +1076,71 @@ public class ResourceManager {
     }
 
     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();
+        if (null == searchTypes || searchTypes.size() < 1) {
             try {
-                SimulatorManager.findResource(rType, findResourceListener);
+                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());
+                        .log(Level.ERROR.ordinal(), new Date(),
+                                Utility.getSimulatorErrorString(e, null));
+            }
+        } 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));
+                }
             }
         }
         return result;
     }
 
     public void deleteResources(final Set<String> searchTypes) {
-        if (null == searchTypes || searchTypes.size() < 1) {
-            return;
+        synchronized (resourceMap) {
+            if (null == resourceMap && 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();
+                        favoriteResources.clear();
+                    }
                     // Change the current resource in selection
-                    updateCurrentResourceInSelection(searchTypes);
+                    setCurrentResourceInSelection(null);
+                    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 +1154,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;
         }
@@ -1036,14 +1191,16 @@ 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();
                     }
                 }
             }
@@ -1061,7 +1218,7 @@ public class ResourceManager {
         }.start();
     }
 
-    public List<MetaProperty> getMetaProperties(RemoteResource resource) {
+    public List<MetaProperty> getDefaultProperties(RemoteResource resource) {
         if (null != resource) {
             String propName;
             String propValue;
@@ -1071,22 +1228,26 @@ public class ResourceManager {
             for (int index = 0; index < Constants.META_PROPERTY_COUNT; index++) {
                 propName = Constants.META_PROPERTIES[index];
                 if (propName.equals(Constants.RESOURCE_URI)) {
-                    propValue = resource.getResourceURI();
+                    propValue = resource.getRemoteResourceRef().getURI();
                 } else if (propName.equals(Constants.CONNECTIVITY_TYPE)) {
-                    propValue = resource.getConnectivityType().toString();
+                    propValue = resource.getRemoteResourceRef()
+                            .getConnectivityType().toString();
+                } else if (propName.equals(Constants.ADDRESS)) {
+                    propValue = resource.getRemoteResourceRef().getHost();
                 } else if (propName.equals(Constants.OBSERVABLE)) {
                     propValue = Utility.getObservableInString(resource
-                            .isObservable());
-                    // see in UI
+                            .getRemoteResourceRef().isObservable());
                 } else if (propName.equals(Constants.RESOURCE_TYPES)) {
-                    List<String> types = resource.getResourceTypes();
+                    Vector<String> types = resource.getRemoteResourceRef()
+                            .getResourceTypes();
                     if (null != types) {
                         propValue = types.toString();
                     } else {
                         propValue = Constants.NOT_AVAILABLE;
                     }
                 } else if (propName.equals(Constants.RESOURCE_INTERFACES)) {
-                    List<String> interfaces = resource.getResourceInterfaces();
+                    Vector<String> interfaces = resource.getRemoteResourceRef()
+                            .getResourceInterfaces();
                     if (null != interfaces) {
                         propValue = interfaces.toString();
                     } else {
@@ -1105,6 +1266,84 @@ public class ResourceManager {
         return null;
     }
 
+    public List<MetaProperty> getDeviceProperties() {
+        if (null == devInfo) {
+            return null;
+        }
+
+        List<MetaProperty> metaProperties = new ArrayList<MetaProperty>();
+
+        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()));
+
+        /*
+         * metaProperties.add(new MetaProperty(Constants.DEVICE_ID, ""));
+         * metaProperties.add(new MetaProperty(Constants.DEVICE_NAME, ""));
+         * metaProperties.add(new MetaProperty(Constants.DEVICE_SPEC_VERSION,
+         * "")); metaProperties.add(new
+         * MetaProperty(Constants.DEVICE_DMV_VERSION, ""));
+         */
+        return metaProperties;
+    }
+
+    public List<MetaProperty> getPlatformProperties() {
+        if (null == platInfo) {
+            return null;
+        }
+
+        List<MetaProperty> metaProperties = new ArrayList<MetaProperty>();
+
+        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()));
+
+        /*
+         * metaProperties.add(new MetaProperty(Constants.PLATFORM_ID, ""));
+         * metaProperties .add(new MetaProperty(Constants.PLATFORM_MANUFAC_NAME,
+         * "")); metaProperties .add(new
+         * MetaProperty(Constants.PLATFORM_MANUFAC_URL, ""));
+         * metaProperties.add(new MetaProperty(Constants.PLATFORM_MODEL_NO,
+         * "")); metaProperties.add(new
+         * MetaProperty(Constants.PLATFORM_DATE_OF_MANUFAC, ""));
+         * metaProperties.add(new MetaProperty(Constants.PLATFORM_VERSION, ""));
+         * metaProperties.add(new MetaProperty(Constants.PLATFORM_OS_VERSION,
+         * "")); metaProperties.add(new MetaProperty(
+         * Constants.PLATFORM_HARDWARE_VERSION, "")); metaProperties.add(new
+         * MetaProperty( Constants.PLATFORM_FIRMWARE_VERSION, ""));
+         * metaProperties .add(new MetaProperty(Constants.PLATFORM_SUPPORT_URL,
+         * "")); metaProperties .add(new
+         * MetaProperty(Constants.PLATFORM_SYSTEM_TIME, ""));
+         */
+        return metaProperties;
+    }
+
     public Map<String, Boolean> getAutomationStatus(RemoteResource resource) {
         if (null == resource) {
             return null;
@@ -1116,13 +1355,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 +1371,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", "");
@@ -1180,7 +1412,7 @@ public class ResourceManager {
         if (null == resource) {
             return;
         }
-        SimulatorRemoteResource resourceN = resource.getResource();
+        SimulatorRemoteResource resourceN = resource.getRemoteResourceRef();
         if (null == resourceN) {
             return;
         }
@@ -1190,56 +1422,46 @@ 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 sendPutRequest(RemoteResource resource,
             List<PutPostAttributeModel> putPostModelList) {
-        System.out.println(putPostModelList);
-        System.out.println("ResourceManager: sendPutRequest");
         if (null == resource) {
             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));
         try {
-            resourceN.put(resourceModel, null, putListener);
-        } catch (SimulatorException e) {
+            SimulatorResourceModel resourceModel = getUpdatedResourceModel(
+                    attMap, putPostModelList);
+            resourceN.put(null, resourceModel, 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) {
             return;
         }
-        SimulatorRemoteResource resourceN = resource.getResource();
+        SimulatorRemoteResource resourceN = resource.getRemoteResourceRef();
         if (null == resourceN) {
             return;
         }
@@ -1257,196 +1479,114 @@ public class ResourceManager {
                 itr.remove();
             }
         }
-        SimulatorResourceModel resourceModel = getUpdatedResourceModel(attMap,
-                putPostModelList);
         try {
-            resourceN.post(resourceModel, null, postListener);
-        } catch (SimulatorException e) {
+            SimulatorResourceModel resourceModel = getUpdatedResourceModel(
+                    attMap, putPostModelList);
+            resourceN.post(null, resourceModel, 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;
+            List<PutPostAttributeModel> putPostModelList) throws Exception {
         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());
-                }
-            }
+        for (PutPostAttributeModel putPostAttribute : putPostModelList)
+        {
+            String attributeName = putPostAttribute.getAttName();
+            RemoteResourceAttribute resourceAttribute = attMap.get(attributeName);
+            AttributeValue attributeValue = AttributeValueBuilder.build(
+                    putPostAttribute.getAttValue(), resourceAttribute.getAttValBaseType());
+            resourceModel.addAttribute(attributeName, attributeValue);
         }
+
         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.startObserve(null, 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;
+    public boolean sendCancelObserveRequest(RemoteResource resource,
+            boolean removeEntry) {
+        if (null == resource || !resource.isObserved()) {
+            return false;
         }
-        resource.setObserved(false);
-        SimulatorRemoteResource resourceN = resource.getResource();
+        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(VerificationType 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) {
+                if (reqType == VerificationType.GET) {
                     // resource.setGetAutomtnInProgress(true);
                     resource.setGetAutomtnId(autoId);
-                } else if (reqType == Constants.PUT_AUTOMATION_INDEX) {
+                } else if (reqType == VerificationType.PUT) {
                     // resource.setPutAutomtnInProgress(true);
                     resource.setPutAutomtnId(autoId);
                 } else {// if(reqType == Constants.POST_AUTOMATION_INDEX) {
-                        // resource.setPostAutomtnInProgress(true);
+                    // resource.setPostAutomtnInProgress(true);
                     resource.setPostAutomtnId(autoId);
                 }
             }
@@ -1454,26 +1594,25 @@ 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 stopAutomationRequest(int reqType, RemoteResource resource) {
+    public void stopAutomationRequest(VerificationType 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 == VerificationType.GET) {
             resource.setGetAutomtnInProgress(false);
             autoId = resource.getGetAutomtnId();
-        } else if (reqType == Constants.PUT_AUTOMATION_INDEX) {
+        } else if (reqType == VerificationType.PUT) {
             resource.setPutAutomtnInProgress(false);
             autoId = resource.getPutAutomtnId();
         } else {// if(reqType == Constants.POST_AUTOMATION_INDEX) {
@@ -1486,60 +1625,53 @@ 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);
+            SimulatorResourceModel resourceModel;
+            resourceModel = resourceN.setConfigInfo(configFilePath);
+            if (null == resourceModel) {
+                return false;
+            }
+            // Store the resource model in the local cache
+            resource.setResourceModelRef(resourceModel);
+
+            // Fetching the allowed values and range for all the attributes
+            Map<String, RemoteResourceAttribute> attributeMap = fetchResourceAttributesFromModel(resourceModel);
+            resource.setResourceAttributesMap(attributeMap);
+            // TODO: Printing the values for debugging
+            if (null != attributeMap) {
+                RemoteResourceAttribute.printAttributes(attributeMap);
+            }
         } catch (SimulatorException e) {
             Activator
                     .getDefault()
                     .getLogManager()
-                    .log(Level.ERROR.ordinal(),
-                            new Date(),
-                            "[" + e.getClass().getSimpleName() + "]"
-                                    + e.code().toString() + "-" + e.message());
-            return;
+                    .log(Level.ERROR.ordinal(), new Date(),
+                            Utility.getSimulatorErrorString(e, null));
+            throw e;
         }
         // 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();
-    }
 
-    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.
     }
 }
index 0b566a07ddbfadc3bb3e5d678e63cf2902d0605e..de3f384e8a804ccd101817a372f813b2aa09331b 100644 (file)
@@ -53,6 +53,13 @@ public class PutPostAttributeModel {
         this.values = values;
     }
 
+    public void prependNewValue(String customValue) {
+        if (values.contains(customValue)) {
+            values.remove(customValue);
+        }
+        values.add(0, customValue);
+    }
+
     public boolean isModified() {
         return modified;
     }
@@ -79,5 +86,4 @@ public class PutPostAttributeModel {
     public String toString() {
         return attName + "," + attValue + "\n";
     }
-
 }
index 17a052efc3f53c6774824508728c4457180b4f86..04c39d1c39f6092fa59a97572bc29e936542f018 100644 (file)
@@ -18,34 +18,25 @@ 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;
 
 /**
  * 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;
 
     // Native object references
-    private SimulatorRemoteResource              resourceN;
-    private SimulatorResourceModel               resourceModel;
+    private SimulatorRemoteResource              remoteResourceRef;
+    private SimulatorResourceModel               resourceModelRef;
     private Map<String, RemoteResourceAttribute> resourceAttributesMap;
 
     private boolean                              configUploaded;
@@ -60,12 +51,12 @@ public class RemoteResource {
 
     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() {
@@ -101,54 +92,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 +124,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() {
@@ -226,14 +169,6 @@ public class RemoteResource {
         return String.valueOf(attribute.getAttributeValue());
     }
 
-    public String getuId() {
-        return uId;
-    }
-
-    public void setuId(String uId) {
-        this.uId = uId;
-    }
-
     public int getAutomationtype(int autoId) {
         if (getAutomtnId == autoId) {
             return Constants.GET_AUTOMATION_INDEX;
index 27cbdc8391e9adfaa83d7a4b244b15a03dd1954d..e014bdcd21139c1de873783180ffcd781ec780d1 100644 (file)
@@ -21,8 +21,10 @@ import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
 
-import org.oic.simulator.ResourceAttribute;
-import org.oic.simulator.ResourceAttribute.Type;
+import org.oic.simulator.AttributeProperty.Type;
+import org.oic.simulator.AttributeValue;
+import org.oic.simulator.AttributeValue.ValueType;
+import org.oic.simulator.SimulatorResourceAttribute;
 
 /**
  * This class represents an attribute in the remote resource.
@@ -30,23 +32,27 @@ import org.oic.simulator.ResourceAttribute.Type;
 public class RemoteResourceAttribute {
 
     // Native object reference
-    private ResourceAttribute resourceAttribute;
+    private SimulatorResourceAttribute resourceAttributeRef;
 
-    private String            attributeName;
-    private Object            attributeValue;
-    private Type              attValType;
-    private Type              attValBaseType;
-    private List<Object>      allowedValues;
+    private String                     attributeName;
+    private Object                     attributeValue;
 
-    private Object            minValue;
-    private Object            maxValue;
+    private ValueType                  attValType;
+    private ValueType                  attValBaseType;
+    private int                        depth;
 
-    public ResourceAttribute getResourceAttribute() {
-        return resourceAttribute;
+    private Type                       valuesType;
+    private List<Object>               allowedValues;
+    private Object                     minValue;
+    private Object                     maxValue;
+
+    public SimulatorResourceAttribute getResourceAttributeRef() {
+        return resourceAttributeRef;
     }
 
-    public void setResourceAttribute(ResourceAttribute resourceAttribute) {
-        this.resourceAttribute = resourceAttribute;
+    public void setResourceAttributeRef(
+            SimulatorResourceAttribute resourceAttribute) {
+        this.resourceAttributeRef = resourceAttribute;
     }
 
     public String getAttributeName() {
@@ -112,7 +118,7 @@ public class RemoteResourceAttribute {
             clone.setAttValType(attribute.getAttValType());
             clone.setMinValue(attribute.getMinValue());
             clone.setMaxValue(attribute.getMaxValue());
-            clone.setResourceAttribute(null);
+            clone.setResourceAttributeRef(null);
         }
         return clone;
     }
@@ -132,18 +138,10 @@ public class RemoteResourceAttribute {
                 }
             }
         } 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));
-                }
+            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) {
@@ -152,6 +150,7 @@ public class RemoteResourceAttribute {
         return valueList;
     }
 
+    // Method added for debugging purpose
     public static void printAttributes(
             Map<String, RemoteResourceAttribute> attributeMap) {
         Iterator<String> itr = attributeMap.keySet().iterator();
@@ -167,19 +166,35 @@ public class RemoteResourceAttribute {
         }
     }
 
-    public Type getAttValType() {
+    public ValueType getAttValType() {
         return attValType;
     }
 
-    public void setAttValType(Type attValType) {
+    public void setAttValType(ValueType attValType) {
         this.attValType = attValType;
     }
 
-    public Type getAttValBaseType() {
+    public ValueType getAttValBaseType() {
         return attValBaseType;
     }
 
-    public void setAttValBaseType(Type attValBaseType) {
+    public void setAttValBaseType(ValueType attValBaseType) {
         this.attValBaseType = attValBaseType;
     }
+
+    public Type getValuesType() {
+        return valuesType;
+    }
+
+    public void setValuesType(Type valuesType) {
+        this.valuesType = valuesType;
+    }
+
+    public int getDepth() {
+        return depth;
+    }
+
+    public void setDepth(int depth) {
+        this.depth = depth;
+    }
 }
\ 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..c41a96f
--- /dev/null
@@ -0,0 +1,77 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.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 Exception {
+        try {
+            FileOutputStream fileOut = new FileOutputStream(filePath);
+            ObjectOutputStream out = new ObjectOutputStream(fileOut);
+            out.writeObject(this);
+            out.close();
+            fileOut.close();
+        } catch (IOException i) {
+            throw new Exception("Failed to Serialize data : IOException");
+        }
+    }
+
+    public static SerializedClientController deSerialize(String filePath)
+            throws Exception {
+        SerializedClientController r = null;
+        try {
+            FileInputStream fileIn = new FileInputStream(filePath);
+            ObjectInputStream in = new ObjectInputStream(fileIn);
+            r = (SerializedClientController) in.readObject();
+            in.close();
+            fileIn.close();
+        } catch (IOException i) {
+            throw new Exception("Failed to DeSerialize data : IOException");
+        } catch (ClassNotFoundException c) {
+            throw new Exception("Failed to DeSerialize data : ClassNotFound");
+        }
+        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..1716846
--- /dev/null
@@ -0,0 +1,266 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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) {
+        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;
+
+        if (valueType == AttributeValue.ValueType.INTEGER)
+            return new AttributeValue(Integer.parseInt(valueString));
+        else if (valueType == AttributeValue.ValueType.DOUBLE)
+            return new AttributeValue(Double.parseDouble(valueString));
+        else if (valueType == AttributeValue.ValueType.BOOLEAN)
+            return new AttributeValue(Boolean.parseBoolean(valueString));
+        else if (valueType == AttributeValue.ValueType.STRING)
+            return new AttributeValue(valueString);
+        return null;
+    }
+
+    private static String[] splitIntoArrays(String value) {
+        Vector<String> values = new Vector<String>();
+        String valueString = new String(value);
+        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) {
+            Integer[] result = new Integer[valuesString.length];
+            for (int index = 0; index < valuesString.length; index++) {
+                Integer value = (Integer) handleDepth0(valuesString[index],
+                        valueType).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++) {
+                Double value = (Double) handleDepth0(valuesString[index],
+                        valueType).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++) {
+                Boolean value = (Boolean) handleDepth0(valuesString[index],
+                        valueType).get();
+                if (null == value)
+                    return null;
+                result[index] = value;
+            }
+            return new AttributeValue(result);
+        } else if (valueType == AttributeValue.ValueType.STRING) {
+            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++) {
+                Integer[] value = (Integer[]) handleDepth1(valuesString[index],
+                        valueType).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++) {
+                Double[] value = (Double[]) handleDepth1(valuesString[index],
+                        valueType).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++) {
+                Boolean[] value = (Boolean[]) handleDepth1(valuesString[index],
+                        valueType).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++) {
+                String[] value = (String[]) handleDepth1(valuesString[index],
+                        valueType).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++) {
+                Integer[][] value = (Integer[][]) handleDepth2(
+                        valuesString[index], valueType).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++) {
+                Double[][] value = (Double[][]) handleDepth2(
+                        valuesString[index], valueType).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++) {
+                Boolean[][] value = (Boolean[][]) handleDepth2(
+                        valuesString[index], valueType).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++) {
+                String[][] value = (String[][]) handleDepth2(
+                        valuesString[index], valueType).get();
+                if (null == value)
+                    return null;
+                result[index] = value;
+            }
+            return new AttributeValue(result);
+        }
+
+        return null;
+    }
+}
index 3fe81ac214eb4ff39951a4780b220ed3f66f943c..eba2905e0e6b690ebe4e38d9a349ff8c784fb33f 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";
 }
index 8baed7cd07efc0df3e961301ec87765f74a961f4..254f1f876c44070446e1f47fc032fb23a44a5b09 100644 (file)
 package oic.simulator.clientcontroller.utils;
 
 import java.util.ArrayList;
+import java.util.HashSet;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Set;
 
+import org.oic.simulator.SimulatorException;
+
 /**
  * This class has common utility methods.
  */
@@ -55,25 +58,39 @@ 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;
+    }
 }
\ No newline at end of file
index 255d9f1f32d9a0c52b25ef9a06acb8fd5df3e5ea..e61d4845e22053c2c5d8a3dea5fbd2ac2c994a29 100644 (file)
@@ -57,6 +57,7 @@ import org.eclipse.swt.widgets.Group;
 import org.eclipse.swt.widgets.Table;
 import org.eclipse.ui.PlatformUI;
 import org.eclipse.ui.part.ViewPart;
+import org.oic.simulator.client.SimulatorRemoteResource.VerificationType;
 
 /**
  * This class manages and shows the attribute view in the perspective.
@@ -100,8 +101,6 @@ public class AttributeView extends ViewPart {
 
                     @Override
                     public void run() {
-                        System.out
-                                .println("AttributeView: onResourceSelectionChange");
                         resourceInSelection = resource;
 
                         // Set visibility of manual and automation controls
@@ -110,14 +109,11 @@ public class AttributeView extends ViewPart {
                         // Update the attribute table
                         if (null != attTblViewer
                                 && !attTblViewer.getControl().isDisposed()) {
-                            System.out.println("viewer is alive");
                             updateViewer(getData(resource));
                         }
 
                         // Update the observe status
                         updateObserve(resource);
-
-                        // Update the pay-load details if any
                     }
                 });
             }
@@ -131,30 +127,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));
 
                         // Update the observe status
                         updateObserve(resource);
-
-                        // Update the pay-load details if any
                     }
                 });
             }
-
-            @Override
-            public void onGetFailed(RemoteResource resource) {
-            }
         };
 
         putUIListener = new IPutUIListener() {
@@ -165,30 +151,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));
 
                         // Update the observe status
                         updateObserve(resource);
-
-                        // Update the pay-load details if any
                     }
                 });
             }
-
-            @Override
-            public void onPutFailed(RemoteResource resource) {
-            }
         };
 
         postUIListener = new IPostUIListener() {
@@ -199,30 +175,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));
 
                         // Update the observe status
                         updateObserve(resource);
-
-                        // Update the pay-load details if any
                     }
                 });
             }
-
-            @Override
-            public void onPostFailed(RemoteResource resource) {
-            }
         };
 
         observeUIListener = new IObserveUIListener() {
@@ -233,30 +199,20 @@ 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));
 
                         // Update the observe status
                         updateObserve(resource);
-
-                        // Update the pay-load details if any
                     }
                 });
             }
-
-            @Override
-            public void onObserveFailed(RemoteResource resource) {
-            }
         };
 
         verificationUIListener = new IVerificationUIListener() {
@@ -268,7 +224,7 @@ public class AttributeView extends ViewPart {
 
                     @Override
                     public void run() {
-                        changeReqBtnVisibility(autoType, false);
+                        // changeReqBtnVisibility(autoType, false);
                     }
                 });
             }
@@ -280,7 +236,7 @@ public class AttributeView extends ViewPart {
 
                     @Override
                     public void run() {
-                        changeReqBtnVisibility(autoType, true);
+                        // changeReqBtnVisibility(autoType, true);
                     }
                 });
             }
@@ -292,7 +248,7 @@ public class AttributeView extends ViewPart {
 
                     @Override
                     public void run() {
-                        changeReqBtnVisibility(autoType, true);
+                        // changeReqBtnVisibility(autoType, true);
                     }
                 });
             }
@@ -306,15 +262,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()) {
@@ -348,7 +299,6 @@ public class AttributeView extends ViewPart {
         }
         Map<String, RemoteResourceAttribute> attMap = resource
                 .getResourceAttributesMap();
-        System.out.println("AttributeView: \n" + attMap);
         return attMap;
     }
 
@@ -370,12 +320,14 @@ public class AttributeView extends ViewPart {
     }
 
     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 +335,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 +354,7 @@ public class AttributeView extends ViewPart {
 
         setupAttributeTable(attGroup);
 
-        setupMessageArea(parent);
-
-        setupResourceLevelOpsArea(parent);
+        setupRequestControls(parent);
 
         setUIListeners();
 
@@ -419,20 +369,19 @@ public class AttributeView extends ViewPart {
         }
     }
 
-    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 +389,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,41 +397,27 @@ 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) {
@@ -631,12 +566,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,15 +609,123 @@ 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) != 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) != 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) != 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) {
+                                MessageDialog.openInformation(Display
+                                        .getDefault().getActiveShell(),
+                                        "Verification", "No New Changes.");
+                            } else {
+                                boolean answer = MessageDialog.openQuestion(
+                                        Display.getDefault().getActiveShell(),
+                                        "Verification", status
+                                                + "\nDo you want to proceed?");
+                                if (answer) {
+                                    if (startGet || stopGet)
+                                        automate(VerificationType.GET,
+                                                autoStatus.get(Constants.GET));
+                                    if (startPut || stopPut)
+                                        automate(VerificationType.PUT,
+                                                autoStatus.get(Constants.PUT));
+                                    if (startPost || stopPost)
+                                        automate(VerificationType.POST,
+                                                autoStatus.get(Constants.POST));
+                                }
+                            }
+                        }
                     }
                 });
             }
         });
     }
 
+    private void automate(VerificationType type, boolean start) {
+        if (start) {
+            resourceManager.startAutomationRequest(type, resourceInSelection);
+        } else {
+            resourceManager.stopAutomationRequest(type, resourceInSelection);
+        }
+    }
+
     private void addManagerListeners() {
         resourceManager
                 .addResourceSelectionChangedUIListener(resourceSelectionChangedListener);
index 3c4d76eb4d0e1580b2d78b0d5a6a91c2e17af9ff..a2a7d2e53197a734ca37033d2e1c941da4afa346 100644 (file)
@@ -21,6 +21,7 @@ import java.io.FileWriter;
 import java.io.IOException;
 import java.text.DateFormat;
 import java.text.SimpleDateFormat;
+import java.util.Date;
 import java.util.HashMap;
 import java.util.List;
 
@@ -444,7 +445,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 ae9fa40e4c7cc3598e9583a9e9ab33aeb1319ae9..acf893351a0f92b6d2c7224034ab055d4c6ed698 100644 (file)
@@ -19,6 +19,7 @@ package oic.simulator.clientcontroller.view;
 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.remoteresource.MetaProperty;
@@ -30,10 +31,14 @@ 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;
 
@@ -44,7 +49,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 +59,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 +80,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 != deviceTblViewer) {
+                            updateViewer(deviceTblViewer, getDevicePropData());
+                        }
+                    }
+                });
+
+            }
+
+            @Override
+            public void onDeviceInfoFound() {
+                Display.getDefault().asyncExec(new Runnable() {
+
+                    @Override
+                    public void run() {
+                        if (null != platformTblViewer) {
+                            updateViewer(platformTblViewer,
+                                    getPlatformPropData());
                         }
                     }
                 });
@@ -76,48 +118,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();
+
+        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);
 
-        tableViewer = new TableViewer(parent, SWT.SINGLE | SWT.H_SCROLL
+        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 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> getData(RemoteResource resource) {
+    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 void updateViewer(List<MetaProperty> metaPropertyList) {
-        if (null != tableViewer) {
-            Table tbl = tableViewer.getTable();
+    private List<MetaProperty> getDevicePropData() {
+        List<MetaProperty> metaPropertyList = resourceManager
+                .getDeviceProperties();
+        return metaPropertyList;
+    }
+
+    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);
                 }
@@ -167,6 +325,8 @@ public class MetaPropertiesView extends ViewPart {
     private void addManagerListeners() {
         resourceManager
                 .addResourceSelectionChangedUIListener(resourceSelectionChangedListener);
+        resourceManager
+                .addDevicePlatformInfoUIListener(devicePlatformInfoUIListener);
     }
 
     class PropertycontentProvider implements IStructuredContentProvider {
@@ -183,7 +343,6 @@ public class MetaPropertiesView extends ViewPart {
         public Object[] getElements(Object element) {
             return (Object[]) element;
         }
-
     }
 
     @Override
index 2082a42f74b2a95cae6ee81a56bfc14de0c1dfe6..b059a4d347892b2c1a8dedda42830b545ff1d1aa 100644 (file)
@@ -60,6 +60,7 @@ import org.eclipse.ui.PlatformUI;
 import org.eclipse.ui.dialogs.FilteredTree;
 import org.eclipse.ui.dialogs.PatternFilter;
 import org.eclipse.ui.part.ViewPart;
+import org.oic.simulator.SimulatorException;
 
 /**
  * This class manages and shows the resource manager view in the perspective.
@@ -97,7 +98,6 @@ public class ResourceManagerView extends ViewPart {
 
             @Override
             public void onNewResourceFound(final RemoteResource resource) {
-                System.out.println("View: onNewResourceFound");
                 if (null == resource) {
                     return;
                 }
@@ -123,16 +123,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 +178,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 +267,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 +282,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 +349,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 +377,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 +464,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 +506,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 +549,6 @@ public class ResourceManagerView extends ViewPart {
                     if (null == resource) {
                         return;
                     }
-                    System.out.println("Selected resource: "
-                            + resource.getResourceURI());
                     resourceManager.resourceSelectionChanged(resource);
                 }
             }
@@ -608,7 +601,6 @@ public class ResourceManagerView extends ViewPart {
                         try {
                             Thread.sleep(Constants.FIND_RESOURCES_TIMEOUT * 1000);
                         } catch (InterruptedException e) {
-                            System.out.println("Interrupted during sleep.");
                             return;
                         }
 
@@ -695,7 +687,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 +722,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 +743,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 6316674c5195aeb3853593e85a17d267bb832cb7..eeda973294d144fd2e0c9c5c60cecdff86056784 100644 (file)
 
 package oic.simulator.clientcontroller.view.dialogs;
 
-import java.util.HashSet;
 import java.util.Set;
 
 import oic.simulator.clientcontroller.utils.Constants;
+import oic.simulator.clientcontroller.utils.Utility;
 
 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;
@@ -41,24 +40,19 @@ import org.eclipse.swt.widgets.Text;
  */
 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 d19e1d446b058a1cf5415b7f82e28e8be07d2c45..90ace2b1aeccc743bd3687859b18cbbd5c00054e 100644 (file)
 
 package oic.simulator.clientcontroller.view.dialogs;
 
+import java.io.FileInputStream;
+
 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;
@@ -100,10 +103,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);
             }
@@ -114,6 +118,25 @@ public class LoadRAMLDialog extends TitleAreaDialog {
         return configFilePath;
     }
 
+    @Override
+    protected void okPressed() {
+        configFilePath = locationTxt.getText();
+        if (null == configFilePath) {
+            return;
+        }
+        try {
+            new FileInputStream(configFilePath);
+        } catch (Exception e) {
+            MessageDialog
+                    .openError(getShell(), "Invalid File",
+                            "File doesn't exist. Either the file path or file name is invalid.");
+            // TODO: Instead of MessageDialog, errors may be shown on wizard
+            // itself.
+            return;
+        }
+        close();
+    }
+
     @Override
     public boolean isHelpAvailable() {
         return false;
index 26c11b422dcdf306eb660e35ee447fbe717dfa3b..2e9bc3c1eb246d7c9a78f5a488ae38a6179860d4 100644 (file)
 
 package oic.simulator.clientcontroller.view.dialogs;
 
+import java.util.Iterator;
 import java.util.List;
 
 import oic.simulator.clientcontroller.Activator;
+import oic.simulator.clientcontroller.manager.ResourceManager;
 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.ComboBoxCellEditor;
 import org.eclipse.jface.viewers.EditingSupport;
 import org.eclipse.jface.viewers.IStructuredContentProvider;
 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.Viewer;
 import org.eclipse.jface.viewers.ViewerCell;
 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.graphics.Image;
@@ -45,9 +49,9 @@ 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.Shell;
 import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.Text;
 
 /**
  * This dialog is used for generating a POST request.
@@ -61,7 +65,7 @@ public class PostRequestDialog extends TitleAreaDialog {
     private final Integer[]             attTblColWidth = { 200, 200, 50 };
 
     private List<PutPostAttributeModel> modelList      = null;
-    
+
     public PostRequestDialog(Shell parentShell,
             List<PutPostAttributeModel> modelList) {
         super(parentShell);
@@ -139,6 +143,7 @@ public class PostRequestDialog extends TitleAreaDialog {
                 }
             }
         });
+
         attValue.setEditingSupport(new AttributeValueEditor(attTblViewer));
 
         TableViewerColumn updateColumn = new TableViewerColumn(tableViewer,
@@ -203,62 +208,97 @@ public class PostRequestDialog extends TitleAreaDialog {
 
     class AttributeValueEditor extends EditingSupport {
         private final TableViewer viewer;
-        private final CellEditor  editor;
-        private final Text txt;
+        private CCombo            comboBox;
+
         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
+        protected boolean canEdit(Object arg0) {
+            return true;
+        }
+
+        @Override
+        protected CellEditor getCellEditor(Object element) {
+            PutPostAttributeModel attributeInSelection = (PutPostAttributeModel) element;
+
+            String values[] = null;
+            List<String> valueSet = attributeInSelection.getValues();
+            values = convertListToStringArray(valueSet);
+
+            ComboBoxCellEditor comboEditor = new ComboBoxCellEditor(
+                    viewer.getTable(), values);
+            comboBox = (CCombo) comboEditor.getControl();
+            if (null != comboBox) {
+                comboBox.addModifyListener(new ModifyListener() {
                     @Override
-                    public void modifyText(ModifyEvent e) {                 
-                        IStructuredSelection selection = (IStructuredSelection)AttributeValueEditor.this.viewer.getSelection();
-                        PutPostAttributeModel att = (PutPostAttributeModel)selection.getFirstElement();             
-                        if(null == att) {
+                    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()) {
+                        String newValue = comboBox.getText();
+                        if (null != newValue && !newValue.isEmpty()) {
                             att.setModified(true);
-                        }
-                        else {
+                        } else {
                             att.setModified(false);
                         }
                         AttributeValueEditor.this.viewer.update(att, null);
                     }
                 });
-              
             }
-        }
-
-        @Override
-        protected boolean canEdit(Object arg0) {
-            return true;
-        }
-
-        @Override
-        protected CellEditor getCellEditor(Object element) {
-            return editor;
+            return comboEditor;
         }
 
         @Override
         protected Object getValue(Object element) {
-            PutPostAttributeModel model = (PutPostAttributeModel) element;
-            return model.getAttValue();
+            int indexOfItem = 0;
+            PutPostAttributeModel att = (PutPostAttributeModel) element;
+            String valueString = att.getAttValue();
+            List<String> valueSet = att.getValues();
+            if (null != valueSet) {
+                indexOfItem = valueSet.indexOf(valueString);
+            }
+            if (indexOfItem == -1) {
+                indexOfItem = 0;
+            }
+            return indexOfItem;
         }
 
         @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);
+            PutPostAttributeModel att = (PutPostAttributeModel) element;
+            int index;
+            try {
+                index = Integer.parseInt(String.valueOf(value));
+            } catch (NumberFormatException nfe) {
+                index = -1;
+            }
+            String newValue;
+            if (index == -1) {
+                newValue = comboBox.getText();
+                att.prependNewValue(newValue);
+            } else {
+                newValue = att.getValues().get(index);
+            }
+            att.setAttValue(newValue);
             viewer.update(element, 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];
+            }
+            return strArr;
+        }
     }
 
     class UpdateEditor extends EditingSupport {
@@ -289,9 +329,30 @@ public class PostRequestDialog extends TitleAreaDialog {
         @Override
         protected void setValue(Object element, Object value) {
             PutPostAttributeModel model = (PutPostAttributeModel) element;
-            boolean status = (boolean) value;
+            boolean status = (Boolean) value;
             model.setModified(status);
             viewer.update(element, null);
         }
     }
+
+    @Override
+    protected void okPressed() {
+        String value;
+        PutPostAttributeModel attModel;
+        Iterator<PutPostAttributeModel> itr;
+        itr = modelList.iterator();
+        while (itr.hasNext()) {
+            attModel = itr.next();
+            if (null == attModel) {
+                return;
+            }
+            value = attModel.getAttValue();
+            if (null == value || value.isEmpty()) {
+                MessageDialog.openError(Display.getDefault().getActiveShell(),
+                        "Empty value", "Attribute value should not be empty.");
+                return;
+            }
+        }
+        close();
+    }
 }
index 3ba0c87349e49bc5b79b3190fecd745acc7c7d06..69dbeeb7fe42c1da2d13da5e2967891bdcd496a8 100644 (file)
 
 package oic.simulator.clientcontroller.view.dialogs;
 
+import java.util.Iterator;
 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.ComboBoxCellEditor;
 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.CCombo;
 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.Shell;
 import org.eclipse.swt.widgets.Table;
 
@@ -148,12 +152,11 @@ public class PutRequestDialog extends TitleAreaDialog {
 
     class AttributeValueEditor extends EditingSupport {
         private final TableViewer viewer;
-        private final CellEditor  editor;
+        private CCombo            comboBox;
 
         public AttributeValueEditor(TableViewer viewer) {
             super(viewer);
             this.viewer = viewer;
-            editor = new TextCellEditor(viewer.getTable());
         }
 
         @Override
@@ -163,21 +166,62 @@ public class PutRequestDialog extends TitleAreaDialog {
 
         @Override
         protected CellEditor getCellEditor(Object element) {
-            return editor;
+            PutPostAttributeModel attributeInSelection = (PutPostAttributeModel) element;
+
+            String values[] = null;
+            List<String> valueSet = attributeInSelection.getValues();
+            values = convertListToStringArray(valueSet);
+
+            ComboBoxCellEditor comboEditor = new ComboBoxCellEditor(
+                    viewer.getTable(), values);
+            comboBox = (CCombo) comboEditor.getControl();
+            return comboEditor;
         }
 
         @Override
         protected Object getValue(Object element) {
-            PutPostAttributeModel model = (PutPostAttributeModel) element;
-            return model.getAttValue();
+            int indexOfItem = 0;
+            PutPostAttributeModel att = (PutPostAttributeModel) element;
+            String valueString = att.getAttValue();
+            List<String> valueSet = att.getValues();
+            if (null != valueSet) {
+                indexOfItem = valueSet.indexOf(valueString);
+            }
+            if (indexOfItem == -1) {
+                indexOfItem = 0;
+            }
+            return indexOfItem;
         }
 
         @Override
         protected void setValue(Object element, Object value) {
-            PutPostAttributeModel model = (PutPostAttributeModel) element;
-            model.setAttValue(String.valueOf(value));
+            PutPostAttributeModel att = (PutPostAttributeModel) element;
+            int index;
+            try {
+                index = Integer.parseInt(String.valueOf(value));
+            } catch (NumberFormatException nfe) {
+                index = -1;
+            }
+            if (index == -1) {
+                String customValue = comboBox.getText();
+                att.prependNewValue(customValue);
+                att.setAttValue(customValue);
+            } else {
+                String attValue = att.getValues().get(index);
+                att.setAttValue(attValue);
+            }
             viewer.update(element, 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];
+            }
+            return strArr;
+        }
     }
 
     public List<PutPostAttributeModel> getUpdatedModel() {
@@ -202,4 +246,25 @@ public class PutRequestDialog extends TitleAreaDialog {
         }
         return super.createButton(parent, id, label, defaultButton);
     }
+
+    @Override
+    protected void okPressed() {
+        String value;
+        PutPostAttributeModel attModel;
+        Iterator<PutPostAttributeModel> itr;
+        itr = modelList.iterator();
+        while (itr.hasNext()) {
+            attModel = itr.next();
+            if (null == attModel) {
+                return;
+            }
+            value = attModel.getAttValue();
+            if (null == value || value.isEmpty()) {
+                MessageDialog.openError(Display.getDefault().getActiveShell(),
+                        "Empty value", "Attribute value should not be empty.");
+                return;
+            }
+        }
+        close();
+    }
 }
index a22176052c6454165db9b6956c13934eba1e5314..b6ab69ffb938fd5d414dcbbf8b2f2253509e71e4 100644 (file)
@@ -20,12 +20,9 @@ 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,7 +32,6 @@ 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;
 
@@ -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 ca80ad1f4c09133acce3820ef842b77a57ea1db7..d2abfbb8e0ed40cc5be2d45c3f1f85358b4dbcbc 100644 (file)
@@ -50,7 +50,12 @@ public class LogLabelProvider extends LabelProvider implements
         } else if (columnIndex == 1) {
             return dateFormat.format(entry.getDate());
         } else {
-            return entry.getMessage();
+            String msg = entry.getMessage();
+            int pos = msg.indexOf('\n');
+            if (pos != -1) {
+                msg = msg.substring(0, pos);
+            }
+            return msg;
         }
     }
 
index 81110b07609857bf386e6c876d88722ac1f56ac1..ac2e8ed30963c76b3c95276007cfa588673142d1 100644 (file)
@@ -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 f79c607fac73ba9dacb483f9206918504405fa5a..046db293cf4d470e461bc83544aecddd94cf7d07 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 3db113873e1f060d2d28f046cf963a5b38f6e0b7..8dc5385adec0812ac947967dedb59e4c3a2d5dd1 100644 (file)
@@ -5,5 +5,4 @@ bin.includes = META-INF/,\
                icons/,\
                plugin.xml,\
                libs/,\
-               resource/
 
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/collection_resource.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/collection_resource.gif
new file mode 100644 (file)
index 0000000..173661c
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/collection_resource.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/device.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/device.gif
new file mode 100644 (file)
index 0000000..e3ecc55
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/device.gif differ
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 52ec74b185b271f66b87c71eb317b036601c1002..8fe0d3aa594aef4127489630ca401cd86449bca9 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 f392bc805e10a5bcc0c56cbbd1edbf7d1914697b..9861d775e5af898dfc94e8307849e3a1f1ede584 100644 (file)
@@ -50,7 +50,12 @@ public class LogLabelProvider extends LabelProvider implements
         } else if (columnIndex == 1) {
             return dateFormat.format(entry.getDate());
         } else {
-            return entry.getMessage();
+            String msg = entry.getMessage();
+            int pos = msg.indexOf('\n');
+            if (pos != -1) {
+                msg = msg.substring(0, pos);
+            }
+            return msg;
         }
     }
 
index 215fb5f6f3fff7f0e8f15ad4321a1fe1797f84d9..395a7441a72380130667f84bc75b84b6248e40e8 100644 (file)
 
 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 IAutomationUIListener {
-    public void onResourceAutomationStart(String resourceURI);
+    public void onResourceAutomationStart(SingleResource resource);
 
-    public void onAutomationComplete(String resourceURI, String attName);
+    public void onAutomationComplete(SingleResource resource, String attName);
 }
index 3beb52a393af6c0a21128c3b62e8ea5eaf38eb85..a3bde637dec68b63893c0f50c7ce04e8d46283d2 100644 (file)
 
 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 IObserverListChangedUIListener {
-    public void onObserverListChanged(String resourceURI);
+    public void onObserverListChanged(Resource resource);
 }
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IPropertiesChangedUIListener.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IPropertiesChangedUIListener.java
new file mode 100644 (file)
index 0000000..864d5c0
--- /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;
+
+/**
+ * Interface through which the resource property change UI events are sent to
+ * the other UI listeners.
+ */
+public interface IPropertiesChangedUIListener {
+    public void onResourcePropertyChange();
+
+    public void onDevicePropertyChange();
+}
\ No newline at end of file
index b5eb3311c5ffbe7714c66745f5d4e1e737689553..fac61eb78041b1348fd81b1f05025e74856b814c 100644 (file)
 
 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 IResourceListChangedUIListener {
-    public void onResourceCreation();
+    public void onResourceCreation(ResourceType type);
+
+    public void onResourceDeletion(ResourceType type);
 
-    public void onResourceDeletion();
+    public void onResourceListUpdate(ResourceType type);
 }
\ No newline at end of file
index b778e0ef6e7ddd093844b5e01fa5decc7579a63f..e55539d3d7d3acb0495ccbab732d407a83ee8e0a 100644 (file)
 
 package oic.simulator.serviceprovider.listener;
 
-import java.util.Set;
-
-import oic.simulator.serviceprovider.resource.ModelChangeNotificationType;
-import oic.simulator.serviceprovider.resource.LocalResourceAttribute;
+import oic.simulator.serviceprovider.model.Resource;
 
 /**
  * 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);
+    public void onResourceModelChange(Resource resource);
 }
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/ISelectionChangedUIListener.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/ISelectionChangedUIListener.java
new file mode 100644 (file)
index 0000000..f4c9c14
--- /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 oic.simulator.serviceprovider.model.Device;
+import oic.simulator.serviceprovider.model.Resource;
+
+/**
+ * Interface through which the resource selection UI event is sent to the other
+ * UI listeners.
+ */
+public interface ISelectionChangedUIListener {
+    public void onResourceSelectionChange(Resource resource);
+
+    public void onDeviceSelectionChange(Device dev);
+}
\ 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..17517f1
--- /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 oic.simulator.serviceprovider.manager;
+
+import java.util.ArrayList;
+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 oic.simulator.serviceprovider.model.CollectionResource;
+import oic.simulator.serviceprovider.model.Device;
+import oic.simulator.serviceprovider.model.Resource;
+import oic.simulator.serviceprovider.model.SingleResource;
+
+public class Data {
+    private Map<String, SingleResource>     singleResourceMap;
+
+    private Map<String, CollectionResource> collectionResourceMap;
+
+    private Map<String, Device>             deviceMap;
+
+    // Holds resource type as key and a resource URI set as values.
+    // Helps in performing operations based on resource type.
+    private Map<String, Set<String>>        resTypeToResUriMap;
+
+    public Data() {
+        singleResourceMap = new HashMap<String, SingleResource>();
+        collectionResourceMap = new HashMap<String, CollectionResource>();
+        deviceMap = new HashMap<String, Device>();
+        resTypeToResUriMap = new HashMap<String, Set<String>>();
+    }
+
+    public synchronized void addResource(Resource resource) {
+        if (null == resource) {
+            return;
+        }
+        if (resource instanceof SingleResource) {
+            singleResourceMap.put(resource.getResourceURI(),
+                    (SingleResource) resource);
+        } else {
+            collectionResourceMap.put(resource.getResourceURI(),
+                    (CollectionResource) resource);
+        }
+        addToTypeAndUriMap(resource);
+    }
+
+    public synchronized void addToTypeAndUriMap(Resource resource) {
+        if (null == resource) {
+            return;
+        }
+        Set<String> resTypes = resource.getResourceTypes();
+        if (null == resTypes || resTypes.isEmpty()) {
+            return;
+        }
+        String uri = resource.getResourceURI();
+        if (null == uri || uri.isEmpty()) {
+            return;
+        }
+        Iterator<String> itr = resTypes.iterator();
+        String rType;
+        Set<String> newTypeSet;
+        while (itr.hasNext()) {
+            rType = itr.next();
+            newTypeSet = resTypeToResUriMap.get(rType);
+            if (null == newTypeSet) {
+                newTypeSet = new HashSet<String>();
+                resTypeToResUriMap.put(rType, newTypeSet);
+            }
+            newTypeSet.add(uri);
+        }
+    }
+
+    public void addDevice(Device dev) {
+        if (null == dev) {
+            return;
+        }
+        synchronized (deviceMap) {
+            deviceMap.put(dev.getDeviceName(), dev);
+        }
+    }
+
+    public synchronized void deleteResource(Resource resource) {
+        if (null == resource) {
+            return;
+        }
+        if (resource instanceof SingleResource) {
+            singleResourceMap.remove(resource.getResourceURI());
+        } else {
+            collectionResourceMap.remove(resource.getResourceURI());
+        }
+        removeFromTypeAndUriMap(resource);
+    }
+
+    public synchronized void deleteDevice(Device dev) {
+        if (null == dev) {
+            return;
+        }
+        deviceMap.remove(dev.getDeviceName());
+    }
+
+    public synchronized void removeFromTypeAndUriMap(Resource resource) {
+        if (null == resource) {
+            return;
+        }
+        Set<String> resTypes = resource.getResourceTypes();
+        if (null == resTypes || resTypes.isEmpty()) {
+            return;
+        }
+        String uri = resource.getResourceURI();
+        if (null == uri || uri.isEmpty()) {
+            return;
+        }
+        Iterator<String> itr = resTypes.iterator();
+        String rType;
+        Set<String> newTypeSet;
+        while (itr.hasNext()) {
+            rType = itr.next();
+            newTypeSet = resTypeToResUriMap.get(rType);
+            if (null != newTypeSet) {
+                newTypeSet.remove(uri);
+            }
+            if (null == newTypeSet || newTypeSet.isEmpty()) {
+                resTypeToResUriMap.remove(rType);
+            }
+        }
+    }
+
+    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<CollectionResource> getCollectionResources() {
+        List<CollectionResource> resources;
+        synchronized (collectionResourceMap) {
+            if (collectionResourceMap.isEmpty()) {
+                return null;
+            }
+            resources = new ArrayList<CollectionResource>();
+            Set<String> uriSet = collectionResourceMap.keySet();
+            Iterator<String> itr = uriSet.iterator();
+            while (itr.hasNext()) {
+                resources.add(collectionResourceMap.get(itr.next()));
+            }
+        }
+        return resources;
+    }
+
+    public List<Resource> getResources() {
+        if (singleResourceMap.isEmpty() && collectionResourceMap.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()));
+            }
+        }
+        synchronized (collectionResourceMap) {
+            Set<String> uriSet = collectionResourceMap.keySet();
+            Iterator<String> itr = uriSet.iterator();
+            while (itr.hasNext()) {
+                resourceList.add(collectionResourceMap.get(itr.next()));
+            }
+        }
+        return resourceList;
+    }
+
+    public List<Device> getDevices() {
+        List<Device> devices;
+        synchronized (deviceMap) {
+            if (deviceMap.isEmpty()) {
+                return null;
+            }
+            devices = new ArrayList<Device>();
+            Set<String> uriSet = deviceMap.keySet();
+            Iterator<String> itr = uriSet.iterator();
+            while (itr.hasNext()) {
+                devices.add(deviceMap.get(itr.next()));
+            }
+        }
+        return devices;
+    }
+
+    public synchronized boolean isResourceExist(String resourceURI) {
+        if (null == resourceURI || resourceURI.isEmpty()) {
+            return false;
+        }
+        if ((null != singleResourceMap && singleResourceMap
+                .containsKey(resourceURI))
+                || (null != collectionResourceMap && collectionResourceMap
+                        .containsKey(resourceURI))) {
+            return true;
+        }
+        return false;
+    }
+
+    public synchronized boolean isAnyResourceExist() {
+        return ((null != singleResourceMap && !singleResourceMap.isEmpty()) || (null != collectionResourceMap && !collectionResourceMap
+                .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);
+            }
+        } else {
+            synchronized (collectionResourceMap) {
+                collectionResourceMap.remove(curURI);
+                collectionResourceMap
+                        .put(newURI, (CollectionResource) resource);
+            }
+        }
+        resource.setResourceURI(newURI);
+    }
+
+    public void changeDeviceName(Device dev, String curName, String newName) {
+        if (null == dev || null == curName || null == newName) {
+            return;
+        }
+        synchronized (deviceMap) {
+            deviceMap.remove(curName);
+            deviceMap.put(newName, dev);
+        }
+        dev.setDeviceName(newName);
+    }
+
+    public SingleResource getSingleResourceByURI(String resourceURI) {
+        if (null == resourceURI) {
+            return null;
+        }
+        SingleResource res;
+        synchronized (singleResourceMap) {
+            res = singleResourceMap.get(resourceURI);
+        }
+        return res;
+    }
+
+    public CollectionResource getCollectionResourceByURI(String resourceURI) {
+        if (null == resourceURI) {
+            return null;
+        }
+        CollectionResource res;
+        synchronized (collectionResourceMap) {
+            res = collectionResourceMap.get(resourceURI);
+        }
+        return res;
+    }
+
+    public Resource getResourceByURI(String resourceURI) {
+        Resource res = getSingleResourceByURI(resourceURI);
+        if (null == res) {
+            res = getCollectionResourceByURI(resourceURI);
+        }
+        return res;
+    }
+
+}
index ee700d103b95a16617db3f2b667062c382059fbc..9e5842492d0cacd87c1dcf60c0b33a50b2237b77 100644 (file)
@@ -56,8 +56,13 @@ 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")));
+        r.put(Constants.COLLECTION_RESOURCE, ImageDescriptor
+                .createFromURL(bundle
+                        .getEntry("/icons/collection_resource.gif")));
+        r.put(Constants.DEVICE, ImageDescriptor.createFromURL(bundle
+                .getEntry("/icons/device.gif")));
 
         // Log View related icons
         r.put(Constants.DEBUG_LOG, ImageDescriptor.createFromURL(bundle
index e7ca9a9580531d10726614d118fd6c466a1bbff8..765d87c18aba5cb788e2f31182974a9e1fb8a7f2 100644 (file)
@@ -26,11 +26,13 @@ import oic.simulator.logger.LoggerCallback;
 import oic.simulator.serviceprovider.Activator;
 import oic.simulator.serviceprovider.listener.ILogUIListener;
 import oic.simulator.serviceprovider.utils.Constants;
+import oic.simulator.serviceprovider.utils.Utility;
 
 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.SimulatorException;
 import org.oic.simulator.SimulatorManager;
 
 /**
@@ -55,7 +57,14 @@ public class LogManager {
 
         // Set the logger callback with the native layer
         logger = new LoggerCallback();
-        SimulatorManager.setLogger(logger);
+        try {
+            SimulatorManager.setLogger(logger);
+        } catch (SimulatorException e) {
+            log(Level.ERROR.ordinal(),
+                    new Date(),
+                    "Failed to register the logger.\n"
+                            + Utility.getSimulatorErrorString(e, null));
+        }
     }
 
     private static class LogManagerSynchronizerThread implements Runnable {
index e6cca32bcd90969058018bae981d08f01df8a8ba..3e80941878f40ed3b27b278859a0d09c8c188587 100644 (file)
@@ -20,41 +20,44 @@ 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 java.util.Vector;
 
 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.model.CollectionResource;
+import oic.simulator.serviceprovider.model.Device;
+import oic.simulator.serviceprovider.model.LocalResourceAttribute;
+import oic.simulator.serviceprovider.model.MetaProperty;
+import oic.simulator.serviceprovider.model.Resource;
+import oic.simulator.serviceprovider.model.ResourceType;
+import oic.simulator.serviceprovider.model.SRMItem;
+import oic.simulator.serviceprovider.model.SingleResource;
 import oic.simulator.serviceprovider.utils.Constants;
 import oic.simulator.serviceprovider.utils.Utility;
 
-import org.eclipse.swt.graphics.Image;
-import org.oic.simulator.IAutomation;
+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.ILogger.Level;
-import org.oic.simulator.ResourceAttribute;
-import org.oic.simulator.ResourceAttribute.Range;
-import org.oic.simulator.ResourceAttribute.Type;
+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.server.Observer;
+import org.oic.simulator.server.SimulatorCollectionResource;
+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;
 
 /**
  * This class acts as an interface between the simulator java SDK and the
@@ -65,49 +68,67 @@ import org.oic.simulator.serviceprovider.SimulatorResourceServer;
  */
 public class ResourceManager {
 
-    private Map<String, Map<String, SimulatorResource>> resourceMap;
+    private Data                           data;
 
-    private Map<String, ArrayList<String>>              orderedResourceUriMap;
+    private Resource                       currentResourceInSelection;
 
-    private Map<String, String>                         displayNameMap;
+    private Device                         currentDeviceInSelection;
 
-    private StandardConfiguration                       stdConfig;
+    private ResourceModelChangeListener    resourceModelChangeListener;
 
-    private SimulatorResource                           currentResourceInSelection;
+    private AutoUpdateListener             automationListener;
 
-    private List<IResourceListChangedUIListener>        resourceListChangedUIListeners;
+    private ObserverListener               observer;
 
-    private List<IResourceSelectionChangedUIListener>   resourceSelectionChangedUIListeners;
+    private NotificationSynchronizerThread synchronizerThread;
 
-    private List<IResourceModelChangedUIListener>       resourceModelChangedUIListeners;
+    private Thread                         threadHandle;
 
-    private List<IAutomationUIListener>                 automationUIListeners;
-
-    private List<IObserverListChangedUIListener>        observerUIListeners;
-
-    private IResourceModelChangedListener               resourceModelChangeListener;
-
-    private IAutomation                                 automationListener;
-
-    private IObserver                                   observer;
-
-    private NotificationSynchronizerThread              synchronizerThread;
-
-    private Thread                                      threadHandle;
+    private String                         deviceName;
+    private PlatformInfo                   platformInfo;
 
     public ResourceManager() {
-        resourceMap = new HashMap<String, Map<String, SimulatorResource>>();
-        orderedResourceUriMap = new HashMap<String, ArrayList<String>>();
-        displayNameMap = new HashMap<String, String>();
-        stdConfig = new StandardConfiguration();
+        data = new Data();
 
-        resourceListChangedUIListeners = new ArrayList<IResourceListChangedUIListener>();
-        resourceSelectionChangedUIListeners = new ArrayList<IResourceSelectionChangedUIListener>();
-        resourceModelChangedUIListeners = new ArrayList<IResourceModelChangedUIListener>();
-        automationUIListeners = new ArrayList<IAutomationUIListener>();
-        observerUIListeners = new ArrayList<IObserverListChangedUIListener>();
+        // Set the default device and platform information
+        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));
+        }
+
+        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));
+        }
 
-        resourceModelChangeListener = new IResourceModelChangedListener() {
+        resourceModelChangeListener = new ResourceModelChangeListener() {
 
             @Override
             public void onResourceModelChanged(final String resourceURI,
@@ -119,59 +140,44 @@ public class ResourceManager {
                         if (null == resourceURI || null == resourceModelN) {
                             return;
                         }
-                        SimulatorResource resource = getSimulatorResourceByURI(resourceURI);
+
+                        Resource resource = data.getResourceByURI(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;
-                        }
+                        resource.setResourceModel(resourceModelN);
 
-                        // 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);
+                        // 7. Fetch the resource attributes.
+                        Map<String, LocalResourceAttribute> resourceAttributeMap;
+                        try {
+                            resourceAttributeMap = fetchResourceAttributesFromModel(resourceModelN);
+                            if (null != resourceAttributeMap) {
+                                resource.setResourceAttributes(resourceAttributeMap);
+                            }
+                        } catch (SimulatorException e) {
+                            // TODO Auto-generated catch block
+                            e.printStackTrace();
                         }
+
+                        UiListenerHandler.getInstance()
+                                .resourceModelChangedUINotification(resource);
                     }
                 });
             }
         };
 
-        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,7 +186,9 @@ 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;
@@ -190,30 +198,37 @@ public class ResourceManager {
                                 attribute.setAutomationInProgress(false);
                                 resource.setAttributeAutomationInProgress(isAnyAttributeInAutomation(resource));
                                 // Notify the UI listeners
-                                automationCompleteUINotification(resourceURI,
-                                        attribute.getAttributeName());
+                                UiListenerHandler
+                                        .getInstance()
+                                        .automationCompleteUINotification(
+                                                resource,
+                                                attribute
+                                                        .getResourceAttributeRef()
+                                                        .name());
+                            } else {
+                                // TODO: Temporarily reset the attribute
+                                // automation status to false for making
+                                // resource-level automation work after
+                                // attribute-level automations.
+                                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,10 +239,21 @@ 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();
@@ -277,900 +303,1319 @@ public class ResourceManager {
         }
     }
 
-    // This method gives a list of available RAML resource configurations.
-    public Map<String, String> getResourceConfigurationList() {
-        return stdConfig.getStandardResourceConfigurationList();
+    public String getDeviceName() {
+        return deviceName;
     }
 
-    public String getConfigFilePath(String fileName) {
-        return stdConfig.getFilePath(fileName);
+    public void setDeviceName(String deviceName) {
+        this.deviceName = deviceName;
+        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 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;
+        }
+        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);
+            }
+        }
+        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 addResourceListChangedUIListener(
-            IResourceListChangedUIListener resourceListChangedUIListener) {
-        synchronized (resourceListChangedUIListeners) {
-            resourceListChangedUIListeners.add(resourceListChangedUIListener);
-        }
+    public synchronized Resource getCurrentResourceInSelection() {
+        return currentResourceInSelection;
     }
 
-    public void addResourceSelectionChangedUIListener(
-            IResourceSelectionChangedUIListener resourceSelectionChangedUIListener) {
-        synchronized (resourceSelectionChangedUIListeners) {
-            resourceSelectionChangedUIListeners
-                    .add(resourceSelectionChangedUIListener);
-        }
+    public synchronized void setCurrentResourceInSelection(Resource resource) {
+        this.currentResourceInSelection = resource;
     }
 
-    public void addResourceModelChangedUIListener(
-            IResourceModelChangedUIListener resourceModelChangedUIListener) {
-        synchronized (resourceModelChangedUIListeners) {
-            resourceModelChangedUIListeners.add(resourceModelChangedUIListener);
-        }
+    public synchronized Device getCurrentDeviceInSelection() {
+        return currentDeviceInSelection;
     }
 
-    public void addAutomationUIListener(
-            IAutomationUIListener automationUIListener) {
-        synchronized (automationUIListeners) {
-            automationUIListeners.add(automationUIListener);
-        }
+    public synchronized void setCurrentDeviceInSelection(Device dev) {
+        this.currentDeviceInSelection = dev;
     }
 
-    public void addObserverListChangedUIListener(
-            IObserverListChangedUIListener observerListChangedUIListener) {
-        synchronized (observerUIListeners) {
-            observerUIListeners.add(observerListChangedUIListener);
-        }
+    public boolean isResourceExist(String resourceURI) {
+        return data.isResourceExist(resourceURI);
     }
 
-    public void removeResourceListChangedUIListener(
-            IResourceListChangedUIListener listener) {
-        synchronized (resourceListChangedUIListeners) {
-            if (null != listener && resourceListChangedUIListeners.size() > 0) {
-                resourceListChangedUIListeners.remove(listener);
-            }
-        }
+    public boolean isAnyResourceExist() {
+        return data.isAnyResourceExist();
     }
 
-    public void removeResourceSelectionChangedUIListener(
-            IResourceSelectionChangedUIListener listener) {
-        synchronized (resourceSelectionChangedUIListeners) {
-            if (null != listener
-                    && resourceSelectionChangedUIListeners.size() > 0) {
-                resourceSelectionChangedUIListeners.remove(listener);
-            }
+    public boolean createSingleResource(SingleResource resource)
+            throws SimulatorException {
+        if (null == resource) {
+            return false;
         }
-    }
+        String resType = (String) resource.getResourceTypes().toArray()[0];
+        try {
+            // 1. Create the resource.
+            SimulatorResource jSimulatorResource = SimulatorManager
+                    .createResource(SimulatorResource.Type.SINGLE,
+                            resource.getResourceName(),
+                            resource.getResourceURI(), resType);
+            if (null == jSimulatorResource
+                    || !(jSimulatorResource instanceof SimulatorSingleResource)) {
+                return false;
+            }
+            SimulatorSingleResource jSimulatorSingleResource = (SimulatorSingleResource) jSimulatorResource;
+            resource.setSimulatorResource(jSimulatorSingleResource);
 
-    public void removeResourceModelChangedUIListener(
-            IResourceModelChangedUIListener listener) {
-        synchronized (resourceModelChangedUIListeners) {
-            if (null != listener && resourceModelChangedUIListeners.size() > 0) {
-                resourceModelChangedUIListeners.remove(listener);
+            // 2. Cancel observable property if requested by user.
+            if (!resource.isObservable()) {
+                jSimulatorSingleResource.setObservable(false);
             }
-        }
-    }
 
-    public void removeAutomationUIListener(IAutomationUIListener listener) {
-        synchronized (automationUIListeners) {
-            if (null != listener && automationUIListeners.size() > 0) {
-                automationUIListeners.remove(listener);
+            // 3. Set the model change listener.
+            jSimulatorSingleResource
+                    .setResourceModelChangeListener(resourceModelChangeListener);
+
+            // 4. Set the observer listener if the resource is observable.
+            if (resource.isObservable()) {
+                jSimulatorSingleResource.setObserverListener(observer);
             }
-        }
-    }
 
-    public void removeObserverListChangedUIListener(
-            IObserverListChangedUIListener listener) {
-        synchronized (observerUIListeners) {
-            if (null != listener && observerUIListeners.size() > 0) {
-                observerUIListeners.remove(listener);
+            // 5. Add attributes.
+            Map<String, LocalResourceAttribute> attributes = resource
+                    .getResourceAttributes();
+            if (null != attributes && !attributes.isEmpty()) {
+                Set<String> keySet = attributes.keySet();
+                Iterator<String> itr = keySet.iterator();
+
+                String attName;
+                LocalResourceAttribute localAtt;
+                SimulatorResourceAttribute simResAtt;
+
+                while (itr.hasNext()) {
+                    attName = itr.next();
+                    localAtt = attributes.get(attName);
+                    if (null == localAtt) {
+                        continue;
+                    }
+                    simResAtt = localAtt.getResourceAttributeRef();
+                    if (null == simResAtt) {
+                        continue;
+                    }
+                    jSimulatorSingleResource.addAttribute(simResAtt);
+                }
+
+                // 6. Get the resource model java object reference.
+                resource.setResourceModel(jSimulatorSingleResource
+                        .getResourceModel());
             }
+
+            // 7. 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;
         }
-    }
 
-    public synchronized SimulatorResource getCurrentResourceInSelection() {
-        return currentResourceInSelection;
-    }
+        // 8. Add to local cache.
+        data.addResource(resource);
 
-    public synchronized void setCurrentResourceInSelection(
-            SimulatorResource resource) {
-        this.currentResourceInSelection = resource;
+        // 9. Update UI listeners
+        UiListenerHandler.getInstance().resourceCreatedUINotification(
+                ResourceType.SINGLE);
+
+        return true;
     }
 
-    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 createCollectionResource(CollectionResource resource)
+            throws SimulatorException {
+        if (null == resource) {
+            return false;
+        }
+        String resType = (String) resource.getResourceTypes().toArray()[0];
+        try {
+            // 1. Create the resource.
+            SimulatorResource jSimulatorResource = SimulatorManager
+                    .createResource(SimulatorResource.Type.COLLECTION,
+                            resource.getResourceName(),
+                            resource.getResourceURI(), resType);
+            if (null == jSimulatorResource
+                    || !(jSimulatorResource instanceof SimulatorCollectionResource)) {
+                return false;
+            }
+            SimulatorCollectionResource jSimulatorCollectionResource = (SimulatorCollectionResource) jSimulatorResource;
+            resource.setSimulatorResource(jSimulatorCollectionResource);
+
+            // 2. Cancel observable property if requested by user.
+            if (!resource.isObservable()) {
+                jSimulatorCollectionResource.setObservable(false);
+            }
+
+            // 3. Set the observer listener if the resource is observable.
+            if (resource.isObservable()) {
+                jSimulatorCollectionResource.setObserverListener(observer);
             }
+
+            // 4. Set the model change listener.
+            jSimulatorCollectionResource
+                    .setResourceModelChangeListener(resourceModelChangeListener);
+
+            // 5. Register the resource with the platform.
+            jSimulatorCollectionResource.start();
+            resource.setStarted(true);
+        } catch (SimulatorException e) {
+            Activator
+                    .getDefault()
+                    .getLogManager()
+                    .log(Level.ERROR.ordinal(), new Date(),
+                            Utility.getSimulatorErrorString(e, null));
+            throw e;
         }
+
+        // 6. Add to local cache.
+        data.addResource(resource);
+
+        // 7. Update UI listeners
+        UiListenerHandler.getInstance().resourceCreatedUINotification(
+                ResourceType.COLLECTION);
+
+        return true;
     }
 
-    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);
-                    }
-                }
-            } else if (null != resourceType) {
-                orderedResourceUriMap.remove(resourceType);
+    public Resource createResourceByRAML(String configFilePath)
+            throws SimulatorException {
+        Resource resource = null;
+        try {
+            // 1. Create the resource
+            SimulatorResource jSimulatorResource = SimulatorManager
+                    .createResource(configFilePath);
+            if (null == jSimulatorResource) {
+                return null;
+            }
+            if (jSimulatorResource instanceof SimulatorSingleResource) {
+                resource = new SingleResource();
             } else {
-                orderedResourceUriMap.clear();
+                resource = new CollectionResource();
             }
-        }
-    }
+            resource.setSimulatorResource(jSimulatorResource);
 
-    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);
+            // 2. 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());
 
-    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);
-                }
+            String name = jSimulatorResource.getName();
+            if (null == name || name.trim().isEmpty()) {
+                return null;
             }
+            resource.setResourceName(name.trim());
+        } catch (SimulatorException e) {
+            Activator
+                    .getDefault()
+                    .getLogManager()
+                    .log(Level.ERROR.ordinal(), new Date(),
+                            Utility.getSimulatorErrorString(e, null));
+            throw e;
         }
+        return resource;
     }
 
-    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);
-                    }
+    /**
+     * 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;
+            }
+
+            // 1. 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);
                 }
             }
-        }
-    }
 
-    public boolean isResourceExist(String resourceURI) {
-        boolean result = false;
-        if (null != resourceURI) {
-            SimulatorResource resource = getSimulatorResourceByURI(resourceURI);
-            if (null != resource) {
-                result = true;
+            // 2. Set the model change listener.
+            jSimulatorSingleResource
+                    .setResourceModelChangeListener(resourceModelChangeListener);
+
+            // 3. Set the observer listener if the resource is observable.
+            if (jSimulatorSingleResource.isObservable()) {
+                jSimulatorSingleResource.setObserverListener(observer);
+                singleRes.setObservable(true);
             }
-        }
-        return result;
-    }
 
-    public void addResourceDisplayName(String displayName, String completeURI) {
-        synchronized (displayNameMap) {
-            displayNameMap.put(displayName, completeURI);
-        }
-    }
+            // 4. Fetch the resource model.
+            SimulatorResourceModel jResModel = jSimulatorSingleResource
+                    .getResourceModel();
+            if (null == jResModel) {
+                return false;
+            }
+            singleRes.setResourceModel(jResModel);
+
+            // 5. Fetch the basic details of the resource.
+            singleRes.addResourceType(jSimulatorSingleResource
+                    .getResourceType());
+            singleRes
+                    .setResourceInterfaces(Utility
+                            .convertVectorToSet(jSimulatorSingleResource
+                                    .getInterface()));
+
+            // 6. Register the resource with the platform.
+            jSimulatorSingleResource.start();
+            singleRes.setStarted(true);
+
+            // 7. Fetch the resource attributes.
+            Map<String, LocalResourceAttribute> resourceAttributeMap;
+            resourceAttributeMap = fetchResourceAttributesFromModel(jResModel);
+            if (null != resourceAttributeMap) {
+                singleRes.setResourceAttributes(resourceAttributeMap);
+            }
 
-    public void removeResourceDisplayName(String displayName) {
-        synchronized (displayNameMap) {
-            displayNameMap.remove(displayName);
-        }
-    }
+            // 8. Add to local cache.
+            data.addResource(singleRes);
 
-    public boolean isDisplayName(String displayName) {
-        boolean exist = false;
-        synchronized (displayNameMap) {
-            exist = displayNameMap.containsKey(displayName);
+            // 9. Update UI listeners for single instance creation
+            if (!multiInstance)
+                UiListenerHandler.getInstance().resourceCreatedUINotification(
+                        ResourceType.SINGLE);
+        } catch (SimulatorException e) {
+            Activator
+                    .getDefault()
+                    .getLogManager()
+                    .log(Level.ERROR.ordinal(), new Date(),
+                            Utility.getSimulatorErrorString(e, null));
+            throw e;
         }
-        return exist;
+        return true;
     }
 
-    public String getCompleteUriFromDisplayName(String displayName) {
-        String completeURI = null;
-        synchronized (displayNameMap) {
-            completeURI = displayNameMap.get(displayName);
+    /**
+     * 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 completeCollectionResourceCreationByRAML(Resource resource,
+            String uri, String name) throws SimulatorException {
+        if (null == resource || !(resource instanceof CollectionResource)) {
+            return false;
         }
-        return completeURI;
-    }
+        try {
+            CollectionResource collectionRes = (CollectionResource) resource;
 
-    public void createResource(final String configFilePath) {
-        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!");
-                    }
+            SimulatorCollectionResource jSimulatorCollectionResource = (SimulatorCollectionResource) resource
+                    .getSimulatorResource();
+            if (null == jSimulatorCollectionResource) {
+                return false;
+            }
 
-                    // 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());
-                    }
+            // 1. Update resource URI and Name if they are changed.
+            String newUri = uri.trim();
+            String newName = name.trim();
 
-                    // Print the resource data
-                    simulatorResource.printResourceInfo();
-                }
+            if (!collectionRes.getResourceURI().equals(newUri)) {
+                jSimulatorCollectionResource.setURI(newUri);
+                collectionRes.setResourceURI(newUri);
             }
-        }.start();
+            if (!collectionRes.getResourceName().equals(newName)) {
+                jSimulatorCollectionResource.setName(newName);
+                collectionRes.setResourceName(newName);
+            }
+
+            // 2. Set the model change listener.
+            jSimulatorCollectionResource
+                    .setResourceModelChangeListener(resourceModelChangeListener);
+
+            // 3. Fetch the resource model.
+            SimulatorResourceModel jResModel = jSimulatorCollectionResource
+                    .getResourceModel();
+            if (null == jResModel) {
+                return false;
+            }
+            collectionRes.setResourceModel(jResModel);
+
+            // 4. Fetch the basic details of the resource.
+            collectionRes.addResourceType(jSimulatorCollectionResource
+                    .getResourceType());
+            collectionRes.setResourceInterfaces(Utility
+                    .convertVectorToSet(jSimulatorCollectionResource
+                            .getInterface()));
+
+            // 5. Set the observer listener if the resource is observable.
+            if (jSimulatorCollectionResource.isObservable()) {
+                jSimulatorCollectionResource.setObserverListener(observer);
+                collectionRes.setObservable(true);
+            }
+
+            // 6. Register the resource with the platform.
+            jSimulatorCollectionResource.start();
+            collectionRes.setStarted(true);
+
+            // 7. Fetch the resource attributes.
+            Map<String, LocalResourceAttribute> resourceAttributeMap;
+            resourceAttributeMap = fetchResourceAttributesFromModel(jResModel);
+            if (null != resourceAttributeMap) {
+                collectionRes.setResourceAttributes(resourceAttributeMap);
+            }
+
+            // 6. Add to local cache.
+            data.addResource(collectionRes);
+
+            // 7. Update UI listeners for single instance creation
+            UiListenerHandler.getInstance().resourceCreatedUINotification(
+                    ResourceType.COLLECTION);
+        } catch (SimulatorException e) {
+            Activator
+                    .getDefault()
+                    .getLogManager()
+                    .log(Level.ERROR.ordinal(), new Date(),
+                            Utility.getSimulatorErrorString(e, null));
+            throw e;
+        }
+        return true;
     }
 
-    public void createResource(final String configFilePath,
-            final int noOfInstances) {
-        new Thread() {
-            @Override
-            public void run() {
-                Map<String, SimulatorResource> resourceTypeMap;
-                SimulatorResourceServer[] simulatorResourceServers = null;
+    public int createSingleResourceMultiInstances(String configFile, int count)
+            throws SimulatorException {
+        int createCount = 0;
+        try {
+            Vector<SimulatorResource> jSimulatorResources = SimulatorManager
+                    .createResource(configFile, count);
+            if (null == jSimulatorResources || jSimulatorResources.size() < 1) {
+                return 0;
+            }
+            SimulatorSingleResource jResource;
+            SingleResource resource;
+            boolean result;
+            for (SimulatorResource jSimulatorResource : jSimulatorResources) {
+                jResource = (SimulatorSingleResource) jSimulatorResource;
+                resource = new SingleResource();
+                resource.setSimulatorResource(jResource);
                 try {
-                    simulatorResourceServers = SimulatorManager.createResource(
-                            configFilePath, noOfInstances,
-                            resourceModelChangeListener);
-                } catch (SimulatorException e) {
+                    result = completeSingleResourceCreationByRAML(resource,
+                            jResource.getURI(), jResource.getName(), true);
+                    if (result) {
+                        createCount++;
+                    }
+                } catch (SimulatorException eInner) {
                     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());
-                    }
-                }
-
-                // 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();
-                        }
-                    }
+                                    Utility.getSimulatorErrorString(eInner,
+                                            null));
                 }
             }
-        }.start();
+            if (createCount > 0) {
+                UiListenerHandler.getInstance().resourceCreatedUINotification(
+                        ResourceType.SINGLE);
+            }
+        } catch (SimulatorException eOuter) {
+            Activator
+                    .getDefault()
+                    .getLogManager()
+                    .log(Level.ERROR.ordinal(), new Date(),
+                            Utility.getSimulatorErrorString(eOuter, null));
+            throw eOuter;
+        }
+        return createCount;
     }
 
-    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);
+    public void createDevice(String deviceName, Set<Resource> childs) {
+        // 1. Create device
+        Device dev = new Device();
+        dev.setDeviceName(deviceName);
+        data.addDevice(dev);
 
-                // Fetch the resource attributes
-                Map<String, LocalResourceAttribute> resourceAttributeMap;
-                resourceAttributeMap = fetchResourceAttributesFromModel(resourceModelN);
-                if (null != resourceAttributeMap) {
-                    simulatorResource
-                            .setResourceAttributesMap(resourceAttributeMap);
-                }
-            }
-        }
-        return simulatorResource;
+        // 2. Add children to device
+        if (null != childs && !childs.isEmpty())
+            addResourceToDevice(dev, childs);
+
+        // 3. Update ui listeners
+        UiListenerHandler.getInstance().resourceListUpdateUINotification(
+                ResourceType.DEVICE);
     }
 
     private Map<String, LocalResourceAttribute> fetchResourceAttributesFromModel(
-            SimulatorResourceModel resourceModelN) {
+            SimulatorResourceModel jResModel) throws SimulatorException {
         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) {
+        if (null != jResModel) {
+            Map<String, SimulatorResourceAttribute> jAttributeMap;
+            jAttributeMap = jResModel.getAttributes();
+            if (null != jAttributeMap) {
                 resourceAttributeMap = new HashMap<String, LocalResourceAttribute>();
-
-                Set<String> attNameSet = attributeMapN.keySet();
+                Iterator<String> itr = jAttributeMap.keySet().iterator();
                 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);
-                        }
+                SimulatorResourceAttribute jResAtt;
+                LocalResourceAttribute localAtt;
+                while (itr.hasNext()) {
+                    attName = itr.next();
+                    if (null != attName) {
+                        jResAtt = jAttributeMap.get(attName);
+                        if (null != jResAtt) {
+                            localAtt = new LocalResourceAttribute();
 
-                        // Set the attribute value list.
-                        attribute.setAttValues(getValueList(attributeN));
+                            localAtt.setResourceAttributeRef(jResAtt);
 
-                        // Initially disabling the automation
-                        attribute.setAutomationInProgress(false);
+                            // Initially disabling the automation
+                            localAtt.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);
+                            // Assigning the default automation interval
+                            localAtt.setAutomationUpdateInterval(Constants.DEFAULT_AUTOMATION_INTERVAL);
 
-                        // Setting the default automation type
-                        attribute
-                                .setAutomationType(Constants.DEFAULT_AUTOMATION_TYPE);
+                            // Setting the default automation type
+                            localAtt.setAutomationType(Constants.DEFAULT_AUTOMATION_TYPE);
 
-                        resourceAttributeMap.put(attName, attribute);
+                            resourceAttributeMap.put(attName, localAtt);
+                        }
                     }
                 }
             }
         }
         return resourceAttributeMap;
+
     }
 
     // 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();
+    private List<String> getValueList(SimulatorResourceAttribute attributeN) {
+        AttributeProperty attProp = attributeN.property();
+        if (null == attProp) {
+            return null;
+        }
         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));
+        Type valuesType = attProp.type();
+        if (valuesType == Type.VALUESET) {
+            Object[] allowedValues = attProp.valueSet();
+            if (null != allowedValues && allowedValues.length > 0) {
+                for (Object value : allowedValues) {
+                    if (null != value) {
+                        valueList.add(String.valueOf(((AttributeValue) value)
+                                .get()));
                     }
                 }
             }
+        } else if (valuesType == Type.RANGE) {
+            double minD = attProp.min();
+            double maxD = attProp.max();
+            for (double value = minD; value <= maxD; value++) {
+                valueList.add(String.valueOf(value));
+            }
         }
-        Object attValue = attributeN.getValue();
+        Object attValue = attributeN.value().get();
         if (valueList.size() < 1 && null != attValue) {
             valueList.add(String.valueOf(attValue));
         }
         return valueList;
     }
 
-    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();
+    public List<Resource> getResourceList() {
+        List<Resource> resourceList = data.getResources();
+        if (null == resourceList) {
+            return null;
+        }
+        // Sort the list
+        Collections.sort(resourceList, Utility.resourceComparator);
+
+        return resourceList;
+    }
 
-                        // Unregister the resource from the platform
-                        deleteResource(resource);
+    public List<SingleResource> getSingleResourceList() {
+        List<SingleResource> resourceList = data.getSingleResources();
+        if (null == resourceList) {
+            return null;
+        }
+        // Sort the list
+        Collections.sort(resourceList, Utility.singleResourceComparator);
 
-                        // Delete from the local data structure
-                        deleteLocalResourceDetails(resourceType, resourceURI);
+        return resourceList;
+    }
 
-                        // Notify the UI listener for removing this resource
-                        // from UI
-                        resourceDeletedUINotification();
+    public List<CollectionResource> getCollectionResourceList() {
+        List<CollectionResource> resourceList = data.getCollectionResources();
+        if (null == resourceList) {
+            return null;
+        }
+        // Sort the list
+        Collections.sort(resourceList, Utility.collectionResourceComparator);
 
-                        if (null != currentResourceInSelection
-                                && resource == currentResourceInSelection) {
-                            // Listeners might query the resource being deleted
-                            // if exists. So set the currently selection to
-                            // null.
-                            setCurrentResourceInSelection(null);
+        return resourceList;
+    }
 
-                            // Notify all observers for resource selection
-                            // change event
-                            resourceSelectionChangedUINotification();
-                        }
-                    }
-                }
-            }.start();
-        }
-    }
-
-    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;
-                        }
-                    }
-                }
+    public List<Device> getDeviceList() {
+        List<Device> deviceList = data.getDevices();
+        if (null == deviceList) {
+            return null;
+        }
+        // Sort the list
+        Collections.sort(deviceList, Utility.deviceComparator);
+        return deviceList;
+    }
+
+    // Returns the number of resources which are added properly to the
+    // collection.
+    public int addResourceToCollection(CollectionResource collectionParent,
+            Set<Resource> childs) {
+        if (null == collectionParent || null == childs || childs.isEmpty()) {
+            return -1;
+        }
+        Iterator<Resource> itr = childs.iterator();
+        Resource res;
+        int count = childs.size();
+        while (itr.hasNext()) {
+            res = itr.next();
+            try {
+                addResourceToCollection(collectionParent, res);
+            } catch (SimulatorException e) {
+                count--;
             }
         }
-        return resource;
+        return count;
     }
 
-    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());
-                }
+    public void addResourceToCollection(CollectionResource collectionParent,
+            Resource child) throws SimulatorException {
+        if (null == collectionParent || null == child) {
+            return;
+        }
+        try {
+            // 1. Add child to collection
+            collectionParent.addChildResource(child);
+
+            // 2. Add a reference to the collection in the child
+            if (child instanceof SingleResource) {
+                ((SingleResource) child)
+                        .addCollectionMembership(collectionParent);
+            } else {
+                ((CollectionResource) child).addMembership(collectionParent);
+            }
+        } catch (SimulatorException e) {
+            Activator
+                    .getDefault()
+                    .getLogManager()
+                    .log(Level.ERROR.ordinal(), new Date(),
+                            Utility.getSimulatorErrorString(e, null));
+            throw e;
+        }
+    }
+
+    public int addResourceToCollection(Set<CollectionResource> collections,
+            Resource child) {
+        if (null == collections || collections.isEmpty() || null == child) {
+            return -1;
+        }
+        Iterator<CollectionResource> itr = collections.iterator();
+        CollectionResource res;
+        int count = collections.size();
+        while (itr.hasNext()) {
+            res = itr.next();
+            try {
+                addResourceToCollection(res, child);
+            } catch (SimulatorException e) {
+                count--;
             }
         }
+        return count;
     }
 
-    public void deleteResourceByType(final String resourceType) {
-        if (null != resourceType) {
-            new Thread() {
-                @Override
-                public void run() {
-                    // Unregister the resources from the platform
-                    deleteResource(resourceType);
+    public void addResourceToDevice(Device dev, Set<Resource> childs) {
+        // 1. Add children to the device.
+        dev.addChildResource(childs);
+
+        // 2. Add a reference to the device in all children.
+        Iterator<Resource> itr = childs.iterator();
+        Resource res;
+        while (itr.hasNext()) {
+            res = itr.next();
+            if (res instanceof SingleResource) {
+                ((SingleResource) res).addDeviceMembership(dev);
+            } else {
+                ((CollectionResource) res).addDeviceMembership(dev);
+            }
+        }
+    }
 
-                    // Delete from the local data structure
-                    deleteLocalResourceDetails(resourceType, null);
+    public void addResourceToDevice(Device dev, Resource child) {
+        // 1. Add child to the device.
+        dev.addChildResource(child);
 
-                    // Notify the UI listener for removing this resource from UI
-                    resourceDeletedUINotification();
+        // 2. Add a reference to the device in the child.
+        if (child instanceof SingleResource) {
+            ((SingleResource) child).addDeviceMembership(dev);
+        } else {
+            ((CollectionResource) child).addDeviceMembership(dev);
+        }
+    }
 
-                    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);
+    public void addResourceToDevice(Set<Device> devices, Resource child) {
+        // 1. Add device reference in child.
+        if (child instanceof SingleResource)
+            ((SingleResource) child).addDeviceMembership(devices);
+        else
+            ((CollectionResource) child).addDeviceMembership(devices);
 
-                        // Notify all observers for resource selection change
-                        // event
-                        resourceSelectionChangedUINotification();
-                    }
-                }
-            }.start();
+        // 2. Add a reference to the child in all devices.
+        Iterator<Device> itr = devices.iterator();
+        Device dev;
+        while (itr.hasNext()) {
+            dev = itr.next();
+            dev.addChildResource(child);
         }
     }
 
-    private void deleteResource(String resourceType) {
-        if (null != resourceType) {
+    public int removeResourceFromCollection(
+            Set<CollectionResource> collections, Resource resource) {
+        // 1. Remove the reference of resource from all the collections.
+        Iterator<CollectionResource> itr = collections.iterator();
+        CollectionResource colRes;
+        int count = collections.size();
+        while (itr.hasNext()) {
+            colRes = itr.next();
             try {
-                SimulatorManager.deleteResources(resourceType);
+                removeResourceFromCollection(colRes, resource);
             } catch (SimulatorException e) {
-                Activator
-                        .getDefault()
-                        .getLogManager()
-                        .log(Level.ERROR.ordinal(),
-                                new Date(),
-                                "[" + e.getClass().getSimpleName() + "]"
-                                        + e.code().toString() + "-"
-                                        + e.message());
+                count--;
             }
         }
+        return count;
+
     }
 
-    public void deleteAllResources() {
-        new Thread() {
-            @Override
-            public void run() {
-                // Unregister the resources from the platform
-                deleteResource();
+    public void removeResourceFromDevice(Set<Device> devices, Resource resource) {
+        // 1. Remove the reference of resource from all the devices.
+        Iterator<Device> itr = devices.iterator();
+        Device dev;
+        while (itr.hasNext()) {
+            dev = itr.next();
+            dev.removeChildResource(resource);
+        }
 
-                // Delete from the local data structure
-                deleteLocalResourceDetails(null, null);
+        // 2. Remove the reference of devices from the resource.
+        resource.removeDeviceMembership(devices);
+    }
 
-                // Notify the UI listener for removing this resource from UI
-                resourceDeletedUINotification();
+    // Returns the count of resources removed from the collection
+    public int removeResourcesFromCollection(CollectionResource colRes,
+            Set<Resource> resources) {
+        Iterator<Resource> itr = resources.iterator();
+        Resource res;
+        int count = resources.size();
+        while (itr.hasNext()) {
+            res = itr.next();
+            try {
+                removeResourceFromCollection(colRes, res);
+            } catch (SimulatorException e) {
+                count--;
+            }
+        }
+        return count;
+    }
 
-                // Listeners might query the resource being deleted if exists.
-                // So set the currently selection to null.
-                setCurrentResourceInSelection(null);
+    public void removeResourcesFromDevice(Device dev, Set<Resource> resources) {
+        Iterator<Resource> itr = resources.iterator();
+        Resource res;
+        while (itr.hasNext()) {
+            res = itr.next();
+            res.removeDeviceMembership(dev);
+        }
+        dev.removeChildResource(resources);
+    }
 
-                // Notify all observers for resource selection change event
-                resourceSelectionChangedUINotification();
+    public void removeResourceFromCollection(CollectionResource parent,
+            Resource child) throws SimulatorException {
+        try {
+            // 1. Remove the child from the parent
+            parent.removeChildResource(child);
+
+            // 2. Remove the reference to parent from child
+            if (child instanceof SingleResource) {
+                ((SingleResource) child).removeCollectionMembership(parent);
+            } else {
+                ((CollectionResource) child).removeMembership(parent);
             }
-        }.start();
+        } catch (SimulatorException e) {
+            Activator
+                    .getDefault()
+                    .getLogManager()
+                    .log(Level.ERROR.ordinal(), new Date(),
+                            Utility.getSimulatorErrorString(e, null));
+            throw e;
+        }
     }
 
-    private void deleteResource() {
+    public void removeResourceFromDevice(Device parent, Resource child) {
+        // 1. Remove the reference to parent from child
+        child.removeDeviceMembership(parent);
+
+        // 2. Remove the child from the parent
+        parent.removeChildResource(child);
+    }
+
+    public void removeSingleResources(Set<SingleResource> resources)
+            throws SimulatorException {
+        if (null == resources) {
+            return;
+        }
+        Iterator<SingleResource> itr = resources.iterator();
+        while (itr.hasNext()) {
+            removeResource(itr.next());
+        }
+    }
+
+    public void removeCollectionResources(Set<CollectionResource> resources)
+            throws SimulatorException {
+        if (null == resources) {
+            return;
+        }
+        Iterator<CollectionResource> itr = resources.iterator();
+        while (itr.hasNext()) {
+            removeResource(itr.next());
+        }
+    }
+
+    public void removeResource(Resource res) throws SimulatorException {
+        // 1. Unregister the resource from the platform.
+        SimulatorResource simRes = res.getSimulatorResource();
         try {
-            SimulatorManager.deleteResources(null);
+            simRes.stop();
         } 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));
+            throw e;
         }
-    }
 
-    private void deleteLocalResourceDetails(String resourceType,
-            String resourceURI) {
-        if (null != resourceType && null != resourceURI) {
-            removeResourceFromMap(resourceType, resourceURI);
-            removeResourceUriFromOrderedMap(resourceType, resourceURI);
+        Set<CollectionResource> collectionMembership;
+        Set<Device> deviceMembership;
+
+        if (res instanceof SingleResource) {
+            collectionMembership = ((SingleResource) res)
+                    .getCollectionMembership();
+            deviceMembership = ((SingleResource) res).getDeviceMembership();
         } else {
-            synchronized (resourceMap) {
-                if (null != resourceType) {
-                    removeResourceUriFromOrderedMap(resourceType, null);
-                    resourceMap.remove(resourceType);
-                } else {
-                    resourceMap.clear();
-                    removeResourceUriFromOrderedMap(null, null);
-                }
-            }
+            collectionMembership = ((CollectionResource) res).getMembership();
+            deviceMembership = ((CollectionResource) res).getDeviceMembership();
+        }
+
+        // 2. Delete from the collections to which this resource is a member.
+        if (null != collectionMembership && !collectionMembership.isEmpty()) {
+            removeResourceFromCollection(collectionMembership, res);
         }
-        // Remove the display name from the map
-        if (null != resourceURI) {
-            String dispName = Utility.uriToDisplayName(resourceURI);
-            if (null != dispName)
-                removeResourceDisplayName(dispName);
+
+        // 3. Delete from the devices to which this resource is a member.
+        if (null != deviceMembership && !deviceMembership.isEmpty()) {
+            removeResourceFromDevice(deviceMembership, res);
         }
+
+        // 4. Delete this resource
+        data.deleteResource(res);
     }
 
-    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 void removeDevice(Device dev) {
+        Set<Resource> childs = dev.getChildResources();
+        if (null != childs && !childs.isEmpty()) {
+            // 1. Remove the reference from all the children.
+            Iterator<Resource> itr = childs.iterator();
+            Resource res;
+            while (itr.hasNext()) {
+                res = itr.next();
+                res.removeDeviceMembership(dev);
             }
         }
+        // 2. Delete the device.
+        data.deleteDevice(dev);
     }
 
-    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();
-                    }
-                }
+    public boolean isUriUnique(List<MetaProperty> properties) {
+        if (null == properties) {
+            return false;
+        }
+        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;
     }
 
-    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();
-                    }
-                }
-            }
+    public List<CollectionResource> getCollectionsForAddingToSingleResource(
+            SingleResource resource) {
+        List<CollectionResource> collectionResources = data
+                .getCollectionResources();
+        if (null == collectionResources || collectionResources.isEmpty()) {
+            return null;
         }
+
+        Set<CollectionResource> collectionMembership;
+        collectionMembership = resource.getCollectionMembership();
+        if (null == collectionMembership || collectionMembership.isEmpty()) {
+            return collectionResources;
+        }
+
+        if (collectionMembership.size() == collectionResources.size()) {
+            return null;
+        }
+
+        collectionResources.removeAll(collectionMembership);
+
+        // Sort the list
+        Collections.sort(collectionResources,
+                Utility.collectionResourceComparator);
+
+        return collectionResources;
     }
 
-    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);
-                    }
-                }
-            }
+    public List<SingleResource> getSingleTypeResourcesForAddingToCollectionResource(
+            CollectionResource colRes) {
+        List<SingleResource> singleResources = data.getSingleResources();
+        if (null == singleResources || singleResources.isEmpty()) {
+            return null;
+        }
+
+        Set<SingleResource> childs;
+        childs = colRes.getSingleTypeChildResources();
+        if (null == childs || childs.isEmpty()) {
+            return singleResources;
+        }
+
+        if (childs.size() == singleResources.size()) {
+            return null;
         }
+
+        singleResources.removeAll(childs);
+
+        // Sort the list
+        Collections.sort(singleResources, Utility.singleResourceComparator);
+
+        return singleResources;
     }
 
-    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);
-                    }
-                }
-            }
+    public List<SingleResource> getSingleTypeResourcesForAddingToDevice(
+            Device dev) {
+        List<SingleResource> singleResources = data.getSingleResources();
+        if (null == singleResources || singleResources.isEmpty()) {
+            return null;
+        }
+
+        Set<SingleResource> childs;
+        childs = dev.getSingleTypeChildResources();
+        if (null == childs || childs.isEmpty()) {
+            return singleResources;
         }
+
+        if (childs.size() == singleResources.size()) {
+            return null;
+        }
+
+        singleResources.removeAll(childs);
+
+        // Sort the list
+        Collections.sort(singleResources, Utility.singleResourceComparator);
+
+        return singleResources;
     }
 
-    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);
-                    }
-                }
-            }
+    public List<CollectionResource> getCollectionTypeResourcesForAddingToCollectionResource(
+            CollectionResource colRes) {
+        List<CollectionResource> collectionResources = data
+                .getCollectionResources();
+        if (null == collectionResources || collectionResources.isEmpty()) {
+            return null;
         }
+
+        // Remove the colRes from the list
+        collectionResources.remove(colRes);
+
+        Set<CollectionResource> childs;
+        childs = colRes.getCollectionTypeChildResources();
+        if (null == childs || childs.isEmpty()) {
+            return collectionResources;
+        }
+
+        if (childs.size() == collectionResources.size()) {
+            return null;
+        }
+
+        collectionResources.removeAll(childs);
+
+        // Sort the list
+        Collections.sort(collectionResources,
+                Utility.collectionResourceComparator);
+
+        return collectionResources;
     }
 
-    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 List<CollectionResource> getCollectionTypeResourcesForAddingToDevice(
+            Device dev) {
+        List<CollectionResource> collectionResources = data
+                .getCollectionResources();
+        if (null == collectionResources || collectionResources.isEmpty()) {
+            return null;
         }
+
+        Set<CollectionResource> childs;
+        childs = dev.getCollectionTypeChildResources();
+        if (null == childs || childs.isEmpty()) {
+            return collectionResources;
+        }
+
+        if (childs.size() == collectionResources.size()) {
+            return null;
+        }
+
+        collectionResources.removeAll(childs);
+
+        // Sort the list
+        Collections.sort(collectionResources,
+                Utility.collectionResourceComparator);
+
+        return collectionResources;
     }
 
-    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());
-                }
-            }
+    public List<Device> getDevicesForAddingToResource(Resource resource) {
+        List<Device> devices = data.getDevices();
+        if (null == devices || devices.isEmpty()) {
+            return null;
         }
-        return typeList;
+
+        Set<Device> deviceMembership;
+        if (resource instanceof SingleResource) {
+            deviceMembership = ((SingleResource) resource)
+                    .getDeviceMembership();
+        } else {
+            deviceMembership = ((CollectionResource) resource)
+                    .getDeviceMembership();
+        }
+        if (null == deviceMembership || deviceMembership.isEmpty()) {
+            return devices;
+        }
+
+        if (devices.size() == deviceMembership.size()) {
+            return null;
+        }
+
+        devices.removeAll(deviceMembership);
+
+        // Sort the list
+        Collections.sort(devices, Utility.deviceComparator);
+
+        return devices;
     }
 
-    public boolean isTypeExist(String resType) {
-        synchronized (resourceMap) {
-            if (resourceMap.containsKey(resType)) {
-                return true;
-            }
+    public List<CollectionResource> getResourceReferences(
+            SingleResource resource) {
+        List<CollectionResource> resources = Utility
+                .getCollectionResourceListFromSet(resource
+                        .getCollectionMembership());
+        if (null == resources || resources.isEmpty()) {
+            return null;
         }
-        return false;
+
+        Collections.sort(resources, Utility.collectionResourceComparator);
+
+        return resources;
     }
 
-    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;
-            }
-            list = new ArrayList<String>();
+    public List<Device> getDeviceReferences(Resource resource) {
+        Set<Device> deviceMembership;
+        if (resource instanceof SingleResource) {
+            deviceMembership = ((SingleResource) resource)
+                    .getDeviceMembership();
+        } else {
+            deviceMembership = ((CollectionResource) resource)
+                    .getDeviceMembership();
+        }
 
-            // Sort the types
-            Collections.sort(typeList);
+        List<Device> devices = Utility.getDeviceListFromSet(deviceMembership);
+        if (null == devices || devices.isEmpty()) {
+            return null;
+        }
 
-            // 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);
+        Collections.sort(devices, Utility.deviceComparator);
+
+        return devices;
+    }
+
+    public List<SingleResource> getSingleTypeChilds(CollectionResource colRes) {
+        Set<SingleResource> childs = colRes.getSingleTypeChildResources();
+        return Utility.getSingleResourceListFromSet(childs);
+    }
+
+    public List<SingleResource> getSingleTypeChilds(Device dev) {
+        Set<SingleResource> childs = dev.getSingleTypeChildResources();
+        return Utility.getSingleResourceListFromSet(childs);
+    }
+
+    public List<CollectionResource> getCollectionTypeChilds(
+            CollectionResource colRes) {
+        Set<CollectionResource> childs = colRes
+                .getCollectionTypeChildResources();
+        return Utility.getCollectionResourceListFromSet(childs);
+    }
+
+    public List<CollectionResource> getCollectionTypeChilds(Device dev) {
+        Set<CollectionResource> childs = dev.getCollectionTypeChildResources();
+        return Utility.getCollectionResourceListFromSet(childs);
+    }
+
+    /*
+     * public void deleteResourceByURI(String resourceURI) { if (null !=
+     * resourceURI) { Resource resource =
+     * getSimulatorResourceByURI(resourceURI); if (null != resource) { //
+     * Unregister the resource from the platform deleteResource(resource);
+     * 
+     * // Delete from the local data structure deleteLocalResourceDetails(null,
+     * resourceURI);
+     * 
+     * // Notify the UI listener for removing this resource // from UI //
+     * resourceDeletedUINotification(); if (resource ==
+     * getCurrentResourceInSelection()) { // 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(); } } } }
+     * 
+     * private SingleResource getSimulatorResourceByURI(String resourceURI) {
+     * SingleResource resource = null; if (null != resourceURI) { synchronized
+     * (resourceMap) { resource = resourceMap.get(resourceURI); } } return
+     * resource; }
+     * 
+     * private void deleteResource(SingleResource 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(),
+     * Utility.getSimulatorErrorString(e, null)); } } } }
+     * 
+     * public void deleteResourceByType(final String resourceType) {
+     * System.out.println(resourceType + "to be deleted."); 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 &&
+     * currentResourceInSelection.getResourceTypes() .contains(resourceType)) {
+     * // 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(null); } } }.start(); } }
+     * 
+     * private void deleteResource(String resourceType) { if (null !=
+     * resourceType) { try { SimulatorManager.deleteResources(resourceType); }
+     * catch (SimulatorException e) { Activator .getDefault() .getLogManager()
+     * .log(Level.ERROR.ordinal(), new Date(),
+     * Utility.getSimulatorErrorString(e, null)); } } }
+     * 
+     * public void deleteAllResources() { new Thread() {
+     * 
+     * @Override public void run() { // Unregister the resources from the
+     * platform deleteResource();
+     * 
+     * // Delete from the local data structure deleteLocalResourceDetails(null,
+     * null);
+     * 
+     * // Notify the UI listener for removing this resource from UI
+     * resourceDeletedUINotification();
+     * 
+     * // 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(null); } }.start(); }
+     * 
+     * private void deleteResource() { try {
+     * SimulatorManager.deleteResources(null); } catch (SimulatorException e) {
+     * Activator .getDefault() .getLogManager() .log(Level.ERROR.ordinal(), new
+     * Date(), Utility.getSimulatorErrorString(e, null)); } }
+     * 
+     * private void deleteLocalResourceDetails(String resourceType, String
+     * resourceURI) { synchronized (resourceMap) { if (null == resourceType &&
+     * null == resourceURI) { resourceMap.clear(); } else if (null !=
+     * resourceType) { Set<String> uriSet = resourceMap.keySet(); if (null ==
+     * uriSet) { return; } String uri; SingleResource simpleRes;
+     * Iterator<String> uriItr = uriSet.iterator(); while (uriItr.hasNext()) {
+     * uri = uriItr.next(); simpleRes = resourceMap.get(uri); if
+     * (simpleRes.getResourceTypes().contains(resourceType)) { uriItr.remove();
+     * } } } else { removeResourceFromMap(resourceURI); } } }
+     * 
+     * 
+     * 
+     * public Set<String> getResourceTypeList() { Set<String> types = null;
+     * synchronized (resourceMap) { if (resourceMap.size() > 0) { types = new
+     * TreeSet<String>(); Set<String> typeSet = resourceMap.keySet();
+     * Iterator<String> typeItr = typeSet.iterator(); SingleResource resource;
+     * while (typeItr.hasNext()) { resource = resourceMap.get(typeItr.next());
+     * Set<String> subTypes = resource.getResourceTypes();
+     * types.addAll(subTypes); } } } return types; }
+     */
+
+    public void resourceSelectionChanged(final Resource selectedResource) {
+        new Thread() {
+            @Override
+            public void run() {
+
+                setCurrentDeviceInSelection(null);
+
+                if (null != selectedResource) {
+                    setCurrentResourceInSelection(selectedResource);
+                } else {
+                    setCurrentResourceInSelection(null);
                 }
+                // Notify all observers for resource selection change event
+                UiListenerHandler.getInstance()
+                        .resourceSelectionChangedUINotification(
+                                selectedResource);
             }
-        }
-        return list;
+        }.start();
     }
 
-    public void resourceSelectionChanged(final String selectedItem) {
+    public void deviceSelectionChanged(final Device selectedDevice) {
         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);
+
+                setCurrentResourceInSelection(null);
+
+                if (null != selectedDevice) {
+                    setCurrentDeviceInSelection(selectedDevice);
                 } else {
-                    // Given item is a resource URI
-                    SimulatorResource resource = getSimulatorResourceByURI(selectedItem);
-                    if (null != resource) {
-                        setCurrentResourceInSelection(resource);
-                    } else {
-                        setCurrentResourceInSelection(null);
-                    }
+                    setCurrentDeviceInSelection(null);
                 }
                 // Notify all observers for resource selection change event
-                resourceSelectionChangedUINotification();
+                UiListenerHandler.getInstance()
+                        .deviceSelectionChangedUINotification(selectedDevice);
             }
         }.start();
     }
 
-    public List<MetaProperty> getMetaProperties(SimulatorResource resource) {
+    public List<MetaProperty> getMetaProperties(Resource resource) {
         if (null != resource) {
             String propName;
             String propValue;
@@ -1179,13 +1624,12 @@ public class ResourceManager {
 
             for (int index = 0; index < Constants.META_PROPERTY_COUNT; index++) {
                 propName = Constants.META_PROPERTIES[index];
-                if (propName.equals(Constants.RESOURCE_URI)) {
+                if (propName.equals(Constants.RESOURCE_NAME)) {
+                    propValue = resource.getResourceName();
+                } else if (propName.equals(Constants.RESOURCE_URI)) {
                     propValue = resource.getResourceURI();
                 } 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;
+                    propValue = resource.getResourceTypes().toString();
                 } else {
                     propValue = null;
                 }
@@ -1193,17 +1637,228 @@ public class ResourceManager {
                     metaPropertyList.add(new MetaProperty(propName, propValue));
                 }
             }
+            return metaPropertyList;
+        }
+        return null;
+    }
 
+    public List<MetaProperty> getMetaProperties(Device dev) {
+        if (null != dev) {
+            List<MetaProperty> metaPropertyList = new ArrayList<MetaProperty>();
+            metaPropertyList.add(new MetaProperty(Constants.DEVICE_NAME, dev
+                    .getDeviceName()));
             return metaPropertyList;
         }
         return null;
     }
 
-    public List<LocalResourceAttribute> getAttributes(SimulatorResource resource) {
+    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 true;
+    }
+
+    public boolean stopResource(Resource resource) throws SimulatorException {
+        if (null == resource) {
+            return false;
+        }
+        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 true;
+    }
+
+    public boolean changeResourceName(Resource resource, String newName)
+            throws SimulatorException {
+        if (null == resource || null == newName) {
+            return false;
+        }
+
+        if (!stopResource(resource)) {
+            return false;
+        }
+
+        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;
+        }
+
+        if (!startResource(resource)) {
+            return false;
+        }
+
+        return true;
+    }
+
+    public boolean changeDeviceName(Device dev, String newName) {
+        if (null == dev || null == newName) {
+            return false;
+        }
+        data.changeDeviceName(dev, dev.getDeviceName(), newName);
+        return true;
+    }
+
+    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();
+        SimulatorResource server = resource.getSimulatorResource();
+        try {
+            server.setURI(newURI);
+            data.changeResourceURI(resource, curURI, newURI);
+        } catch (SimulatorException e) {
+            Activator
+                    .getDefault()
+                    .getLogManager()
+                    .log(Level.ERROR.ordinal(),
+                            new Date(),
+                            "There is an error while changing the resource URI.\n"
+                                    + Utility.getSimulatorErrorString(e, null));
+            throw e;
+        }
+
+        if (!startResource(resource)) {
+            return false;
+        }
+        return true;
+    }
+
+    public boolean updateResourceProperties(Resource resource,
+            List<MetaProperty> properties, boolean uriChanged,
+            boolean nameChanged) throws SimulatorException {
+        if (null == resource || null == properties) {
+            return false;
+        }
+
+        // Updating the properties
+        Iterator<MetaProperty> itr = properties.iterator();
+        MetaProperty property;
+        String propName;
+        String propValue;
+        String resName = null;
+        String resURI = null;
+        while (itr.hasNext()) {
+            property = itr.next();
+            if (null == property) {
+                continue;
+            }
+            propName = property.getPropName();
+            propValue = property.getPropValue();
+            if (propName.equals(Constants.RESOURCE_NAME)) {
+                resName = propValue;
+            } else if (propName.equals(Constants.RESOURCE_URI)) {
+                resURI = propValue;
+            }
+        }
+
+        if (nameChanged) {
+            if (!changeResourceName(resource, resName)) {
+                return false;
+            }
+
+            // Notify UI Listeners
+            UiListenerHandler.getInstance().propertiesChangedUINotification(
+                    Resource.class);
+        }
+
+        if (uriChanged) {
+            if (!changeResourceURI(resource, resURI)) {
+                return false;
+            }
+        }
+
+        return true;
+    }
+
+    public boolean updateDeviceProperties(Device dev,
+            List<MetaProperty> properties) {
+        if (null == dev || null == properties) {
+            return false;
+        }
+
+        // Updating the properties
+        Iterator<MetaProperty> itr = properties.iterator();
+        MetaProperty property;
+        String propName;
+        String propValue;
+        String devName = null;
+        while (itr.hasNext()) {
+            property = itr.next();
+            if (null == property) {
+                continue;
+            }
+            propName = property.getPropName();
+            propValue = property.getPropValue();
+            if (propName.equals(Constants.DEVICE_NAME)) {
+                devName = propValue;
+            }
+        }
+
+        if (!changeDeviceName(dev, devName)) {
+            return false;
+        }
+
+        // Notify UI Listeners
+        UiListenerHandler.getInstance().propertiesChangedUINotification(
+                Device.class);
+
+        return true;
+    }
+
+    public List<LocalResourceAttribute> getAttributes(Resource resource) {
         List<LocalResourceAttribute> attList = null;
         if (null != resource) {
             Map<String, LocalResourceAttribute> attMap = resource
-                    .getResourceAttributesMap();
+                    .getResourceAttributes();
             if (null != attMap && attMap.size() > 0) {
                 attList = new ArrayList<LocalResourceAttribute>();
                 Set<String> attNameSet = attMap.keySet();
@@ -1219,137 +1874,313 @@ public class ResourceManager {
                 }
             }
         }
-        return attList;
+        return attList;
+    }
+
+    public List<SimulatorResourceAttribute> getAttributes(
+            SimulatorResourceModel model) {
+        List<SimulatorResourceAttribute> attList = null;
+        if (null != model) {
+            Map<String, SimulatorResourceAttribute> attMap = model
+                    .getAttributes();
+            if (null != attMap && attMap.size() > 0) {
+                attList = new ArrayList<SimulatorResourceAttribute>();
+                Set<String> attNameSet = attMap.keySet();
+                String attName;
+                SimulatorResourceAttribute attribute;
+                Iterator<String> attNameItr = attNameSet.iterator();
+                while (attNameItr.hasNext()) {
+                    attName = attNameItr.next();
+                    attribute = attMap.get(attName);
+                    if (null != attribute) {
+                        attList.add(attribute);
+                    }
+                }
+            }
+        }
+        return attList;
+    }
+
+    public List<SRMItem> getIndexedAttributes(SimulatorResourceModel[] model) {
+        List<SRMItem> indexedAttList = null;
+        if (null != model && model.length > 0) {
+            indexedAttList = new ArrayList<SRMItem>();
+            int i = 0;
+            for (SimulatorResourceModel m : model) {
+                indexedAttList.add(new SRMItem(i++, m));
+            }
+        }
+        return indexedAttList;
+    }
+
+    public void 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);
+                } catch (SimulatorException e) {
+                    Activator
+                            .getDefault()
+                            .getLogManager()
+                            .log(Level.ERROR.ordinal(), new Date(),
+                                    Utility.getSimulatorErrorString(e, 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; } } // 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; } } return notificationType;
+     * }
+     */
+
+    // TODO: This method should get the status from the native layer.
+    public boolean isResourceStarted(Resource resource) {
+        if (null == resource) {
+            return false;
+        }
+        return resource.isStarted();
+    }
+
+    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 (null == value || value.trim().isEmpty()) {
+                    invalid = true;
+                }
+            }
+        }
+        return invalid;
+    }
+
+    public boolean isPropertyValueInvalid(Device dev,
+            List<MetaProperty> properties, String propName) {
+        if (null == dev || 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 (null == value || value.trim().isEmpty()) {
+                    invalid = true;
+                }
+            }
+        }
+        return invalid;
+    }
+
+    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 changed;
+    }
+
+    public boolean isPropValueChanged(Device dev,
+            List<MetaProperty> properties, String propName) {
+        if (null == dev || 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 = dev.getDeviceName();
+                if (null != oldValue && !prop.getPropValue().equals(oldValue)) {
+                    changed = true;
+                }
+                break;
+            }
+        }
+        return changed;
+    }
+
+    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.getResourceTypes().toString();
+        } else {
+            return null;
+        }
     }
 
-    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());
+    public boolean isURIChanged(Resource resource, List<MetaProperty> properties) {
+        if (null == resource || null == properties) {
+            return false;
+        }
+        boolean changed = false;
+        MetaProperty prop;
+        Iterator<MetaProperty> itr = properties.iterator();
+        while (itr.hasNext()) {
+            prop = itr.next();
+            if (prop.getPropName().equals(Constants.RESOURCE_URI)) {
+                if (!prop.getPropValue().equals(resource.getResourceURI())) {
+                    changed = true;
                 }
+                break;
             }
         }
+        return changed;
     }
 
-    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 startResource(SingleResource resource) {
+        if (null == resource || resource.isStarted()) {
+            return false;
+        }
+        boolean result;
+        SimulatorResource server = resource.getSimulatorResource();
+        if (null == server) {
+            result = false;
+        } else {
+            try {
+                server.start();
+                resource.setStarted(true);
+                result = true;
+            } catch (SimulatorException e) {
+                Activator
+                        .getDefault()
+                        .getLogManager()
+                        .log(Level.ERROR.ordinal(), new Date(),
+                                Utility.getSimulatorErrorString(e, null));
+                result = 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;
+        }
+        return result;
+    }
+
+    public boolean stopResource(SingleResource resource) {
+        if (null == resource || !resource.isStarted()) {
+            return false;
+        }
+        boolean result;
+        SimulatorResource server = resource.getSimulatorResource();
+        if (null == server) {
+            result = false;
+        } else {
+            try {
+                server.stop();
+                resource.setStarted(false);
+                result = true;
+            } catch (SimulatorException e) {
+                Activator
+                        .getDefault()
+                        .getLogManager()
+                        .log(Level.ERROR.ordinal(), new Date(),
+                                Utility.getSimulatorErrorString(e, null));
+                result = false;
             }
         }
-        return notificationType;
+        return result;
+    }
+
+    public boolean isAttHasRangeOrAllowedValues(SimulatorResourceAttribute att) {
+        if (null == att) {
+            return false;
+        }
+        AttributeProperty prop = att.property();
+        if (null == prop) {
+            return false;
+        }
+        Type attProp = prop.type();
+        if (attProp == Type.UNKNOWN) {
+            return false;
+        }
+        return true;
     }
 
-    public int startAutomation(SimulatorResource resource,
-            LocalResourceAttribute attribute, AutomationType autoType,
+    public int startAutomation(SingleResource resource,
+            LocalResourceAttribute 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.getResourceAttributeRef().name();
                 try {
-                    autoId = resourceServerN.startAttributeAutomation(attrName,
-                            autoType, autoUpdateInterval, automationListener);
+                    autoId = server.startAttributeUpdation(attrName, autoType,
+                            autoUpdateInterval, automationListener);
                 } catch (SimulatorException e) {
                     Activator
                             .getDefault()
@@ -1375,14 +2206,14 @@ public class ResourceManager {
         return autoId;
     }
 
-    public void stopAutomation(SimulatorResource resource,
+    public void stopAutomation(SingleResource resource,
             LocalResourceAttribute 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()
@@ -1401,113 +2232,55 @@ public class ResourceManager {
         }
     }
 
-    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;
-            }
-        }
-        return status;
-    }
-
-    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;
-                            }
-                        }
-                    }
-                }
+        changeResourceLevelAutomationStatus(resource, true);
+        // 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 targetAttribute;
-    }
+            if (-1 == autoId) {
+                // Automation request failed and hence status is being
+                // rolled back
+                changeResourceLevelAutomationStatus(resource, false);
+            } else {
+                // Automation request accepted.
+                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,40 +2288,62 @@ 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) {
+            return false;
+        }
+        Map<String, LocalResourceAttribute> attMap = resource
+                .getResourceAttributes();
+        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;
+            }
+        }
+        return status;
+    }
+
     // Changes the automation state of the resource and its attributes
-    private void changeResourceLevelAutomationStatus(
-            SimulatorResource resource, boolean status) {
+    private void changeResourceLevelAutomationStatus(SingleResource resource,
+            boolean status) {
 
         Map<String, LocalResourceAttribute> attributeMap = resource
-                .getResourceAttributesMap();
+                .getResourceAttributes();
         if (null != attributeMap) {
             Set<String> attrNameSet = attributeMap.keySet();
             Iterator<String> attrNameItr = attrNameSet.iterator();
@@ -1565,82 +2360,207 @@ public class ResourceManager {
         resource.setResourceAutomationInProgress(status);
     }
 
-    public boolean isResourceAutomationStarted(String resourceURI) {
-        boolean status = false;
-        if (null == resourceURI) {
-            return status;
-        }
-
-        SimulatorResource resource = getSimulatorResourceByURI(resourceURI);
+    private LocalResourceAttribute getAttributeWithGivenAutomationId(
+            SingleResource resource, int automationId) {
+        LocalResourceAttribute targetAttribute = null;
         if (null != resource) {
-            status = resource.isResourceAutomationInProgress();
+            Map<String, LocalResourceAttribute> attributeMap = resource
+                    .getResourceAttributes();
+            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 status;
+        return targetAttribute;
     }
 
-    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 false;
+        }
+        return resource.isAttributeAutomationInProgress();
+    }
+
+    public LocalResourceAttribute getAttributeByResourceURI(
+            SingleResource resource, String attName) {
+        if (null == resource || null == attName) {
             return null;
         }
         Map<String, LocalResourceAttribute> attMap = resource
-                .getResourceAttributesMap();
+                .getResourceAttributes();
         if (null == attMap) {
             return null;
         }
         return attMap.get(attName);
     }
 
-    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 void shutdown() {
+        threadHandle.interrupt();
+    }
+
+    public List<String> getAllValuesOfAttribute(SimulatorResourceAttribute att) {
+        if (null == att) {
             return null;
         }
-        SimulatorResource resource = getSimulatorResourceByURI(resourceURI);
-        if (null == resource) {
+
+        AttributeValue val = att.value();
+        if (null == val) {
+            return null;
+        }
+
+        TypeInfo type = val.typeInfo();
+
+        AttributeProperty prop = att.property();
+        if (null == prop) {
+            return null;
+        }
+
+        List<String> values = new ArrayList<String>();
+
+        Type valuesType = prop.type();
+
+        if (valuesType == Type.UNKNOWN) {
+            // Adding the default value
+            values.add(Utility.getAttributeValueAsString(val));
+            return values;
+        }
+
+        if (type.mType != ValueType.RESOURCEMODEL) {
+            if (type.mType == ValueType.ARRAY) {
+                if (type.mDepth == 1) {
+                    AttributeProperty childProp = prop.getChildProperty();
+                    if (null != childProp) {
+                        valuesType = childProp.type();
+                        if (valuesType == Type.RANGE) {
+                            List<String> list = getRangeForPrimitiveNonArrayAttributes(
+                                    childProp, type.mBaseType);
+                            if (null != list) {
+                                values.addAll(list);
+                            }
+                        } else if (valuesType == Type.VALUESET) {
+                            List<String> list = getAllowedValuesForPrimitiveNonArrayAttributes(
+                                    childProp.valueSet(), type.mBaseType);
+                            if (null != list) {
+                                values.addAll(list);
+                            }
+                        }
+                    }
+                }
+            } else {
+                if (valuesType == Type.RANGE) {
+                    List<String> list = getRangeForPrimitiveNonArrayAttributes(
+                            prop, type.mType);
+                    if (null != list) {
+                        values.addAll(list);
+                    }
+                } else if (valuesType == Type.VALUESET) {
+                    List<String> list = getAllowedValuesForPrimitiveNonArrayAttributes(
+                            prop.valueSet(), type.mType);
+                    if (null != list) {
+                        values.addAll(list);
+                    }
+                }
+            }
+        }
+
+        return values;
+    }
+
+    public List<String> getRangeForPrimitiveNonArrayAttributes(
+            AttributeProperty prop, ValueType type) {
+        if (null == prop) {
             return null;
         }
-        return Activator.getDefault().getImageRegistry()
-                .get(resource.getResourceType());
+
+        if (type == ValueType.ARRAY || type == ValueType.RESOURCEMODEL) {
+            return null;
+        }
+
+        List<String> values = new ArrayList<String>();
+        switch (type) {
+            case INTEGER:
+                int min = (int) prop.min();
+                int max = (int) prop.max();
+                for (int iVal = min; iVal <= max; iVal++) {
+                    values.add(String.valueOf(iVal));
+                }
+                break;
+            case DOUBLE:
+                double minD = (double) prop.min();
+                double maxD = (double) prop.max();
+                for (double iVal = minD; iVal <= maxD; iVal = iVal + 1.0) {
+                    values.add(String.valueOf(iVal));
+                }
+                break;
+            default:
+        }
+        return values;
     }
 
-    public void shutdown() {
-        threadHandle.interrupt();
+    public List<String> getAllowedValuesForPrimitiveNonArrayAttributes(
+            AttributeValue[] attValues, ValueType type) {
+        if (null == attValues || attValues.length < 1) {
+            return null;
+        }
+
+        if (type == ValueType.ARRAY || type == ValueType.RESOURCEMODEL) {
+            return null;
+        }
+
+        Object obj;
+        List<String> values = new ArrayList<String>();
+        for (AttributeValue val : attValues) {
+            if (null == val) {
+                continue;
+            }
+            obj = val.get();
+            if (null == obj) {
+                continue;
+            }
+            values.add(String.valueOf(obj));
+        }
+        return values;
     }
 }
\ No newline at end of file
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..8d1535f
--- /dev/null
@@ -0,0 +1,325 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.IAutomationUIListener;
+import oic.simulator.serviceprovider.listener.IObserverListChangedUIListener;
+import oic.simulator.serviceprovider.listener.IPropertiesChangedUIListener;
+import oic.simulator.serviceprovider.listener.IResourceListChangedUIListener;
+import oic.simulator.serviceprovider.listener.IResourceModelChangedUIListener;
+import oic.simulator.serviceprovider.listener.ISelectionChangedUIListener;
+import oic.simulator.serviceprovider.model.Device;
+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<IResourceListChangedUIListener>  resourceListChangedUIListeners;
+
+    private List<ISelectionChangedUIListener>     selectionChangedUIListeners;
+
+    private List<IResourceModelChangedUIListener> resourceModelChangedUIListeners;
+
+    private List<IAutomationUIListener>           automationUIListeners;
+
+    private List<IObserverListChangedUIListener>  observerUIListeners;
+
+    private List<IPropertiesChangedUIListener>    propertiesChangedUIListeners;
+
+    private UiListenerHandler() {
+        resourceListChangedUIListeners = new ArrayList<IResourceListChangedUIListener>();
+        selectionChangedUIListeners = new ArrayList<ISelectionChangedUIListener>();
+        resourceModelChangedUIListeners = new ArrayList<IResourceModelChangedUIListener>();
+        automationUIListeners = new ArrayList<IAutomationUIListener>();
+        observerUIListeners = new ArrayList<IObserverListChangedUIListener>();
+        propertiesChangedUIListeners = new ArrayList<IPropertiesChangedUIListener>();
+    }
+
+    public static UiListenerHandler getInstance() {
+        if (null == uiHandler) {
+            uiHandler = new UiListenerHandler();
+        }
+        return uiHandler;
+    }
+
+    public void addResourceListChangedUIListener(
+            IResourceListChangedUIListener resourceListChangedUIListener) {
+        synchronized (resourceListChangedUIListeners) {
+            resourceListChangedUIListeners.add(resourceListChangedUIListener);
+        }
+    }
+
+    public void addResourceSelectionChangedUIListener(
+            ISelectionChangedUIListener resourceSelectionChangedUIListener) {
+        synchronized (selectionChangedUIListeners) {
+            selectionChangedUIListeners.add(resourceSelectionChangedUIListener);
+        }
+    }
+
+    public void addResourceModelChangedUIListener(
+            IResourceModelChangedUIListener resourceModelChangedUIListener) {
+        synchronized (resourceModelChangedUIListeners) {
+            resourceModelChangedUIListeners.add(resourceModelChangedUIListener);
+        }
+    }
+
+    public void addAutomationUIListener(
+            IAutomationUIListener automationUIListener) {
+        synchronized (automationUIListeners) {
+            automationUIListeners.add(automationUIListener);
+        }
+    }
+
+    public void addObserverListChangedUIListener(
+            IObserverListChangedUIListener observerListChangedUIListener) {
+        synchronized (observerUIListeners) {
+            observerUIListeners.add(observerListChangedUIListener);
+        }
+    }
+
+    public void addResourcePropertiesChangedUIListener(
+            IPropertiesChangedUIListener resourcePropertiesChangedUIListener) {
+        synchronized (propertiesChangedUIListeners) {
+            propertiesChangedUIListeners
+                    .add(resourcePropertiesChangedUIListener);
+        }
+    }
+
+    public void removeResourceListChangedUIListener(
+            IResourceListChangedUIListener listener) {
+        synchronized (resourceListChangedUIListeners) {
+            if (null != listener && resourceListChangedUIListeners.size() > 0) {
+                resourceListChangedUIListeners.remove(listener);
+            }
+        }
+    }
+
+    public void removeResourceSelectionChangedUIListener(
+            ISelectionChangedUIListener listener) {
+        synchronized (selectionChangedUIListeners) {
+            if (null != listener && selectionChangedUIListeners.size() > 0) {
+                selectionChangedUIListeners.remove(listener);
+            }
+        }
+    }
+
+    public void removeResourceModelChangedUIListener(
+            IResourceModelChangedUIListener listener) {
+        synchronized (resourceModelChangedUIListeners) {
+            if (null != listener && resourceModelChangedUIListeners.size() > 0) {
+                resourceModelChangedUIListeners.remove(listener);
+            }
+        }
+    }
+
+    public void removeAutomationUIListener(IAutomationUIListener listener) {
+        synchronized (automationUIListeners) {
+            if (null != listener && automationUIListeners.size() > 0) {
+                automationUIListeners.remove(listener);
+            }
+        }
+    }
+
+    public void removeObserverListChangedUIListener(
+            IObserverListChangedUIListener listener) {
+        synchronized (observerUIListeners) {
+            if (null != listener && observerUIListeners.size() > 0) {
+                observerUIListeners.remove(listener);
+            }
+        }
+    }
+
+    public void removeResourcePropertiesChangedUIListener(
+            IPropertiesChangedUIListener resourcePropertiesChangedUIListener) {
+        synchronized (propertiesChangedUIListeners) {
+            propertiesChangedUIListeners
+                    .remove(resourcePropertiesChangedUIListener);
+        }
+    }
+
+    public void resourceCreatedUINotification(ResourceType type) {
+        synchronized (resourceListChangedUIListeners) {
+            if (resourceListChangedUIListeners.size() > 0) {
+                IResourceListChangedUIListener listener;
+                Iterator<IResourceListChangedUIListener> 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) {
+                IResourceListChangedUIListener listener;
+                Iterator<IResourceListChangedUIListener> 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) {
+                IResourceListChangedUIListener listener;
+                Iterator<IResourceListChangedUIListener> 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) {
+                ISelectionChangedUIListener listener;
+                Iterator<ISelectionChangedUIListener> listenerItr = selectionChangedUIListeners
+                        .iterator();
+                while (listenerItr.hasNext()) {
+                    listener = listenerItr.next();
+                    if (null != listener) {
+                        listener.onResourceSelectionChange(resource);
+                    }
+                }
+            }
+        }
+    }
+
+    public void deviceSelectionChangedUINotification(Device dev) {
+        synchronized (selectionChangedUIListeners) {
+            if (selectionChangedUIListeners.size() > 0) {
+                ISelectionChangedUIListener listener;
+                Iterator<ISelectionChangedUIListener> listenerItr = selectionChangedUIListeners
+                        .iterator();
+                while (listenerItr.hasNext()) {
+                    listener = listenerItr.next();
+                    if (null != listener) {
+                        listener.onDeviceSelectionChange(dev);
+                    }
+                }
+            }
+        }
+    }
+
+    public void resourceModelChangedUINotification(Resource resource) {
+        synchronized (resourceModelChangedUIListeners) {
+            if (resourceModelChangedUIListeners.size() > 0 && null != resource) {
+                IResourceModelChangedUIListener listener;
+                Iterator<IResourceModelChangedUIListener> listenerItr = resourceModelChangedUIListeners
+                        .iterator();
+                while (listenerItr.hasNext()) {
+                    listener = listenerItr.next();
+                    if (null != listener) {
+                        listener.onResourceModelChange(resource);
+                    }
+                }
+            }
+        }
+    }
+
+    public void resourceAutomationStartedUINotification(SingleResource resource) {
+        synchronized (automationUIListeners) {
+            if (automationUIListeners.size() > 0 && null != resource) {
+                IAutomationUIListener listener;
+                Iterator<IAutomationUIListener> 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) {
+                IAutomationUIListener listener;
+                Iterator<IAutomationUIListener> 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) {
+                IObserverListChangedUIListener listener;
+                Iterator<IObserverListChangedUIListener> 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) {
+                IPropertiesChangedUIListener listener;
+                Iterator<IPropertiesChangedUIListener> listenerItr = propertiesChangedUIListeners
+                        .iterator();
+                while (listenerItr.hasNext()) {
+                    listener = listenerItr.next();
+                    if (null != listener) {
+                        if (targetClass == Resource.class) {
+                            listener.onResourcePropertyChange();
+                        } else {
+                            listener.onDevicePropertyChange();
+                        }
+                    }
+                }
+            }
+        }
+    }
+}
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..50d6a49
--- /dev/null
@@ -0,0 +1,364 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.Set;
+
+import oic.simulator.serviceprovider.utils.Constants;
+import oic.simulator.serviceprovider.utils.Utility;
+
+import org.oic.simulator.AttributeProperty;
+import org.oic.simulator.AttributeProperty.Type;
+import org.oic.simulator.AttributeValue;
+import org.oic.simulator.AttributeValue.ValueType;
+import org.oic.simulator.SimulatorResourceAttribute;
+
+public class AttributeHelper {
+    private String      attributeName;
+    private String      attributeType;
+    private String      min;
+    private String      max;
+    private Set<String> allowedValues;
+    private String      attributeDflValue;
+
+    private Type        validValuesType;
+
+    public AttributeHelper() {
+        allowedValues = new HashSet<String>();
+        setValidValuesType(Type.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 Type getValidValuesType() {
+        return validValuesType;
+    }
+
+    public void setValidValuesType(Type 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 == Type.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 == Type.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);
+                        if (dflValue < min || dflValue > max) {
+                            result = false;
+                        }
+                    } catch (Exception e) {
+                        result = false;
+                    }
+                }
+            } else if (validValuesType == Type.VALUESET
+                    && null != allowedValues && !allowedValues.isEmpty()) {
+                result = allowedValues.contains(value);
+            }
+        }
+        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 LocalResourceAttribute convertToLocalResourceAttribute() {
+        LocalResourceAttribute attribute = new LocalResourceAttribute();
+
+        // Initially disabling the automation
+        attribute.setAutomationInProgress(false);
+
+        // Assigning the default automation interval
+        attribute
+                .setAutomationUpdateInterval(Constants.DEFAULT_AUTOMATION_INTERVAL);
+
+        // Setting the default automation type
+        attribute.setAutomationType(Constants.DEFAULT_AUTOMATION_TYPE);
+
+        AttributeValue attValue = null;
+        AttributeProperty attProperty = null;
+        SimulatorResourceAttribute simResAtt;
+
+        ValueType valueType = Utility.getAttributeTypeEnum(attributeType);
+        switch (valueType) {
+            case INTEGER:
+                attValue = new AttributeValue(
+                        Integer.parseInt(attributeDflValue));
+                if (validValuesType == Type.VALUESET) {
+                    attProperty = new AttributeProperty(
+                            Utility.convertSetToArrayInt(Utility
+                                    .convertSetStringToSetObject(allowedValues,
+                                            valueType)));
+                } else if (validValuesType == Type.RANGE) {
+                    attProperty = new AttributeProperty(
+                            Double.parseDouble(min), Double.parseDouble(max));
+                } else {
+                    attProperty = null;
+                }
+            case DOUBLE:
+                attValue = new AttributeValue(
+                        Double.parseDouble(attributeDflValue));
+                if (validValuesType == Type.VALUESET) {
+                    attProperty = new AttributeProperty(
+                            Utility.convertSetToArrayDouble(Utility
+                                    .convertSetStringToSetObject(allowedValues,
+                                            valueType)));
+                } else if (validValuesType == Type.RANGE) {
+                    attProperty = new AttributeProperty(
+                            Double.parseDouble(min), Double.parseDouble(max));
+                } else {
+                    attProperty = null;
+                }
+                break;
+            case BOOLEAN:
+                attValue = new AttributeValue(
+                        Boolean.parseBoolean(attributeDflValue));
+                boolean[] arr = { true, false };
+                attProperty = new AttributeProperty(arr);
+                break;
+            case STRING:
+                attValue = new AttributeValue(attributeDflValue);
+                if (validValuesType == Type.VALUESET) {
+                    attProperty = new AttributeProperty(
+                            Utility.convertSetToArrayString(Utility
+                                    .convertSetStringToSetObject(allowedValues,
+                                            valueType)));
+                } else {
+                    attProperty = null;
+                }
+                break;
+            default:
+                break;
+        }
+        simResAtt = new SimulatorResourceAttribute(attributeName, attValue,
+                attProperty);
+        attribute.setResourceAttributeRef(simResAtt);
+        return attribute;
+    }
+}
\ 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..9a456b9
--- /dev/null
@@ -0,0 +1,130 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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 oic.simulator.serviceprovider.utils.Constants;
+
+import org.oic.simulator.server.SimulatorResource.AutoUpdateType;
+
+/**
+ * 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;
+
+        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.getAutomationType()
+                            .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
+                            .getAutomationUpdateInterval()));
+                } 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/CollectionResource.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/CollectionResource.java
new file mode 100644 (file)
index 0000000..ff41152
--- /dev/null
@@ -0,0 +1,221 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.SimulatorException;
+import org.oic.simulator.server.SimulatorCollectionResource;
+import org.oic.simulator.server.SimulatorResource;
+
+public class CollectionResource extends Resource {
+    private Set<Resource>           childResources;
+    private Set<String>             supportedResourceTypes;
+
+    private Set<CollectionResource> membership;
+
+    public CollectionResource() {
+        childResources = new HashSet<Resource>();
+        supportedResourceTypes = new HashSet<String>();
+        membership = new HashSet<CollectionResource>();
+        setDeviceMembership(new HashSet<Device>());
+    }
+
+    public Set<String> getSupportedResourceTypes() {
+        return supportedResourceTypes;
+    }
+
+    public void setSupportedResourceTypes(Set<String> supportedResourceTypes) {
+        this.supportedResourceTypes = supportedResourceTypes;
+    }
+
+    public void addSupportedResourceType(String rType) {
+        if (null == supportedResourceTypes) {
+            supportedResourceTypes = new HashSet<String>();
+        }
+        supportedResourceTypes.add(rType);
+    }
+
+    public void removeSupportedResourceType(String rType) {
+        if (null != supportedResourceTypes) {
+            supportedResourceTypes.remove(rType);
+        }
+    }
+
+    public Set<Resource> getChildResources() {
+        return childResources;
+    }
+
+    public Set<SingleResource> getSingleTypeChildResources() {
+        if (null == childResources || childResources.isEmpty()) {
+            return null;
+        }
+        Set<SingleResource> resultSet = new HashSet<SingleResource>();
+        Iterator<Resource> itr = childResources.iterator();
+        Resource res;
+        while (itr.hasNext()) {
+            res = itr.next();
+            if (null != res) {
+                if (res instanceof SingleResource) {
+                    resultSet.add((SingleResource) res);
+                }
+            }
+        }
+        return resultSet;
+    }
+
+    public Set<CollectionResource> getCollectionTypeChildResources() {
+        if (null == childResources || childResources.isEmpty()) {
+            return null;
+        }
+        Set<CollectionResource> resultSet = new HashSet<CollectionResource>();
+        Iterator<Resource> itr = childResources.iterator();
+        Resource res;
+        while (itr.hasNext()) {
+            res = itr.next();
+            if (null != res) {
+                if (res instanceof CollectionResource) {
+                    resultSet.add((CollectionResource) res);
+                }
+            }
+        }
+        return resultSet;
+    }
+
+    public void setChildResources(Set<Resource> childResources) {
+        this.childResources = childResources;
+    }
+
+    public void addChildResource(Resource resource) throws SimulatorException {
+        if (null == resource) {
+            return;
+        }
+        if (null == childResources) {
+            childResources = new HashSet<Resource>();
+        }
+
+        // Native call to add child resource
+        SimulatorResource simRes;
+        simRes = resource.getSimulatorResource();
+        ((SimulatorCollectionResource) simulatorResource)
+                .addChildResource(simRes);
+
+        childResources.add(resource);
+    }
+
+    public void addChildResource(Set<Resource> resources)
+            throws SimulatorException {
+        if (null == resources || resources.isEmpty()) {
+            return;
+        }
+        if (null == childResources) {
+            childResources = new HashSet<Resource>();
+        }
+
+        // Native call to add child resource
+        SimulatorResource simRes;
+        Resource res;
+        Iterator<Resource> itr = resources.iterator();
+        while (itr.hasNext()) {
+            res = itr.next();
+            simRes = res.getSimulatorResource();
+            ((SimulatorCollectionResource) simulatorResource)
+                    .addChildResource(simRes);
+
+            childResources.add(res);
+        }
+    }
+
+    public void removeChildResource(Resource resource)
+            throws SimulatorException {
+        if (null == resource || null == childResources) {
+            return;
+        }
+
+        // Native call to add child resource
+        SimulatorResource simRes;
+        simRes = resource.getSimulatorResource();
+        ((SimulatorCollectionResource) simulatorResource)
+                .removeChildResource(simRes);
+
+        childResources.remove(resource);
+    }
+
+    public void removeChildResource(Set<Resource> resources)
+            throws SimulatorException {
+        if (null == resources || null == childResources) {
+            return;
+        }
+
+        // Native call to add child resource
+        SimulatorResource simRes;
+        Resource res;
+        Iterator<Resource> itr = resources.iterator();
+        while (itr.hasNext()) {
+            res = itr.next();
+            simRes = res.getSimulatorResource();
+            ((SimulatorCollectionResource) simulatorResource)
+                    .removeChildResource(simRes);
+
+            childResources.remove(res);
+        }
+    }
+
+    public Set<CollectionResource> getMembership() {
+        return membership;
+    }
+
+    public void setMembership(Set<CollectionResource> membership) {
+        this.membership = membership;
+    }
+
+    public void addMembership(CollectionResource resource) {
+        if (null == resource) {
+            return;
+        }
+        if (null == membership) {
+            membership = new HashSet<CollectionResource>();
+        }
+        membership.add(resource);
+    }
+
+    public void addMembership(Set<CollectionResource> resources) {
+        if (null == resources) {
+            return;
+        }
+        if (null == membership) {
+            membership = new HashSet<CollectionResource>();
+        }
+        membership.addAll(resources);
+    }
+
+    public void removeMembership(CollectionResource resource) {
+        if (null == resource || null == membership) {
+            return;
+        }
+        membership.remove(resource);
+    }
+
+    public void removeMembership(Set<CollectionResource> collections) {
+        if (null == collections || null == membership) {
+            return;
+        }
+        membership.removeAll(collections);
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/DeleteCategory.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/DeleteCategory.java
new file mode 100644 (file)
index 0000000..831c65f
--- /dev/null
@@ -0,0 +1,24 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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;
+
+/**
+ * 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/model/Device.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/Device.java
new file mode 100644 (file)
index 0000000..f1a9879
--- /dev/null
@@ -0,0 +1,117 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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;
+
+public class Device {
+    private String        deviceName;
+
+    private Set<Resource> childResources;
+
+    public Device() {
+        childResources = new HashSet<Resource>();
+    }
+
+    public String getDeviceName() {
+        return deviceName;
+    }
+
+    public void setDeviceName(String deviceName) {
+        this.deviceName = deviceName;
+    }
+
+    public Set<Resource> getChildResources() {
+        return childResources;
+    }
+
+    public void setChildResources(Set<Resource> childResources) {
+        this.childResources = childResources;
+    }
+
+    public void addChildResource(Resource resource) {
+        if (null == resource) {
+            return;
+        }
+        if (null == childResources) {
+            childResources = new HashSet<Resource>();
+        }
+        childResources.add(resource);
+    }
+
+    public void addChildResource(Set<Resource> resources) {
+        if (null == resources) {
+            return;
+        }
+        if (null == childResources) {
+            childResources = new HashSet<Resource>();
+        }
+        childResources.addAll(resources);
+    }
+
+    public void removeChildResource(Resource resource) {
+        if (null == resource || null == childResources) {
+            return;
+        }
+        childResources.remove(resource);
+    }
+
+    public void removeChildResource(Set<Resource> resources) {
+        if (null == resources || null == childResources) {
+            return;
+        }
+        childResources.removeAll(resources);
+    }
+
+    public Set<SingleResource> getSingleTypeChildResources() {
+        if (null == childResources || childResources.isEmpty()) {
+            return null;
+        }
+        Set<SingleResource> resultSet = new HashSet<SingleResource>();
+        Iterator<Resource> itr = childResources.iterator();
+        Resource res;
+        while (itr.hasNext()) {
+            res = itr.next();
+            if (null != res) {
+                if (res instanceof SingleResource) {
+                    resultSet.add((SingleResource) res);
+                }
+            }
+        }
+        return resultSet;
+    }
+
+    public Set<CollectionResource> getCollectionTypeChildResources() {
+        if (null == childResources || childResources.isEmpty()) {
+            return null;
+        }
+        Set<CollectionResource> resultSet = new HashSet<CollectionResource>();
+        Iterator<Resource> itr = childResources.iterator();
+        Resource res;
+        while (itr.hasNext()) {
+            res = itr.next();
+            if (null != res) {
+                if (res instanceof CollectionResource) {
+                    resultSet.add((CollectionResource) res);
+                }
+            }
+        }
+        return resultSet;
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/LocalResourceAttribute.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/LocalResourceAttribute.java
new file mode 100644 (file)
index 0000000..e958fa1
--- /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.
+ */
+
+package oic.simulator.serviceprovider.model;
+
+import org.oic.simulator.SimulatorResourceAttribute;
+import org.oic.simulator.server.SimulatorResource.AutoUpdateType;
+
+/**
+ * This class represents an attribute in the simulated resource.
+ */
+public class LocalResourceAttribute {
+
+    // Java SDK object reference
+    private SimulatorResourceAttribute resourceAttributeRef;
+
+    private int                        automationId;
+
+    private boolean                    automationInProgress;
+
+    private int                        automationUpdateInterval;
+
+    private AutoUpdateType             automationType;
+
+    public SimulatorResourceAttribute getResourceAttributeRef() {
+        return resourceAttributeRef;
+    }
+
+    public void setResourceAttributeRef(
+            SimulatorResourceAttribute resourceAttribute) {
+        this.resourceAttributeRef = resourceAttribute;
+    }
+
+    public int getAutomationId() {
+        return automationId;
+    }
+
+    public void setAutomationId(int automationId) {
+        this.automationId = automationId;
+    }
+
+    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 AutoUpdateType getAutomationType() {
+        return automationType;
+    }
+
+    public void setAutomationType(AutoUpdateType automationType) {
+        this.automationType = automationType;
+    }
+}
\ 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/ModelChangeNotificationType.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/ModelChangeNotificationType.java
new file mode 100644 (file)
index 0000000..a5e624c
--- /dev/null
@@ -0,0 +1,24 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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;
+
+/**
+ * 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/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..5772cc2
--- /dev/null
@@ -0,0 +1,260 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.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 String                              resourceURI;
+    private String                              resourceName;
+    private Set<String>                         resourceTypes;
+    private Set<String>                         resourceInterfaces;
+    private boolean                             started;
+    private boolean                             observable;
+
+    private Set<Device>                         deviceMembership;
+
+    private Map<String, LocalResourceAttribute> attributes;
+
+    private Map<Integer, ObserverDetail>        observers;
+
+    public Resource() {
+        resourceTypes = new HashSet<String>();
+        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 Set<String> getResourceTypes() {
+        return resourceTypes;
+    }
+
+    public void setResourceTypes(Set<String> resourceTypes) {
+        this.resourceTypes = resourceTypes;
+    }
+
+    public Set<String> getResourceInterfaces() {
+        return resourceInterfaces;
+    }
+
+    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 void addResourceType(String resType) {
+        if (null == resType) {
+            return;
+        }
+        if (null == resourceTypes) {
+            resourceTypes = new HashSet<String>();
+        }
+        resourceTypes.add(resType);
+    }
+
+    public void removeResourceType(String resType) {
+        if (null == resType || null == resourceTypes) {
+            return;
+        }
+        resourceTypes.remove(resType);
+    }
+
+    public boolean isResourceTypeExist(String resType) {
+        if (null == resType || null == resourceTypes) {
+            return false;
+        }
+        return resourceTypes.contains(resType);
+    }
+
+    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 Set<Device> getDeviceMembership() {
+        return deviceMembership;
+    }
+
+    public void setDeviceMembership(Set<Device> deviceMembership) {
+        this.deviceMembership = deviceMembership;
+    }
+
+    public void addDeviceMembership(Device dev) {
+        if (null == dev) {
+            return;
+        }
+        if (null == deviceMembership) {
+            deviceMembership = new HashSet<Device>();
+        }
+        deviceMembership.add(dev);
+    }
+
+    public void addDeviceMembership(Set<Device> devices) {
+        if (null == devices) {
+            return;
+        }
+        if (null == deviceMembership) {
+            deviceMembership = new HashSet<Device>();
+        }
+        deviceMembership.addAll(devices);
+    }
+
+    public void removeDeviceMembership(Device dev) {
+        if (null == dev || null == deviceMembership) {
+            return;
+        }
+        deviceMembership.remove(dev);
+    }
+
+    public void removeDeviceMembership(Set<Device> devices) {
+        if (null == devices || null == deviceMembership) {
+            return;
+        }
+        deviceMembership.removeAll(devices);
+    }
+
+    public boolean isMemberOfAnyDevice() {
+        if (null == deviceMembership || deviceMembership.isEmpty()) {
+            return false;
+        }
+        return true;
+    }
+
+    public Map<String, LocalResourceAttribute> getResourceAttributes() {
+        return attributes;
+    }
+
+    public void setResourceAttributes(
+            Map<String, LocalResourceAttribute> attributes) {
+        this.attributes = attributes;
+    }
+
+    // Added for debugging purpose
+    public void printResourceInfo() {
+        System.out.println("Resource URI: " + getResourceURI());
+        System.out.println("Resource Name: " + getResourceName());
+        System.out.println("Resource types: " + getResourceTypes());
+        System.out.println("Resource Interfaces: " + getResourceInterfaces());
+        System.out.println("Resource Attributes:-");
+        /*
+         * if (null != resourceAttributesMap) { Iterator<String> attItr =
+         * resourceAttributesMap.keySet().iterator(); while (attItr.hasNext()) {
+         * resourceAttributesMap.get(attItr.next()) .printAttributeDetails();; }
+         * }
+         */
+    }
+}
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/ResourceCategory.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/ResourceCategory.java
new file mode 100644 (file)
index 0000000..b932abc
--- /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 ResourceCategory {
+    SIMPLE, COLLECTION
+}
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..f9ec137
--- /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, COLLECTION, DEVICE
+}
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/SRMItem.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/SRMItem.java
new file mode 100644 (file)
index 0000000..f003e3a
--- /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.
+ */
+
+package oic.simulator.serviceprovider.model;
+
+import org.oic.simulator.SimulatorResourceModel;
+
+public class SRMItem {
+    private int                    index;
+    private SimulatorResourceModel model;
+
+    public SRMItem(int index, SimulatorResourceModel model) {
+        this.index = index;
+        this.model = model;
+    }
+
+    public int getIndex() {
+        return index;
+    }
+
+    public void setIndex(int index) {
+        this.index = index;
+    }
+
+    public SimulatorResourceModel getModel() {
+        return model;
+    }
+
+    public void setModel(SimulatorResourceModel model) {
+        this.model = model;
+    }
+}
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..6db7486
--- /dev/null
@@ -0,0 +1,167 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.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 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 SimulatorPluginException {
+        try {
+            FileOutputStream fileOut = new FileOutputStream(filePath);
+            ObjectOutputStream out = new ObjectOutputStream(fileOut);
+            out.writeObject(this);
+            out.close();
+            fileOut.close();
+        } catch (IOException i) {
+            throw new SimulatorPluginException(
+                    "Failed to Serialize data : IOException");
+        }
+    }
+
+    public static SerializedServiceProvider deSerialize(String filePath)
+            throws SimulatorPluginException {
+        SerializedServiceProvider r = null;
+        try {
+            FileInputStream fileIn = new FileInputStream(filePath);
+            ObjectInputStream in = new ObjectInputStream(fileIn);
+            r = (SerializedServiceProvider) in.readObject();
+            in.close();
+            fileIn.close();
+        } catch (IOException i) {
+            throw new SimulatorPluginException(
+                    "Failed to DeSerialize data : IOException");
+        } catch (ClassNotFoundException c) {
+            throw new SimulatorPluginException(
+                    "Failed to DeSerialize data : ClassNotFound");
+        }
+        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/SimulatorPluginException.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/SimulatorPluginException.java
new file mode 100644 (file)
index 0000000..92af95f
--- /dev/null
@@ -0,0 +1,33 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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 class represents the plug-in level exceptions.
+ */
+@SuppressWarnings("serial")
+public class SimulatorPluginException extends Exception {
+    String msg;
+
+    public SimulatorPluginException(String msg) {
+        this.msg = msg;
+    }
+
+    public String toString() {
+        return msg;
+    }
+}
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..899bc60
--- /dev/null
@@ -0,0 +1,173 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.Set;
+
+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 Set<CollectionResource> collectionMembership;
+
+    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 SingleResource() {
+        setCollectionMembership(new HashSet<CollectionResource>());
+    }
+
+    public Set<CollectionResource> getCollectionMembership() {
+        return collectionMembership;
+    }
+
+    public void setCollectionMembership(
+            Set<CollectionResource> collectionMembership) {
+        this.collectionMembership = collectionMembership;
+    }
+
+    public void addCollectionMembership(CollectionResource resource) {
+        if (null == resource) {
+            return;
+        }
+        if (null == collectionMembership) {
+            collectionMembership = new HashSet<CollectionResource>();
+        }
+        collectionMembership.add(resource);
+    }
+
+    public void addCollectionMembership(Set<CollectionResource> resources) {
+        if (null == resources) {
+            return;
+        }
+        if (null == collectionMembership) {
+            collectionMembership = new HashSet<CollectionResource>();
+        }
+        collectionMembership.addAll(resources);
+    }
+
+    public void removeCollectionMembership(CollectionResource resource) {
+        if (null == resource || null == collectionMembership) {
+            return;
+        }
+        collectionMembership.remove(resource);
+    }
+
+    public void removeCollectionMembership(Set<CollectionResource> collections) {
+        if (null == collections || null == collectionMembership) {
+            return;
+        }
+        collectionMembership.removeAll(collections);
+    }
+
+    public boolean isMemberOfAnyCollection() {
+        if (null == collectionMembership || collectionMembership.isEmpty()) {
+            return false;
+        }
+        return true;
+    }
+
+    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;
+    }
+
+    /*
+     * 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
index 079f6456adf7e3bb09aa39ec65567ec1370f689f..e24a456602d29d24c0fd75d18962ff368f8a32d4 100644 (file)
@@ -19,7 +19,7 @@ package oic.simulator.serviceprovider.perspective;
 import oic.simulator.serviceprovider.view.AttributeView;
 import oic.simulator.serviceprovider.view.LogView;
 import oic.simulator.serviceprovider.view.MetaPropertiesView;
-import oic.simulator.serviceprovider.view.MultiResourceOrchestrationView;
+import oic.simulator.serviceprovider.view.DevicePlatformInfoView;
 import oic.simulator.serviceprovider.view.ResourceManagerView;
 import oic.simulator.serviceprovider.view.ResourceObserverView;
 
@@ -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..fdebf0e
--- /dev/null
@@ -0,0 +1,266 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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) {
+        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;
+
+        if (valueType == AttributeValue.ValueType.INTEGER)
+            return new AttributeValue(Integer.parseInt(valueString));
+        else if (valueType == AttributeValue.ValueType.DOUBLE)
+            return new AttributeValue(Double.parseDouble(valueString));
+        else if (valueType == AttributeValue.ValueType.BOOLEAN)
+            return new AttributeValue(Boolean.parseBoolean(valueString));
+        else if (valueType == AttributeValue.ValueType.STRING)
+            return new AttributeValue(valueString);
+        return null;
+    }
+
+    private static String[] splitIntoArrays(String value) {
+        Vector<String> values = new Vector<String>();
+        String valueString = new String(value);
+        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) {
+            Integer[] result = new Integer[valuesString.length];
+            for (int index = 0; index < valuesString.length; index++) {
+                Integer value = (Integer) handleDepth0(valuesString[index],
+                        valueType).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++) {
+                Double value = (Double) handleDepth0(valuesString[index],
+                        valueType).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++) {
+                Boolean value = (Boolean) handleDepth0(valuesString[index],
+                        valueType).get();
+                if (null == value)
+                    return null;
+                result[index] = value;
+            }
+            return new AttributeValue(result);
+        } else if (valueType == AttributeValue.ValueType.STRING) {
+            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++) {
+                Integer[] value = (Integer[]) handleDepth1(valuesString[index],
+                        valueType).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++) {
+                Double[] value = (Double[]) handleDepth1(valuesString[index],
+                        valueType).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++) {
+                Boolean[] value = (Boolean[]) handleDepth1(valuesString[index],
+                        valueType).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++) {
+                String[] value = (String[]) handleDepth1(valuesString[index],
+                        valueType).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++) {
+                Integer[][] value = (Integer[][]) handleDepth2(
+                        valuesString[index], valueType).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++) {
+                Double[][] value = (Double[][]) handleDepth2(
+                        valuesString[index], valueType).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++) {
+                Boolean[][] value = (Boolean[][]) handleDepth2(
+                        valuesString[index], valueType).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++) {
+                String[][] value = (String[][]) handleDepth2(
+                        valuesString[index], valueType).get();
+                if (null == value)
+                    return null;
+                result[index] = value;
+            }
+            return new AttributeValue(result);
+        }
+
+        return null;
+    }
+}
index 09fecfc89569f20d2027a4bae2e8aa29fe4151ed..ef565133d6e0e5d96c6b1f239c9e50e4fe406a8f 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,146 @@ 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                                                 = "Bool";
+    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         DEVICE_NAME                                          = "Device Name";
+    public static final String         RESOURCE_UID                                         = "Resource ID";
+    public static final String         CONNECTIVITY_TYPE                                    = "Connectivity Type";
 
-    public static final int            META_PROPERTY_COUNT              = META_PROPERTIES.length;
+    public static final String[]       META_PROPERTIES                                      = {
+            RESOURCE_NAME, RESOURCE_URI, RESOURCE_TYPE                                     };
 
-    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";
+
+    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                                    = "Simple resource or Collection 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         COLLECTION_RESOURCE_BASIC_DETAILS_PAGE_TITLE1        = "Create Collection Resource";
+    public static final String         COLLECTION_RESOURCE_BASIC_DETAILS_PAGE_TITLE2        = "Create Collection Resource(Step 1 of 2)";
+    public static final String         COLLECTION_RESOURCE_BASIC_DETAILS_PAGE_MESSAGE       = "Fill basic details of the resource";
+
+    public static final String         COLLECTION_RESOURCE_ADD_OTHER_RESOURCES_PAGE_TITLE   = "Create Collection Resource(Step 2 of 2)";
+    public static final String         COLLECTION_RESOURCE_ADD_OTHER_RESOURCES_PAGE_MESSAGE = "Add other resources to this collection resource";
+
+    public static final String         CREATE_DEVICE_PAGE_TITLE                             = "Create Device";
+    public static final String         CREATE_DEVICE_PAGE_MESSAGE                           = "Create a logical device which holds a group of resources";
+
+    public static final String         DEVICE                                               = "Create Device";
+    public static final String         SINGLE_RESOURCE                                      = "Single Resource";
+    public static final String         COLLECTION_RESOURCE                                  = "Collection Resource";
 
-    public static final String         SAMPLE_LIGHT                      = "sample.light";
 }
\ No newline at end of file
index 4c053d30946667bfd7528463076305141ef3717e..73d559c798d2685dcdd01d3098cef489cc919d7f 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.HashSet;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Set;
+import java.util.Vector;
+
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.model.CollectionResource;
+import oic.simulator.serviceprovider.model.Device;
+import oic.simulator.serviceprovider.model.LocalResourceAttribute;
+import oic.simulator.serviceprovider.model.Resource;
+import oic.simulator.serviceprovider.model.SingleResource;
+
+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.SimulatorResourceAttribute;
+import org.oic.simulator.SimulatorResourceModel;
 
 /**
  * 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;
@@ -100,9 +109,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 +137,669 @@ 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 List<CollectionResource> getCollectionResourceListFromSet(
+            Set<CollectionResource> resources) {
+        if (null == resources) {
+            return null;
+        }
+        List<CollectionResource> list = new ArrayList<CollectionResource>();
+        Iterator<CollectionResource> typeItr = resources.iterator();
+        while (typeItr.hasNext()) {
+            list.add(typeItr.next());
+        }
+        return list;
+    }
+
+    public static List<Device> getDeviceListFromSet(Set<Device> devices) {
+        if (null == devices) {
+            return null;
+        }
+        List<Device> list = new ArrayList<Device>();
+        Iterator<Device> typeItr = devices.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().toString());
+        }
+        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 {
+            detail = info + "\n";
+            detail += "Exception Type: " + e.getClass().getSimpleName() + "\n";
+            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<Object> allowedValues) {
+        if (null == allowedValues || allowedValues.size() < 1) {
+            return null;
+        }
+        Vector<String> resultVec = new Vector<String>();
+        Iterator<Object> 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 (type.equals(Constants.INT)) {
+            int val;
+            Iterator<String> itr = values.iterator();
+            while (itr.hasNext()) {
+                try {
+                    val = Integer.parseInt(itr.next());
+                    resultSet.add(val);
+                } catch (NumberFormatException nfe) {
+                    // Added for safety. Nothing to do.
+                }
+            }
+        } else if (type.equals(Constants.DOUBLE)) {
+            double val;
+            Iterator<String> itr = values.iterator();
+            while (itr.hasNext()) {
+                try {
+                    val = Double.parseDouble(itr.next());
+                    resultSet.add(val);
+                } catch (NumberFormatException nfe) {
+                    // Added for safety. Nothing to do.
+                }
+            }
+        } else if (type.equals(Constants.BOOL)) {
+            resultSet.add(true);
+            resultSet.add(false);
+        } else {
+            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 List<Resource> convertCollectionTypeResourceListToBaseType(
+            List<CollectionResource> resources) {
+        if (null == resources || resources.isEmpty()) {
+            return null;
+        }
+        List<Resource> resultSet = new ArrayList<Resource>();
+        Iterator<CollectionResource> itr = resources.iterator();
+        while (itr.hasNext()) {
+            resultSet.add(itr.next());
+        }
+        return resultSet;
+    }
+
+    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<CollectionResource> collectionResourceComparator = new Comparator<CollectionResource>() {
+                                                                                  public int compare(
+                                                                                          CollectionResource res1,
+                                                                                          CollectionResource 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<Device>             deviceComparator             = new Comparator<Device>() {
+                                                                                  public int compare(
+                                                                                          Device res1,
+                                                                                          Device res2) {
+                                                                                      String s1 = res1
+                                                                                              .getDeviceName();
+                                                                                      String s2 = res2
+                                                                                              .getDeviceName();
+
+                                                                                      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.mType == ValueType.RESOURCEMODEL
+                || (type.mType == ValueType.ARRAY && type.mBaseType == ValueType.RESOURCEMODEL)
+                || (type.mType == ValueType.ARRAY && type.mDepth > 1)) {
+            return null;
+        }
+        if (type.mType == ValueType.ARRAY) {
+            if (type.mBaseType == ValueType.INTEGER) {
+                Integer[] values = (Integer[]) value;
+                if (null == values || values.length < 1) {
+                    return null;
+                }
+                List<Integer> list = new ArrayList<Integer>();
+                for (Integer i : values) {
+                    list.add(i);
+                }
+                return list.toString();
+            } else if (type.mBaseType == ValueType.DOUBLE) {
+                Double[] values = (Double[]) value;
+                if (null == values || values.length < 1) {
+                    return null;
+                }
+                List<Double> list = new ArrayList<Double>();
+                for (Double i : values) {
+                    list.add(i);
+                }
+                return list.toString();
+            } else if (type.mBaseType == ValueType.BOOLEAN) {
+                Boolean[] values = (Boolean[]) value;
+                if (null == values || values.length < 1) {
+                    return null;
+                }
+                List<Boolean> list = new ArrayList<Boolean>();
+                for (Boolean i : values) {
+                    list.add(i);
+                }
+                return list.toString();
+            } else if (type.mBaseType == ValueType.STRING) {
+                String[] values = (String[]) value;
+                if (null == values || values.length < 1) {
+                    return null;
+                }
+                List<String> list = new ArrayList<String>();
+                for (String i : values) {
+                    list.add(i);
+                }
+                return list.toString();
+            } else {
+                return null;
+            }
+        } else {
+            return String.valueOf(value);
+        }
+    }
+
+    public static List<LocalResourceAttribute> getDummyAttributes() {
+        List<LocalResourceAttribute> attributes = null;
+        attributes = new ArrayList<LocalResourceAttribute>();
+
+        // Integer attribute
+        SimulatorResourceAttribute attribute = new SimulatorResourceAttribute(
+                "integer", new AttributeValue(2), null);
+        attributes.add(addAttribute(attribute));
+
+        // Boolean attribute
+        attribute = new SimulatorResourceAttribute("boolean",
+                new AttributeValue(false), null);
+        attributes.add(addAttribute(attribute));
+
+        // String attribute
+        attribute = new SimulatorResourceAttribute("string",
+                new AttributeValue("india"), null);
+        attributes.add(addAttribute(attribute));
+
+        // Integer array attribute
+        int iarr[] = { 1, 2, 3 };
+        attribute = new SimulatorResourceAttribute("integerArr",
+                new AttributeValue(iarr), null);
+        attributes.add(addAttribute(attribute));
+
+        // Double array attribute
+        double darr[] = { 1.5, 2.51, 3.15 };
+        attribute = new SimulatorResourceAttribute("doubleArr",
+                new AttributeValue(darr), null);
+        attributes.add(addAttribute(attribute));
+
+        // Boolean array attribute
+        boolean barr[] = { false, true, false };
+        attribute = new SimulatorResourceAttribute("boolArr",
+                new AttributeValue(barr), null);
+        attributes.add(addAttribute(attribute));
+
+        // String array attribute
+        String sarr[] = { "senthil", "muruga", "sriram" };
+        attribute = new SimulatorResourceAttribute("stringArr",
+                new AttributeValue(sarr), null);
+        attributes.add(addAttribute(attribute));
+
+        // Model type complex attribute
+        attribute = new SimulatorResourceAttribute("subAtt1",
+                new AttributeValue("chennai"), null);
+        SimulatorResourceModel model = new SimulatorResourceModel();
+        try {
+            model.addAttribute(attribute);
+        } catch (InvalidArgsException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
+        attribute = new SimulatorResourceAttribute("subAtt2",
+                new AttributeValue("madurai"), null);
+        try {
+            model.addAttribute(attribute);
+        } catch (InvalidArgsException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
+
+        SimulatorResourceModel subModel = new SimulatorResourceModel();
+        try {
+            subModel.addAttribute(attribute);
+        } catch (InvalidArgsException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
+        attribute = new SimulatorResourceAttribute("modelsubAtt3",
+                new AttributeValue(subModel), null);
+        try {
+            model.addAttribute(attribute);
+        } catch (InvalidArgsException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
+
+        SimulatorResourceAttribute modelAtt = new SimulatorResourceAttribute(
+                "modelAtt1", new AttributeValue(model));
+        attributes.add(addAttribute(modelAtt));
+
+        // 1-D array of model
+        attribute = new SimulatorResourceAttribute("subAtt1",
+                new AttributeValue("chennai"), null);
+        SimulatorResourceModel[] modelArr = new SimulatorResourceModel[2];
+        model = new SimulatorResourceModel();
+        try {
+            model.addAttribute(attribute);
+            modelArr[0] = model;
+        } catch (InvalidArgsException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
+        attribute = new SimulatorResourceAttribute("subAtt2",
+                new AttributeValue("madurai"), null);
+        model = new SimulatorResourceModel();
+        try {
+            model.addAttribute(attribute);
+            modelArr[1] = model;
+        } catch (InvalidArgsException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
+        modelAtt = new SimulatorResourceAttribute("modelAtt2",
+                new AttributeValue(modelArr));
+        attributes.add(addAttribute(modelAtt));
+
+        return attributes;
+    }
+
+    private static LocalResourceAttribute addAttribute(
+            SimulatorResourceAttribute att) {
+        LocalResourceAttribute localAtt = new LocalResourceAttribute();
+
+        localAtt = new LocalResourceAttribute();
+
+        localAtt.setResourceAttributeRef(att);
+
+        // Initially disabling the automation
+        localAtt.setAutomationInProgress(false);
+
+        // Assigning the default automation interval
+        localAtt.setAutomationUpdateInterval(Constants.DEFAULT_AUTOMATION_INTERVAL);
+
+        // Setting the default automation type
+        localAtt.setAutomationType(Constants.DEFAULT_AUTOMATION_TYPE);
+
+        return localAtt;
+    }
+
 }
\ No newline at end of file
index 5b8e2995d734f5aacd18dc47f18daaaf4a9cc25d..1544fb6a1d6461a982376561856e0959aee6ad39 100644 (file)
@@ -20,9 +20,13 @@ 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.model.AutomationSettingHelper;
+import oic.simulator.serviceprovider.model.CollectionResource;
+import oic.simulator.serviceprovider.model.LocalResourceAttribute;
+import oic.simulator.serviceprovider.model.Resource;
+import oic.simulator.serviceprovider.model.SRMItem;
+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;
 
@@ -31,7 +35,8 @@ 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.IStructuredSelection;
+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 +44,16 @@ 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.Tree;
+import org.eclipse.swt.widgets.TreeItem;
+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.InvalidArgsException;
+import org.oic.simulator.SimulatorResourceAttribute;
+import org.oic.simulator.SimulatorResourceModel;
+import org.oic.simulator.server.SimulatorResource.AutoUpdateType;
 
 /**
  * This class provides editing support to the resources attributes table in the
@@ -50,23 +64,22 @@ public class AttributeEditingSupport {
     private AttributeValueEditor attValueEditor;
     private AutomationEditor     automationEditor;
 
-    public AttributeValueEditor createAttributeValueEditor(TableViewer viewer) {
+    public AttributeValueEditor createAttributeValueEditor(TreeViewer viewer) {
         attValueEditor = new AttributeValueEditor(viewer);
         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;
 
-        public AttributeValueEditor(TableViewer viewer) {
+        public AttributeValueEditor(TreeViewer viewer) {
             super(viewer);
             this.viewer = viewer;
         }
@@ -77,49 +90,130 @@ 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 a collection, then editor support is not
+            // required.
+            if (res instanceof CollectionResource) {
+                return null;
+            }
+
+            final SimulatorResourceAttribute att;
+            if (element instanceof SimulatorResourceAttribute
+                    || element instanceof LocalResourceAttribute) {
+                if (element instanceof LocalResourceAttribute) {
+                    LocalResourceAttribute localAtt = (LocalResourceAttribute) element;
+                    att = localAtt.getResourceAttributeRef();
+                } else {
+                    att = (SimulatorResourceAttribute) element;
+                }
+            } else {
+                return null;
+            }
+
+            if (null == att) {
+                return null;
+            }
+
+            final AttributeValue val = att.value();
+            if (null == val) {
+                return null;
+            }
+
+            final TypeInfo type = val.typeInfo();
+            if (type.mType == ValueType.RESOURCEMODEL
+                    || (type.mType == ValueType.ARRAY && type.mBaseType == ValueType.RESOURCEMODEL)) {
+                return null;
+            }
+
+            AttributeProperty prop = att.property();
+            if (null == prop) {
+                return null;
+            }
+
+            if (!resourceManager.isAttHasRangeOrAllowedValues(att)) {
+                return null;
+            }
 
             // CellEditor is not required as the automation is in progress.
-            if (attributeInSelection.isAutomationInProgress()) {
+            if (element instanceof LocalResourceAttribute
+                    && ((LocalResourceAttribute) element)
+                            .isAutomationInProgress()) {
                 return null;
             }
 
             String values[] = null;
-            List<String> valueSet = attributeInSelection.getAttValues();
+            List<String> valueSet = resourceManager
+                    .getAllValuesOfAttribute(att);
             values = convertListToStringArray(valueSet);
 
-            ComboBoxCellEditor comboEditor = new ComboBoxCellEditor(
-                    viewer.getTable(), values, SWT.READ_ONLY);
+            ComboBoxCellEditor comboEditor;
+            if (type.mType == ValueType.ARRAY) {
+                comboEditor = new ComboBoxCellEditor(viewer.getTree(), values);
+            } else {
+                comboEditor = new ComboBoxCellEditor(viewer.getTree(), values,
+                        SWT.READ_ONLY);
+            }
             comboBox = (CCombo) comboEditor.getControl();
             comboBox.addModifyListener(new ModifyListener() {
 
                 @Override
                 public void modifyText(ModifyEvent event) {
-                    String oldValue = String.valueOf(attributeInSelection
-                            .getAttributeValue());
+                    if (type.mType == ValueType.ARRAY) {
+                        return;
+                    }
+                    String oldValue = String.valueOf(Utility
+                            .getAttributeValueAsString(val));
                     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);
+                        // Get the AttriuteValue from the string
+                        AttributeValue value = AttributeValueBuilder.build(
+                                newValue, type.mBaseType);
+                        TypeInfo resTypeInfo = value.typeInfo();
+                        if (null == value || type.mDepth != resTypeInfo.mDepth
+                                || type.mType != resTypeInfo.mType
+                                || type.mBaseType != resTypeInfo.mBaseType) {
+                            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 {
-                            ResourceManager resourceManager;
-                            resourceManager = Activator.getDefault()
-                                    .getResourceManager();
-                            SimulatorResource resource = resourceManager
-                                    .getCurrentResourceInSelection();
-                            resourceManager.attributeValueUpdated(resource,
-                                    attributeInSelection.getAttributeName(),
-                                    newValue);
+                            updateAttributeValue(att, value);
+                            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) {
+                                value = AttributeValueBuilder.build(oldValue,
+                                        type.mBaseType);
+                                updateAttributeValue(att, value);
+                            } else {
+                                ResourceManager resourceManager;
+                                resourceManager = Activator.getDefault()
+                                        .getResourceManager();
+
+                                Resource resource = resourceManager
+                                        .getCurrentResourceInSelection();
+
+                                AttributeValue resultValue = getResultantValue(value);
+
+                                resourceManager.attributeValueUpdated(
+                                        (SingleResource) resource, att.name(),
+                                        resultValue);
+
+                            }
                         }
-                        viewer.update(attributeInSelection, null);
+                        viewer.update(element, null);
                         comboBox.setVisible(false);
                     }
                 }
@@ -130,9 +224,23 @@ public class AttributeEditingSupport {
         @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;
+
+            if (element instanceof LocalResourceAttribute) {
+                LocalResourceAttribute localAtt = (LocalResourceAttribute) element;
+                att = localAtt.getResourceAttributeRef();
+                if (null == att) {
+                    return 0;
+                }
+            } else if (element instanceof SimulatorResourceAttribute) {
+                att = (SimulatorResourceAttribute) element;
+            } else {
+                return 0;
+            }
+
+            String valueString = Utility.getAttributeValueAsString(att.value());
+            List<String> valueSet = Activator.getDefault().getResourceManager()
+                    .getAllValuesOfAttribute(att);
             if (null != valueSet) {
                 indexOfItem = valueSet.indexOf(valueString);
             }
@@ -144,11 +252,81 @@ public class AttributeEditingSupport {
 
         @Override
         protected void setValue(Object element, Object value) {
-            Object valueObj = attributeInSelection.getAttributeValue();
-            if (null == valueObj)
+            SimulatorResourceAttribute att;
+
+            if (element instanceof LocalResourceAttribute) {
+                LocalResourceAttribute localAtt = (LocalResourceAttribute) element;
+                att = localAtt.getResourceAttributeRef();
+                if (null == att) {
+                    return;
+                }
+            } else if (element instanceof SimulatorResourceAttribute) {
+                att = (SimulatorResourceAttribute) element;
+            } else {
+                return;
+            }
+
+            AttributeValue val = att.value();
+            if (null == val) {
                 return;
-            String attValue = String.valueOf(valueObj);
-            ((LocalResourceAttribute) element).setAttributeValue(attValue);
+            }
+            TypeInfo type = val.typeInfo();
+            if (type.mType == ValueType.ARRAY) {
+                int index;
+                try {
+                    index = Integer.parseInt(String.valueOf(value));
+                } catch (NumberFormatException nfe) {
+                    index = -1;
+                }
+                if (index == -1) {
+                    String oldValue = String.valueOf(Utility
+                            .getAttributeValueAsString(val));
+                    String newValue = comboBox.getText();
+                    if (!oldValue.equals(newValue)) {
+                        // Get the AttriuteValue from the string
+                        AttributeValue attValue = AttributeValueBuilder.build(
+                                newValue, type.mBaseType);
+                        TypeInfo resTypeInfo = attValue.typeInfo();
+                        if (null == attValue
+                                || type.mDepth != resTypeInfo.mDepth
+                                || type.mType != resTypeInfo.mType
+                                || type.mBaseType != resTypeInfo.mBaseType) {
+                            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(att, attValue);
+                            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) {
+                                attValue = AttributeValueBuilder.build(
+                                        oldValue, type.mBaseType);
+                                updateAttributeValue(att, attValue);
+                            } else {
+                                ResourceManager resourceManager;
+                                resourceManager = Activator.getDefault()
+                                        .getResourceManager();
+
+                                Resource resource = resourceManager
+                                        .getCurrentResourceInSelection();
+
+                                AttributeValue resultValue = getResultantValue(attValue);
+
+                                resourceManager.attributeValueUpdated(
+                                        (SingleResource) resource, att.name(),
+                                        resultValue);
+                            }
+                        }
+                    }
+                }
+            }
+
             viewer.update(element, null);
         }
 
@@ -161,13 +339,119 @@ public class AttributeEditingSupport {
             }
             return strArr;
         }
+
+        public void updateAttributeValue(SimulatorResourceAttribute att,
+                AttributeValue value) {
+            att.setValue(value);
+
+            IStructuredSelection selection = (IStructuredSelection) viewer
+                    .getSelection();
+            if (null == selection) {
+                return;
+            }
+
+            Object obj = selection.getFirstElement();
+            if (null == obj) {
+                return;
+            }
+
+            Tree t = viewer.getTree();
+            TreeItem item = t.getSelection()[0];
+            if (null == item) {
+                return;
+            }
+            TreeItem parent = item.getParentItem();
+
+            // Get the parent model
+            if (null == parent) {
+                // Top-level attribute
+                Resource res = Activator.getDefault().getResourceManager()
+                        .getCurrentResourceInSelection();
+                if (null == res) {
+                    return;
+                }
+                SimulatorResourceModel model = res.getResourceModel();
+                if (null == model) {
+                    return;
+                }
+                try {
+                    model.setAttributeValue(att.name(), value);
+                } catch (InvalidArgsException e) {
+                    // TODO Auto-generated catch block
+                    e.printStackTrace();
+                }
+            } else {
+                SimulatorResourceModel model;
+                Object data = parent.getData();
+                if (null == data) {
+                    return;
+                }
+                if (data instanceof SRMItem) {
+                    model = ((SRMItem) data).getModel();
+                } else {
+                    SimulatorResourceAttribute parentAtt;
+                    if (data instanceof LocalResourceAttribute) {
+                        parentAtt = ((LocalResourceAttribute) data)
+                                .getResourceAttributeRef();
+                    } else {
+                        parentAtt = (SimulatorResourceAttribute) data;
+                    }
+                    model = (SimulatorResourceModel) parentAtt.value().get();
+                }
+                try {
+                    model.setAttributeValue(att.name(), value);
+                } catch (InvalidArgsException e) {
+                    // TODO Auto-generated catch block
+                    e.printStackTrace();
+                }
+            }
+        }
+
+        public AttributeValue getResultantValue(AttributeValue newValue) {
+            AttributeValue val = null;
+            IStructuredSelection selection = (IStructuredSelection) viewer
+                    .getSelection();
+            if (null == selection) {
+                return null;
+            }
+
+            Object obj = selection.getFirstElement();
+            if (null == obj) {
+                return null;
+            }
+
+            Tree t = viewer.getTree();
+            TreeItem item = t.getSelection()[0];
+            if (null == item) {
+                return null;
+            }
+
+            TreeItem parent = item.getParentItem();
+            if (null == parent) {
+                Object data = item.getData();
+                // SimulatorResourceAttribute att =
+                // ((LocalResourceAttribute)data).getResourceAttributeRef();
+                val = newValue;
+            } else {
+                while (parent.getParentItem() != null) {
+                    parent = parent.getParentItem();
+                }
+                // Parent will point to the top-level attribute of type
+                // LocalResourceAttribute
+                Object data = parent.getData();
+                val = ((LocalResourceAttribute) data).getResourceAttributeRef()
+                        .value();
+            }
+
+            return val;
+        }
     }
 
     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,11 +466,41 @@ 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 CollectionResource) {
+                return null;
+            }
+            if (((SingleResource) resource).isResourceAutomationInProgress()) {
+                return null;
+            }
+
+            SimulatorResourceAttribute att = null;
+            if (element instanceof LocalResourceAttribute) {
+                LocalResourceAttribute localAtt = (LocalResourceAttribute) element;
+                att = localAtt.getResourceAttributeRef();
+            }
+
+            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;
+            }
+
             return new CheckboxCellEditor(null, SWT.CHECK | SWT.READ_ONLY);
         }
 
@@ -202,8 +516,7 @@ public class AttributeEditingSupport {
                     .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;
             }
@@ -219,18 +532,18 @@ 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",
@@ -241,7 +554,7 @@ public class AttributeEditingSupport {
                 }
             } else {
                 // Stop the automation
-                resourceManager.stopAutomation(resource, att,
+                resourceManager.stopAutomation((SingleResource) resource, att,
                         att.getAutomationId());
                 MessageDialog.openInformation(Display.getDefault()
                         .getActiveShell(), "Automation Status",
index d4443b4f84905c317f539af25b9dc72f7d0abda3..f81bda6d73f0b79b553176445f8640a4fa7aa3a8 100644 (file)
 package oic.simulator.serviceprovider.view;
 
 import java.util.List;
-import java.util.Set;
+import java.util.Map;
 
 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.listener.ISelectionChangedUIListener;
 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.manager.UiListenerHandler;
+import oic.simulator.serviceprovider.model.CollectionResource;
+import oic.simulator.serviceprovider.model.Device;
+import oic.simulator.serviceprovider.model.LocalResourceAttribute;
+import oic.simulator.serviceprovider.model.Resource;
+import oic.simulator.serviceprovider.model.SRMItem;
+import oic.simulator.serviceprovider.model.SingleResource;
 import oic.simulator.serviceprovider.utils.Constants;
+import oic.simulator.serviceprovider.utils.Utility;
 
-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.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.jface.viewers.ViewerCell;
 import org.eclipse.swt.SWT;
 import org.eclipse.swt.graphics.Color;
 import org.eclipse.swt.graphics.Image;
@@ -44,81 +48,90 @@ 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.Tree;
+import org.eclipse.swt.widgets.TreeColumn;
 import org.eclipse.ui.part.ViewPart;
+import org.oic.simulator.AttributeValue;
+import org.oic.simulator.AttributeValue.TypeInfo;
+import org.oic.simulator.AttributeValue.ValueType;
+import org.oic.simulator.SimulatorResourceAttribute;
+import org.oic.simulator.SimulatorResourceModel;
 
 /**
  * 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 ISelectionChangedUIListener     resourceSelectionChangedListener;
+    private IResourceModelChangedUIListener resourceModelChangedUIListener;
+    private IAutomationUIListener           automationUIListener;
 
-    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 ISelectionChangedUIListener() {
 
             @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 != attViewer) {
+                            updateViewer(getData(resource));
+                            Tree tree = attViewer.getTree();
+                            if (!tree.isDisposed()) {
                                 if (null != resource
-                                        && resource
-                                                .isResourceAutomationInProgress()) {
-                                    tbl.setEnabled(false);
+                                        && (resource instanceof SingleResource && ((SingleResource) resource)
+                                                .isResourceAutomationInProgress())) {
+                                    tree.setEnabled(false);
                                 } else {
-                                    tbl.setEnabled(true);
+                                    tree.setEnabled(true);
                                 }
                             }
                         }
                     }
                 });
             }
+
+            @Override
+            public void onDeviceSelectionChange(Device dev) {
+                Display.getDefault().asyncExec(new Runnable() {
+                    @Override
+                    public void run() {
+                        updateViewer(null);
+                    }
+                });
+            }
         };
 
         resourceModelChangedUIListener = new IResourceModelChangedUIListener() {
 
             @Override
-            public void onResourceModelChange(
-                    final ModelChangeNotificationType notificationType,
-                    final String resourceURI,
-                    final Set<LocalResourceAttribute> valueChangeSet) {
+            public void onResourceModelChange(final Resource resource) {
                 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
+                        Resource resourceInSelection = resourceManager
                                 .getCurrentResourceInSelection();
-                        if (null == resource) {
+                        if (null == resourceInSelection) {
                             return;
                         }
-                        if (!resourceURI.equals(resource.getResourceURI())) {
+                        if (resource != resourceInSelection) {
                             // This notification is for a different resource
                             // whose attributes are not
                             // currently not being shown in UI. So ignoring this
@@ -127,17 +140,11 @@ public class AttributeView extends ViewPart {
                         }
                         // 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);
-                                }
+                        if (null != attViewer) {
+                            if (resource instanceof CollectionResource) {
+                                updateViewer(getData(resource));
+                            } else {
+                                updateViewer(getData(resource));
                             }
                         }
                     }
@@ -148,33 +155,32 @@ public class AttributeView extends ViewPart {
         automationUIListener = new IAutomationUIListener() {
 
             @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) {
                             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()) {
+                                attViewer.refresh();
 
                                 // Disabling the table to prevent interactions
                                 // during the automation
-                                tbl.setEnabled(false);
-                                tbl.deselectAll();
+                                tree.setEnabled(false);
+                                tree.deselectAll();
                             }
                         }
                     }
@@ -182,7 +188,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,40 +196,39 @@ 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 (null == resourceInSelection) {
                             return;
                         }
-                        String uri = resource.getResourceURI();
-                        if (null == uri || !uri.equals(resourceURI)) {
+                        if (resource != resourceInSelection) {
                             return;
                         }
-                        Table tbl;
-                        tbl = attTblViewer.getTable();
-                        if (!tbl.isDisposed()) {
+                        Tree tree;
+                        tree = attViewer.getTree();
+                        if (!tree.isDisposed()) {
                             if (null != attName) {
                                 // Attribute level automation has stopped
                                 LocalResourceAttribute att = resourceManager
-                                        .getAttributeByResourceURI(resourceURI,
+                                        .getAttributeByResourceURI(resource,
                                                 attName);
                                 if (null == att) {
                                     return;
                                 } else {
-                                    attTblViewer.update(att, null);
+                                    attViewer.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.setEnabled(true);
+                                attViewer.refresh();
                             }
                         }
                     }
@@ -247,114 +252,74 @@ 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);
+
+        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());
 
         addManagerListeners();
 
         // Check whether there is any resource selected already
-        List<LocalResourceAttribute> propertyList = getData();
+        List<LocalResourceAttribute> propertyList = getData(resourceManager
+                .getCurrentResourceInSelection());
         if (null != propertyList) {
             updateViewer(propertyList);
         }
     }
 
-    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());
-                    }
-                }
-            }
-        });
-
-        TableViewerColumn attValue = new TableViewerColumn(tableViewer,
-                SWT.NONE);
-        attValue.getColumn().setWidth(attTblColWidth[1]);
-        attValue.getColumn().setText(attTblHeaders[1]);
-        attValue.setLabelProvider(new ColumnLabelProvider() {
-            @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);
-                        }
-                    }
-                }
-                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() {
-            @Override
-            public String getText(Object element) {
-                LocalResourceAttribute att = (LocalResourceAttribute) element;
-                if (att.isAutomationInProgress()) {
-                    return Constants.ENABLED;
-                }
-                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);
-                }
-            }
-        });
-        automation.setEditingSupport(attributeEditor
-                .createAutomationEditor(attTblViewer));
+        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));
+
+        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));
     }
 
     private void addManagerListeners() {
-        resourceManager
-                .addResourceSelectionChangedUIListener(resourceSelectionChangedListener);
-        resourceManager
-                .addResourceModelChangedUIListener(resourceModelChangedUIListener);
-        resourceManager.addAutomationUIListener(automationUIListener);
+        UiListenerHandler.getInstance().addResourceSelectionChangedUIListener(
+                resourceSelectionChangedListener);
+        UiListenerHandler.getInstance().addResourceModelChangedUIListener(
+                resourceModelChangedUIListener);
+        UiListenerHandler.getInstance().addAutomationUIListener(
+                automationUIListener);
     }
 
-    private List<LocalResourceAttribute> getData() {
-        SimulatorResource resourceInSelection = resourceManager
-                .getCurrentResourceInSelection();
-        if (null != resourceInSelection) {
+    private List<LocalResourceAttribute> getData(Resource resource) {
+        if (null != resource) {
             List<LocalResourceAttribute> attList = resourceManager
-                    .getAttributes(resourceInSelection);
+                    .getAttributes((Resource) resource);
+            // List<LocalResourceAttribute> attList =
+            // Utility.getDummyAttributes();
             return attList;
         } else {
             return null;
@@ -362,27 +327,25 @@ public class AttributeView extends ViewPart {
     }
 
     private void updateViewer(List<LocalResourceAttribute> attList) {
-        Table tbl;
+        Tree tree = attViewer.getTree();;
         if (null != attList) {
-            tbl = attTblViewer.getTable();
-            if (null != tbl && !tbl.isDisposed()) {
-                tbl.setLinesVisible(true);
-                attTblViewer.setInput(attList.toArray());
+            if (null != tree && !tree.isDisposed()) {
+                tree.setLinesVisible(true);
+                attViewer.setInput(attList.toArray());
             }
         } else {
             // Clear the attributes table viewer
-            if (null != attTblViewer) {
-                tbl = attTblViewer.getTable();
-                if (null != tbl && !tbl.isDisposed()) {
+            if (null != attViewer) {
+                if (null != tree && !tree.isDisposed()) {
                     // tbl.deselectAll();
-                    tbl.removeAll();
-                    tbl.setLinesVisible(false);
+                    tree.removeAll();
+                    tree.setLinesVisible(false);
                 }
             }
         }
     }
 
-    class AttributeContentProvider implements IStructuredContentProvider {
+    class AttributeContentProvider implements ITreeContentProvider {
 
         @Override
         public void dispose() {
@@ -392,9 +355,249 @@ public class AttributeView extends ViewPart {
         public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
         }
 
+        @Override
+        public Object[] getChildren(Object element) {
+            if (element instanceof SimulatorResourceAttribute
+                    || element instanceof LocalResourceAttribute) {
+                SimulatorResourceAttribute att;
+                if (element instanceof LocalResourceAttribute) {
+                    LocalResourceAttribute localAtt = (LocalResourceAttribute) element;
+                    att = localAtt.getResourceAttributeRef();
+                    if (null == att) {
+                        return new Object[1];
+                    }
+                } else {
+                    att = (SimulatorResourceAttribute) element;
+                }
+                AttributeValue val = att.value();
+                if (null == val) {
+                    return new Object[1];
+                }
+                TypeInfo type = val.typeInfo();
+                if (type.mType == ValueType.RESOURCEMODEL) {
+                    SimulatorResourceModel model = (SimulatorResourceModel) val
+                            .get();
+                    if (null == model) {
+                        return new Object[1];
+                    }
+                    return resourceManager.getAttributes(model).toArray();
+                } else if (type.mType == ValueType.ARRAY
+                        && type.mBaseType == ValueType.RESOURCEMODEL
+                        && type.mDepth == 1) {
+                    SimulatorResourceModel[] model = (SimulatorResourceModel[]) val
+                            .get();
+                    if (null == model || model.length < 1) {
+                        return new Object[1];
+                    }
+                    return resourceManager.getIndexedAttributes(model)
+                            .toArray();
+                }
+            } else if (element instanceof SRMItem) {
+                SRMItem item = (SRMItem) element;
+                SimulatorResourceModel model = (SimulatorResourceModel) item
+                        .getModel();
+                if (null == model) {
+                    return new Object[1];
+                }
+                return resourceManager.getAttributes(model).toArray();
+            }
+            return new Object[1];
+        }
+
         @Override
         public Object[] getElements(Object element) {
-            return (Object[]) element;
+            Object[] elements = (Object[]) element;
+            return elements;
+        }
+
+        @Override
+        public Object getParent(Object element) {
+            return null;
+        }
+
+        @Override
+        public boolean hasChildren(Object element) {
+            if (element instanceof SimulatorResourceAttribute
+                    || element instanceof LocalResourceAttribute) {
+                SimulatorResourceAttribute att;
+                if (element instanceof LocalResourceAttribute) {
+                    LocalResourceAttribute localAtt = (LocalResourceAttribute) element;
+                    att = localAtt.getResourceAttributeRef();
+                    if (null == att) {
+                        return false;
+                    }
+                } else {
+                    att = (SimulatorResourceAttribute) element;
+                }
+                AttributeValue val = att.value();
+                if (null == val) {
+                    return false;
+                }
+                TypeInfo type = val.typeInfo();
+                if (type.mType == ValueType.RESOURCEMODEL) {
+                    SimulatorResourceModel model = (SimulatorResourceModel) val
+                            .get();
+                    if (null == model) {
+                        return false;
+                    }
+                    Map<String, SimulatorResourceAttribute> attributes = model
+                            .getAttributes();
+                    if (null != attributes && attributes.size() > 0) {
+                        return true;
+                    }
+                } else if (type.mType == ValueType.ARRAY
+                        && type.mBaseType == ValueType.RESOURCEMODEL
+                        && type.mDepth == 1) {
+                    SimulatorResourceModel[] model = (SimulatorResourceModel[]) val
+                            .get();
+                    if (null != model && model.length > 0) {
+                        return true;
+                    }
+                }
+            } else if (element instanceof SRMItem) {
+                SRMItem srmItem = (SRMItem) element;
+                SimulatorResourceModel model = srmItem.getModel();
+                if (null == model) {
+                    return false;
+                }
+                Map<String, SimulatorResourceAttribute> attributes = model
+                        .getAttributes();
+                if (null != attributes && attributes.size() > 0) {
+                    return true;
+                }
+            }
+            return false;
+        }
+    }
+
+    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) {
+            if (col == 2) {
+                if (element instanceof SimulatorResourceAttribute
+                        || element instanceof LocalResourceAttribute) {
+                    SimulatorResourceAttribute att;
+                    if (element instanceof LocalResourceAttribute) {
+                        LocalResourceAttribute localAtt = (LocalResourceAttribute) element;
+                        att = localAtt.getResourceAttributeRef();
+                    } else {
+                        att = (SimulatorResourceAttribute) element;
+                    }
+                    AttributeValue val = att.value();
+                    if (null == val) {
+                        return null;
+                    }
+                    TypeInfo type = val.typeInfo();
+                    if (type.mType == ValueType.RESOURCEMODEL
+                            || type.mType == ValueType.ARRAY) {
+                        return null;
+                    }
+                    if (element instanceof LocalResourceAttribute) {
+                        if (!resourceManager.isAttHasRangeOrAllowedValues(att)) {
+                            System.out.println("No range or allowed values");
+                            return null;
+                        }
+                        if (((LocalResourceAttribute) element)
+                                .isAutomationInProgress()) {
+                            return Activator.getDefault().getImageRegistry()
+                                    .get(Constants.CHECKED);
+                        }
+                        return Activator.getDefault().getImageRegistry()
+                                .get(Constants.UNCHECKED);
+                    }
+                    return null;
+                }
+            }
+            return null;
+        }
+
+        @Override
+        public String getColumnText(Object element, int col) {
+            if (element instanceof SimulatorResourceAttribute
+                    || element instanceof LocalResourceAttribute) {
+                SimulatorResourceAttribute att;
+                if (element instanceof LocalResourceAttribute) {
+                    LocalResourceAttribute localAtt = (LocalResourceAttribute) element;
+                    att = localAtt.getResourceAttributeRef();
+                } else {
+                    att = (SimulatorResourceAttribute) element;
+                }
+                AttributeValue val = att.value();
+                if (null == val) {
+                    return "";
+                }
+                TypeInfo type = val.typeInfo();
+                switch (col) {
+                    case 0:
+                        return att.name();
+                    case 1:
+                        if (!(type.mType == ValueType.RESOURCEMODEL || (type.mType == ValueType.ARRAY && type.mBaseType == ValueType.RESOURCEMODEL))) {
+                            String value = Utility
+                                    .getAttributeValueAsString(val);
+                            if (null == value) {
+                                value = "";
+                            }
+                            return value;
+                        } else {
+                            return "";
+                        }
+                    case 2:
+                        Resource res = resourceManager
+                                .getCurrentResourceInSelection();
+                        if (null != res && res instanceof CollectionResource) {
+                            return "-";
+                        }
+
+                        if (type.mType == ValueType.RESOURCEMODEL
+                                || type.mType == ValueType.ARRAY) {
+                            return "";
+                        }
+                        if (element instanceof LocalResourceAttribute) {
+                            if (!resourceManager
+                                    .isAttHasRangeOrAllowedValues(att)) {
+                                System.out
+                                        .println("No range or allowed values");
+                                return "Read Only";
+                            }
+                            if (((LocalResourceAttribute) element)
+                                    .isAutomationInProgress()) {
+                                return Constants.ENABLED;
+                            }
+                            return Constants.DISABLED;
+                        }
+                        return "NA";
+                }
+            } else if (element instanceof SRMItem) {
+                SRMItem item = (SRMItem) element;
+                switch (col) {
+                    case 0:
+                        return "[" + item.getIndex() + "]";
+                    case 1:
+                        return "";
+                    case 2:
+                        return "";
+                }
+            }
+            return null;
         }
 
     }
@@ -403,19 +606,22 @@ 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);
+            UiListenerHandler.getInstance()
+                    .removeResourceModelChangedUIListener(
+                            resourceModelChangedUIListener);
         }
 
         // 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..b8ebf77
--- /dev/null
@@ -0,0 +1,377 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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 java.util.List;
+
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.model.MetaProperty;
+
+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.Label;
+import org.eclipse.swt.widgets.Table;
+import org.eclipse.swt.widgets.Text;
+import org.eclipse.ui.part.ViewPart;
+
+/**
+ * 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 };
+
+    private List<MetaProperty> metaProperties;
+
+    private boolean            enable_edit;
+
+    private Text               deviceNameTxt;
+    private Button             devEditBtn;
+    private Button             devCancelBtn;
+    private Button             platEditBtn;
+    private Button             platCancelBtn;
+
+    private TableViewer        platformTblViewer;
+
+    private CTabFolder         folder;
+    private CTabItem           devicePropTab;
+    private CTabItem           platformPropTab;
+
+    @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);
+
+        metaProperties = getPlatformPropData();
+
+        updateViewer(metaProperties);
+    }
+
+    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);
+        gd.horizontalIndent = 5;
+        gd.verticalIndent = 5;
+        propGroup.setLayoutData(gd);
+
+        Label devNameLbl = new Label(propGroup, SWT.NULL);
+        devNameLbl.setText("Device Name");
+        gd = new GridData();
+        gd.horizontalAlignment = SWT.FILL;
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalSpan = 2;
+        devNameLbl.setLayoutData(gd);
+
+        deviceNameTxt = new Text(propGroup, SWT.BORDER);
+        deviceNameTxt.setText(Activator.getDefault().getResourceManager()
+                .getDeviceName());
+        gd = new GridData();
+        gd.horizontalAlignment = SWT.FILL;
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalSpan = 2;
+        deviceNameTxt.setLayoutData(gd);
+        deviceNameTxt.setEnabled(false);
+
+        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")) {
+                    deviceNameTxt.setEnabled(true);
+                    devCancelBtn.setEnabled(true);
+
+                    deviceNameTxt.selectAll();
+                    deviceNameTxt.setFocus();
+                    devEditBtn.setText("Save");
+                } else {
+                    String devName = deviceNameTxt.getText();
+                    if (null == devName || devName.trim().length() < 1) {
+                        MessageDialog.openError(Display.getDefault()
+                                .getActiveShell(), "Invalid Device Name",
+                                "Device name is Invalid!!");
+                        deviceNameTxt.setFocus();
+                        return;
+                    }
+                    Activator.getDefault().getResourceManager()
+                            .setDeviceName(devName);
+                    deviceNameTxt.setEnabled(false);
+                    devCancelBtn.setEnabled(false);
+                    devEditBtn.setText("Edit");
+                }
+            }
+        });
+
+        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) {
+                deviceNameTxt.setText(Activator.getDefault()
+                        .getResourceManager().getDeviceName());
+                deviceNameTxt.setEnabled(false);
+                devCancelBtn.setEnabled(false);
+                devEditBtn.setText("Edit");
+            }
+        });
+
+        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);
+
+        // 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");
+                    enable_edit = true;
+                } else {
+                    Activator.getDefault().getResourceManager()
+                            .setPlatformInfo(metaProperties);
+                    platCancelBtn.setEnabled(false);
+                    platEditBtn.setText("Edit");
+                    enable_edit = false;
+                }
+            }
+        });
+
+        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) {
+                metaProperties = getPlatformPropData();
+                updateViewer(metaProperties);
+
+                platCancelBtn.setEnabled(false);
+                platEditBtn.setText("Edit");
+                enable_edit = false;
+            }
+        });
+
+        platformPropTab.setControl(propGroup);
+    }
+
+    public void createColumns(TableViewer tableViewer) {
+        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 "";
+                }
+            }
+        });
+        propValue.setEditingSupport(new PropValueEditor(platformTblViewer));
+    }
+
+    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 void updateViewer(List<MetaProperty> metaPropertyList) {
+        if (null != platformTblViewer) {
+            Table tbl = platformTblViewer.getTable();
+            if (null != metaPropertyList) {
+                platformTblViewer.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;
+
+        public PropValueEditor(TableViewer viewer) {
+            super(viewer);
+            this.viewer = viewer;
+        }
+
+        @Override
+        protected boolean canEdit(Object element) {
+            return true;
+        }
+
+        @Override
+        protected CellEditor getCellEditor(Object element) {
+            if (!enable_edit) {
+                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 8f8ff185c224813018f063b2cbeb1051ffde7c3c..c8f6668ea559821c3ee11c9fb339b0302e93c91a 100644 (file)
@@ -19,57 +19,92 @@ package oic.simulator.serviceprovider.view;
 import java.util.List;
 
 import oic.simulator.serviceprovider.Activator;
-import oic.simulator.serviceprovider.listener.IResourceSelectionChangedUIListener;
+import oic.simulator.serviceprovider.listener.ISelectionChangedUIListener;
 import oic.simulator.serviceprovider.manager.ResourceManager;
-import oic.simulator.serviceprovider.resource.MetaProperty;
-import oic.simulator.serviceprovider.resource.SimulatorResource;
-
+import oic.simulator.serviceprovider.manager.UiListenerHandler;
+import oic.simulator.serviceprovider.model.Device;
+import oic.simulator.serviceprovider.model.MetaProperty;
+import oic.simulator.serviceprovider.model.Resource;
+import oic.simulator.serviceprovider.utils.Constants;
+
+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.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.ui.part.ViewPart;
+import org.oic.simulator.SimulatorException;
 
 /**
  * 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 final String[]              columnHeaders = { "Property", "Value" };
 
-    private TableViewer                         tableViewer;
+    private final Integer[]             columnWidth   = { 150, 150 };
 
-    private final String[]                      columnHeaders = { "Property",
-            "Value"                                          };
+    private ISelectionChangedUIListener resourceSelectionChangedListener;
 
-    private final Integer[]                     columnWidth   = { 150, 150 };
+    private ResourceManager             resourceManagerRef;
 
-    private IResourceSelectionChangedUIListener resourceSelectionChangedListener;
+    private List<MetaProperty>          properties;
 
-    private ResourceManager                     resourceManagerRef;
+    private boolean                     enable_edit;
+    private Button                      editBtn;
+    private Button                      cancelBtn;
 
     public MetaPropertiesView() {
 
         resourceManagerRef = Activator.getDefault().getResourceManager();
 
-        resourceSelectionChangedListener = new IResourceSelectionChangedUIListener() {
+        resourceSelectionChangedListener = new ISelectionChangedUIListener() {
 
             @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);
+                    }
+                });
+            }
+
+            @Override
+            public void onDeviceSelectionChange(final Device dev) {
+                Display.getDefault().asyncExec(new Runnable() {
+
+                    @Override
+                    public void run() {
+                        if (null != tableViewer) {
+                            properties = getData(dev);
+                            updateViewer(properties);
+                        }
+                        updateEditControls(dev);
                     }
                 });
             }
@@ -77,8 +112,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 +122,211 @@ 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");
+                    enable_edit = true;
+                } else {
+                    boolean result = false;
+                    Resource resourceInSelection = resourceManagerRef
+                            .getCurrentResourceInSelection();
+                    if (null != resourceInSelection) {
+
+                        // Null Check
+                        result = resourceManagerRef.isPropertyValueInvalid(
+                                resourceInSelection, properties,
+                                Constants.RESOURCE_URI);
+                        if (result) {
+                            MessageDialog.openError(parent.getShell(),
+                                    "Invalid Input", "Resource URI is invalid.");
+                            return;
+                        }
+
+                        result = resourceManagerRef.isPropertyValueInvalid(
+                                resourceInSelection, properties,
+                                Constants.RESOURCE_NAME);
+                        if (result) {
+                            MessageDialog.openError(parent.getShell(),
+                                    "Invalid Input",
+                                    "Resource Name is invalid.");
+                            return;
+                        }
+
+                        boolean update = false;
+                        boolean uriChange = false;
+                        boolean nameChange = 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
+                                    .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;
+                                }
+                            }
+                        }
+                        if (update) {
+                            try {
+                                result = Activator
+                                        .getDefault()
+                                        .getResourceManager()
+                                        .updateResourceProperties(
+                                                resourceManagerRef
+                                                        .getCurrentResourceInSelection(),
+                                                properties, uriChange,
+                                                nameChange);
+                            } catch (SimulatorException ex) {
+                                result = false;
+                            }
+                            if (result) {
+                                MessageDialog.openInformation(
+                                        parent.getShell(), "Operation status",
+                                        "Resource properties updated.");
+                            } else {
+                                MessageDialog.openInformation(
+                                        parent.getShell(), "Operation status",
+                                        "Failed to update the resource properties.");
+
+                                // Reset the old property values.
+                                properties = getData(resourceManagerRef
+                                        .getCurrentResourceInSelection());
+                                updateViewer(properties);
+                            }
+                        }
+                    } else {
+                        Device dev = resourceManagerRef
+                                .getCurrentDeviceInSelection();
+
+                        // Null check
+                        result = resourceManagerRef.isPropertyValueInvalid(dev,
+                                properties, Constants.DEVICE_NAME);
+                        if (result) {
+                            MessageDialog.openError(parent.getShell(),
+                                    "Invalid Input", "Device Name is invalid.");
+                            return;
+                        }
+
+                        if (resourceManagerRef.isPropValueChanged(dev,
+                                properties, Constants.DEVICE_NAME)) {
+                            resourceManagerRef.updateDeviceProperties(dev,
+                                    properties);
+                        }
+
+                    }
+                    cancelBtn.setEnabled(false);
+                    editBtn.setText("Edit");
+                    enable_edit = 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);
+                } else {
+                    Device dev = resourceManagerRef
+                            .getCurrentDeviceInSelection();
+                    if (null != dev) {
+                        properties = getData(dev);
+                    }
+                }
+                updateViewer(properties);
+
+                cancelBtn.setEnabled(false);
+                editBtn.setText("Edit");
+                enable_edit = false;
+            }
+        });
+
         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");
+                enable_edit = false;
+            }
+
+            if (null == obj) {
+                editBtn.setEnabled(false);
+            } else {
+                editBtn.setEnabled(true);
+            }
+            cancelBtn.setEnabled(false);
+        }
+    }
+
+    private List<MetaProperty> getData(Resource resource) {
+        if (null != resource) {
+            List<MetaProperty> metaPropertyList = resourceManagerRef
+                    .getMetaProperties(resource);
+            return metaPropertyList;
+        } else {
+            return null;
+        }
     }
 
-    private List<MetaProperty> getData() {
-        SimulatorResource resourceInSelection = resourceManagerRef
-                .getCurrentResourceInSelection();
-        if (null != resourceInSelection) {
+    private List<MetaProperty> getData(Device dev) {
+        if (null != dev) {
             List<MetaProperty> metaPropertyList = resourceManagerRef
-                    .getMetaProperties(resourceInSelection);
+                    .getMetaProperties(dev);
             return metaPropertyList;
         } else {
             return null;
@@ -137,15 +355,12 @@ public class MetaPropertiesView extends ViewPart {
                 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);
             }
         });
 
@@ -164,11 +379,12 @@ public class MetaPropertiesView extends ViewPart {
                 }
             }
         });
+        propValue.setEditingSupport(new PropValueEditor(tableViewer));
     }
 
     private void addManagerListeners() {
-        resourceManagerRef
-                .addResourceSelectionChangedUIListener(resourceSelectionChangedListener);
+        UiListenerHandler.getInstance().addResourceSelectionChangedUIListener(
+                resourceSelectionChangedListener);
     }
 
     class PropertycontentProvider implements IStructuredContentProvider {
@@ -185,19 +401,61 @@ 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(Object element) {
+            if (!enable_edit) {
+                return null;
+            }
+            // Disabling edit for resource type
+            String propName = ((MetaProperty) element).getPropName();
+            if (null != propName && propName.equals(Constants.RESOURCE_TYPE)) {
+                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() {
     }
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 a9abf802aeeaa1c082d251ca186a15c973c5c8fb..c102e66ad260157f0c7b259fd9b961f9238d4694 100644 (file)
@@ -18,24 +18,45 @@ package oic.simulator.serviceprovider.view;
 
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Set;
 
 import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.listener.IPropertiesChangedUIListener;
 import oic.simulator.serviceprovider.listener.IResourceListChangedUIListener;
 import oic.simulator.serviceprovider.manager.ResourceManager;
-import oic.simulator.serviceprovider.resource.DeleteCategory;
+import oic.simulator.serviceprovider.manager.UiListenerHandler;
+import oic.simulator.serviceprovider.model.AutomationSettingHelper;
+import oic.simulator.serviceprovider.model.CollectionResource;
+import oic.simulator.serviceprovider.model.Device;
+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.AddResourceToCollections;
+import oic.simulator.serviceprovider.view.dialogs.AddResourceToDevices;
+import oic.simulator.serviceprovider.view.dialogs.AddResources;
+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.RemoveResourceFromCollections;
+import oic.simulator.serviceprovider.view.dialogs.RemoveResourceFromDevices;
+import oic.simulator.serviceprovider.view.dialogs.RemoveResources;
 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.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.custom.CTabFolder;
+import org.eclipse.swt.custom.CTabItem;
 import org.eclipse.swt.events.MenuAdapter;
 import org.eclipse.swt.events.MenuEvent;
 import org.eclipse.swt.events.SelectionAdapter;
@@ -56,6 +77,8 @@ import org.eclipse.ui.PlatformUI;
 import org.eclipse.ui.dialogs.FilteredTree;
 import org.eclipse.ui.dialogs.PatternFilter;
 import org.eclipse.ui.part.ViewPart;
+import org.oic.simulator.SimulatorException;
+import org.oic.simulator.server.SimulatorResource.AutoUpdateType;
 
 /**
  * This class manages and shows the resource manager view in the perspective.
@@ -67,10 +90,19 @@ public class ResourceManagerView extends ViewPart {
     private Button                         createButton;
     private Button                         deleteButton;
 
-    private TreeViewer                     treeViewer;
+    private TreeViewer                     singleResTreeViewer;
+    private TreeViewer                     collectionResTreeViewer;
+    private TreeViewer                     deviceTreeViewer;
+
+    private CTabFolder                     folder;
+    private CTabItem                       singleResTab;
+    private CTabItem                       collectionResTab;
+    private CTabItem                       deviceTab;
 
     private IResourceListChangedUIListener resourceListChangedListener;
 
+    private IPropertiesChangedUIListener   resourcePropertiesChangedListener;
+
     private ResourceManager                resourceManager;
 
     public ResourceManagerView() {
@@ -80,13 +112,23 @@ public class ResourceManagerView extends ViewPart {
         resourceListChangedListener = new IResourceListChangedUIListener() {
 
             @Override
-            public void onResourceCreation() {
+            public void onResourceCreation(final ResourceType type) {
                 Display.getDefault().asyncExec(new Runnable() {
 
                     @Override
                     public void run() {
-                        if (null != treeViewer) {
-                            treeViewer.refresh();
+                        if (type == ResourceType.SINGLE) {
+                            if (null != singleResTreeViewer) {
+                                singleResTreeViewer.refresh();
+                            }
+                        } else if (type == ResourceType.COLLECTION) {
+                            if (null != collectionResTreeViewer) {
+                                collectionResTreeViewer.refresh();
+                            }
+                        } else {
+                            if (null != deviceTreeViewer) {
+                                deviceTreeViewer.refresh();
+                            }
                         }
 
                         // Trigger the visibility of delete button
@@ -96,34 +138,86 @@ 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();
+                        if (null != singleResTreeViewer
+                                && null != collectionResTreeViewer
+                                && null != deviceTreeViewer) {
+                            switch (type) {
+                                case SINGLE:
+                                    singleResTreeViewer.refresh();
+                                case COLLECTION:
+                                    collectionResTreeViewer.refresh();
+                                default:
+                                    deviceTreeViewer.refresh();
+                            }
                         }
-
                         // Trigger the visibility of delete button
                         changeDeleteVisibility();
                     }
                 });
             }
+
+            @Override
+            public void onResourceListUpdate(final ResourceType type) {
+                Display.getDefault().asyncExec(new Runnable() {
+
+                    @Override
+                    public void run() {
+                        if (null != singleResTreeViewer
+                                && null != collectionResTreeViewer
+                                && null != deviceTreeViewer) {
+                            switch (type) {
+                                case SINGLE:
+                                    singleResTreeViewer.refresh();
+                                case COLLECTION:
+                                    collectionResTreeViewer.refresh();
+                                default:
+                                    deviceTreeViewer.refresh();
+                            }
+                        }
+                    }
+                });
+            }
+        };
+
+        resourcePropertiesChangedListener = new IPropertiesChangedUIListener() {
+
+            @Override
+            public void onResourcePropertyChange() {
+                Display.getDefault().asyncExec(new Runnable() {
+                    @Override
+                    public void run() {
+                        if (null != singleResTreeViewer
+                                && null != collectionResTreeViewer
+                                && null != deviceTreeViewer) {
+                            singleResTreeViewer.refresh();
+                            collectionResTreeViewer.refresh();
+                            deviceTreeViewer.refresh();
+                        }
+                    }
+                });
+            }
+
+            @Override
+            public void onDevicePropertyChange() {
+                Display.getDefault().asyncExec(new Runnable() {
+                    @Override
+                    public void run() {
+                        if (null != deviceTreeViewer) {
+                            deviceTreeViewer.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,135 +257,883 @@ public class ResourceManagerView extends ViewPart {
         gd.widthHint = 90;
         deleteButton.setLayoutData(gd);
 
-        Group resourceGroup = new Group(compContent, SWT.NONE);
-        resourceGroup.setText("Created Resources");
+        // Create a Tab Folder.
+        folder = new CTabFolder(compContent, SWT.BORDER);
+        gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        folder.setLayoutData(gd);
+        folder.setSimple(false);
+        folder.setUnselectedCloseVisible(false);
+        folder.setUnselectedImageVisible(false);
+        folder.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                // Tab is switched.
+                singleResTreeViewer.setSelection(null);
+                collectionResTreeViewer.setSelection(null);
+                deviceTreeViewer.setSelection(null);
+                resourceManager.resourceSelectionChanged(null);
+            }
+        });
+
+        createSimpleResourcesArea();
+
+        createCollectionResourcesArea();
+
+        createDeviceArea();
+
+        folder.setSelection(singleResTab);
+
+        addUIListeners();
+
+        addManagerListeners();
+
+        // If there is at least one resource exist, then enable the delete
+        // resource button
+        changeDeleteVisibility();
+    }
+
+    private void createSimpleResourcesArea() {
+        singleResTab = new CTabItem(folder, SWT.NULL);
+        singleResTab.setText("Simple Resources");
+
+        // Create a group to show all the discovered resources.
+        // Adding the group to the folder.
+        Group resourceGroup = new Group(folder, SWT.NONE);
+        // resourceGroup.setText("Discovered 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();
+        // TODO: Add menu items
+        addMenuToSimpleResources();
+
+        singleResTab.setControl(resourceGroup);
     }
 
-    private void addUIListeners() {
+    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();
+                        }
 
-        createButton.addSelectionListener(new SelectionAdapter() {
-            @Override
-            public void widgetSelected(SelectionEvent e) {
-                PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {
+                        IStructuredSelection selection = ((IStructuredSelection) singleResTreeViewer
+                                .getSelection());
+                        final SingleResource resource = (SingleResource) selection
+                                .getFirstElement();
+                        if (null == resource) {
+                            return;
+                        }
+
+                        addAutomationMenu(menu, resource);
 
+                        // Menu to add resource to one or more collections.
+                        MenuItem addToCollection = new MenuItem(menu, SWT.NONE);
+                        addToCollection.setText("Add to Collection");
+                        addToCollection
+                                .addSelectionListener(new SelectionAdapter() {
+                                    @Override
+                                    public void widgetSelected(SelectionEvent e) {
+                                        List<CollectionResource> possibleCollections;
+                                        possibleCollections = resourceManager
+                                                .getCollectionsForAddingToSingleResource(resource);
+                                        if (null == possibleCollections
+                                                || possibleCollections
+                                                        .isEmpty()) {
+                                            MessageDialog
+                                                    .openError(
+                                                            Display.getDefault()
+                                                                    .getActiveShell(),
+                                                            "No possible candidates",
+                                                            "There are no possible collections to which the resource can be added.");
+                                            return;
+                                        }
+
+                                        AddResourceToCollections addToCollectionsDlg = new AddResourceToCollections(
+                                                Display.getDefault()
+                                                        .getActiveShell(),
+                                                possibleCollections);
+                                        if (addToCollectionsDlg.open() != Window.OK) {
+                                            return;
+                                        }
+
+                                        Set<CollectionResource> resultSet = addToCollectionsDlg
+                                                .getSelectedResourceList();
+
+                                        int addedCount = resourceManager
+                                                .addResourceToCollection(
+                                                        resultSet, resource);
+                                        if (addedCount <= 0) {
+                                            MessageDialog
+                                                    .openInformation(Display
+                                                            .getDefault()
+                                                            .getActiveShell(),
+                                                            "Operation failed",
+                                                            "Failed to add resources to the collection.");
+                                            return;
+                                        }
+
+                                        collectionResTreeViewer.refresh();
+
+                                        deviceTreeViewer.refresh();
+
+                                        MessageDialog.openInformation(
+                                                Display.getDefault()
+                                                        .getActiveShell(),
+                                                "Added",
+                                                "["
+                                                        + addedCount
+                                                        + "/"
+                                                        + resultSet.size()
+                                                        + "] added to selected collections");
+                                    }
+                                });
+
+                        // Menu to remove resource from one or more collections
+                        // to which it is a member.
+                        MenuItem removeFromCollection = new MenuItem(menu,
+                                SWT.NONE);
+                        removeFromCollection.setText("Remove from Collection");
+                        removeFromCollection
+                                .addSelectionListener(new SelectionAdapter() {
+                                    @Override
+                                    public void widgetSelected(SelectionEvent e) {
+                                        List<CollectionResource> possibleCollectionstoRemoveFrom;
+                                        possibleCollectionstoRemoveFrom = resourceManager
+                                                .getResourceReferences(resource);
+                                        if (null == possibleCollectionstoRemoveFrom
+                                                || possibleCollectionstoRemoveFrom
+                                                        .isEmpty()) {
+                                            MessageDialog
+                                                    .openError(
+                                                            Display.getDefault()
+                                                                    .getActiveShell(),
+                                                            "No possible candidates",
+                                                            "Resource has not been added to any collections.");
+                                            return;
+                                        }
+
+                                        RemoveResourceFromCollections removeFromCollectionsDlg = new RemoveResourceFromCollections(
+                                                Display.getDefault()
+                                                        .getActiveShell(),
+                                                possibleCollectionstoRemoveFrom);
+                                        if (removeFromCollectionsDlg.open() != Window.OK) {
+                                            return;
+                                        }
+
+                                        Set<CollectionResource> resultSet = removeFromCollectionsDlg
+                                                .getSelectedResourceList();
+
+                                        int removeCount = resourceManager
+                                                .removeResourceFromCollection(
+                                                        resultSet, resource);
+                                        if (removeCount <= 0) {
+                                            MessageDialog
+                                                    .openInformation(Display
+                                                            .getDefault()
+                                                            .getActiveShell(),
+                                                            "Operation failed",
+                                                            "Failed to remove resources from the collection.");
+                                            return;
+                                        }
+
+                                        collectionResTreeViewer.refresh();
+
+                                        deviceTreeViewer.refresh();
+
+                                        MessageDialog.openInformation(
+                                                Display.getDefault()
+                                                        .getActiveShell(),
+                                                "Removed",
+                                                "["
+                                                        + removeCount
+                                                        + "/"
+                                                        + resultSet.size()
+                                                        + "] resource removed from selected collections");
+                                    }
+                                });
+
+                        // Menu to add resource to one or more devices.
+                        MenuItem addToDevice = new MenuItem(menu, SWT.NONE);
+                        addToDevice.setText("Add to Device");
+                        addToDevice
+                                .addSelectionListener(new SelectionAdapter() {
+                                    @Override
+                                    public void widgetSelected(SelectionEvent e) {
+                                        List<Device> possibleDevices;
+                                        possibleDevices = resourceManager
+                                                .getDevicesForAddingToResource(resource);
+                                        if (null == possibleDevices
+                                                || possibleDevices.isEmpty()) {
+                                            MessageDialog
+                                                    .openError(
+                                                            Display.getDefault()
+                                                                    .getActiveShell(),
+                                                            "No possible candidates",
+                                                            "There are no possible devices to which the resource can be added.");
+                                            return;
+                                        }
+
+                                        AddResourceToDevices addToDevicesDlg = new AddResourceToDevices(
+                                                Display.getDefault()
+                                                        .getActiveShell(),
+                                                possibleDevices);
+                                        if (addToDevicesDlg.open() != Window.OK) {
+                                            return;
+                                        }
+
+                                        Set<Device> resultSet = addToDevicesDlg
+                                                .getSelectedDeviceList();
+
+                                        resourceManager.addResourceToDevice(
+                                                resultSet, resource);
+
+                                        deviceTreeViewer.refresh();
+
+                                        MessageDialog
+                                                .openInformation(Display
+                                                        .getDefault()
+                                                        .getActiveShell(),
+                                                        "Added",
+                                                        "Resource added to selected devices.");
+                                    }
+                                });
+
+                        // Menu to remove resource from one or more device to
+                        // which it is a member.
+                        MenuItem removeFromDevice = new MenuItem(menu, SWT.NONE);
+                        removeFromDevice.setText("Remove from Device");
+                        removeFromDevice
+                                .addSelectionListener(new SelectionAdapter() {
+                                    @Override
+                                    public void widgetSelected(SelectionEvent e) {
+                                        List<Device> possibleDevices;
+                                        possibleDevices = resourceManager
+                                                .getDeviceReferences(resource);
+                                        if (null == possibleDevices
+                                                || possibleDevices.isEmpty()) {
+                                            MessageDialog
+                                                    .openError(
+                                                            Display.getDefault()
+                                                                    .getActiveShell(),
+                                                            "No possible candidates",
+                                                            "Resource has not been added to any devices.");
+                                            return;
+                                        }
+
+                                        RemoveResourceFromDevices removeFromDevicesDlg = new RemoveResourceFromDevices(
+                                                Display.getDefault()
+                                                        .getActiveShell(),
+                                                possibleDevices);
+                                        if (removeFromDevicesDlg.open() != Window.OK) {
+                                            return;
+                                        }
+
+                                        Set<Device> resultSet = removeFromDevicesDlg
+                                                .getSelectedDeviceList();
+
+                                        resourceManager
+                                                .removeResourceFromDevice(
+                                                        resultSet, resource);
+
+                                        deviceTreeViewer.refresh();
+
+                                        MessageDialog
+                                                .openInformation(Display
+                                                        .getDefault()
+                                                        .getActiveShell(),
+                                                        "Removed",
+                                                        "Resource removed from selected devices");
+                                    }
+                                });
+
+                        // Menu to remove resource from one or more device to
+                        // which it is a member.
+                        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();
+                                            // if(refreshCollectionTree)
+                                            collectionResTreeViewer.refresh();
+                                            // if(refreshDeviceTree)
+                                            deviceTreeViewer.refresh();
+                                            MessageDialog.openInformation(
+                                                    Display.getDefault()
+                                                            .getActiveShell(),
+                                                    "Deleted",
+                                                    "Resource deleted.");
+                                        } catch (SimulatorException e1) {
+                                            MessageDialog
+                                                    .openInformation(Display
+                                                            .getDefault()
+                                                            .getActiveShell(),
+                                                            "Deletion Failed",
+                                                            "Failed to delete the resource.");
+                                        }
+                                        changeDeleteVisibility();
+                                    }
+                                });
+                    }
+                });
+            }
+        }
+    }
+
+    private void createCollectionResourcesArea() {
+        collectionResTab = new CTabItem(folder, SWT.NULL);
+        collectionResTab.setText("Collection Resources");
+
+        // Create a group to show all the discovered resources.
+        // Adding the group to the folder.
+        Group resourceGroup = new Group(folder, SWT.NONE);
+        // resourceGroup.setText("Discovered Resources");
+
+        Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE);
+        resourceGroup.setBackground(color);
+
+        resourceGroup.setLayout(new GridLayout(1, false));
+        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);
+        collectionResTreeViewer = filteredTree.getViewer();
+        collectionResTreeViewer.getTree().setLayoutData(
+                new GridData(SWT.FILL, SWT.FILL, true, true));
+        collectionResTreeViewer
+                .setContentProvider(new CollectionResourceContentProvider());
+        collectionResTreeViewer.setLabelProvider(new TreeLabelProvider());
+        collectionResTreeViewer.setInput(new Object());
+
+        collectionResTreeViewer
+                .addSelectionChangedListener(new ISelectionChangedListener() {
                     @Override
-                    public void run() {
-                        CreateResourceWizard createWizard = new CreateResourceWizard();
-                        ResourceWizardDialog wizardDialog = new ResourceWizardDialog(
-                                PlatformUI.getWorkbench().getDisplay()
-                                        .getActiveShell(), createWizard);
-                        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);
-                                }
+                    public void selectionChanged(SelectionChangedEvent e) {
+                        IStructuredSelection selection = (IStructuredSelection) e
+                                .getSelection();
+                        if (null == selection) {
+                            return;
+                        }
+
+                        Resource res = null;
+                        int size = selection.size();
+                        if (size == 1) {
+                            res = (Resource) selection.getFirstElement();
+                        }
+                        resourceManager.resourceSelectionChanged(res);
+                    }
+                });
+
+        // TODO: Add menu items
+        addMenuToCollectionResources();
+
+        collectionResTab.setControl(resourceGroup);
+    }
+
+    private void addMenuToCollectionResources() {
+        if (null != collectionResTreeViewer) {
+            final Tree resourceTreeHead = collectionResTreeViewer.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) collectionResTreeViewer
+                                .getSelection());
+                        final Resource resource = (Resource) selection
+                                .getFirstElement();
+                        TreeItem[] treeItems = resourceTreeHead.getSelection();
+                        if (null == resource || null == treeItems) {
+                            return;
+                        }
+
+                        final TreeItem parent = treeItems[0].getParentItem();
+                        if (null == parent) {
+                            System.out.println("No parent exist");
+                            // Selected item is a top-level collection
+                            addMenuToTopLevelCollectionResources(menu,
+                                    (CollectionResource) resource);
+                        } else {
+                            if (resource instanceof SingleResource)
+                                addAutomationMenu(menu,
+                                        (SingleResource) resource);
+
+                            MenuItem remFromParent = new MenuItem(menu,
+                                    SWT.NONE);
+                            remFromParent.setText("Remove from Parent");
+                            remFromParent
+                                    .addSelectionListener(new SelectionAdapter() {
+                                        @Override
+                                        public void widgetSelected(
+                                                SelectionEvent e) {
+                                            CollectionResource parentCollection = (CollectionResource) parent
+                                                    .getData();
+                                            String status;
+                                            try {
+                                                resourceManager
+                                                        .removeResourceFromCollection(
+                                                                parentCollection,
+                                                                resource);
+                                                collectionResTreeViewer
+                                                        .refresh();
+                                                deviceTreeViewer.refresh();
+
+                                                status = "Resource removed from its parent";
+                                            } catch (SimulatorException e1) {
+                                                status = "Failed to remove the resource from its parent";
+                                            }
+                                            MessageDialog.openInformation(
+                                                    Display.getDefault()
+                                                            .getActiveShell(),
+                                                    "Status", status);
+                                        }
+                                    });
+
+                            if (resource instanceof SingleResource) {
+                                // Menu Items for single resource will be added
+                                // here.
                             }
                         }
                     }
                 });
             }
+        }
+    }
+
+    private void addMenuToTopLevelCollectionResources(final Menu menu,
+            final CollectionResource colRes) {
+        // Menu to add one or more resources to the collection.
+        MenuItem addResources = new MenuItem(menu, SWT.CASCADE);
+        addResources.setText("Add Resources");
+
+        Menu addSubMenu = new Menu(menu);
+        addResources.setMenu(addSubMenu);
+
+        MenuItem simpleResources = new MenuItem(addSubMenu, SWT.NONE);
+        simpleResources.setText("Simple");
+        simpleResources.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                List<SingleResource> possibleResources;
+                possibleResources = resourceManager
+                        .getSingleTypeResourcesForAddingToCollectionResource(colRes);
+                if (null == possibleResources || possibleResources.isEmpty()) {
+                    MessageDialog
+                            .openError(Display.getDefault().getActiveShell(),
+                                    "No possible candidates",
+                                    "There are no possible simple resources that can be added.");
+                    return;
+                }
+
+                List<Resource> resources = Utility
+                        .convertSingleTypeResourceListToBaseType(possibleResources);
+
+                AddResources addToCollectionsDlg = new AddResources(Display
+                        .getDefault().getActiveShell(), resources);
+                if (addToCollectionsDlg.open() != Window.OK) {
+                    return;
+                }
+
+                Set<Resource> resultSet = addToCollectionsDlg
+                        .getSelectedResourceList();
+
+                int addedCount = resourceManager.addResourceToCollection(
+                        colRes, resultSet);
+                if (addedCount <= 0) {
+                    MessageDialog.openInformation(Display.getDefault()
+                            .getActiveShell(), "Operation failed",
+                            "Failed to add resources to the collection.");
+                    return;
+                }
+
+                collectionResTreeViewer.refresh();
+
+                deviceTreeViewer.refresh();
+
+                MessageDialog.openInformation(Display.getDefault()
+                        .getActiveShell(), "Added", "[" + addedCount + "/"
+                        + resultSet.size()
+                        + "] resources added to the collection");
+            }
         });
 
-        deleteButton.addSelectionListener(new SelectionAdapter() {
+        MenuItem collectionResources = new MenuItem(addSubMenu, SWT.NONE);
+        collectionResources.setText("Collection");
+        collectionResources.addSelectionListener(new SelectionAdapter() {
             @Override
             public void widgetSelected(SelectionEvent e) {
-                PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {
+                List<CollectionResource> possibleResources;
+                possibleResources = resourceManager
+                        .getCollectionTypeResourcesForAddingToCollectionResource(colRes);
+                if (null == possibleResources || possibleResources.isEmpty()) {
+                    MessageDialog
+                            .openError(Display.getDefault().getActiveShell(),
+                                    "No possible candidates",
+                                    "There are no possible collections that can be added.");
+                    return;
+                }
+
+                List<Resource> resources = Utility
+                        .convertCollectionTypeResourceListToBaseType(possibleResources);
+
+                AddResources addToCollectionsDlg = new AddResources(Display
+                        .getDefault().getActiveShell(), resources);
+                if (addToCollectionsDlg.open() != Window.OK) {
+                    return;
+                }
+
+                Set<Resource> resultSet = addToCollectionsDlg
+                        .getSelectedResourceList();
+
+                int addedCount = resourceManager.addResourceToCollection(
+                        colRes, resultSet);
+                if (addedCount <= 0) {
+                    MessageDialog.openInformation(Display.getDefault()
+                            .getActiveShell(), "Operation failed",
+                            "Failed to add resources to the collection.");
+                    return;
+                }
+
+                collectionResTreeViewer.refresh();
+
+                deviceTreeViewer.refresh();
+
+                MessageDialog.openInformation(Display.getDefault()
+                        .getActiveShell(), "Added", "[" + addedCount + "/"
+                        + resultSet.size()
+                        + "] resources added to the collection");
+            }
+        });
+
+        // Menu to remove one or more resources from the collection.
+        MenuItem removeResources = new MenuItem(menu, SWT.CASCADE);
+        removeResources.setText("Remove Resources");
+
+        Menu removeSubMenu = new Menu(menu);
+        removeResources.setMenu(removeSubMenu);
+
+        simpleResources = new MenuItem(removeSubMenu, SWT.NONE);
+        simpleResources.setText("Simple");
+        simpleResources.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                List<SingleResource> possibleResources;
+                possibleResources = resourceManager.getSingleTypeChilds(colRes);
+                if (null == possibleResources || possibleResources.isEmpty()) {
+                    MessageDialog
+                            .openError(Display.getDefault().getActiveShell(),
+                                    "No possible candidates",
+                                    "There are no possible simple resources which can be removed.");
+                    return;
+                }
+
+                List<Resource> resources = Utility
+                        .convertSingleTypeResourceListToBaseType(possibleResources);
 
+                RemoveResources removeFromCollectionsDlg = new RemoveResources(
+                        Display.getDefault().getActiveShell(), resources);
+                if (removeFromCollectionsDlg.open() != Window.OK) {
+                    return;
+                }
+
+                Set<Resource> resultSet = removeFromCollectionsDlg
+                        .getSelectedResourceList();
+
+                int removeCount = resourceManager
+                        .removeResourcesFromCollection(colRes, resultSet);
+                if (removeCount <= 0) {
+                    MessageDialog.openInformation(Display.getDefault()
+                            .getActiveShell(), "Operation failed",
+                            "Failed to remove resources from the collection.");
+                    return;
+                }
+
+                collectionResTreeViewer.refresh();
+
+                deviceTreeViewer.refresh();
+
+                MessageDialog.openInformation(Display.getDefault()
+                        .getActiveShell(), "Removed", "[" + removeCount + "/"
+                        + resultSet.size()
+                        + "] resources removed from the collection");
+            }
+        });
+
+        collectionResources = new MenuItem(removeSubMenu, SWT.NONE);
+        collectionResources.setText("Collection");
+        collectionResources.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                List<CollectionResource> possibleResources;
+                possibleResources = resourceManager
+                        .getCollectionTypeChilds(colRes);
+                if (null == possibleResources || possibleResources.isEmpty()) {
+                    MessageDialog
+                            .openError(Display.getDefault().getActiveShell(),
+                                    "No possible candidates",
+                                    "There are no possible collections which can be removed.");
+                    return;
+                }
+
+                List<Resource> resources = Utility
+                        .convertCollectionTypeResourceListToBaseType(possibleResources);
+
+                RemoveResources removeFromCollectionsDlg = new RemoveResources(
+                        Display.getDefault().getActiveShell(), resources);
+                if (removeFromCollectionsDlg.open() != Window.OK) {
+                    return;
+                }
+
+                Set<Resource> resultSet = removeFromCollectionsDlg
+                        .getSelectedResourceList();
+
+                int removeCount = resourceManager
+                        .removeResourcesFromCollection(colRes, resultSet);
+                if (removeCount <= 0) {
+                    MessageDialog.openInformation(Display.getDefault()
+                            .getActiveShell(), "Operation failed",
+                            "Failed to remove resources from the collection.");
+                    return;
+                }
+
+                collectionResTreeViewer.refresh();
+
+                deviceTreeViewer.refresh();
+
+                MessageDialog.openInformation(Display.getDefault()
+                        .getActiveShell(), "Removed", "[" + removeCount + "/"
+                        + resultSet.size()
+                        + "] resources removed from the collection");
+            }
+        });
+
+        // Menu to add resource to one or more devices.
+        MenuItem addToDevice = new MenuItem(menu, SWT.NONE);
+        addToDevice.setText("Add to Device");
+        addToDevice.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                List<Device> possibleDevices;
+                possibleDevices = resourceManager
+                        .getDevicesForAddingToResource(colRes);
+                if (null == possibleDevices || possibleDevices.isEmpty()) {
+                    MessageDialog
+                            .openError(Display.getDefault().getActiveShell(),
+                                    "No possible candidates",
+                                    "There are no possible devices to which the resource can be added.");
+                    return;
+                }
+
+                AddResourceToDevices addToDevicesDlg = new AddResourceToDevices(
+                        Display.getDefault().getActiveShell(), possibleDevices);
+                if (addToDevicesDlg.open() != Window.OK) {
+                    return;
+                }
+
+                Set<Device> resultSet = addToDevicesDlg.getSelectedDeviceList();
+
+                resourceManager.addResourceToDevice(resultSet, colRes);
+
+                deviceTreeViewer.refresh();
+
+                MessageDialog.openInformation(Display.getDefault()
+                        .getActiveShell(), "Added",
+                        "Resource added to selected devices.");
+            }
+        });
+
+        // Menu to remove resource from one or more device to which it is a
+        // member.
+        MenuItem removeFromDevice = new MenuItem(menu, SWT.NONE);
+        removeFromDevice.setText("Remove from Device");
+        removeFromDevice.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                List<Device> possibleDevices;
+                possibleDevices = resourceManager.getDeviceReferences(colRes);
+                if (null == possibleDevices || possibleDevices.isEmpty()) {
+                    MessageDialog.openError(Display.getDefault()
+                            .getActiveShell(), "No possible candidates",
+                            "Resource has not been added to any devices.");
+                    return;
+                }
+
+                RemoveResourceFromDevices removeFromDevicesDlg = new RemoveResourceFromDevices(
+                        Display.getDefault().getActiveShell(), possibleDevices);
+                if (removeFromDevicesDlg.open() != Window.OK) {
+                    return;
+                }
+
+                Set<Device> resultSet = removeFromDevicesDlg
+                        .getSelectedDeviceList();
+
+                resourceManager.removeResourceFromDevice(resultSet, colRes);
+
+                deviceTreeViewer.refresh();
+
+                MessageDialog.openInformation(Display.getDefault()
+                        .getActiveShell(), "Removed",
+                        "Resource removed from selected devices");
+            }
+        });
+
+        // Menu to remove resource from one or more device to which it is a
+        // member.
+        MenuItem deleteResource = new MenuItem(menu, SWT.NONE);
+        deleteResource.setText("Delete");
+        deleteResource.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                /*
+                 * boolean refreshCollectionTree = false; boolean
+                 * refreshDeviceTree = false;
+                 * if(resource.isMemberOfAnyCollection()) {
+                 * refreshCollectionTree = true; }
+                 * if(resource.isMemberOfAnyDevice()) { refreshDeviceTree =
+                 * true; }
+                 */
+                try {
+                    resourceManager.removeResource(colRes);
+                    // if(refreshCollectionTree)
+                    collectionResTreeViewer.refresh();
+                    // if(refreshDeviceTree)
+                    deviceTreeViewer.refresh();
+                    MessageDialog.openInformation(Display.getDefault()
+                            .getActiveShell(), "Deleted", "Resource deleted.");
+                } catch (SimulatorException e1) {
+                    MessageDialog.openInformation(Display.getDefault()
+                            .getActiveShell(), "Deletion Failed",
+                            "Failed to delete the resource.");
+                }
+
+                changeDeleteVisibility();
+            }
+        });
+
+    }
+
+    private void createDeviceArea() {
+        deviceTab = new CTabItem(folder, SWT.NULL);
+        deviceTab.setText("Devices");
+
+        // Create a group to show all the discovered resources.
+        // Adding the group to the folder.
+        Group resourceGroup = new Group(folder, SWT.NONE);
+        // resourceGroup.setText("Discovered Resources");
+
+        Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE);
+        resourceGroup.setBackground(color);
+
+        resourceGroup.setLayout(new GridLayout(1, false));
+        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);
+        deviceTreeViewer = filteredTree.getViewer();
+        deviceTreeViewer.getTree().setLayoutData(
+                new GridData(SWT.FILL, SWT.FILL, true, true));
+        deviceTreeViewer.setContentProvider(new DeviceContentProvider());
+        deviceTreeViewer.setLabelProvider(new TreeLabelProvider());
+        deviceTreeViewer.setInput(new Object());
+
+        deviceTreeViewer
+                .addSelectionChangedListener(new ISelectionChangedListener() {
                     @Override
-                    public void run() {
-                        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) {
+                    public void selectionChanged(SelectionChangedEvent e) {
+                        IStructuredSelection selection = (IStructuredSelection) e
+                                .getSelection();
+                        if (null == selection) {
+                            return;
+                        }
+
+                        int size = selection.size();
+                        if (size == 1) {
+                            Object obj = selection.getFirstElement();
+                            if (obj instanceof Device) {
+                                resourceManager
+                                        .deviceSelectionChanged((Device) obj);
+                            } else {
                                 resourceManager
-                                        .deleteResourceByType(deleteWizard
-                                                .getDeleteCandidate());
-                            } else if (deleteCategory == DeleteCategory.ALL) {
-                                resourceManager.deleteAllResources();
+                                        .resourceSelectionChanged((Resource) obj);
                             }
+                        } else {
+                            resourceManager.deviceSelectionChanged(null);
                         }
                     }
                 });
-            }
-        });
 
-        if (null != treeViewer) {
-            final Tree resourceTreeHead = treeViewer.getTree();
+        // TODO: Add menu items
+        addMenuToDevices();
+
+        deviceTab.setControl(resourceGroup);
+    }
+
+    private void addMenuToDevices() {
+        if (null != deviceTreeViewer) {
+            final Tree resourceTreeHead = deviceTreeViewer.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);
@@ -304,71 +1146,394 @@ public class ResourceManagerView extends ViewPart {
                         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(
+
+                        IStructuredSelection selection = ((IStructuredSelection) deviceTreeViewer
+                                .getSelection());
+                        final Object element = selection.getFirstElement();
+                        if (element instanceof Device) {
+                            addMenuToDevices(menu, (Device) element);
+                        } else {
+                            final Resource resource = (Resource) element;
+                            TreeItem[] treeItems = resourceTreeHead
+                                    .getSelection();
+                            if (null == resource || null == treeItems) {
+                                return;
+                            }
+
+                            if (resource instanceof SingleResource)
+                                addAutomationMenu(menu,
+                                        (SingleResource) resource);
+
+                            final TreeItem parent = treeItems[0]
+                                    .getParentItem();
+                            MenuItem remFromParent = new MenuItem(menu,
+                                    SWT.NONE);
+                            remFromParent.setText("Remove from Parent");
+                            remFromParent
+                                    .addSelectionListener(new SelectionAdapter() {
+                                        @Override
+                                        public void widgetSelected(
+                                                SelectionEvent e) {
+                                            String status = "Resource removed from its parent.";
+                                            Object obj = parent.getData();
+                                            if (obj instanceof Device) {
+                                                resourceManager
+                                                        .removeResourceFromDevice(
+                                                                (Device) obj,
+                                                                resource);
+                                            } else {
+                                                try {
+                                                    resourceManager
+                                                            .removeResourceFromCollection(
+                                                                    (CollectionResource) obj,
+                                                                    resource);
+                                                    collectionResTreeViewer
+                                                            .refresh();
+                                                    status = "Resource removed from its parent";
+                                                } catch (SimulatorException e1) {
+                                                    status = "Failed to remove the resource from its parent";
+                                                }
+                                            }
+
+                                            deviceTreeViewer.refresh();
+
+                                            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);
-                            }
-                        });
+                                                    "Status", status);
+                                        }
+                                    });
 
-                        // Set the initial visibility of menu items
-                        boolean status = resourceManager.isResourceAutomationStarted(resourceManager
-                                .getCompleteUriFromDisplayName(selectedItem));
-                        startItem.setEnabled(!status);
-                        stopItem.setEnabled(status);
+                            if (resource instanceof SingleResource) {
+                                // Menu Items for single resource will be added
+                                // here.
+                            }
+                        }
                     }
                 });
             }
         }
     }
 
+    private void addMenuToDevices(Menu menu, final Device dev) {
+        // Menu to add one or more resources to the collection.
+        MenuItem addResources = new MenuItem(menu, SWT.CASCADE);
+        addResources.setText("Add Resources");
+
+        Menu addSubMenu = new Menu(menu);
+        addResources.setMenu(addSubMenu);
+
+        MenuItem simpleResources = new MenuItem(addSubMenu, SWT.NONE);
+        simpleResources.setText("Simple");
+        simpleResources.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                List<SingleResource> possibleResources;
+                possibleResources = resourceManager
+                        .getSingleTypeResourcesForAddingToDevice(dev);
+                if (null == possibleResources || possibleResources.isEmpty()) {
+                    MessageDialog
+                            .openError(Display.getDefault().getActiveShell(),
+                                    "No possible candidates",
+                                    "There are no possible simple resources that can be added.");
+                    return;
+                }
+
+                List<Resource> resources = Utility
+                        .convertSingleTypeResourceListToBaseType(possibleResources);
+
+                AddResources addDlg = new AddResources(Display.getDefault()
+                        .getActiveShell(), resources);
+                if (addDlg.open() != Window.OK) {
+                    return;
+                }
+
+                Set<Resource> resultSet = addDlg.getSelectedResourceList();
+
+                resourceManager.addResourceToDevice(dev, resultSet);
+
+                deviceTreeViewer.refresh();
+
+                MessageDialog.openInformation(Display.getDefault()
+                        .getActiveShell(), "Added",
+                        "Single Resources added to the device");
+            }
+        });
+
+        MenuItem collectionResources = new MenuItem(addSubMenu, SWT.NONE);
+        collectionResources.setText("Collection");
+        collectionResources.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                List<CollectionResource> possibleResources;
+                possibleResources = resourceManager
+                        .getCollectionTypeResourcesForAddingToDevice(dev);
+                if (null == possibleResources || possibleResources.isEmpty()) {
+                    MessageDialog
+                            .openError(Display.getDefault().getActiveShell(),
+                                    "No possible candidates",
+                                    "There are no possible collections that can be added.");
+                    return;
+                }
+
+                List<Resource> resources = Utility
+                        .convertCollectionTypeResourceListToBaseType(possibleResources);
+
+                AddResources addDlg = new AddResources(Display.getDefault()
+                        .getActiveShell(), resources);
+                if (addDlg.open() != Window.OK) {
+                    return;
+                }
+
+                Set<Resource> resultSet = addDlg.getSelectedResourceList();
+
+                resourceManager.addResourceToDevice(dev, resultSet);
+
+                deviceTreeViewer.refresh();
+
+                MessageDialog.openInformation(Display.getDefault()
+                        .getActiveShell(), "Added",
+                        "Collection Resources added to the device");
+            }
+        });
+
+        // Menu to remove one or more resources from the collection.
+        MenuItem removeResources = new MenuItem(menu, SWT.CASCADE);
+        removeResources.setText("Remove Resources");
+
+        Menu removeSubMenu = new Menu(menu);
+        removeResources.setMenu(removeSubMenu);
+
+        simpleResources = new MenuItem(removeSubMenu, SWT.NONE);
+        simpleResources.setText("Simple");
+        simpleResources.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                List<SingleResource> possibleResources;
+                possibleResources = resourceManager.getSingleTypeChilds(dev);
+                if (null == possibleResources || possibleResources.isEmpty()) {
+                    MessageDialog
+                            .openError(Display.getDefault().getActiveShell(),
+                                    "No possible candidates",
+                                    "There are no possible simple resources which can be removed.");
+                    return;
+                }
+
+                List<Resource> resources = Utility
+                        .convertSingleTypeResourceListToBaseType(possibleResources);
+
+                RemoveResources removeDlg = new RemoveResources(Display
+                        .getDefault().getActiveShell(), resources);
+                if (removeDlg.open() != Window.OK) {
+                    return;
+                }
+
+                Set<Resource> resultSet = removeDlg.getSelectedResourceList();
+
+                resourceManager.removeResourcesFromDevice(dev, resultSet);
+
+                collectionResTreeViewer.refresh();
+
+                deviceTreeViewer.refresh();
+
+                MessageDialog.openInformation(Display.getDefault()
+                        .getActiveShell(), "Removed",
+                        "Single Resources removed from the device");
+            }
+        });
+
+        collectionResources = new MenuItem(removeSubMenu, SWT.NONE);
+        collectionResources.setText("Collection");
+        collectionResources.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                List<CollectionResource> possibleResources;
+                possibleResources = resourceManager
+                        .getCollectionTypeChilds(dev);
+                if (null == possibleResources || possibleResources.isEmpty()) {
+                    MessageDialog
+                            .openError(Display.getDefault().getActiveShell(),
+                                    "No possible candidates",
+                                    "There are no possible collections which can be removed.");
+                    return;
+                }
+
+                List<Resource> resources = Utility
+                        .convertCollectionTypeResourceListToBaseType(possibleResources);
+
+                RemoveResources removeDlg = new RemoveResources(Display
+                        .getDefault().getActiveShell(), resources);
+                if (removeDlg.open() != Window.OK) {
+                    return;
+                }
+
+                Set<Resource> resultSet = removeDlg.getSelectedResourceList();
+
+                resourceManager.removeResourcesFromDevice(dev, resultSet);
+
+                collectionResTreeViewer.refresh();
+
+                deviceTreeViewer.refresh();
+
+                MessageDialog.openInformation(Display.getDefault()
+                        .getActiveShell(), "Removed",
+                        "Collection Resources removed from the device");
+            }
+        });
+
+        // Menu to remove the device.
+        MenuItem deleteDevice = new MenuItem(menu, SWT.NONE);
+        deleteDevice.setText("Delete");
+        deleteDevice.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                resourceManager.removeDevice(dev);
+                deviceTreeViewer.refresh();
+            }
+        });
+    }
+
+    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);
+                        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(selectedResource);
+                String statusMsg = status ? "Automation stopped!!!"
+                        : "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() {
+
+        createButton.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {
+
+                    @Override
+                    public void run() {
+                        CreateResourceWizard createWizard = new CreateResourceWizard();
+                        ResourceWizardDialog wizardDialog = new ResourceWizardDialog(
+                                PlatformUI.getWorkbench().getDisplay()
+                                        .getActiveShell(), createWizard);
+                        createWizard.setWizardDialog(wizardDialog);
+                        int open = wizardDialog.open();
+                        if (open == WizardDialog.OK
+                                || createWizard.isDlgForceClosed()) {
+                            MessageDialog.openInformation(Display.getDefault()
+                                    .getActiveShell(),
+                                    "Resource Creation Status", createWizard
+                                            .getStatus());
+                        }
+                    }
+                });
+            }
+        });
+
+        deleteButton.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {
+
+                    @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 == Window.OK) {
+                            singleResTreeViewer.refresh();
+                            collectionResTreeViewer.refresh();
+                            deviceTreeViewer.refresh();
+                            MessageDialog.openInformation(Display.getDefault()
+                                    .getActiveShell(),
+                                    "Resource Deletion Status", deleteWizard
+                                            .getStatus());
+
+                            changeDeleteVisibility();
+                        }
+                    }
+                });
+            }
+        });
+    }
+
     public void addManagerListeners() {
-        resourceManager
-                .addResourceListChangedUIListener(resourceListChangedListener);
+        UiListenerHandler.getInstance().addResourceListChangedUIListener(
+                resourceListChangedListener);
+        UiListenerHandler.getInstance().addResourcePropertiesChangedUIListener(
+                resourcePropertiesChangedListener);
     }
 
     @Override
@@ -379,15 +1544,110 @@ 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() {
+    }
+
+    @Override
+    public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
+    }
+
+    @Override
+    public Object[] getChildren(Object parent) {
+        return null;
+    }
+
+    @Override
+    public Object[] getElements(Object parent) {
+        List<SingleResource> resList;
+        resList = Activator.getDefault().getResourceManager()
+                .getSingleResourceList();
+        if (null == resList) {
+            resList = new ArrayList<SingleResource>();
+        }
+        return resList.toArray();
+    }
+
+    @Override
+    public Object getParent(Object child) {
+        return null;
+    }
+
+    @Override
+    public boolean hasChildren(Object parent) {
+        return false;
+    }
+}
+
+class CollectionResourceContentProvider implements ITreeContentProvider {
+
+    @Override
+    public void dispose() {
+    }
+
+    @Override
+    public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
+    }
+
+    @Override
+    public Object[] getChildren(Object parent) {
+        if (parent instanceof CollectionResource) {
+            CollectionResource cRes = (CollectionResource) parent;
+            Set<Resource> childs = cRes.getChildResources();
+            if (null == childs) {
+                return null;
+            }
+            return childs.toArray();
+        }
+        return null;
+    }
+
+    @Override
+    public Object[] getElements(Object parent) {
+        List<CollectionResource> resList;
+        resList = Activator.getDefault().getResourceManager()
+                .getCollectionResourceList();
+        if (null == resList) {
+            resList = new ArrayList<CollectionResource>();
+        }
+        return resList.toArray();
+    }
+
+    @Override
+    public Object getParent(Object child) {
+        return null;
+    }
+
+    @Override
+    public boolean hasChildren(Object parent) {
+        if (parent instanceof CollectionResource) {
+            CollectionResource cRes = (CollectionResource) parent;
+            Set<Resource> children = cRes.getChildResources();
+            if (null != children && children.size() > 0) {
+                return true;
+            }
+        }
+        return false;
+    }
+}
+
+class DeviceContentProvider implements ITreeContentProvider {
 
     @Override
     public void dispose() {
@@ -399,17 +1659,31 @@ class TreeContentProvider implements ITreeContentProvider {
 
     @Override
     public Object[] getChildren(Object parent) {
+        if (parent instanceof Device) {
+            Device dev = (Device) parent;
+            Set<Resource> children = dev.getChildResources();
+            if (null != children && children.size() > 0) {
+                return children.toArray();
+            }
+        } else if (parent instanceof CollectionResource) {
+            CollectionResource res = (CollectionResource) parent;
+            Set<Resource> children = res.getChildResources();
+            if (null != children && children.size() > 0) {
+                return children.toArray();
+            }
+        }
         return null;
     }
 
     @Override
     public Object[] getElements(Object parent) {
-        List<String> uriList;
-        uriList = Activator.getDefault().getResourceManager().getURIList();
-        if (null == uriList) {
-            uriList = new ArrayList<String>();
+        List<Device> deviceList;
+        deviceList = Activator.getDefault().getResourceManager()
+                .getDeviceList();
+        if (null == deviceList) {
+            deviceList = new ArrayList<Device>();
         }
-        return uriList.toArray();
+        return deviceList.toArray();
     }
 
     @Override
@@ -419,6 +1693,19 @@ class TreeContentProvider implements ITreeContentProvider {
 
     @Override
     public boolean hasChildren(Object parent) {
+        if (parent instanceof Device) {
+            Device dev = (Device) parent;
+            Set<Resource> children = dev.getChildResources();
+            if (null != children && children.size() > 0) {
+                return true;
+            }
+        } else if (parent instanceof CollectionResource) {
+            CollectionResource res = (CollectionResource) parent;
+            Set<Resource> children = res.getChildResources();
+            if (null != children && children.size() > 0) {
+                return true;
+            }
+        }
         return false;
     }
 }
@@ -426,15 +1713,26 @@ 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();
+        } else {
+            Device dev = (Device) element;
+            return dev.getDeviceName();
+        }
     }
 
     @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);
+        } else if (element instanceof CollectionResource) {
+            return Activator.getDefault().getImageRegistry()
+                    .get(Constants.COLLECTION_RESOURCE);
+        } else {
+            return Activator.getDefault().getImageRegistry()
+                    .get(Constants.DEVICE);
+        }
     }
 }
\ No newline at end of file
index 5e9361fc5fcb923cf5aa4bdf3724a74ba7141f24..14fd2b207fab4c556444b28b03ee6f00e00a122f 100644 (file)
@@ -22,10 +22,12 @@ 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.listener.ISelectionChangedUIListener;
 import oic.simulator.serviceprovider.manager.ResourceManager;
-import oic.simulator.serviceprovider.resource.ObserverDetail;
-import oic.simulator.serviceprovider.resource.SimulatorResource;
+import oic.simulator.serviceprovider.manager.UiListenerHandler;
+import oic.simulator.serviceprovider.model.Device;
+import oic.simulator.serviceprovider.model.ObserverDetail;
+import oic.simulator.serviceprovider.model.Resource;
 import oic.simulator.serviceprovider.utils.Constants;
 
 import org.eclipse.jface.viewers.CellEditor;
@@ -51,60 +53,65 @@ import org.eclipse.ui.part.ViewPart;
  * 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 ISelectionChangedUIListener    resourceSelectionChangedListener;
 
-    private IObserverListChangedUIListener      resourceObserverListChangedListener;
+    private IObserverListChangedUIListener resourceObserverListChangedListener;
 
-    private ResourceManager                     resourceManagerRef;
+    private ResourceManager                resourceManagerRef;
 
     public ResourceObserverView() {
 
         resourceManagerRef = Activator.getDefault().getResourceManager();
 
-        resourceSelectionChangedListener = new IResourceSelectionChangedUIListener() {
+        resourceSelectionChangedListener = new ISelectionChangedUIListener() {
 
             @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));
                         }
                     }
                 });
             }
+
+            @Override
+            public void onDeviceSelectionChange(Device dev) {
+                // TODO Auto-generated method stub
+
+            }
         };
 
         resourceObserverListChangedListener = new IObserverListChangedUIListener() {
 
             @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 +123,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;
         }
@@ -229,10 +236,10 @@ 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 {
@@ -273,7 +280,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 +287,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 +303,7 @@ public class ResourceObserverView extends ViewPart {
     }
 
     private void changeButtonStatus() {
-        SimulatorResource resource = resourceManagerRef
-                .getCurrentResourceInSelection();
+        Resource resource = resourceManagerRef.getCurrentResourceInSelection();
         if (null == resource) {
             return;
         }
@@ -318,13 +322,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..6fc69fa
--- /dev/null
@@ -0,0 +1,731 @@
+package oic.simulator.serviceprovider.view.dialogs;
+
+import java.util.Iterator;
+import java.util.Set;
+
+import oic.simulator.serviceprovider.model.AttributeHelper;
+import oic.simulator.serviceprovider.utils.Constants;
+
+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 org.oic.simulator.AttributeProperty.Type;
+
+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 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 final String         msgForBoolType   = "Possible attribute values of Bool are "
+                                                          + "true and false.\nSo range and custom options are disabled.";
+    private 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 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 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();
+            System.out.println("Cloned attribute's data:" + attClone);
+            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);
+        /*
+         * layout.verticalSpacing = 10; layout.marginTop = 10;
+         */
+        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());
+            Type valuesType = attHelper.getValidValuesType();
+            /*
+             * if (valuesType == Type.UNKNOWN) { noneBtn.setSelection(true); }
+             * else
+             */if (valuesType == Type.RANGE) {
+                rangeBtn.setSelection(true);
+                noneBtn.setSelection(false);
+                rangeOptionSelected(true);
+                minRangeTxt.setText(attHelper.getMin());
+                maxRangeTxt.setText(attHelper.getMax());
+            } else if (valuesType == Type.VALUESET) {
+                cusValuesBtn.setSelection(true);
+                noneBtn.setSelection(false);
+                customOptionSelected(true);
+                Set<String> allowedValues = attHelper.getAllowedValues();
+                customValuesList.setItems(allowedValues.toArray(new String[1]));
+            }
+        }
+    }
+
+    private void setUiListeners() {
+
+        /*
+         * attNameTxt.addModifyListener(new ModifyListener() {
+         * 
+         * @Override public void modifyText(ModifyEvent e) { String value =
+         * attNameTxt.getText(); if(null != value) { value = value.trim(); }
+         * attHelper.setAttributeName(value); } });
+         * 
+         * dflValueTxt.addModifyListener(new ModifyListener() {
+         * 
+         * @Override public void modifyText(ModifyEvent arg0) { String value =
+         * dflValueTxt.getText(); if(null != value) { value = value.trim(); }
+         * attHelper.setAttributeDflValue(value); } });
+         */
+        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;
+                System.out.println(string);
+                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')) {
+                        if (attTypeCmb.getText().equals(Constants.INT)) {
+                            e.doit = false;
+                            return;
+                        } else if (attTypeCmb.getText()
+                                .equals(Constants.DOUBLE)) {
+                            if (!(chars[i] == '.')) {
+                                e.doit = false;
+                                return;
+                            }
+                        }
+                    }
+                }
+                // attHelper.setMin(minRangeTxt.getText() + string);
+            }
+        });
+
+        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')) {
+                        if (attTypeCmb.getText().equals(Constants.INT)) {
+                            e.doit = false;
+                            return;
+                        } else if (attTypeCmb.getText()
+                                .equals(Constants.DOUBLE)) {
+                            if (!(chars[i] == '.')) {
+                                e.doit = false;
+                                return;
+                            }
+                        }
+                    }
+                }
+                // attHelper.setMax(maxRangeTxt.getText() + string);
+            }
+        });
+
+        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) {
+                    System.out.println(dialog.getValue());
+                    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);
+                        // attHelper.addValueToAllowedValues(value);
+                    }
+                }
+            }
+        });
+
+        remBtn.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                int[] selection = customValuesList.getSelectionIndices();
+                // String[] selectionStr = customValuesList.getSelection();
+                if (null != selection && selection.length > 0) {
+                    customValuesList.remove(selection);
+                    /*
+                     * for (String selected : selectionStr) {
+                     * attHelper.removeValueFromAllowedValues(selected); }
+                     */
+                }
+
+                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();
+        // attHelper.setAttributeType(selected);
+
+        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)) {
+            // noneBtn.setSelection(true);
+            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);
+            // cusValuesBtn.setSelection(true);
+            detail.setText(defaultMessage + msgForStringType);
+        } else {
+            // noneBtn.setSelection(true);
+            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(Type.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(Type.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(Type.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 getInitialSize() { Point curSize =
+     * super.getInitialSize(); return new Point(curSize.x, curSize.y + 200); }
+     */
+
+    @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/AddResourceToCollections.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/AddResourceToCollections.java
new file mode 100644 (file)
index 0000000..914e515
--- /dev/null
@@ -0,0 +1,206 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.model.CollectionResource;
+import oic.simulator.serviceprovider.utils.Constants;
+
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.dialogs.TitleAreaDialog;
+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.Viewer;
+import org.eclipse.swt.SWT;
+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.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.Shell;
+
+/**
+ * This dialog is used for loading the RAML file.
+ */
+public class AddResourceToCollections extends TitleAreaDialog {
+
+    private CheckboxTreeViewer treeViewer;
+
+    List<CollectionResource>   sourceList;
+
+    Set<CollectionResource>    selectedResourceList;
+
+    public AddResourceToCollections(Shell parentShell,
+            List<CollectionResource> sourceList) {
+        super(parentShell);
+        this.sourceList = sourceList;
+        selectedResourceList = new HashSet<CollectionResource>();
+    }
+
+    @Override
+    public void create() {
+        super.create();
+        setTitle("Add To Collections");
+        setMessage("Select one or more collection resources to which the single resource will be added.");
+    }
+
+    @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();
+        layout.verticalSpacing = 10;
+        layout.marginTop = 10;
+        container.setLayout(layout);
+
+        Label lbl = new Label(container, SWT.NONE);
+        lbl.setText("Select Resources from:");
+        GridData gd;
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        lbl.setLayoutData(gd);
+
+        Group resourceGroup = new Group(container, SWT.NONE);
+
+        Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE);
+
+        resourceGroup.setLayout(new GridLayout());
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.heightHint = 300;
+        gd.horizontalSpan = 2;
+        resourceGroup.setLayoutData(gd);
+
+        treeViewer = new CheckboxTreeViewer(resourceGroup);
+        treeViewer.getTree().setBackground(color);
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.grabExcessVerticalSpace = true;
+        gd.verticalAlignment = SWT.FILL;
+        // gd.heightHint = 300;
+        treeViewer.getTree().setLayoutData(gd);
+        treeViewer.setContentProvider(new TreeContentProvider());
+        treeViewer.setLabelProvider(new TreeLabelProvider());
+        treeViewer.setInput(new Object());
+        treeViewer.addCheckStateListener(new ICheckStateListener() {
+
+            @Override
+            public void checkStateChanged(CheckStateChangedEvent e) {
+                CollectionResource res = (CollectionResource) e.getElement();
+                if (null != res) {
+                    if (e.getChecked()) {
+                        selectedResourceList.add(res);
+                        System.out.println("Checked" + res.getResourceName());
+                    } else {
+                        selectedResourceList.remove(res);
+                        System.out.println("Unchecked:" + res.getResourceName());
+                    }
+                }
+            }
+        });
+
+        return compLayout;
+    }
+
+    public Set<CollectionResource> getSelectedResourceList() {
+        return selectedResourceList;
+    }
+
+    class TreeContentProvider implements ITreeContentProvider {
+
+        @Override
+        public void dispose() {
+        }
+
+        @Override
+        public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
+        }
+
+        @Override
+        public Object[] getChildren(Object parent) {
+            return null;
+        }
+
+        @Override
+        public Object[] getElements(Object parent) {
+            if (null == sourceList) {
+                sourceList = new ArrayList<CollectionResource>();
+            }
+            return sourceList.toArray();
+        }
+
+        @Override
+        public Object getParent(Object child) {
+            return null;
+        }
+
+        @Override
+        public boolean hasChildren(Object parent) {
+            return false;
+        }
+    }
+
+    class TreeLabelProvider extends LabelProvider {
+        @Override
+        public String getText(Object element) {
+            CollectionResource res = (CollectionResource) element;
+            return res.getResourceName();
+        }
+
+        @Override
+        public Image getImage(Object element) {
+            if (element instanceof CollectionResource) {
+                return Activator.getDefault().getImageRegistry()
+                        .get(Constants.COLLECTION_RESOURCE);
+            } else {
+                return null;
+            }
+        }
+    }
+
+    @Override
+    protected void okPressed() {
+        if (selectedResourceList.isEmpty()) {
+            MessageDialog.openInformation(
+                    Display.getDefault().getActiveShell(),
+                    "No selection done.", "No resources are selected.");
+            return;
+        }
+        close();
+    }
+
+    @Override
+    public boolean isHelpAvailable() {
+        return false;
+    }
+}
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/AddResourceToDevices.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/AddResourceToDevices.java
new file mode 100644 (file)
index 0000000..8eaaa5f
--- /dev/null
@@ -0,0 +1,205 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.model.Device;
+import oic.simulator.serviceprovider.utils.Constants;
+
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.dialogs.TitleAreaDialog;
+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.Viewer;
+import org.eclipse.swt.SWT;
+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.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.Shell;
+
+/**
+ * This dialog is used for loading the RAML file.
+ */
+public class AddResourceToDevices extends TitleAreaDialog {
+
+    private CheckboxTreeViewer treeViewer;
+
+    List<Device>               sourceList;
+
+    Set<Device>                selectedDeviceList;
+
+    public AddResourceToDevices(Shell parentShell, List<Device> sourceList) {
+        super(parentShell);
+        this.sourceList = sourceList;
+        selectedDeviceList = new HashSet<Device>();
+    }
+
+    @Override
+    public void create() {
+        super.create();
+        setTitle("Add To Devices");
+        setMessage("Select one or more devices to which the single resource will be added.");
+    }
+
+    @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();
+        layout.verticalSpacing = 10;
+        layout.marginTop = 10;
+        container.setLayout(layout);
+
+        Label lbl = new Label(container, SWT.NONE);
+        lbl.setText("Select Resources from:");
+        GridData gd;
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        lbl.setLayoutData(gd);
+
+        Group resourceGroup = new Group(container, SWT.NONE);
+
+        Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE);
+
+        resourceGroup.setLayout(new GridLayout());
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.heightHint = 300;
+        gd.horizontalSpan = 2;
+        resourceGroup.setLayoutData(gd);
+
+        treeViewer = new CheckboxTreeViewer(resourceGroup);
+        treeViewer.getTree().setBackground(color);
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.grabExcessVerticalSpace = true;
+        gd.verticalAlignment = SWT.FILL;
+        // gd.heightHint = 300;
+        treeViewer.getTree().setLayoutData(gd);
+        treeViewer.setContentProvider(new TreeContentProvider());
+        treeViewer.setLabelProvider(new TreeLabelProvider());
+        treeViewer.setInput(new Object());
+        treeViewer.addCheckStateListener(new ICheckStateListener() {
+
+            @Override
+            public void checkStateChanged(CheckStateChangedEvent e) {
+                Device dev = (Device) e.getElement();
+                if (null != dev) {
+                    if (e.getChecked()) {
+                        selectedDeviceList.add(dev);
+                        System.out.println("Checked" + dev.getDeviceName());
+                    } else {
+                        selectedDeviceList.remove(dev);
+                        System.out.println("Unchecked:" + dev.getDeviceName());
+                    }
+                }
+            }
+        });
+
+        return compLayout;
+    }
+
+    public Set<Device> getSelectedDeviceList() {
+        return selectedDeviceList;
+    }
+
+    class TreeContentProvider implements ITreeContentProvider {
+
+        @Override
+        public void dispose() {
+        }
+
+        @Override
+        public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
+        }
+
+        @Override
+        public Object[] getChildren(Object parent) {
+            return null;
+        }
+
+        @Override
+        public Object[] getElements(Object parent) {
+            if (null == sourceList) {
+                sourceList = new ArrayList<Device>();
+            }
+            return sourceList.toArray();
+        }
+
+        @Override
+        public Object getParent(Object child) {
+            return null;
+        }
+
+        @Override
+        public boolean hasChildren(Object parent) {
+            return false;
+        }
+    }
+
+    class TreeLabelProvider extends LabelProvider {
+        @Override
+        public String getText(Object element) {
+            Device dev = (Device) element;
+            return dev.getDeviceName();
+        }
+
+        @Override
+        public Image getImage(Object element) {
+            if (element instanceof Device) {
+                return Activator.getDefault().getImageRegistry()
+                        .get(Constants.DEVICE);
+            } else {
+                return null;
+            }
+        }
+    }
+
+    @Override
+    protected void okPressed() {
+        if (selectedDeviceList.isEmpty()) {
+            MessageDialog.openInformation(
+                    Display.getDefault().getActiveShell(),
+                    "No selection done.", "No devices are selected.");
+            return;
+        }
+        close();
+    }
+
+    @Override
+    public boolean isHelpAvailable() {
+        return false;
+    }
+}
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/AddResources.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/AddResources.java
new file mode 100644 (file)
index 0000000..6e13f6c
--- /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.
+ */
+
+package oic.simulator.serviceprovider.view.dialogs;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.model.CollectionResource;
+import oic.simulator.serviceprovider.model.Resource;
+import oic.simulator.serviceprovider.utils.Constants;
+
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.dialogs.TitleAreaDialog;
+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.Viewer;
+import org.eclipse.swt.SWT;
+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.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.Shell;
+
+/**
+ * This dialog is used for loading the RAML file.
+ */
+public class AddResources extends TitleAreaDialog {
+
+    private CheckboxTreeViewer treeViewer;
+
+    List<Resource>             sourceList;
+
+    Set<Resource>              selectedResourceList;
+
+    public AddResources(Shell parentShell, List<Resource> sourceList) {
+        super(parentShell);
+        this.sourceList = sourceList;
+        selectedResourceList = new HashSet<Resource>();
+    }
+
+    @Override
+    public void create() {
+        super.create();
+        setTitle("Add Resources");
+        setMessage("Select one or more resources to be added.");
+    }
+
+    @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();
+        layout.verticalSpacing = 10;
+        layout.marginTop = 10;
+        container.setLayout(layout);
+
+        Label lbl = new Label(container, SWT.NONE);
+        lbl.setText("Select Resources from:");
+        GridData gd;
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        lbl.setLayoutData(gd);
+
+        Group resourceGroup = new Group(container, SWT.NONE);
+
+        Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE);
+
+        resourceGroup.setLayout(new GridLayout());
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.heightHint = 300;
+        gd.horizontalSpan = 2;
+        resourceGroup.setLayoutData(gd);
+
+        treeViewer = new CheckboxTreeViewer(resourceGroup);
+        treeViewer.getTree().setBackground(color);
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.grabExcessVerticalSpace = true;
+        gd.verticalAlignment = SWT.FILL;
+        // gd.heightHint = 300;
+        treeViewer.getTree().setLayoutData(gd);
+        treeViewer.setContentProvider(new TreeContentProvider());
+        treeViewer.setLabelProvider(new TreeLabelProvider());
+        treeViewer.setInput(new Object());
+        treeViewer.addCheckStateListener(new ICheckStateListener() {
+
+            @Override
+            public void checkStateChanged(CheckStateChangedEvent e) {
+                Resource res = (Resource) e.getElement();
+                if (null != res) {
+                    if (e.getChecked()) {
+                        selectedResourceList.add(res);
+                        System.out.println("Checked" + res.getResourceName());
+                    } else {
+                        selectedResourceList.remove(res);
+                        System.out.println("Unchecked:" + res.getResourceName());
+                    }
+                }
+            }
+        });
+
+        return compLayout;
+    }
+
+    public Set<Resource> getSelectedResourceList() {
+        return selectedResourceList;
+    }
+
+    class TreeContentProvider implements ITreeContentProvider {
+
+        @Override
+        public void dispose() {
+        }
+
+        @Override
+        public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
+        }
+
+        @Override
+        public Object[] getChildren(Object parent) {
+            return null;
+        }
+
+        @Override
+        public Object[] getElements(Object parent) {
+            if (null == sourceList) {
+                sourceList = new ArrayList<Resource>();
+            }
+            return sourceList.toArray();
+        }
+
+        @Override
+        public Object getParent(Object child) {
+            return null;
+        }
+
+        @Override
+        public boolean hasChildren(Object parent) {
+            return false;
+        }
+    }
+
+    class TreeLabelProvider extends LabelProvider {
+        @Override
+        public String getText(Object element) {
+            Resource res = (Resource) element;
+            return res.getResourceName();
+        }
+
+        @Override
+        public Image getImage(Object element) {
+            if (element instanceof CollectionResource) {
+                return Activator.getDefault().getImageRegistry()
+                        .get(Constants.COLLECTION_RESOURCE);
+            } else {
+                return Activator.getDefault().getImageRegistry()
+                        .get(Constants.SINGLE_RESOURCE);
+            }
+        }
+    }
+
+    @Override
+    protected void okPressed() {
+        if (selectedResourceList.isEmpty()) {
+            MessageDialog.openInformation(
+                    Display.getDefault().getActiveShell(),
+                    "No selection done.", "No resources are selected.");
+            return;
+        }
+        close();
+    }
+
+    @Override
+    public boolean isHelpAvailable() {
+        return false;
+    }
+}
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/AddResourcesToCollectionPage.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/AddResourcesToCollectionPage.java
new file mode 100644 (file)
index 0000000..d745c38
--- /dev/null
@@ -0,0 +1,169 @@
+package oic.simulator.serviceprovider.view.dialogs;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.model.CollectionResource;
+import oic.simulator.serviceprovider.model.Resource;
+import oic.simulator.serviceprovider.model.SingleResource;
+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.Viewer;
+import org.eclipse.jface.wizard.IWizardPage;
+import org.eclipse.jface.wizard.WizardPage;
+import org.eclipse.swt.SWT;
+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.Composite;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Group;
+
+public class AddResourcesToCollectionPage extends WizardPage {
+
+    private CheckboxTreeViewer treeViewer;
+
+    Set<Resource>              selectedResourceList;
+
+    protected AddResourcesToCollectionPage() {
+        super("Add Resources To Collection");
+        selectedResourceList = new HashSet<Resource>();
+    }
+
+    @Override
+    public void createControl(Composite parent) {
+        setPageComplete(false);
+        setTitle(Constants.COLLECTION_RESOURCE_ADD_OTHER_RESOURCES_PAGE_TITLE);
+        setMessage(Constants.COLLECTION_RESOURCE_ADD_OTHER_RESOURCES_PAGE_MESSAGE);
+
+        Composite container = new Composite(parent, SWT.NONE);
+        GridLayout gridLayout = new GridLayout();
+        container.setLayout(gridLayout);
+        GridData gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.heightHint = 300;
+        container.setLayoutData(gd);
+
+        Group resourceGroup = new Group(container, SWT.NONE);
+
+        Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE);
+
+        resourceGroup.setLayout(new GridLayout());
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.heightHint = 300;
+        resourceGroup.setLayoutData(gd);
+
+        treeViewer = new CheckboxTreeViewer(resourceGroup);
+        treeViewer.getTree().setBackground(color);
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.grabExcessVerticalSpace = true;
+        gd.verticalAlignment = SWT.FILL;
+        // gd.heightHint = 300;
+        treeViewer.getTree().setLayoutData(gd);
+        treeViewer.setContentProvider(new TreeContentProvider());
+        treeViewer.setLabelProvider(new TreeLabelProvider());
+        treeViewer.setInput(new Object());
+        treeViewer.addCheckStateListener(new ICheckStateListener() {
+
+            @Override
+            public void checkStateChanged(CheckStateChangedEvent e) {
+                Resource res = (Resource) e.getElement();
+                if (null != res) {
+                    if (e.getChecked()) {
+                        selectedResourceList.add(res);
+                        System.out.println("Checked" + res.getResourceName());
+                    } else {
+                        selectedResourceList.remove(res);
+                        System.out.println("Unchecked:" + res.getResourceName());
+                    }
+                }
+            }
+        });
+
+        setControl(container);
+    }
+
+    @Override
+    public IWizardPage getNextPage() {
+        return null;
+    }
+
+    public Set<Resource> getSelectedResourceList() {
+        return selectedResourceList;
+    }
+
+    class TreeContentProvider implements ITreeContentProvider {
+
+        @Override
+        public void dispose() {
+        }
+
+        @Override
+        public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
+        }
+
+        @Override
+        public Object[] getChildren(Object parent) {
+            System.out.println("getChildren()");
+
+            return null;
+        }
+
+        @Override
+        public Object[] getElements(Object parent) {
+            List<Resource> resList;
+            resList = Activator.getDefault().getResourceManager()
+                    .getResourceList();
+            if (null == resList) {
+                resList = new ArrayList<Resource>();
+            }
+            return resList.toArray();
+        }
+
+        @Override
+        public Object getParent(Object child) {
+            return null;
+        }
+
+        @Override
+        public boolean hasChildren(Object parent) {
+            return false;
+        }
+    }
+
+    class TreeLabelProvider extends LabelProvider {
+        @Override
+        public String getText(Object element) {
+            Resource res = (Resource) element;
+            return res.getResourceName();
+        }
+
+        @Override
+        public Image getImage(Object element) {
+            if (element instanceof SingleResource) {
+                return Activator.getDefault().getImageRegistry()
+                        .get(Constants.SINGLE_RESOURCE);
+            } else if (element instanceof CollectionResource) {
+                return Activator.getDefault().getImageRegistry()
+                        .get(Constants.COLLECTION_RESOURCE);
+            } else {
+                return Activator.getDefault().getImageRegistry()
+                        .get(Constants.DEVICE);
+            }
+        }
+    }
+}
index e2bb48f23e047b76812ab4a99a7b1bdb9aa1d05a..f6ab64be8050d0658517092401993d233f405865 100644 (file)
@@ -19,7 +19,7 @@ package oic.simulator.serviceprovider.view.dialogs;
 import java.util.Iterator;
 import java.util.List;
 
-import oic.simulator.serviceprovider.resource.AutomationSettingHelper;
+import oic.simulator.serviceprovider.model.AutomationSettingHelper;
 import oic.simulator.serviceprovider.utils.Constants;
 
 import org.eclipse.jface.dialogs.TitleAreaDialog;
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/CollectionResourceBasicDetailsPage.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/CollectionResourceBasicDetailsPage.java
new file mode 100644 (file)
index 0000000..5024c6d
--- /dev/null
@@ -0,0 +1,337 @@
+package oic.simulator.serviceprovider.view.dialogs;
+
+import java.util.HashSet;
+import java.util.Set;
+
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.utils.Constants;
+
+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;
+
+public class CollectionResourceBasicDetailsPage extends WizardPage {
+
+    private Text        resNameTxt;
+    private Text        resUriTxt;
+    private List        resTypeslist;
+    private Button      addToListBtn;
+    private Button      remFromListBtn;
+    private Button      observeBtn;
+    // private Button startBtn;
+
+    private String      resName;
+    private String      resURI;
+    private Set<String> resTypes;
+    // private boolean start;
+    private boolean     observable;
+    private boolean     anyResourceExist;
+
+    protected CollectionResourceBasicDetailsPage() {
+        super("Basic Details");
+        resTypes = new HashSet<String>();
+        anyResourceExist = Activator.getDefault().getResourceManager()
+                .isAnyResourceExist();
+    }
+
+    @Override
+    public void createControl(Composite parent) {
+        setPageComplete(false);
+        if (anyResourceExist)
+            setTitle(Constants.COLLECTION_RESOURCE_BASIC_DETAILS_PAGE_TITLE2);
+        else
+            setTitle(Constants.COLLECTION_RESOURCE_BASIC_DETAILS_PAGE_TITLE1);
+        setMessage(Constants.COLLECTION_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();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        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.widthHint = 300;
+        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.widthHint = 300;
+        gd.horizontalSpan = 3;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.grabExcessHorizontalSpace = true;
+        resUriTxt.setLayoutData(gd);
+        /*
+         * Composite resTypesComp = new Composite(compContent, SWT.NONE);
+         * gridLayout = new GridLayout(3, false);
+         * resTypesComp.setLayout(gridLayout); gd = new GridData();
+         * gd.grabExcessHorizontalSpace = true; gd.horizontalAlignment =
+         * SWT.FILL; resTypesComp.setLayoutData(gd);
+         */
+
+        Label resTypesLbl = new Label(resDetGrp, SWT.NULL);
+        resTypesLbl.setText(Constants.RESOURCE_TYPES);
+
+        resTypeslist = new List(resDetGrp, SWT.BORDER | SWT.MULTI
+                | SWT.V_SCROLL);
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.horizontalSpan = 2;
+        gd.heightHint = 100;
+        /* gd.widthHint = 200; */
+        resTypeslist.setLayoutData(gd);
+        // resTypeslist.setBackground(new Color());
+
+        Composite resTypesActionsComp = new Composite(resDetGrp, SWT.NONE);
+        gridLayout = new GridLayout();
+        resTypesActionsComp.setLayout(gridLayout);
+        gd = new GridData();
+        gd.verticalAlignment = SWT.TOP;
+        /*
+         * gd.grabExcessHorizontalSpace = true; gd.horizontalAlignment =
+         * SWT.FILL;
+         */
+        resTypesActionsComp.setLayoutData(gd);
+
+        addToListBtn = new Button(resTypesActionsComp, SWT.PUSH);
+        addToListBtn.setText("Add");
+        gd = new GridData();
+        gd.widthHint = 70;
+        addToListBtn.setLayoutData(gd);
+
+        remFromListBtn = new Button(resTypesActionsComp, SWT.PUSH);
+        remFromListBtn.setText("Remove");
+        gd = new GridData();
+        gd.widthHint = 70;
+        remFromListBtn.setLayoutData(gd);
+        remFromListBtn.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);
+
+        observeBtn = new Button(otherOptionsGrp, SWT.CHECK);
+        observeBtn.setText("Observable");
+        observeBtn.setSelection(true);
+        observable = true;
+
+        /*
+         * startBtn = new Button(otherOptionsGrp, SWT.CHECK);
+         * startBtn.setText("Start the resource immediately after creation");
+         * startBtn.setSelection(true);
+         */
+
+        addUiListeners();
+
+        setControl(container);
+    }
+
+    private void addUiListeners() {
+
+        resUriTxt.addModifyListener(new ModifyListener() {
+            @Override
+            public void modifyText(ModifyEvent arg0) {
+                resURI = resUriTxt.getText();
+                if (null == resURI) {
+                    return;
+                }
+                if (anyResourceExist)
+                    getWizard().getContainer().updateButtons();
+                else
+                    setPageComplete(isSelectionDone());
+            }
+        });
+
+        resNameTxt.addModifyListener(new ModifyListener() {
+            @Override
+            public void modifyText(ModifyEvent arg0) {
+                resName = resNameTxt.getText();
+                if (null == resName) {
+                    return;
+                }
+                if (anyResourceExist)
+                    getWizard().getContainer().updateButtons();
+                else
+                    setPageComplete(isSelectionDone());
+            }
+        });
+
+        addToListBtn.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                SingleTextInputDialog dialog = new SingleTextInputDialog(
+                        getShell(), "Add Resource Type", "Resource Type");
+                if (dialog.open() == Window.OK) {
+                    System.out.println(dialog.getValue());
+                    String resType = dialog.getValue();
+                    // Duplicate check.
+                    if (resTypes.contains(resType)) {
+                        MessageDialog.openError(Display.getDefault()
+                                .getActiveShell(), "Duplicate value",
+                                "value already exist.");
+                        return;
+                    }
+                    resTypeslist.add(resType);
+                    resTypeslist.deselectAll();
+                    resTypeslist.select(resTypeslist.getItemCount() - 1);
+                    resTypeslist.showSelection();
+                    remFromListBtn.setEnabled(true);
+                    resTypes.add(resType);
+                    if (anyResourceExist)
+                        getWizard().getContainer().updateButtons();
+                    else
+                        setPageComplete(isSelectionDone());
+                }
+            }
+        });
+
+        remFromListBtn.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                int[] selection = resTypeslist.getSelectionIndices();
+                String[] selectionStr = resTypeslist.getSelection();
+                if (null != selection && selection.length > 0) {
+                    resTypeslist.remove(selection);
+                    for (String selected : selectionStr) {
+                        resTypes.remove(selected);
+                    }
+                }
+                changeVisibility();
+                if (anyResourceExist)
+                    getWizard().getContainer().updateButtons();
+                else
+                    setPageComplete(isSelectionDone());
+            }
+        });
+
+        resTypeslist.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                changeVisibility();
+            }
+        });
+
+        observeBtn.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                observable = observeBtn.getSelection();
+            }
+        });
+
+        /*
+         * startBtn.addSelectionListener(new SelectionAdapter() {
+         * 
+         * @Override public void widgetSelected(SelectionEvent e) { start =
+         * startBtn.getSelection(); } });
+         */
+    }
+
+    private void changeVisibility() {
+        int[] selection = resTypeslist.getSelectionIndices();
+        if (null != selection && selection.length > 0) {
+            remFromListBtn.setEnabled(true);
+        } else {
+            remFromListBtn.setEnabled(false);
+        }
+    }
+
+    @Override
+    public boolean canFlipToNextPage() {
+        System.out.println("canFlipToNextPage()");
+        if (!anyResourceExist) {
+            return false;
+        }
+        return isSelectionDone();
+    }
+
+    public boolean isSelectionDone() {
+        if (null == resName || resName.trim().length() < 1 || null == resURI
+                || resURI.trim().length() < 1 || null == resTypes
+                || resTypes.size() < 1) {
+            return false;
+        }
+        return true;
+    }
+
+    @Override
+    public IWizardPage getNextPage() {
+        // 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.");
+            // TODO: Instead of MessageDialog, errors may be shown on wizard
+            // itself.
+            return null;
+        }
+        if (anyResourceExist) {
+            return ((CreateResourceWizard) getWizard())
+                    .getAddResourcesToCollectionPage();
+        }
+        return null;
+    }
+
+    public String getResName() {
+        return resName;
+    }
+
+    public String getResURI() {
+        return resURI;
+    }
+
+    public Set<String> getResTypes() {
+        return resTypes;
+    }
+
+    /*
+     * public boolean isStart() { return start; }
+     */
+
+    public boolean isObservable() {
+        return observable;
+    }
+
+    public boolean isAnyResourceExist() {
+        return anyResourceExist;
+    }
+}
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 5a11cc0d8a5038db9d9a311a541f0c0577817da4..9098bcf1ffd631e4329d168786ca34016074e854 100644 (file)
 
 package oic.simulator.serviceprovider.view.dialogs;
 
+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 oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.manager.UiListenerHandler;
+import oic.simulator.serviceprovider.model.AttributeHelper;
+import oic.simulator.serviceprovider.model.CollectionResource;
+import oic.simulator.serviceprovider.model.LocalResourceAttribute;
+import oic.simulator.serviceprovider.model.Resource;
+import oic.simulator.serviceprovider.model.ResourceType;
+import oic.simulator.serviceprovider.model.SingleResource;
+import oic.simulator.serviceprovider.utils.Utility;
+import oic.simulator.serviceprovider.view.dialogs.MainPage.ResourceOption;
 
 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.oic.simulator.ILogger.Level;
+import org.oic.simulator.SimulatorException;
 
 /**
  * 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 CollectionResourceBasicDetailsPage collectionResourceBasicDetailsPage;
+    private AddResourcesToCollectionPage       addResourcesToCollectionPage;
+    private LoadRamlPage                       loadRamlPage;
+    private UpdatePropertiesPage               updatePropPage;
+    private DevicePage                         devicePage;
+    private StartStopResourcePage              startStopPage;
+
+    // private SingleResource simResource;
+    private String                             status;
+
+    private WizardDialog                       wizDialog;
+    private boolean                            dlgForceClosed;
 
     public CreateResourceWizard() {
         setWindowTitle("Create resources");
@@ -39,30 +76,544 @@ 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();
+        collectionResourceBasicDetailsPage = new CollectionResourceBasicDetailsPage();
+        addResourcesToCollectionPage = new AddResourcesToCollectionPage();
+        loadRamlPage = new LoadRamlPage();
+        updatePropPage = new UpdatePropertiesPage();
+        devicePage = new DevicePage();
+        startStopPage = new StartStopResourcePage();
+
+        addPage(mainPage);
+        addPage(simpleResourceBasicDetailsPage);
+        addPage(simpleResourceAddAttributePage);
+        addPage(simpleResourceOtherDetailsPage);
+        addPage(collectionResourceBasicDetailsPage);
+        if (Activator.getDefault().getResourceManager().isAnyResourceExist())
+            addPage(addResourcesToCollectionPage);
+        addPage(loadRamlPage);
+        addPage(updatePropPage);
+        addPage(devicePage);
+        addPage(startStopPage);
+    }
+
+    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();
+    }
+
+    @Override
+    public boolean canFinish() {
+        System.out.println("canFinish()");
+        IWizardPage curPage = this.getContainer().getCurrentPage();
+        System.out.println(curPage.getName());
+        if ((curPage == updatePropPage && ((mainPage.getResourceOption() == ResourceOption.SIMPLE_FROM_RAML) || !Activator
+                .getDefault().getResourceManager().isAnyResourceExist()))
+                || (curPage == collectionResourceBasicDetailsPage
+                        && !Activator.getDefault().getResourceManager()
+                                .isAnyResourceExist() && collectionResourceBasicDetailsPage
+                            .isSelectionDone())
+                || curPage == addResourcesToCollectionPage
+                || curPage == simpleResourceAddAttributePage
+                || (curPage == loadRamlPage && loadRamlPage.isSelectionDone() && loadRamlPage
+                        .isMultiResourceCreation()) || curPage == devicePage) {
+            return true;
+        }
+        return false;
     }
 
     @Override
     public boolean performFinish() {
+        System.out.println("performFinish()");
+        final IWizardPage curPage = this.getContainer().getCurrentPage();
+        System.out.println(curPage.getClass().getSimpleName());
+        if (curPage == simpleResourceAddAttributePage) { // Handling Simple
+            // Resource Creation
+            // without RAML
+            try {
+                getContainer().run(true, true, new IRunnableWithProgress() {
+
+                    @Override
+                    public void run(IProgressMonitor monitor)
+                            throws InvocationTargetException,
+                            InterruptedException {
+                        try {
+                            monitor.beginTask(
+                                    "Single Resource Creation Without RAML", 2);
+                            monitor.worked(1);
+                            createSingleResourceWithoutRAML();
+                            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();
+            }
+        } else if (curPage == loadRamlPage) { // Handling multi-instance
+            // creation of simple resource
+            // with RAML
+            try {
+                getContainer().run(true, true, new IRunnableWithProgress() {
+
+                    @Override
+                    public void run(IProgressMonitor monitor)
+                            throws InvocationTargetException,
+                            InterruptedException {
+                        try {
+                            monitor.beginTask(
+                                    "Single Resource Creation(multi-instance) With RAML",
+                                    3);
+                            monitor.worked(1);
+                            createMultiInstanceSingleResourceWithoutRAML();
+                            monitor.worked(2);
+                        } 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 == updatePropPage) { // Handling the single instance
+            // creation of simple resource
+            // with RAML
+            // String resURI = updatePropPage.getResURI();
+            // 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.");
+                // TODO: Instead of MessageDialog, errors may be shown on wizard
+                // itself.
+                return false;
+            }
+            // Resource resource = loadRamlPage.getResource();
+            // resource.setResourceName(updatePropPage.getResName());
+            try {
+                getContainer().run(true, true, 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();
+            }
+        } else if (curPage == collectionResourceBasicDetailsPage
+                || curPage == addResourcesToCollectionPage) { // Handling
+            // Collection
+            // Resource
+            // Creation
+            // without RAML
+            if (mainPage.getResourceOption() == ResourceOption.COLLECTION_FROM_RAML) {
+                Resource res = loadRamlPage.getResource();
+                if (null != res && res instanceof CollectionResource) {
+                    Set<Resource> selectedResources = addResourcesToCollectionPage
+                            .getSelectedResourceList();
+                    if (!selectedResources.isEmpty()) {
+                        int addedCount = Activator
+                                .getDefault()
+                                .getResourceManager()
+                                .addResourceToCollection(
+                                        (CollectionResource) res,
+                                        selectedResources);
+                        if (addedCount > 0) {
+
+                            status = "[" + addedCount + "/"
+                                    + selectedResources.size()
+                                    + "] resources added to the collection";
+
+                            UiListenerHandler.getInstance()
+                                    .resourceListUpdateUINotification(
+                                            ResourceType.COLLECTION);
+                        } else {
+                            status = "Failed to add resources to the collection";
+                        }
+                    }
+                }
+            } else {
+                // Checking whether the uri is used by any other resource.
+                if (Activator
+                        .getDefault()
+                        .getResourceManager()
+                        .isResourceExist(
+                                collectionResourceBasicDetailsPage.getResURI())) {
+                    MessageDialog
+                            .openError(getShell(), "Resource URI in use",
+                                    "Entered resource URI is in use. Please try a different one.");
+                    // TODO: Instead of MessageDialog, errors may be shown on
+                    // wizard
+                    // itself.
+                    return false;
+                }
+                try {
+                    getContainer().run(true, true, new IRunnableWithProgress() {
+
+                        @Override
+                        public void run(IProgressMonitor monitor)
+                                throws InvocationTargetException,
+                                InterruptedException {
+                            try {
+                                monitor.beginTask(
+                                        "Collection Resource Creation Without RAML",
+                                        3);
+                                monitor.worked(1);
+                                createCollectionResourceWithoutRAML((curPage == addResourcesToCollectionPage) ? true
+                                        : false);
+                                monitor.worked(1);
+                                if (curPage == addResourcesToCollectionPage) {
+                                    UiListenerHandler.getInstance()
+                                            .resourceListUpdateUINotification(
+                                                    ResourceType.COLLECTION);
+                                }
+                                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();
+                }
+            }
+        } else if (curPage == devicePage) {
+            final String devName = devicePage.getDeviceName();
+            final Set<Resource> resourceList = devicePage
+                    .getSelectedResourceList();
+            try {
+                getContainer().run(true, true, new IRunnableWithProgress() {
+
+                    @Override
+                    public void run(IProgressMonitor monitor)
+                            throws InvocationTargetException,
+                            InterruptedException {
+                        try {
+                            monitor.beginTask("Device Creation", 3);
+                            monitor.worked(1);
+                            createDevice(devName, resourceList);
+                            monitor.worked(1);
+                            UiListenerHandler.getInstance()
+                                    .resourceListUpdateUINotification(
+                                            ResourceType.DEVICE);
+                            status = "Device Created.";
+                            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 CollectionResourceBasicDetailsPage getCollectionResourceBasicDetailsPage() {
+        return collectionResourceBasicDetailsPage;
+    }
+
+    public SimpleResourceOtherDetailsPage getSimpleResourceOtherDetailsPage() {
+        return simpleResourceOtherDetailsPage;
+    }
+
+    public AddResourcesToCollectionPage getAddResourcesToCollectionPage() {
+        return addResourcesToCollectionPage;
+    }
+
+    public LoadRamlPage getLoadRamlPage() {
+        return loadRamlPage;
+    }
+
+    public UpdatePropertiesPage getUpdatePropPage() {
+        return updatePropPage;
+    }
+
+    public DevicePage getDevicePage() {
+        return devicePage;
+    }
+
+    public StartStopResourcePage getStartStopPage() {
+        return startStopPage;
+    }
+
+    /*
+     * public SingleResource getSimResource() { return simResource; }
+     * 
+     * public void setSimResource(SingleResource simResource) { this.simResource
+     * = simResource; }
+     */
+
+    public void setStatus(String status) {
+        this.status = status;
+    }
+
+    public String getStatus() {
+        return status;
+    }
+
+    /*
+     * public SingleResource getCreatedResource() { return simResource; }
+     */
+
+    private void createSingleResourceWithoutRAML() {
+        SingleResource resource = new SingleResource();
+        // Basic resource details
+        resource.setResourceURI(simpleResourceBasicDetailsPage.getResURI());
+        resource.setResourceName(simpleResourceBasicDetailsPage.getResName());
+        resource.setResourceTypes(simpleResourceBasicDetailsPage.getResTypes());
+        resource.setObservable(simpleResourceBasicDetailsPage.isObservable());
+        // resource.setStarted(simpleResourceBasicDetailsPage.isStart());
+
+        // Resource Attributes
+        Map<String, LocalResourceAttribute> attributes = new HashMap<String, LocalResourceAttribute>();
+        Set<AttributeHelper> attributeSet = simpleResourceAddAttributePage
+                .getAttributes();
+        if (null != attributeSet && !attributeSet.isEmpty()) {
+            Iterator<AttributeHelper> itr = attributeSet.iterator();
+            AttributeHelper attHelper;
+            LocalResourceAttribute localResAtt;
+            // List<String> attValues;
+            while (itr.hasNext()) {
+                attHelper = itr.next();
+                if (null != attHelper) {
+                    localResAtt = attHelper.convertToLocalResourceAttribute();
+
+                    // Set the attribute value list.
+                    /*
+                     * attValues =
+                     * Activator.getDefault().getResourceManager().getValueList
+                     * (localResAtt); localResAtt.setAttValues(attValues);
+                     */
+                    attributes.put(
+                            localResAtt.getResourceAttributeRef().name(),
+                            localResAtt);
+                }
+            }
+            resource.setResourceAttributes(attributes);
+        }
+
+        // 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);
+            if (result) {
+                status = "Resource created.";
+                resource.printResourceInfo();
+            } else {
+                status = "Failed to create resource.";
+            }
+        } catch (SimulatorException e) {
+            status = "Failed to create resource.\n"
+                    + Utility.getSimulatorErrorString(e, null);
+        }
+    }
+
+    private void completeResourceCreationWithRAML() {
+        try {
+            boolean result;
+            Resource res = loadRamlPage.getResource();
+            if (res instanceof SingleResource) {
+                result = Activator
+                        .getDefault()
+                        .getResourceManager()
+                        .completeSingleResourceCreationByRAML(res,
+                                updatePropPage.getResURI(),
+                                updatePropPage.getResName(), false);
+            } else {
+                result = Activator
+                        .getDefault()
+                        .getResourceManager()
+                        .completeCollectionResourceCreationByRAML(res,
+                                updatePropPage.getResURI(),
+                                updatePropPage.getResName());
+            }
+
+            if (result) {
+                status = "Resource created.";
+                loadRamlPage.getResource().printResourceInfo();
+            } else {
+                status = "Failed to create resource.";
+            }
+        } catch (SimulatorException e) {
+            status = "Failed to create resource.\n"
+                    + Utility.getSimulatorErrorString(e, null);
+        }
+    }
+
+    private void createMultiInstanceSingleResourceWithoutRAML() {
+        try {
+            int toCreateCount = loadRamlPage.getResourceCount();
+            int resCreatedCount = Activator
+                    .getDefault()
+                    .getResourceManager()
+                    .createSingleResourceMultiInstances(
+                            loadRamlPage.getConfigFilePath(), toCreateCount);
+            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);
+        }
+    }
+
+    private void createCollectionResourceWithoutRAML(boolean childResExist) {
+        CollectionResource resource = new CollectionResource();
+        // Basic resource details
+        resource.setResourceURI(collectionResourceBasicDetailsPage.getResURI());
+        resource.setResourceName(collectionResourceBasicDetailsPage
+                .getResName());
+        resource.setResourceTypes(collectionResourceBasicDetailsPage
+                .getResTypes());
+        resource.setObservable(collectionResourceBasicDetailsPage
+                .isObservable());
+        // resource.setStarted(simpleResourceBasicDetailsPage.isStart());
+
+        // Call method of ResourceManager and update the response in the status
+        // string.
+        try {
+            boolean result = Activator.getDefault().getResourceManager()
+                    .createCollectionResource(resource);
+            if (result) {
+                status = "Resource created.";
+                // Adding child resources.
+                if (childResExist) {
+                    Set<Resource> selectedResources = addResourcesToCollectionPage
+                            .getSelectedResourceList();
+                    if (!selectedResources.isEmpty()) {
+                        int addedCount = Activator
+                                .getDefault()
+                                .getResourceManager()
+                                .addResourceToCollection(resource,
+                                        selectedResources);
+                        if (addedCount > 0) {
+                            status = "[" + addedCount + "/"
+                                    + selectedResources.size()
+                                    + "] resources added to the collection";
+                        } else {
+                            status = "Failed to add resources to the collection.";
+                        }
+                    }
+                }
+            } else {
+                status = "Failed to create resource.";
+            }
+        } catch (SimulatorException e) {
+            status = "Failed to create resource.\n"
+                    + Utility.getSimulatorErrorString(e, null);
+        }
+    }
+
+    private void createDevice(String deviceName, Set<Resource> childs) {
+        Activator.getDefault().getResourceManager()
+                .createDevice(deviceName, childs);
+    }
+
 }
\ No newline at end of file
index be7dae8b73471d15625e1e21184602f3f09f2481..d27ebf6ed300c2df0daf1287d7383ed6bc6c877a 100644 (file)
 
 package oic.simulator.serviceprovider.view.dialogs;
 
-import java.util.Iterator;
+import java.util.ArrayList;
+import java.util.HashSet;
 import java.util.List;
+import java.util.Set;
 
 import oic.simulator.serviceprovider.Activator;
-import oic.simulator.serviceprovider.resource.DeleteCategory;
+import oic.simulator.serviceprovider.model.CollectionResource;
+import oic.simulator.serviceprovider.model.Resource;
+import oic.simulator.serviceprovider.model.SingleResource;
 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.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 org.eclipse.swt.widgets.Tree;
+import org.eclipse.swt.widgets.TreeItem;
 
 /**
  * This class shows UI for deleting resources.
  */
 public class DeleteResourcePage extends WizardPage {
 
-    private Button         allRbtn;
-    private Button         byTypeRbtn;
-    private Button         byUriRbtn;
+    private CheckboxTreeViewer       collectionTreeViewer;
+    private CheckboxTreeViewer       singleTreeViewer;
 
-    private CCombo         resourceTypeCmb;
-    private Text           resourceUriTxt;
+    private Button                   selectAllSingle;
+    private Button                   selectAllCollection;
+    private Button                   deselectAllSingle;
+    private Button                   deselectAllCollection;
 
-    private DeleteCategory deleteCategory;
+    private List<CollectionResource> collectionSourceList;
+    private List<SingleResource>     singleSourceList;
 
-    // It will hold either the resource type or resource uri
-    private String         deleteCandidate;
+    private Set<CollectionResource>  selectedCollections;
+    private Set<SingleResource>      selectedSingles;
 
     protected DeleteResourcePage() {
-        super("Delete Resource");
+        super("Delete Resources");
+
+        singleSourceList = Activator.getDefault().getResourceManager()
+                .getSingleResourceList();
+        collectionSourceList = Activator.getDefault().getResourceManager()
+                .getCollectionResourceList();
+
+        selectedCollections = new HashSet<CollectionResource>();
+        selectedSingles = new HashSet<SingleResource>();
     }
 
     @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 single and/or collection resources for deletion.");
 
-        Composite compContent = new Composite(parent, SWT.NONE);
-        compContent.setLayout(new GridLayout(1, false));
-        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 = new GridData(SWT.FILL, SWT.FILL, true, true);
-        group.setLayoutData(gd);
+        Composite container = new Composite(parent, SWT.NONE);
+        container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+        GridLayout layout = new GridLayout(5, true);
+        container.setLayout(layout);
 
-        allRbtn = new Button(group, SWT.RADIO);
-        allRbtn.setText("All resources");
-        gd = new GridData();
+        createSingleResourcesArea(container);
+
+        createCollectionResourcesArea(container);
+
+        createSelectionControls(container);
+
+        setControl(container);
+    }
+
+    private void createSingleResourcesArea(Composite container) {
+        Composite singleContainer = new Composite(container, SWT.NONE);
+        GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
         gd.horizontalSpan = 2;
-        gd.widthHint = 200;
-        allRbtn.setLayoutData(gd);
+        singleContainer.setLayoutData(gd);
+        GridLayout layout = new GridLayout();
+        singleContainer.setLayout(layout);
 
-        byTypeRbtn = new Button(group, SWT.RADIO);
-        byTypeRbtn.setText("All (By resource type)");
-        gd = new GridData();
-        gd.widthHint = 200;
-        byTypeRbtn.setLayoutData(gd);
+        Label lbl = new Label(singleContainer, SWT.NONE);
+        lbl.setText("Simple Resources:");
+        gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        // gd.grabExcessHorizontalSpace = true;
+        // gd.horizontalAlignment = SWT.FILL;
+        lbl.setLayoutData(gd);
 
-        resourceTypeCmb = new CCombo(group, SWT.READ_ONLY | SWT.BORDER);
-        gd = new GridData();
-        gd.widthHint = 200;
-        resourceTypeCmb.setLayoutData(gd);
+        Group resourceGroup = new Group(singleContainer, SWT.NONE);
+
+        Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE);
 
-        byUriRbtn = new Button(group, SWT.RADIO);
-        byUriRbtn.setText("By Resource URI");
+        resourceGroup.setLayout(new GridLayout());
         gd = new GridData();
-        gd.widthHint = 200;
-        byUriRbtn.setLayoutData(gd);
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.heightHint = 300;
+        gd.horizontalSpan = 2;
+        resourceGroup.setLayoutData(gd);
 
-        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;
+        // gd.heightHint = 300;
+        singleTreeViewer.getTree().setLayoutData(gd);
+        singleTreeViewer
+                .setContentProvider(new SingleResourceContentProvider());
+        singleTreeViewer.setLabelProvider(new TreeLabelProvider());
+        singleTreeViewer.setInput(new Object());
+        singleTreeViewer.addCheckStateListener(new ICheckStateListener() {
 
-        // Setting the initial visibility of controls
-        allRbtn.setSelection(false);
-        byTypeRbtn.setSelection(false);
-        byUriRbtn.setSelection(false);
+            @Override
+            public void checkStateChanged(CheckStateChangedEvent e) {
+                SingleResource res = (SingleResource) e.getElement();
+                if (null != res) {
+                    if (e.getChecked()) {
+                        selectedSingles.add(res);
+                        System.out.println("Checked" + res.getResourceName());
+                    } else {
+                        selectedSingles.remove(res);
+                        System.out.println("Unchecked:" + res.getResourceName());
+                    }
+                    setPageComplete(isSelectionDone());
+                }
+            }
+        });
+    }
 
-        resourceTypeCmb.setEnabled(false);
-        resourceUriTxt.setEnabled(false);
+    private void createCollectionResourcesArea(Composite container) {
+        Composite collectionContainer = new Composite(container, SWT.NONE);
+        GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        gd.horizontalSpan = 2;
+        collectionContainer.setLayoutData(gd);
+        GridLayout layout = new GridLayout();
+        collectionContainer.setLayout(layout);
 
-        deleteCategory = DeleteCategory.NONE;
+        Label lbl = new Label(collectionContainer, SWT.NONE);
+        lbl.setText("Collection Resources:");
+        gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        // gd.grabExcessHorizontalSpace = true;
+        // gd.horizontalAlignment = SWT.FILL;
+        lbl.setLayoutData(gd);
 
-        populateDataInUI();
+        Group resourceGroup = new Group(collectionContainer, SWT.NONE);
 
-        addUIListeners();
+        Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE);
 
-        setControl(compContent);
-    }
+        resourceGroup.setLayout(new GridLayout());
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.heightHint = 300;
+        gd.horizontalSpan = 2;
+        resourceGroup.setLayoutData(gd);
 
-    private void populateDataInUI() {
-        // Populate Resourcetype in Combo
-        populateResourceTypeCombo();
-    }
+        collectionTreeViewer = new CheckboxTreeViewer(resourceGroup);
+        collectionTreeViewer.getTree().setBackground(color);
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.grabExcessVerticalSpace = true;
+        gd.verticalAlignment = SWT.FILL;
+        // gd.heightHint = 300;
+        collectionTreeViewer.getTree().setLayoutData(gd);
+        collectionTreeViewer
+                .setContentProvider(new CollectionResourceContentProvider());
+        collectionTreeViewer.setLabelProvider(new TreeLabelProvider());
+        collectionTreeViewer.setInput(new Object());
+        collectionTreeViewer.addCheckStateListener(new ICheckStateListener() {
 
-    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 checkStateChanged(CheckStateChangedEvent e) {
+                CollectionResource res = (CollectionResource) e.getElement();
+                if (null != res) {
+                    if (e.getChecked()) {
+                        selectedCollections.add(res);
+                        System.out.println("Checked" + res.getResourceName());
+                    } else {
+                        selectedCollections.remove(res);
+                        System.out.println("Unchecked:" + res.getResourceName());
+                    }
+                    setPageComplete(isSelectionDone());
+                }
             }
-        }
-
-        // By default, select the first item in the combo
-        if (resourceTypeCmb.getItemCount() > 0) {
-            resourceTypeCmb.select(0);
-            deleteCandidate = resourceTypeCmb.getText();
-        }
+        });
     }
 
-    public void addUIListeners() {
-        allRbtn.addSelectionListener(new SelectionAdapter() {
+    private void createSelectionControls(Composite container) {
+        Composite innerComp = new Composite(container, SWT.NULL);
+        GridLayout layout = new GridLayout();
+        // layout.verticalSpacing = 10;
+        layout.marginTop = 15;
+        innerComp.setLayout(layout);
+        GridData gd = new GridData();
+        gd.verticalAlignment = SWT.TOP;
+        innerComp.setLayoutData(gd);
+
+        selectAllSingle = new Button(innerComp, SWT.PUSH);
+        selectAllSingle.setText("Select All Simple");
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        // gd.widthHint = 70;
+        selectAllSingle.setLayoutData(gd);
+        selectAllSingle.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());
+                check(singleTreeViewer, true);
             }
         });
 
-        byTypeRbtn.addSelectionListener(new SelectionAdapter() {
+        selectAllCollection = new Button(innerComp, SWT.PUSH);
+        selectAllCollection.setText("Select All Collection");
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        // gd.widthHint = 70;
+        selectAllCollection.setLayoutData(gd);
+        selectAllCollection.addSelectionListener(new SelectionAdapter() {
             @Override
             public void widgetSelected(SelectionEvent e) {
-                // Update the visibility of controls
-                resourceTypeCmb.setEnabled(true);
-                resourceUriTxt.setEnabled(false);
-
-                deleteCategory = DeleteCategory.BY_TYPE;
-                setPageComplete(isSelectionDone());
+                check(collectionTreeViewer, true);
             }
         });
 
-        byUriRbtn.addSelectionListener(new SelectionAdapter() {
+        deselectAllSingle = new Button(innerComp, SWT.PUSH);
+        deselectAllSingle.setText("Deselect All Simple");
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        // gd.widthHint = 70;
+        deselectAllSingle.setLayoutData(gd);
+        deselectAllSingle.addSelectionListener(new SelectionAdapter() {
             @Override
             public void widgetSelected(SelectionEvent e) {
-                // Update the visibility of controls
-                resourceUriTxt.setEnabled(true);
-                resourceUriTxt.setFocus();
-                resourceTypeCmb.setEnabled(false);
-
-                deleteCategory = DeleteCategory.BY_URI;
-                setPageComplete(isSelectionDone());
+                check(singleTreeViewer, false);
             }
         });
 
-        resourceTypeCmb.addModifyListener(new ModifyListener() {
+        deselectAllCollection = new Button(innerComp, SWT.PUSH);
+        deselectAllCollection.setText("Deselect All Collection");
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        // gd.widthHint = 70;
+        deselectAllCollection.setLayoutData(gd);
+
+        deselectAllCollection.addSelectionListener(new SelectionAdapter() {
             @Override
-            public void modifyText(ModifyEvent arg0) {
-                setPageComplete(isSelectionDone());
+            public void widgetSelected(SelectionEvent e) {
+                check(collectionTreeViewer, false);
             }
         });
+    }
 
-        resourceUriTxt.addModifyListener(new ModifyListener() {
-            @Override
-            public void modifyText(ModifyEvent arg0) {
+    private void check(CheckboxTreeViewer viewer, boolean toCheck) {
+        Tree tree = viewer.getTree();
+        if (null != tree) {
+            TreeItem[] items = tree.getItems();
+            if (null != items && items.length > 0) {
+                Object obj;
+                for (TreeItem item : items) {
+                    obj = item.getData();
+                    if (null != obj) {
+                        viewer.setChecked(obj, toCheck);
+                        updateSelectionList((Resource) obj, toCheck);
+                    }
+                }
                 setPageComplete(isSelectionDone());
             }
-        });
+        }
     }
 
-    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;
+    private void updateSelectionList(Resource res, boolean isChecked) {
+        if (res instanceof SingleResource) {
+            if (isChecked) {
+                selectedSingles.add((SingleResource) res);
+            } else {
+                selectedSingles.remove((SingleResource) res);
             }
-        } else if (deleteCategory == DeleteCategory.BY_URI) {
-            deleteCandidate = resourceUriTxt.getText();
-            if (null != deleteCandidate && deleteCandidate.length() > 0) {
-                done = true;
+        } else {
+            if (isChecked) {
+                selectedCollections.add((CollectionResource) res);
+            } else {
+                selectedCollections.remove((CollectionResource) res);
             }
         }
-        return done;
     }
 
-    public DeleteCategory getDeleteCategory() {
-        return deleteCategory;
+    public Set<SingleResource> getSelectedSingleResourcesList() {
+        return selectedSingles;
+    }
+
+    public Set<CollectionResource> getSelectedCollectionResourcesList() {
+        return selectedCollections;
+    }
+
+    class SingleResourceContentProvider implements ITreeContentProvider {
+
+        @Override
+        public void dispose() {
+        }
+
+        @Override
+        public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
+        }
+
+        @Override
+        public Object[] getChildren(Object parent) {
+            return null;
+        }
+
+        @Override
+        public Object[] getElements(Object parent) {
+            if (null == singleSourceList) {
+                singleSourceList = new ArrayList<SingleResource>();
+            }
+            return singleSourceList.toArray();
+        }
+
+        @Override
+        public Object getParent(Object child) {
+            return null;
+        }
+
+        @Override
+        public boolean hasChildren(Object parent) {
+            return false;
+        }
+    }
+
+    class CollectionResourceContentProvider implements ITreeContentProvider {
+
+        @Override
+        public void dispose() {
+        }
+
+        @Override
+        public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
+        }
+
+        @Override
+        public Object[] getChildren(Object parent) {
+            return null;
+        }
+
+        @Override
+        public Object[] getElements(Object parent) {
+            if (null == collectionSourceList) {
+                collectionSourceList = new ArrayList<CollectionResource>();
+            }
+            return collectionSourceList.toArray();
+        }
+
+        @Override
+        public Object getParent(Object child) {
+            return null;
+        }
+
+        @Override
+        public boolean hasChildren(Object parent) {
+            return false;
+        }
     }
 
-    public String getDeleteCandidate() {
-        return deleteCandidate;
+    class TreeLabelProvider extends LabelProvider {
+        @Override
+        public String getText(Object element) {
+            Resource res = (Resource) element;
+            return res.getResourceName();
+        }
+
+        @Override
+        public Image getImage(Object element) {
+            if (element instanceof CollectionResource) {
+                return Activator.getDefault().getImageRegistry()
+                        .get(Constants.COLLECTION_RESOURCE);
+            } else {
+                return Activator.getDefault().getImageRegistry()
+                        .get(Constants.SINGLE_RESOURCE);
+            }
+        }
     }
 
-    public void setFocusToTextBox() {
-        resourceUriTxt.setFocus();
+    public boolean isSelectionDone() {
+        boolean done = true;
+        Object obj[] = singleTreeViewer.getCheckedElements();
+        if (null == obj || obj.length < 1) {
+            obj = collectionTreeViewer.getCheckedElements();
+            if (null == obj || obj.length < 1) {
+                done = false;
+            }
+        }
+        return done;
     }
 }
\ No newline at end of file
index 4d079eb320001b01cd218384109113f8a39681a4..4a2cc9ef8bf848119c39e769e93ae84e758bb6d0 100644 (file)
 
 package oic.simulator.serviceprovider.view.dialogs;
 
+import java.lang.reflect.InvocationTargetException;
 import java.net.URL;
+import java.util.Date;
+import java.util.Set;
 
 import oic.simulator.serviceprovider.Activator;
-import oic.simulator.serviceprovider.resource.DeleteCategory;
+import oic.simulator.serviceprovider.model.CollectionResource;
+import oic.simulator.serviceprovider.model.SingleResource;
 
 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 org.oic.simulator.ILogger.Level;
+import org.oic.simulator.SimulatorException;
 
 /**
  * This class creates a UI wizard for delete resource operation.
@@ -37,6 +42,8 @@ public class DeleteResourceWizard extends Wizard {
 
     private DeleteResourcePage page;
 
+    private String             status;
+
     public DeleteResourceWizard() {
         setWindowTitle("Delete resources");
         IPath path = new Path("/icons/oic_logo_64x64.png");
@@ -56,45 +63,52 @@ 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, true, new IRunnableWithProgress() {
 
-    public DeleteCategory getDeleteCategory() {
-        if (null == page) {
-            return DeleteCategory.NONE;
+                @Override
+                public void run(IProgressMonitor monitor)
+                        throws InvocationTargetException, InterruptedException {
+                    try {
+                        monitor.beginTask("Resource Deletion", 2);
+                        Set<CollectionResource> collectionResources = page
+                                .getSelectedCollectionResourcesList();
+                        if (null != collectionResources
+                                && collectionResources.size() > 0) {
+                            Activator
+                                    .getDefault()
+                                    .getResourceManager()
+                                    .removeCollectionResources(
+                                            collectionResources);
+                        }
+                        monitor.worked(1);
+                        Set<SingleResource> singleResources = page
+                                .getSelectedSingleResourcesList();
+                        if (null != singleResources
+                                && singleResources.size() > 0) {
+                            Activator.getDefault().getResourceManager()
+                                    .removeSingleResources(singleResources);
+                        }
+                        monitor.worked(1);
+                        status = "Resources deleted.";
+                    } catch (SimulatorException e) {
+                        status = "Failed to delete some of the resources. Please try again.";
+                    } 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 String getStatus() {
+        return status;
     }
 }
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/DevicePage.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/DevicePage.java
new file mode 100644 (file)
index 0000000..b6a194f
--- /dev/null
@@ -0,0 +1,207 @@
+package oic.simulator.serviceprovider.view.dialogs;
+
+import java.util.ArrayList;
+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;
+
+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.Viewer;
+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.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.Composite;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Group;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Text;
+
+public class DevicePage extends WizardPage {
+
+    private CheckboxTreeViewer treeViewer;
+
+    private Text               deviceNameTxt;
+
+    private String             deviceName;
+
+    Set<Resource>              selectedResourceList;
+
+    protected DevicePage() {
+        super("Devices");
+        selectedResourceList = new HashSet<Resource>();
+    }
+
+    @Override
+    public void createControl(Composite parent) {
+        setPageComplete(false);
+        setTitle(Constants.CREATE_DEVICE_PAGE_TITLE);
+        setMessage(Constants.CREATE_DEVICE_PAGE_MESSAGE);
+
+        Composite container = new Composite(parent, SWT.NONE);
+        GridLayout gridLayout = new GridLayout(2, false);
+        container.setLayout(gridLayout);
+        GridData gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.heightHint = 300;
+        container.setLayoutData(gd);
+
+        Label deviceNameLbl = new Label(container, SWT.NULL);
+        deviceNameLbl.setText("Device Name");
+
+        deviceNameTxt = new Text(container, SWT.BORDER);
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        deviceNameTxt.setLayoutData(gd);
+
+        Group resourceGroup = new Group(container, SWT.NONE);
+
+        Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE);
+
+        resourceGroup.setLayout(new GridLayout());
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.heightHint = 300;
+        gd.horizontalSpan = 2;
+        resourceGroup.setLayoutData(gd);
+
+        treeViewer = new CheckboxTreeViewer(resourceGroup);
+        treeViewer.getTree().setBackground(color);
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.grabExcessVerticalSpace = true;
+        gd.verticalAlignment = SWT.FILL;
+        // gd.heightHint = 300;
+        treeViewer.getTree().setLayoutData(gd);
+        treeViewer.setContentProvider(new TreeContentProvider());
+        treeViewer.setLabelProvider(new TreeLabelProvider());
+        treeViewer.setInput(new Object());
+        treeViewer.addCheckStateListener(new ICheckStateListener() {
+
+            @Override
+            public void checkStateChanged(CheckStateChangedEvent e) {
+                Resource res = (Resource) e.getElement();
+                if (null != res) {
+                    if (e.getChecked()) {
+                        selectedResourceList.add(res);
+                        System.out.println("Checked" + res.getResourceName());
+                    } else {
+                        selectedResourceList.remove(res);
+                        System.out.println("Unchecked:" + res.getResourceName());
+                    }
+                }
+            }
+        });
+
+        setUiListeners();
+
+        setControl(container);
+    }
+
+    private void setUiListeners() {
+        deviceNameTxt.addModifyListener(new ModifyListener() {
+            @Override
+            public void modifyText(ModifyEvent e) {
+                deviceName = deviceNameTxt.getText();
+                setPageComplete(isSelectionDone());
+            }
+        });
+    }
+
+    private boolean isSelectionDone() {
+        if (null != deviceName) {
+            deviceName = deviceName.trim();
+        }
+        if (deviceName.isEmpty()) {
+            return false;
+        }
+        return true;
+    }
+
+    @Override
+    public IWizardPage getNextPage() {
+        return null;
+    }
+
+    public String getDeviceName() {
+        return deviceName;
+    }
+
+    public Set<Resource> getSelectedResourceList() {
+        return selectedResourceList;
+    }
+
+}
+
+class TreeContentProvider implements ITreeContentProvider {
+
+    @Override
+    public void dispose() {
+    }
+
+    @Override
+    public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
+    }
+
+    @Override
+    public Object[] getChildren(Object parent) {
+        return null;
+    }
+
+    @Override
+    public Object[] getElements(Object parent) {
+        List<Resource> resList;
+        resList = Activator.getDefault().getResourceManager().getResourceList();
+        if (null == resList) {
+            resList = new ArrayList<Resource>();
+        }
+        return resList.toArray();
+    }
+
+    @Override
+    public Object getParent(Object child) {
+        return null;
+    }
+
+    @Override
+    public boolean hasChildren(Object parent) {
+        return false;
+    }
+}
+
+class TreeLabelProvider extends LabelProvider {
+    @Override
+    public String getText(Object element) {
+        Resource res = (Resource) element;
+        return res.getResourceName();
+    }
+
+    @Override
+    public Image getImage(Object element) {
+        if (element instanceof SingleResource) {
+            return Activator.getDefault().getImageRegistry()
+                    .get(Constants.SINGLE_RESOURCE);
+        } else {
+            return Activator.getDefault().getImageRegistry()
+                    .get(Constants.COLLECTION_RESOURCE);
+        }
+    }
+}
\ No newline at end of file
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..8cc4928
--- /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.
+ */
+
+package oic.simulator.serviceprovider.view.dialogs;
+
+import java.io.FileInputStream;
+import java.lang.reflect.InvocationTargetException;
+import java.util.Date;
+
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.model.Resource;
+import oic.simulator.serviceprovider.utils.Constants;
+import oic.simulator.serviceprovider.utils.Utility;
+
+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.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 org.oic.simulator.ILogger.Level;
+import org.oic.simulator.SimulatorException;
+import org.oic.simulator.server.SimulatorResource;
+import org.oic.simulator.server.SimulatorResource.Type;
+
+/**
+ * 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 (typeOfResource == Type.COLLECTION) {
+                done = true;
+            } else {
+                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 (typeOfResource == Type.COLLECTION) {
+                done = true;
+            } else {
+                if (resourceCount >= 1) {
+                    done = true;
+                }
+            }
+        }
+        return done;
+    }
+
+    public boolean isMultiResourceCreation() {
+        if (typeOfResource != Type.COLLECTION && resourceCount > 1) {
+            return true;
+        }
+        return false;
+    }
+
+    @Override
+    public IWizardPage getNextPage() {
+        // Validate the file path.
+        try {
+            new FileInputStream(configFilePath);
+        } catch (Exception e) {
+            MessageDialog
+                    .openError(getShell(), "Invalid File",
+                            "File doesn't exist. Either the file path or file name is invalid.");
+            // TODO: Instead of MessageDialog, errors may be shown on wizard
+            // itself.
+            return null;
+        }
+        final CreateResourceWizard wizard = ((CreateResourceWizard) getWizard());
+
+        try {
+            getContainer().run(true, true, 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;
+        }
+        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
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..f546f64
--- /dev/null
@@ -0,0 +1,191 @@
+package oic.simulator.serviceprovider.view.dialogs;
+
+import oic.simulator.serviceprovider.utils.Constants;
+
+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;
+
+public class MainPage extends WizardPage {
+
+    private Button simpleBtn;
+    private Button collectionBtn;
+    private Button simpleFromRamlBtn;
+    private Button collectionFromRamlBtn;
+    private Button deviceBtn;
+    private Text   description;
+
+    public enum ResourceOption {
+        SIMPLE, SIMPLE_FROM_RAML, COLLECTION, COLLECTION_FROM_RAML, DEVICE, NONE
+    }
+
+    private ResourceOption resOption;
+
+    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)");
+
+        collectionBtn = new Button(compContent, SWT.RADIO);
+        collectionBtn.setText("Collection resource");
+
+        collectionFromRamlBtn = new Button(compContent, SWT.RADIO);
+        collectionFromRamlBtn.setText("Collection resource(From RAML)");
+
+        deviceBtn = new Button(compContent, SWT.RADIO);
+        deviceBtn.setText("Device");
+
+        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 Types, etc.\n"
+                                + "\t2. Options such as Observable, allowed request types, start/stop resource etc.\n"
+                                + "\t3. Adding attributes.");
+                resOption = ResourceOption.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.\n"
+                                + "\t4. Allows to start or stop the resource(s).");
+                resOption = ResourceOption.SIMPLE_FROM_RAML;
+                getWizard().getContainer().updateButtons();
+            }
+        });
+
+        collectionBtn.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                description
+                        .setText("Create a collection resource by manually entering all the details given below.\n"
+                                + "\t1. Basic resource details: URI, Name, Resource Types, etc.\n"
+                                + "\t2. Start/stop the resource.\n"
+                                + "\t3. Adding existing simple resources to this collection.");
+                resOption = ResourceOption.COLLECTION;
+                getWizard().getContainer().updateButtons();
+            }
+        });
+
+        collectionFromRamlBtn.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                description
+                        .setText("Create a collection 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.\n"
+                                + "\t4. Allows to start or stop the resource(s).");
+                resOption = ResourceOption.COLLECTION_FROM_RAML;
+                getWizard().getContainer().updateButtons();
+            }
+        });
+
+        deviceBtn.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                description
+                        .setText("Create a logical device that acts as a top-level logical classification.\n"
+                                + "\t1. Takes a device name for identication.\n"
+                                + "\t2. One or more simple and collection resources can be added to it.");
+                resOption = ResourceOption.DEVICE;
+                getWizard().getContainer().updateButtons();
+            }
+        });
+    }
+
+    @Override
+    public boolean canFlipToNextPage() {
+        if (resOption != ResourceOption.NONE) {
+            return true;
+        }
+        return false;
+    }
+
+    @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;
+        }
+        if (collectionBtn.getSelection()) {
+            return createWizard.getCollectionResourceBasicDetailsPage();
+        }
+        if (collectionFromRamlBtn.getSelection()) {
+            LoadRamlPage page = createWizard.getLoadRamlPage();
+            page.initialSetup(Type.COLLECTION);
+            return page;
+        }
+        if (deviceBtn.getSelection()) {
+            DevicePage page = createWizard.getDevicePage();
+            return page;
+        }
+        return null;
+    }
+
+    public ResourceOption getResourceOption() {
+        return resOption;
+    }
+}
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/RemoveResourceFromCollections.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/RemoveResourceFromCollections.java
new file mode 100644 (file)
index 0000000..627a76f
--- /dev/null
@@ -0,0 +1,206 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.model.CollectionResource;
+import oic.simulator.serviceprovider.utils.Constants;
+
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.dialogs.TitleAreaDialog;
+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.Viewer;
+import org.eclipse.swt.SWT;
+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.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.Shell;
+
+/**
+ * This dialog is used for loading the RAML file.
+ */
+public class RemoveResourceFromCollections extends TitleAreaDialog {
+
+    private CheckboxTreeViewer treeViewer;
+
+    List<CollectionResource>   sourceList;
+
+    Set<CollectionResource>    selectedResourceList;
+
+    public RemoveResourceFromCollections(Shell parentShell,
+            List<CollectionResource> sourceList) {
+        super(parentShell);
+        this.sourceList = sourceList;
+        selectedResourceList = new HashSet<CollectionResource>();
+    }
+
+    @Override
+    public void create() {
+        super.create();
+        setTitle("Remove from Collections");
+        setMessage("Select one or more collection resources from which the simple resource will be removed.");
+    }
+
+    @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();
+        layout.verticalSpacing = 10;
+        layout.marginTop = 10;
+        container.setLayout(layout);
+
+        Label lbl = new Label(container, SWT.NONE);
+        lbl.setText("Select Resources from:");
+        GridData gd;
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        lbl.setLayoutData(gd);
+
+        Group resourceGroup = new Group(container, SWT.NONE);
+
+        Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE);
+
+        resourceGroup.setLayout(new GridLayout());
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.heightHint = 300;
+        gd.horizontalSpan = 2;
+        resourceGroup.setLayoutData(gd);
+
+        treeViewer = new CheckboxTreeViewer(resourceGroup);
+        treeViewer.getTree().setBackground(color);
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.grabExcessVerticalSpace = true;
+        gd.verticalAlignment = SWT.FILL;
+        // gd.heightHint = 300;
+        treeViewer.getTree().setLayoutData(gd);
+        treeViewer.setContentProvider(new TreeContentProvider());
+        treeViewer.setLabelProvider(new TreeLabelProvider());
+        treeViewer.setInput(new Object());
+        treeViewer.addCheckStateListener(new ICheckStateListener() {
+
+            @Override
+            public void checkStateChanged(CheckStateChangedEvent e) {
+                CollectionResource res = (CollectionResource) e.getElement();
+                if (null != res) {
+                    if (e.getChecked()) {
+                        selectedResourceList.add(res);
+                        System.out.println("Checked" + res.getResourceName());
+                    } else {
+                        selectedResourceList.remove(res);
+                        System.out.println("Unchecked:" + res.getResourceName());
+                    }
+                }
+            }
+        });
+
+        return compLayout;
+    }
+
+    public Set<CollectionResource> getSelectedResourceList() {
+        return selectedResourceList;
+    }
+
+    class TreeContentProvider implements ITreeContentProvider {
+
+        @Override
+        public void dispose() {
+        }
+
+        @Override
+        public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
+        }
+
+        @Override
+        public Object[] getChildren(Object parent) {
+            return null;
+        }
+
+        @Override
+        public Object[] getElements(Object parent) {
+            if (null == sourceList) {
+                sourceList = new ArrayList<CollectionResource>();
+            }
+            return sourceList.toArray();
+        }
+
+        @Override
+        public Object getParent(Object child) {
+            return null;
+        }
+
+        @Override
+        public boolean hasChildren(Object parent) {
+            return false;
+        }
+    }
+
+    class TreeLabelProvider extends LabelProvider {
+        @Override
+        public String getText(Object element) {
+            CollectionResource res = (CollectionResource) element;
+            return res.getResourceName();
+        }
+
+        @Override
+        public Image getImage(Object element) {
+            if (element instanceof CollectionResource) {
+                return Activator.getDefault().getImageRegistry()
+                        .get(Constants.COLLECTION_RESOURCE);
+            } else {
+                return null;
+            }
+        }
+    }
+
+    @Override
+    protected void okPressed() {
+        if (selectedResourceList.isEmpty()) {
+            MessageDialog.openInformation(
+                    Display.getDefault().getActiveShell(),
+                    "No selection done.", "No resources are selected.");
+            return;
+        }
+        close();
+    }
+
+    @Override
+    public boolean isHelpAvailable() {
+        return false;
+    }
+}
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/RemoveResourceFromDevices.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/RemoveResourceFromDevices.java
new file mode 100644 (file)
index 0000000..01bedd9
--- /dev/null
@@ -0,0 +1,205 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.model.Device;
+import oic.simulator.serviceprovider.utils.Constants;
+
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.dialogs.TitleAreaDialog;
+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.Viewer;
+import org.eclipse.swt.SWT;
+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.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.Shell;
+
+/**
+ * This dialog is used for loading the RAML file.
+ */
+public class RemoveResourceFromDevices extends TitleAreaDialog {
+
+    private CheckboxTreeViewer treeViewer;
+
+    List<Device>               sourceList;
+
+    Set<Device>                selectedDeviceList;
+
+    public RemoveResourceFromDevices(Shell parentShell, List<Device> sourceList) {
+        super(parentShell);
+        this.sourceList = sourceList;
+        selectedDeviceList = new HashSet<Device>();
+    }
+
+    @Override
+    public void create() {
+        super.create();
+        setTitle("Remove from Device");
+        setMessage("Select one or more devices from which the simple resource will be removed.");
+    }
+
+    @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();
+        layout.verticalSpacing = 10;
+        layout.marginTop = 10;
+        container.setLayout(layout);
+
+        Label lbl = new Label(container, SWT.NONE);
+        lbl.setText("Select Resources from:");
+        GridData gd;
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        lbl.setLayoutData(gd);
+
+        Group resourceGroup = new Group(container, SWT.NONE);
+
+        Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE);
+
+        resourceGroup.setLayout(new GridLayout());
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.heightHint = 300;
+        gd.horizontalSpan = 2;
+        resourceGroup.setLayoutData(gd);
+
+        treeViewer = new CheckboxTreeViewer(resourceGroup);
+        treeViewer.getTree().setBackground(color);
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.grabExcessVerticalSpace = true;
+        gd.verticalAlignment = SWT.FILL;
+        // gd.heightHint = 300;
+        treeViewer.getTree().setLayoutData(gd);
+        treeViewer.setContentProvider(new TreeContentProvider());
+        treeViewer.setLabelProvider(new TreeLabelProvider());
+        treeViewer.setInput(new Object());
+        treeViewer.addCheckStateListener(new ICheckStateListener() {
+
+            @Override
+            public void checkStateChanged(CheckStateChangedEvent e) {
+                Device res = (Device) e.getElement();
+                if (null != res) {
+                    if (e.getChecked()) {
+                        selectedDeviceList.add(res);
+                        System.out.println("Checked" + res.getDeviceName());
+                    } else {
+                        selectedDeviceList.remove(res);
+                        System.out.println("Unchecked:" + res.getDeviceName());
+                    }
+                }
+            }
+        });
+
+        return compLayout;
+    }
+
+    public Set<Device> getSelectedDeviceList() {
+        return selectedDeviceList;
+    }
+
+    class TreeContentProvider implements ITreeContentProvider {
+
+        @Override
+        public void dispose() {
+        }
+
+        @Override
+        public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
+        }
+
+        @Override
+        public Object[] getChildren(Object parent) {
+            return null;
+        }
+
+        @Override
+        public Object[] getElements(Object parent) {
+            if (null == sourceList) {
+                sourceList = new ArrayList<Device>();
+            }
+            return sourceList.toArray();
+        }
+
+        @Override
+        public Object getParent(Object child) {
+            return null;
+        }
+
+        @Override
+        public boolean hasChildren(Object parent) {
+            return false;
+        }
+    }
+
+    class TreeLabelProvider extends LabelProvider {
+        @Override
+        public String getText(Object element) {
+            Device res = (Device) element;
+            return res.getDeviceName();
+        }
+
+        @Override
+        public Image getImage(Object element) {
+            if (element instanceof Device) {
+                return Activator.getDefault().getImageRegistry()
+                        .get(Constants.DEVICE);
+            } else {
+                return null;
+            }
+        }
+    }
+
+    @Override
+    protected void okPressed() {
+        if (selectedDeviceList.isEmpty()) {
+            MessageDialog.openInformation(
+                    Display.getDefault().getActiveShell(),
+                    "No selection done.", "No devices are selected.");
+            return;
+        }
+        close();
+    }
+
+    @Override
+    public boolean isHelpAvailable() {
+        return false;
+    }
+}
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/RemoveResources.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/RemoveResources.java
new file mode 100644 (file)
index 0000000..f76f8f9
--- /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.
+ */
+
+package oic.simulator.serviceprovider.view.dialogs;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.model.CollectionResource;
+import oic.simulator.serviceprovider.model.Resource;
+import oic.simulator.serviceprovider.utils.Constants;
+
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.dialogs.TitleAreaDialog;
+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.Viewer;
+import org.eclipse.swt.SWT;
+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.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.Shell;
+
+/**
+ * This dialog is used for loading the RAML file.
+ */
+public class RemoveResources extends TitleAreaDialog {
+
+    private CheckboxTreeViewer treeViewer;
+
+    List<Resource>             sourceList;
+
+    Set<Resource>              selectedResourceList;
+
+    public RemoveResources(Shell parentShell, List<Resource> sourceList) {
+        super(parentShell);
+        this.sourceList = sourceList;
+        selectedResourceList = new HashSet<Resource>();
+    }
+
+    @Override
+    public void create() {
+        super.create();
+        setTitle("Remove Resources");
+        setMessage("Select one or more resources to be removed.");
+    }
+
+    @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();
+        layout.verticalSpacing = 10;
+        layout.marginTop = 10;
+        container.setLayout(layout);
+
+        Label lbl = new Label(container, SWT.NONE);
+        lbl.setText("Select Resources from:");
+        GridData gd;
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        lbl.setLayoutData(gd);
+
+        Group resourceGroup = new Group(container, SWT.NONE);
+
+        Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE);
+
+        resourceGroup.setLayout(new GridLayout());
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.heightHint = 300;
+        gd.horizontalSpan = 2;
+        resourceGroup.setLayoutData(gd);
+
+        treeViewer = new CheckboxTreeViewer(resourceGroup);
+        treeViewer.getTree().setBackground(color);
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.grabExcessVerticalSpace = true;
+        gd.verticalAlignment = SWT.FILL;
+        // gd.heightHint = 300;
+        treeViewer.getTree().setLayoutData(gd);
+        treeViewer.setContentProvider(new TreeContentProvider());
+        treeViewer.setLabelProvider(new TreeLabelProvider());
+        treeViewer.setInput(new Object());
+        treeViewer.addCheckStateListener(new ICheckStateListener() {
+
+            @Override
+            public void checkStateChanged(CheckStateChangedEvent e) {
+                Resource res = (Resource) e.getElement();
+                if (null != res) {
+                    if (e.getChecked()) {
+                        selectedResourceList.add(res);
+                        System.out.println("Checked" + res.getResourceName());
+                    } else {
+                        selectedResourceList.remove(res);
+                        System.out.println("Unchecked:" + res.getResourceName());
+                    }
+                }
+            }
+        });
+
+        return compLayout;
+    }
+
+    public Set<Resource> getSelectedResourceList() {
+        return selectedResourceList;
+    }
+
+    class TreeContentProvider implements ITreeContentProvider {
+
+        @Override
+        public void dispose() {
+        }
+
+        @Override
+        public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
+        }
+
+        @Override
+        public Object[] getChildren(Object parent) {
+            return null;
+        }
+
+        @Override
+        public Object[] getElements(Object parent) {
+            if (null == sourceList) {
+                sourceList = new ArrayList<Resource>();
+            }
+            return sourceList.toArray();
+        }
+
+        @Override
+        public Object getParent(Object child) {
+            return null;
+        }
+
+        @Override
+        public boolean hasChildren(Object parent) {
+            return false;
+        }
+    }
+
+    class TreeLabelProvider extends LabelProvider {
+        @Override
+        public String getText(Object element) {
+            Resource res = (Resource) element;
+            return res.getResourceName();
+        }
+
+        @Override
+        public Image getImage(Object element) {
+            if (element instanceof CollectionResource) {
+                return Activator.getDefault().getImageRegistry()
+                        .get(Constants.COLLECTION_RESOURCE);
+            } else {
+                return Activator.getDefault().getImageRegistry()
+                        .get(Constants.SINGLE_RESOURCE);
+            }
+        }
+    }
+
+    @Override
+    protected void okPressed() {
+        if (selectedResourceList.isEmpty()) {
+            MessageDialog.openInformation(
+                    Display.getDefault().getActiveShell(),
+                    "No selection done.", "No resources are selected.");
+            return;
+        }
+        close();
+    }
+
+    @Override
+    public boolean isHelpAvailable() {
+        return false;
+    }
+}
index 09f95feda019bcdcee615bfef2a2be2d0663cbf2..511371232cf56cce50bf156c0d823a9d3e8ec106 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,46 @@ 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();
+            CollectionResourceBasicDetailsPage collectionResourceBasicDetailsPage = createWizard
+                    .getCollectionResourceBasicDetailsPage();
+            AddResourcesToCollectionPage addResourcesToCollectionPage = createWizard
+                    .getAddResourcesToCollectionPage();
+            LoadRamlPage loadRamlPage = createWizard.getLoadRamlPage();
+            UpdatePropertiesPage updatePropPage = createWizard
+                    .getUpdatePropPage();
+            DevicePage devPage = createWizard.getDevicePage();
+
+            IWizardPage curPage = wizard.getContainer().getCurrentPage();
+            IWizardPage prevPage = null;
+
+            if (curPage == loadRamlPage
+                    || curPage == simpleResourceBasicDetailsPage
+                    || curPage == collectionResourceBasicDetailsPage
+                    || curPage == devPage) {
+                prevPage = mainPage;
+            } else if (curPage == updatePropPage) {
+                loadRamlPage.setResource(null);
+                prevPage = loadRamlPage;
+            } else if (curPage == addResourcesToCollectionPage) {
+                prevPage = collectionResourceBasicDetailsPage;
+            } 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..0e664ca
--- /dev/null
@@ -0,0 +1,379 @@
+package oic.simulator.serviceprovider.view.dialogs;
+
+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.utils.Constants;
+import oic.simulator.serviceprovider.utils.Utility;
+
+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.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.Display;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Table;
+import org.oic.simulator.AttributeProperty.Type;
+
+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() != Type.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() != Type.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 pre-fill the UI controls.
+                Set<String> rTypes = Utility.getAttributeTypes();
+                AddAttributeDialog dialog = new AddAttributeDialog(Display
+                        .getDefault().getActiveShell(), att, rTypes, attributes);
+                if (dialog.open() != Window.OK) {
+                    AttributeHelper newAtt = dialog.getAttClone();
+                    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);
+                System.out.println("Attribute data after closing edit dialog: "
+                        + att);
+            }
+        });
+
+        remBtn.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                IStructuredSelection selection = (IStructuredSelection) attTblViewer
+                        .getSelection();
+                if (null != selection) {
+                    System.out.println(selection.size());
+                    Iterator<?> itr = selection.iterator();
+                    while (itr.hasNext()) {
+                        AttributeHelper att = (AttributeHelper) itr.next();
+                        System.out.println(att.getAttributeName());
+                        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) {
+                        System.out.println("table selection changed");
+                        remBtn.setEnabled(true);
+                        IStructuredSelection selection = (IStructuredSelection) event
+                                .getSelection();
+                        if (null == selection) {
+                            return;
+                        }
+                        if (selection.size() > 1) {
+                            editBtn.setEnabled(false);
+                        } else {
+                            editBtn.setEnabled(true);
+                        }
+                    }
+                });
+    }
+
+    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..f01939b
--- /dev/null
@@ -0,0 +1,303 @@
+package oic.simulator.serviceprovider.view.dialogs;
+
+import java.util.HashSet;
+import java.util.Set;
+
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.utils.Constants;
+
+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;
+
+public class SimpleResourceBasicDetailsPage extends WizardPage {
+
+    private Text        resNameTxt;
+    private Text        resUriTxt;
+    private List        resTypeslist;
+    private Button      addToListBtn;
+    private Button      remFromListBtn;
+    private Button      observeBtn;
+    // private Button startBtn;
+
+    private String      resName;
+    private String      resURI;
+    private Set<String> resTypes;
+    private boolean     observable;
+
+    // private boolean start;
+
+    protected SimpleResourceBasicDetailsPage() {
+        super("Basic Details");
+        resTypes = 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.widthHint = 300;
+        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.widthHint = 300;
+        gd.horizontalSpan = 3;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.grabExcessHorizontalSpace = true;
+        resUriTxt.setLayoutData(gd);
+        /*
+         * Composite resTypesComp = new Composite(compContent, SWT.NONE);
+         * gridLayout = new GridLayout(3, false);
+         * resTypesComp.setLayout(gridLayout); gd = new GridData();
+         * gd.grabExcessHorizontalSpace = true; gd.horizontalAlignment =
+         * SWT.FILL; resTypesComp.setLayoutData(gd);
+         */
+
+        Label resTypesLbl = new Label(resDetGrp, SWT.NULL);
+        resTypesLbl.setText(Constants.RESOURCE_TYPES);
+
+        resTypeslist = new List(resDetGrp, SWT.BORDER | SWT.MULTI
+                | SWT.V_SCROLL);
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.horizontalSpan = 2;
+        gd.heightHint = 100;
+        /* gd.widthHint = 200; */
+        resTypeslist.setLayoutData(gd);
+        // resTypeslist.setBackground(new Color());
+
+        Composite resTypesActionsComp = new Composite(resDetGrp, SWT.NONE);
+        gridLayout = new GridLayout();
+        resTypesActionsComp.setLayout(gridLayout);
+        gd = new GridData();
+        gd.verticalAlignment = SWT.TOP;
+        /*
+         * gd.grabExcessHorizontalSpace = true; gd.horizontalAlignment =
+         * SWT.FILL;
+         */
+        resTypesActionsComp.setLayoutData(gd);
+
+        addToListBtn = new Button(resTypesActionsComp, SWT.PUSH);
+        addToListBtn.setText("Add");
+        gd = new GridData();
+        gd.widthHint = 70;
+        addToListBtn.setLayoutData(gd);
+
+        remFromListBtn = new Button(resTypesActionsComp, SWT.PUSH);
+        remFromListBtn.setText("Remove");
+        gd = new GridData();
+        gd.widthHint = 70;
+        remFromListBtn.setLayoutData(gd);
+        remFromListBtn.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);
+
+        observeBtn = new Button(otherOptionsGrp, SWT.CHECK);
+        observeBtn.setText("Observable");
+        observeBtn.setSelection(true);
+        observable = true;
+
+        /*
+         * startBtn = new Button(otherOptionsGrp, SWT.CHECK);
+         * startBtn.setText("Start the resource immediately after creation");
+         * startBtn.setSelection(true);
+         */
+        addUiListeners();
+
+        setControl(container);
+    }
+
+    private void addUiListeners() {
+
+        resUriTxt.addModifyListener(new ModifyListener() {
+            @Override
+            public void modifyText(ModifyEvent arg0) {
+                resURI = resUriTxt.getText();
+                getWizard().getContainer().updateButtons();
+            }
+        });
+
+        resNameTxt.addModifyListener(new ModifyListener() {
+            @Override
+            public void modifyText(ModifyEvent arg0) {
+                resName = resNameTxt.getText();
+                getWizard().getContainer().updateButtons();
+            }
+        });
+
+        addToListBtn.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                SingleTextInputDialog dialog = new SingleTextInputDialog(
+                        getShell(), "Add Resource Type", "Resource Type");
+                if (dialog.open() == Window.OK) {
+                    System.out.println(dialog.getValue());
+                    String resType = dialog.getValue();
+                    // Duplicate check.
+                    if (resTypes.contains(resType)) {
+                        MessageDialog.openError(Display.getDefault()
+                                .getActiveShell(), "Duplicate value",
+                                "value already exist.");
+                        return;
+                    }
+                    resTypeslist.add(resType);
+                    resTypeslist.deselectAll();
+                    resTypeslist.select(resTypeslist.getItemCount() - 1);
+                    resTypeslist.showSelection();
+                    remFromListBtn.setEnabled(true);
+
+                    resTypes.add(resType);
+
+                    getWizard().getContainer().updateButtons();
+                }
+            }
+        });
+
+        remFromListBtn.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                int[] selection = resTypeslist.getSelectionIndices();
+                String[] selectionStr = resTypeslist.getSelection();
+                if (null != selection && selection.length > 0) {
+                    resTypeslist.remove(selection);
+                    for (String selected : selectionStr) {
+                        resTypes.remove(selected);
+                    }
+                }
+
+                changeVisibility();
+                getWizard().getContainer().updateButtons();
+            }
+        });
+
+        resTypeslist.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                changeVisibility();
+            }
+        });
+
+        observeBtn.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                observable = observeBtn.getSelection();
+            }
+        });
+
+        /*
+         * startBtn.addSelectionListener(new SelectionAdapter() {
+         * 
+         * @Override public void widgetSelected(SelectionEvent e) { start =
+         * startBtn.getSelection(); } });
+         */
+    }
+
+    private void changeVisibility() {
+        int[] selection = resTypeslist.getSelectionIndices();
+        if (null != selection && selection.length > 0) {
+            remFromListBtn.setEnabled(true);
+        } else {
+            remFromListBtn.setEnabled(false);
+        }
+    }
+
+    @Override
+    public boolean canFlipToNextPage() {
+        if (null == resName || null == resURI || resTypes.size() < 1) {
+            return false;
+        }
+        resName = resName.trim();
+        resURI = resURI.trim();
+        if (resName.length() < 1 || resURI.length() < 1) {
+            return false;
+        }
+        return true;
+    }
+
+    @Override
+    public IWizardPage getNextPage() {
+        // 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.");
+            // TODO: Instead of MessageDialog, errors may be shown on wizard
+            // itself.
+            return null;
+        }
+        return ((CreateResourceWizard) getWizard())
+                .getSimpleResourceAddAttributePage();
+    }
+
+    public String getResName() {
+        return resName;
+    }
+
+    public String getResURI() {
+        return resURI;
+    }
+
+    public Set<String> getResTypes() {
+        return resTypes;
+    }
+
+    public boolean isObservable() {
+        return observable;
+    }
+
+    /*
+     * public boolean isStart() { return start; }
+     */
+
+}
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..41cd07b
--- /dev/null
@@ -0,0 +1,119 @@
+package oic.simulator.serviceprovider.view.dialogs;
+
+import oic.simulator.serviceprovider.utils.Constants;
+
+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;
+
+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/SimpleResourcePage.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/SimpleResourcePage.java
new file mode 100644 (file)
index 0000000..e743332
--- /dev/null
@@ -0,0 +1,96 @@
+package oic.simulator.serviceprovider.view.dialogs;
+
+import oic.simulator.serviceprovider.utils.Constants;
+
+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;
+
+public class SimpleResourcePage extends WizardPage {
+
+    Button manualBtn;
+    Button ramlBtn;
+
+    protected SimpleResourcePage() {
+        super("Simle Page");
+    }
+
+    @Override
+    public void createControl(Composite parent) {
+        setPageComplete(false);
+        setTitle(Constants.SIMPLE_PAGE_TITLE);
+        setMessage(Constants.SIMPLE_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);
+
+        manualBtn = new Button(compContent, SWT.RADIO);
+        manualBtn.setText("Manually");
+
+        ramlBtn = new Button(compContent, SWT.RADIO);
+        ramlBtn.setText("From RAML file");
+
+        Label lbl = new Label(compContent, SWT.NULL);
+        lbl.setText("Details:");
+        gd = new GridData();
+        gd.verticalIndent = 20;
+        lbl.setLayoutData(gd);
+
+        Text desc = new Text(compContent, SWT.MULTI | SWT.READ_ONLY
+                | SWT.BORDER | SWT.WRAP | SWT.V_SCROLL);
+        desc.setBackground(compContent.getBackground());
+        desc.setText("[Select an option to view more details]");
+        gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        desc.setLayoutData(gd);
+
+        addUIListeners();
+
+        setControl(compContent);
+    }
+
+    private void addUIListeners() {
+        manualBtn.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                getWizard().getContainer().updateButtons();
+            }
+        });
+
+        ramlBtn.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                getWizard().getContainer().updateButtons();
+            }
+        });
+    }
+
+    @Override
+    public boolean canFlipToNextPage() {
+        if (manualBtn.getSelection() || ramlBtn.getSelection()) {
+            return true;
+        }
+        return false;
+    }
+
+    @Override
+    public IWizardPage getNextPage() {
+        CreateResourceWizard createWizard = (CreateResourceWizard) getWizard();
+        if (manualBtn.getSelection()) {
+            return createWizard.getSimpleResourceBasicDetailsPage();
+        }
+        if (ramlBtn.getSelection()) {
+            return createWizard.getLoadRamlPage();
+        }
+        return null;
+    }
+}
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/StartStopResourcePage.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/StartStopResourcePage.java
new file mode 100644 (file)
index 0000000..4f2a3c8
--- /dev/null
@@ -0,0 +1,90 @@
+package oic.simulator.serviceprovider.view.dialogs;
+
+import oic.simulator.serviceprovider.utils.Constants;
+
+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;
+
+public class StartStopResourcePage extends WizardPage {
+
+    private Button  startButton;
+
+    private boolean start;
+
+    protected StartStopResourcePage() {
+        super("Start/Stop Resource");
+        setStart(true);
+    }
+
+    @Override
+    public void createControl(Composite parent) {
+        setPageComplete(false);
+        setTitle(Constants.START_STOP_PAGE_TITLE);
+        setMessage(Constants.START_STOP_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);
+
+        startButton = new Button(compContent, SWT.CHECK);
+        startButton.setText("Start Resource(s)");
+        startButton.setSelection(true);
+        gd = new GridData();
+        gd.verticalIndent = 10;
+        startButton.setLayoutData(gd);
+
+        Label descLbl = new Label(compContent, SWT.NONE);
+        descLbl.setText("Description:");
+        gd = new GridData();
+        gd.verticalIndent = 50;
+        descLbl.setLayoutData(gd);
+
+        final Text text = new Text(compContent, SWT.MULTI | SWT.READ_ONLY
+                | SWT.BORDER | SWT.WRAP | SWT.V_SCROLL);
+        text.setText("Starting the resource will register it with the platform and makes it visible on the network.\n"
+                + "Resources can be started or stopped later from 'Resource Manager' view.");
+        gd = new GridData();
+        gd.horizontalAlignment = SWT.FILL;
+        gd.grabExcessHorizontalSpace = true;
+        gd.heightHint = 100;
+        gd.verticalAlignment = SWT.BOTTOM;
+        text.setLayoutData(gd);
+
+        addUIListeners();
+
+        setControl(compContent);
+    }
+
+    private void addUIListeners() {
+        startButton.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                setStart(startButton.getSelection());
+            }
+        });
+    }
+
+    public boolean isStart() {
+        return start;
+    }
+
+    public void setStart(boolean start) {
+        this.start = start;
+    }
+
+    @Override
+    public IWizardPage getNextPage() {
+        System.out.println(this.getClass().getName() + ": getNextPage");
+        return null;
+    }
+}
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..e2faddb
--- /dev/null
@@ -0,0 +1,255 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.lang.reflect.InvocationTargetException;
+import java.util.Date;
+
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.utils.Constants;
+import oic.simulator.serviceprovider.utils.Utility;
+import oic.simulator.serviceprovider.view.dialogs.MainPage.ResourceOption;
+
+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.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 org.oic.simulator.ILogger.Level;
+import org.oic.simulator.SimulatorException;
+
+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());
+                // getWizard().getContainer().updateButtons();
+            }
+        });
+
+        resUriTxt.addModifyListener(new ModifyListener() {
+            @Override
+            public void modifyText(ModifyEvent e) {
+                resURI = resUriTxt.getText();
+                setPageComplete(isSelectionDone());
+                // getWizard().getContainer().updateButtons();
+            }
+        });
+    }
+
+    @Override
+    public boolean canFlipToNextPage() {
+        CreateResourceWizard createWizard = (CreateResourceWizard) getWizard();
+        if (isSelectionDone()
+                && (createWizard.getMainPage().getResourceOption() == ResourceOption.COLLECTION_FROM_RAML)
+                && Activator.getDefault().getResourceManager()
+                        .isAnyResourceExist()) {
+            return true;
+        }
+        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() {
+        final boolean done[] = new boolean[1];
+        CreateResourceWizard createWizard = (CreateResourceWizard) getWizard();
+        // 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.");
+            // TODO: Instead of MessageDialog, errors may be shown on wizard
+            // itself.
+            return null;
+        }
+        try {
+            getContainer().run(true, true, new IRunnableWithProgress() {
+
+                @Override
+                public void run(IProgressMonitor monitor)
+                        throws InvocationTargetException, InterruptedException {
+                    try {
+                        monitor.beginTask(
+                                "Completing Collection Resource Creation With RAML",
+                                2);
+                        monitor.worked(1);
+                        done[0] = completeCollectionResourceCreationWithRAML();
+                        monitor.worked(1);
+                    } finally {
+                        monitor.done();
+                    }
+                }
+            });
+        } catch (InvocationTargetException e) {
+            Activator.getDefault().getLogManager()
+                    .log(Level.ERROR.ordinal(), new Date(), e.getMessage());
+            e.printStackTrace();
+            return null;
+        } catch (InterruptedException e) {
+            Activator.getDefault().getLogManager()
+                    .log(Level.ERROR.ordinal(), new Date(), e.getMessage());
+            e.printStackTrace();
+            return null;
+        }
+        if (!done[0]) {
+            return null;
+        }
+        return createWizard.getAddResourcesToCollectionPage();
+    }
+
+    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;
+    }
+
+    private boolean completeCollectionResourceCreationWithRAML() {
+        boolean result = false;
+        String status;
+        CreateResourceWizard createWizard = (CreateResourceWizard) getWizard();
+        try {
+            result = Activator
+                    .getDefault()
+                    .getResourceManager()
+                    .completeCollectionResourceCreationByRAML(
+                            createWizard.getLoadRamlPage().getResource(),
+                            resURI, resName);
+            if (result)
+                status = "Resource created.";
+            else {
+                status = "Failed to create resource.";
+            }
+        } catch (SimulatorException e) {
+            status = "Failed to create resource.\n"
+                    + Utility.getSimulatorErrorString(e, null);
+        }
+        createWizard.setStatus(status);
+        return result;
+    }
+}
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..254aa68
--- /dev/null
@@ -0,0 +1,54 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_queryparam.cpp b/service/simulator/java/jni/jni_queryparam.cpp
new file mode 100644 (file)
index 0000000..fd59abf
--- /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, key);
+
+        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..7b63171
--- /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 queryParams);
+
+    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..95e77de
--- /dev/null
@@ -0,0 +1,46 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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..5f2135f
--- /dev/null
@@ -0,0 +1,92 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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)
+{
+    m_vectorCls = gSimulatorClassRefs.vectorCls;
+}
+
+jobject JniVector::toJava()
+{
+    static jmethodID vectorCtor = m_env->GetMethodID(m_vectorCls, "<init>", "()V");
+    return m_env->NewObject(m_vectorCls, vectorCtor);
+}
+
+jobject JniVector::toJava(std::vector<std::string> &cppVector)
+{
+    static jmethodID addMethod = m_env->GetMethodID(m_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;
+}
+
+void JniVector::addElementsCpp(jobject vector, int size, std::vector<int> &result)
+{
+    static jmethodID getMethod = m_env->GetMethodID(m_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(m_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(m_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..860c082
--- /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 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 vector)
+        {
+            std::vector<TYPE> result;
+            jmethodID sizeMethodID = m_env->GetMethodID(m_vectorCls, "size", "()I");
+
+            int size = m_env->CallIntMethod(vector, sizeMethodID);
+            addElementsCpp(vector, size, result);
+            return result;
+        }
+
+        jobject toJava(std::vector<std::string> &cppVector);
+        jobject toJava();
+
+    private:
+        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;
+        jclass m_vectorCls;
+};
+
+#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..1b9c2dc
--- /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);
+
+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_getSupportedResources
+(JNIEnv *env, jobject object)
+{
+    SimulatorCollectionResourceSP 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_addChildResource
+(JNIEnv *env, jobject object, jobject resource)
+{
+    VALIDATE_INPUT(env, !resource, "Child resource is null!")
+
+    SimulatorResourceSP childResource = SimulatorResourceToCpp(env, resource);
+    VALIDATE_INPUT(env, !childResource, "No corresponding native object of child resource!")
+
+    SimulatorCollectionResourceSP 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_removeChildResource
+(JNIEnv *env, jobject object, jobject resource)
+{
+    VALIDATE_INPUT(env, !resource, "Child resource is null!")
+
+    SimulatorResourceSP childResource = SimulatorResourceToCpp(env, resource);
+    VALIDATE_INPUT(env, !childResource, "No corresponding native object of child resource!")
+
+    SimulatorCollectionResourceSP 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_removeChildResourceByUri
+(JNIEnv *env, jobject object, jstring uri)
+{
+    SimulatorCollectionResourceSP 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_getChildResource
+(JNIEnv *env, jobject object)
+{
+    SimulatorCollectionResourceSP 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_dispose
+(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 c954a971a01eaf88e8d9286c29cb045373515013..a2f17eda205b5a1f656bd7b95d65165f3d3bc895 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,54 +39,33 @@ 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)
+void onDeviceInfoReceived(jobject listener, 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;
-    }
+    jmethodID listenerMethodId = env->GetMethodID(listenerCls, "onDeviceFound",
+                                 "(Lorg/oic/simulator/DeviceInfo;)V");
 
-    // Convert CPP to Java DeviceInfo object
-    jobject jDeviceInfo = JDeviceInfo(env).toJava(deviceInfo);
+    jobject jDeviceInfo = JniDeviceInfo(env).toJava(deviceInfo);
     if (!jDeviceInfo)
     {
         releaseEnv();
         return;
     }
 
-    // Invoke java listener with DeviceInfo
-    env->CallVoidMethod(listener, listenerMId, jDeviceInfo);
+    env->CallVoidMethod(listener, listenerMethodId, jDeviceInfo);
     if (env->ExceptionCheck())
     {
         releaseEnv();
index ac538672e381af304e80795d70450ae087f9f3a8..27e845d4bdf9405216d1966d0c93662934cb14f4 100644 (file)
 #include "simulator_device_info.h"
 #include <jni.h>
 
-class JDeviceInfo
+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 +41,6 @@ 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;
-};
+void onDeviceInfoReceived(jobject listener, DeviceInfo &deviceInfo);
 
 #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..041b844
--- /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..f7cc9d9
--- /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_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..63178ae
--- /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.
+ *
+ ******************************************************************/
+
+#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 AUTOMATION_TYPE_CLS "org/oic/simulator/server/SimulatorResource$AutoUpdateType"
+
+#define SIMULATOR_REMOTE_RESOURCE_CLS "org/oic/simulator/client/SimulatorRemoteResource"
+#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_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_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_REMOTE_RESOURCE_CLS, gSimulatorClassRefs.simulatorRemoteResourceCls);
+    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, AUTOMATION_TYPE_CLS, gSimulatorClassRefs.automationTypeCls);
+    getClassRef(env, OBSERVER_CLS, gSimulatorClassRefs.observerCls);
+    getClassRef(env, DEVICE_INFO_CLS, gSimulatorClassRefs.deviceInfoCls);
+    getClassRef(env, PLATFORM_INFO_CLS, gSimulatorClassRefs.platformInfoCls);
+    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.automationTypeCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.simulatorRemoteResourceCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.observerCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.deviceInfoCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.platformInfoCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.simulatorExceptionCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.invalidArgsExceptionCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.noSupportExceptionCls);
+    env->DeleteGlobalRef(gSimulatorClassRefs.operationInProgressExceptionCls);
+}
+
+#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 0fc579634979174371c57955d2eb86c621e27e72..3391685e0d057143ee1350689346a07b9b1f2603 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
 {
@@ -109,448 +78,185 @@ class JNILogger : public ILogger
         jweak m_logger;
 };
 
-
-jobject SimulatorRemoteResourceToJava(JNIEnv *env, jlong resource)
-{
-    jmethodID constructor = env->GetMethodID(gSimulatorClassRefs.classSimulatorRemoteResource, "<init>",
-                            "(J)V");
-    if (NULL == constructor)
-    {
-        return NULL;
-    }
-
-    jobject resourceObj = (jobject) env->NewObject(gSimulatorClassRefs.classSimulatorRemoteResource,
-                          constructor, resource);
-    if (NULL == resourceObj)
-    {
-        return NULL;
-    }
-
-    return resourceObj;
-}
-
-class JNIFoundResourceListener
-{
-    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;
-
-};
-
-void onResourceModelChange(jweak jlistenerRef, const std::string &uri,
-                           const SimulatorResourceModel &resModel)
+void onResourceFound(jobject listener, std::shared_ptr<SimulatorRemoteResource> remoteResource)
 {
     JNIEnv *env = getEnv();
-    if (nullptr == env)
-        return;
-
-    jobject modelChangeListener = env->NewLocalRef(jlistenerRef);
-    if (!modelChangeListener)
-    {
-        releaseEnv();
-        return;
-    }
-
-    jclass modelChangeCls = env->GetObjectClass(modelChangeListener);
-    if (!modelChangeCls)
-    {
-        releaseEnv();
+    if (!env)
         return;
-    }
 
-    jmethodID foundModelChangeMId = env->GetMethodID(modelChangeCls, "onResourceModelChanged",
-                                    "(Ljava/lang/String;Lorg/oic/simulator/SimulatorResourceModel;)V");
-    if (!foundModelChangeMId)
-    {
-        releaseEnv();
-        return;
-    }
-
-    JSimulatorResourceModel *jniModel = new JSimulatorResourceModel(resModel);
-    if (!jniModel)
-    {
-        releaseEnv();
-        return;
-    }
+    jclass listenerCls = env->GetObjectClass(listener);
+    jmethodID callbackMethod = env->GetMethodID(listenerCls, "onResourceFound",
+                               "(Lorg/oic/simulator/client/SimulatorRemoteResource;)V");
 
-    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())
-    {
-        delete jniModel;
-        releaseEnv();
+    jobject resource = createSimulatorRemoteResource(env, remoteResource);
+    if (!resource)
         return;
-    }
-
-    env->DeleteLocalRef(jUri);
 
+    env->CallVoidMethod(listener, callbackMethod, resource);
     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_createResource
+(JNIEnv *env, jclass object, jstring configPath)
 {
-    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, !configPath, "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, configPath);
+        SimulatorResourceSP resource = SimulatorManager::getInstance()->createResource(
+                                           jniPath.get());
+        return createSimulatorResource(env, resource);
     }
     catch (InvalidArgsException &e)
     {
         throwInvalidArgsException(env, e.code(), e.what());
-        return nullptr;
     }
     catch (SimulatorException &e)
     {
         throwSimulatorException(env, e.code(), e.what());
-        return nullptr;
     }
-    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_createResources
+(JNIEnv *env, jclass object, jstring configPath, jint count)
 {
-    if (!configPath)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM,
-                                  "Configuration file path is empty!");
-        return nullptr;
-    }
+    VALIDATE_INPUT_RET(env, !configPath, "Path is null!", nullptr)
+    VALIDATE_INPUT_RET(env, !count || count < 0, "Invalid count value!", 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);
-    };
-
-    const char *configPathCStr = env->GetStringUTFChars(configPath, NULL);
-    std::vector<SimulatorResourceServerSP> resources;
     try
     {
-        resources = SimulatorManager::getInstance()->createResource(configPathCStr, count, callback);
+        JniString jniPath(env, configPath);
+        std::vector<SimulatorResourceSP> resources =
+            SimulatorManager::getInstance()->createResource(jniPath.get(), count);
+        return createSimulatorResourceVector(env, resources);
     }
     catch (InvalidArgsException &e)
     {
         throwInvalidArgsException(env, e.code(), e.what());
-        return nullptr;
     }
     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);
-        }
-    }
-
-    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_createSingleResource
+(JNIEnv *env, jclass object, jstring name, jstring uri, jstring resourceType)
 {
-    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, !name, "Name is null!", nullptr)
+    VALIDATE_INPUT_RET(env, !uri, "URI is null!", nullptr)
+    VALIDATE_INPUT_RET(env, !resourceType, "Resource type is null!", nullptr)
 
     try
     {
-        SimulatorManager::getInstance()->deleteResource(resource);
+        JniString jniName(env, name);
+        JniString jniUri(env, uri);
+        JniString jniResourceType(env, resourceType);
+
+        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());
     }
-    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_createCollectionResource
+(JNIEnv *env, jclass object, jstring name, jstring uri, jstring resourceType)
 {
-    std::string type;
-    const char *typeCStr = NULL;
-    if (resourceType)
-    {
-        typeCStr = env->GetStringUTFChars(resourceType, NULL);
-        type = typeCStr;
-    }
+    VALIDATE_INPUT_RET(env, !name, "Name is null!", nullptr)
+    VALIDATE_INPUT_RET(env, !uri, "URI is null!", nullptr)
+    VALIDATE_INPUT_RET(env, !resourceType, "Resource type is null!", nullptr)
 
     try
     {
-        SimulatorManager::getInstance()->deleteResource(type);
+        JniString jniName(env, name);
+        JniString jniUri(env, uri);
+        JniString jniResourceType(env, resourceType);
+
+        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_searchResource
+(JNIEnv *env, jobject object, jstring resourceType, jobject listener)
 {
-    if (!jListener)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
-        return;
-    }
+    VALIDATE_CALLBACK(env, listener)
 
-    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, listener));
 
     try
     {
-        if (!jResourceType)
+        if (!resourceType)
         {
-            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, resourceType);
+            SimulatorManager::getInstance()->findResource(type.get(), callback);
         }
 
     }
     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;
-    }
-
-    if (typeCStr)
-        env->ReleaseStringUTFChars(jResourceType, typeCStr);
 }
 
-
 JNIEXPORT void JNICALL
-Java_org_oic_simulator_SimulatorManagerNativeInterface_setLogger
-(JNIEnv *env, jclass object, jobject logger)
+Java_org_oic_simulator_SimulatorManager_setDeviceInfo
+(JNIEnv *env, jobject object, jstring deviceName)
 {
-    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)
-{
-    if (!deviceInfo)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid device info!");
-        return;
-    }
-
-    const char *deviceName = env->GetStringUTFChars(deviceInfo, NULL);
+    VALIDATE_INPUT(env, !deviceName, "Device name is null!")
 
     try
     {
-        SimulatorManager::getInstance()->setDeviceInfo(deviceName);
+        JniString jniDeviceName(env, deviceName);
+        SimulatorManager::getInstance()->setDeviceInfo(jniDeviceName.get());
     }
     catch (InvalidArgsException &e)
     {
@@ -560,31 +266,19 @@ Java_org_oic_simulator_SimulatorManagerNativeInterface_setDeviceInfo
     {
         throwSimulatorException(env, e.code(), e.what());
     }
-    catch (...)
-    {
-        throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
-        return;
-    }
-
-    env->ReleaseStringUTFChars(deviceInfo, deviceName);
 }
 
 JNIEXPORT void JNICALL
-Java_org_oic_simulator_SimulatorManagerNativeInterface_getDeviceInfo
-(JNIEnv *env, jobject interfaceObject, jobject jListener)
+Java_org_oic_simulator_SimulatorManager_findDevices
+(JNIEnv *env, jobject object, jobject listener)
 {
-    if (!jListener)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
-        return;
-    }
+    VALIDATE_CALLBACK(env, listener)
 
-    JniDeviceInfoListener *deviceInfoListener = new JniDeviceInfoListener(env, jListener);
-    DeviceInfoCallback callback = std::bind([deviceInfoListener](DeviceInfo & deviceInfo)
+    DeviceInfoCallback callback =  std::bind([](DeviceInfo & deviceInfo,
+                                   const std::shared_ptr<JniListenerHolder> &listenerRef)
     {
-        deviceInfoListener->onDeviceInfoReceived(deviceInfo);
-        delete deviceInfoListener;
-    }, std::placeholders::_1);
+        onDeviceInfoReceived(listenerRef->get(), deviceInfo);
+    }, std::placeholders::_1, JniListenerHolder::create(env, listener));
 
     try
     {
@@ -598,56 +292,37 @@ Java_org_oic_simulator_SimulatorManagerNativeInterface_getDeviceInfo
     {
         throwSimulatorException(env, e.code(), e.what());
     }
-    catch (...)
-    {
-        throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
-        return;
-    }
 }
 
 JNIEXPORT void JNICALL
-Java_org_oic_simulator_SimulatorManagerNativeInterface_setPlatformInfo
-(JNIEnv *env, jobject interfaceObject, jobject jPlatformInfo)
+Java_org_oic_simulator_SimulatorManager_setPlatformInfo
+(JNIEnv *env, jobject object, jobject platformInfo)
 {
-    if (!jPlatformInfo)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid platform info!");
-        return;
-    }
+    VALIDATE_INPUT(env, !platformInfo, "Platform info is null!")
 
-    JPlatformInfo jniPlatformInfo(env);
     try
     {
-        PlatformInfo platformInfo = jniPlatformInfo.toCPP(jPlatformInfo);
-        SimulatorManager::getInstance()->setPlatformInfo(platformInfo);
+        JniPlatformInfo jniPlatformInfo(env);
+        PlatformInfo info = jniPlatformInfo.toCpp(platformInfo);
+        SimulatorManager::getInstance()->setPlatformInfo(info);
     }
     catch (SimulatorException &e)
     {
         throwSimulatorException(env, e.code(), e.what());
     }
-    catch (...)
-    {
-        throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
-        return;
-    }
 }
 
 JNIEXPORT void JNICALL
-Java_org_oic_simulator_SimulatorManagerNativeInterface_getPlatformInfo
-(JNIEnv *env, jobject interfaceObject, jobject jListener)
+Java_org_oic_simulator_SimulatorManager_getPlatformInformation
+(JNIEnv *env, jobject object, jobject listener)
 {
-    if (!jListener)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
-        return;
-    }
+    VALIDATE_CALLBACK(env, listener)
 
-    JniPlatformInfoListener *platformInfoListener = new JniPlatformInfoListener(env, jListener);
-    PlatformInfoCallback callback = std::bind([platformInfoListener](PlatformInfo & platformInfo)
+    PlatformInfoCallback callback =  std::bind([](PlatformInfo & platformInfo,
+                                     const std::shared_ptr<JniListenerHolder> &listenerRef)
     {
-        platformInfoListener->onPlatformInfoReceived(platformInfo);
-        delete platformInfoListener;
-    }, std::placeholders::_1);
+        onPlatformInfoReceived(listenerRef->get(), platformInfo);
+    }, std::placeholders::_1, JniListenerHolder::create(env, listener));
 
     try
     {
@@ -661,308 +336,17 @@ Java_org_oic_simulator_SimulatorManagerNativeInterface_getPlatformInfo
     {
         throwSimulatorException(env, e.code(), e.what());
     }
-    catch (...)
-    {
-        throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
-        return;
-    }
 }
 
-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_setLogger
+(JNIEnv *env, jobject object, jobject logger)
 {
+    static std::shared_ptr<JNILogger> target(new JNILogger());
+    target->setJavaLogger(env, logger);
+    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 f3be7639fcb8dda73385b6f23571d242e65dd2b7..4fb7702a956282bfac70d453d234910005c4066f 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)
+void onPlatformInfoReceived(jobject listener, 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;
-    }
+    jmethodID listenerMethodId = env->GetMethodID(listenerCls, "onPlatformFound",
+                                 "(Lorg/oic/simulator/PlatformInfo;)V");
 
-    // Convert CPP to Java DeviceInfo object
-    jobject jPlatformInfo = JPlatformInfo(env).toJava(platformInfo);
+    jobject jPlatformInfo = JniPlatformInfo(env).toJava(platformInfo);
     if (!jPlatformInfo)
     {
         releaseEnv();
         return;
     }
 
-    // Invoke java listener with DeviceInfo
-    env->CallVoidMethod(listener, listenerMId, jPlatformInfo);
+    env->CallVoidMethod(listener, listenerMethodId, jPlatformInfo);
     if (env->ExceptionCheck())
     {
         releaseEnv();
index e623b8160e433332d4a0a3f09d6c907736ab9779..ba75df7356807aa2be09d647270aa36b635999ee 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,6 @@ 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;
-};
+void onPlatformInfoReceived(jobject listener, PlatformInfo &platformInfo);
 
 #endif
index 63215b639b1e8ab6bf3c8f396128a4561353b53f..f41369691939fdfb3ddb63b74caa826f979ae058 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"
+#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"
 
-extern SimulatorClassRefs gSimulatorClassRefs;
+#include "simulator_remote_resource.h"
 
-SimulatorRemoteResourceSP JniSimulatorRemoteResource::getResourceHandle
-(JNIEnv *env, jobject object)
-{
-    JniSimulatorRemoteResource *jniResource = GetHandle<JniSimulatorRemoteResource>(env, object);
-    if (env->ExceptionCheck() || !jniResource)
-    {
-        return nullptr;
-    }
+#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;}
 
-    return jniResource->m_resource;
+SimulatorRemoteResourceSP SimulatorRemoteResourceToCpp(JNIEnv *env, jobject object)
+{
+    JniSharedObjectHolder<SimulatorRemoteResource> *jniResource =
+        GetHandle<JniSharedObjectHolder<SimulatorRemoteResource>>(env, object);
+    if (jniResource)
+        return jniResource->get();
+    return nullptr;
 }
 
-class JNIOnObserveListener
+void onObserveCallback(jobject listener, const std::string &uid, const int errorCode,
+                       SimulatorResourceModelSP 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;
-
-            jobject onObserveListener = env->NewLocalRef(m_listener);
-            if (!onObserveListener)
-            {
-                releaseEnv();
-                return;
-            }
-
-            jclass onObserveCls = env->GetObjectClass(onObserveListener);
-            if (!onObserveCls)
-            {
-                releaseEnv();
-                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();
-                }
-            }
-        }
-
-    private:
-        jweak m_listener;
-};
-
-class JNIOnGetListener
-{
-    public:
-        void setJavaOnGetListener(JNIEnv *env, jobject listener)
-        {
-            m_listener = env->NewWeakGlobalRef(listener);
-        }
+    jclass listenerCls = env->GetObjectClass(listener);
+    jmethodID listenerMethodId = env->GetMethodID(listenerCls, "onObserveNotification",
+                                 "(Ljava/lang/String;Lorg/oic/simulator/SimulatorResourceModel;I)V");
 
-        void onGetCallback(const std::string &uId, int errorCode,
-                           SimulatorResourceModelSP representation)
-        {
-            JNIEnv *env = getEnv();
-            if (nullptr == env)
-                return;
-
-            jobject onGetListener = env->NewLocalRef(m_listener);
-            if (!onGetListener)
-            {
-                releaseEnv();
-                return;
-            }
-
-            jclass onGetCls = env->GetObjectClass(onGetListener);
-            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, "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();
-                }
-            }
-        }
-
-    private:
-        jweak m_listener;
-};
-
-class JNIOnPutListener
-{
-    public:
-        void setJavaOnPutListener(JNIEnv *env, jobject listener)
-        {
-            m_listener = env->NewWeakGlobalRef(listener);
-        }
+    SimulatorResourceModel *resModel = representation.get();
+    jobject jResModel = simulatorResourceModelToJava(env, *resModel);
+    jstring jUid = env->NewStringUTF(uid.c_str());
+    env->CallVoidMethod(listener, listenerMethodId, jUid, jResModel, seq);
+    releaseEnv();
+}
 
-        void onPutCallback(const std::string &uId, int errorCode,
-                           SimulatorResourceModelSP representation)
-        {
-            JNIEnv *env = getEnv();
-            if (nullptr == env)
-                return;
-
-            jobject onPutListener = env->NewLocalRef(m_listener);
-            if (!onPutListener)
-            {
-                releaseEnv();
-                return;
-            }
-
-            jclass onGetCls = env->GetObjectClass(onPutListener);
-            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, "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();
-                }
-            }
-        }
-
-    private:
-        jweak m_listener;
-};
-
-class JNIOnPostListener
+void onGetCallback(jobject listener, const std::string &uid, int errorCode,
+                   SimulatorResourceModelSP representation)
 {
-    public:
-        void setJavaOnPostListener(JNIEnv *env, jobject listener)
-        {
-            m_listener = env->NewWeakGlobalRef(listener);
-        }
+    JNIEnv *env = getEnv();
+    if (!env)
+        return;
 
-        void onPostCallback(const std::string &uId, int errorCode,
-                            SimulatorResourceModelSP representation)
-        {
-            JNIEnv *env = getEnv();
-            if (nullptr == env)
-                return;
-
-            jobject onPostListener = env->NewLocalRef(m_listener);
-            if (!onPostListener)
-            {
-                releaseEnv();
-                return;
-            }
-
-            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();
-                }
-            }
-        }
-
-    private:
-        jweak m_listener;
-
-};
-
-class JNIOnVerificationListener
-{
-    public:
-        void setJavaOnVerificationListener(JNIEnv *env, jobject listener)
-        {
-            m_listener = env->NewWeakGlobalRef(listener);
-        }
+    jclass listenerCls = env->GetObjectClass(listener);
+    jmethodID listenerMethodId = env->GetMethodID(listenerCls, "onGetResponse",
+                                 "(Ljava/lang/String;Lorg/oic/simulator/SimulatorResult;Lorg/oic/simulator/SimulatorResourceModel;)V");
 
-        void onVerificationCallback(const std::string &uId, int id, OperationState opState)
-        {
-            JNIEnv *env = getEnv();
-            if (nullptr == env)
-                return;
-
-            jobject onVerificationListener = env->NewLocalRef(m_listener);
-            if (!onVerificationListener)
-            {
-                releaseEnv();
-                return;
-            }
-
-            jclass onVerificationCls = env->GetObjectClass(onVerificationListener);
-            if (!onVerificationCls)
-            {
-                releaseEnv();
-                return;
-            }
-
-            jmethodID midL;
-
-            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());
-
-            env->CallVoidMethod(onVerificationListener, midL, jUid, (jint)id);
-
-            if (env->ExceptionCheck())
-            {
-                releaseEnv();
-            }
-        }
-
-    private:
-        jweak m_listener;
-
-};
+    SimulatorResourceModel *resModel = representation.get();
+    jobject jResModel = simulatorResourceModelToJava(env, *resModel);
+    jstring jUid = env->NewStringUTF(uid.c_str());
+    env->CallVoidMethod(listener, listenerMethodId, jUid,
+                        simulatorResultToJava(env, static_cast<SimulatorResult>(errorCode)), jResModel);
 
+    releaseEnv();
+}
 
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_startObserve
-(JNIEnv *env, jobject thiz, jint observeType, jobject jQueryParamsMap, jobject jListener)
+void onPutCallback(jobject listener, const std::string &uid, int errorCode,
+                   SimulatorResourceModelSP representation)
 {
-    if (!jListener)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
+    JNIEnv *env = getEnv();
+    if (!env)
         return;
-    }
 
-    SimulatorRemoteResourceSP resource = JniSimulatorRemoteResource::getResourceHandle(env,
-                                         thiz);
-    if (!resource)
-    {
-        throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
-        return;
-    }
+    jclass listenerCls = env->GetObjectClass(listener);
+    jmethodID listenerMethodId = env->GetMethodID(listenerCls, "onPutResponse",
+                                 "(Ljava/lang/String;Lorg/oic/simulator/SimulatorResult;Lorg/oic/simulator/SimulatorResourceModel;)V");
 
-    std::map<std::string, std::string> queryParams;
-    if (jQueryParamsMap)
-        convertJavaMapToQueryParamsMap(env, jQueryParamsMap, queryParams);
+    SimulatorResourceModel *resModel = representation.get();
+    jobject jResModel = simulatorResourceModelToJava(env, *resModel);
+    jstring jUid = env->NewStringUTF(uid.c_str());
+    env->CallVoidMethod(listener, listenerMethodId, jUid,
+                        simulatorResultToJava(env, static_cast<SimulatorResult>(errorCode)), jResModel);
 
-    ObserveType type = ObserveType::OBSERVE;
-    if (1 == observeType)
-        type = ObserveType::OBSERVE_ALL;
+    releaseEnv();
+}
 
-    JNIOnObserveListener *onObserveListener = new JNIOnObserveListener();
-    onObserveListener->setJavaOnObserveListener(env, jListener);
+void onPostCallback(jobject listener, const std::string &uid, int errorCode,
+                    SimulatorResourceModelSP representation)
+{
+    JNIEnv *env = getEnv();
+    if (!env)
+        return;
 
-    try
-    {
-        resource->observe(type,
-                          std::bind(&JNIOnObserveListener::onObserveCallback,
-                                    onObserveListener, std::placeholders::_1,
-                                    std::placeholders::_2, std::placeholders::_3,
-                                    std::placeholders::_4));
-    }
-    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");
-    }
+    jclass listenerCls = env->GetObjectClass(listener);
+    jmethodID listenerMethodId = env->GetMethodID(listenerCls, "onPostResponse",
+                                 "(Ljava/lang/String;Lorg/oic/simulator/SimulatorResult;Lorg/oic/simulator/SimulatorResourceModel;)V");
+
+    SimulatorResourceModel *resModel = representation.get();
+    jobject jResModel = simulatorResourceModelToJava(env, *resModel);
+    jstring jUid = env->NewStringUTF(uid.c_str());
+    env->CallVoidMethod(listener, listenerMethodId, jUid,
+                        simulatorResultToJava(env, static_cast<SimulatorResult>(errorCode)), jResModel);
+
+    releaseEnv();
 }
 
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_stopObserve
-(JNIEnv *env, jobject thiz)
+void onVerificationCallback(jobject listener, const std::string &uid, int id,
+                            OperationState opState)
 {
-    SimulatorRemoteResourceSP resource = JniSimulatorRemoteResource::getResourceHandle(env,
-                                         thiz);
-    if (!resource)
-    {
-        throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
+    JNIEnv *env = getEnv();
+    if (!env)
         return;
-    }
 
-    try
+    jclass listenerCls = env->GetObjectClass(listener);
+    jmethodID listenerMethodId;
+    if (OP_START == opState)
     {
-        resource->cancelObserve();
+        listenerMethodId = env->GetMethodID(listenerCls, "onVerificationStarted", "(Ljava/lang/String;I)V");
     }
-    catch (SimulatorException &e)
+    else if (OP_COMPLETE == opState)
     {
-        throwSimulatorException(env, e.code(), e.what());
+        listenerMethodId = env->GetMethodID(listenerCls, "onVerificationCompleted",
+                                            "(Ljava/lang/String;I)V");
     }
-    catch (...)
+    else if (OP_ABORT == opState)
     {
-        throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
+        listenerMethodId = env->GetMethodID(listenerCls, "onVerificationAborted", "(Ljava/lang/String;I)V");
     }
+
+    jstring jUid = env->NewStringUTF(uid.c_str());
+    env->CallVoidMethod(listener, listenerMethodId, jUid, id);
+
+    if (OP_COMPLETE == opState || OP_ABORT == opState)
+        env->DeleteGlobalRef(listener);
+    releaseEnv();
 }
 
+#ifdef __cplusplus
+extern "C" {
+#endif
+
 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_nativeGet
+(JNIEnv *env, jobject object, jstring resInterface, jobject queryParamsMap, jobject listener)
 {
-    if (!jListener)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
-        return;
-    }
+    VALIDATE_CALLBACK(env, listener)
 
-    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;
-    }
-
-    // Query parameters
-    std::map<std::string, std::string> queryParams;
-    if (jQueryParamsMap)
-        convertJavaMapToQueryParamsMap(env, jQueryParamsMap, queryParams);
+        JniString jniInterface(env, resInterface);
+        std::map<std::string, std::string> queryParams =
+            JniQueryParameter(env).toCpp(queryParamsMap);
 
-    // Create listener
-    JNIOnGetListener *onGetListener = new JNIOnGetListener();
-    onGetListener->setJavaOnGetListener(env, jListener);
+        SimulatorRemoteResource::ResponseCallback callback =  std::bind([](
+                    const std::string & uid, int errorCode, SimulatorResourceModelSP representation,
+                    const std::shared_ptr<JniListenerHolder> &listenerRef)
+        {
+            onGetCallback(listenerRef->get(), uid, errorCode, representation);
+        }, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3,
+        JniListenerHolder::create(env, listener));
 
-    try
-    {
-        resource->get(interfaceType,
-                      queryParams,
-                      std::bind(&JNIOnGetListener::onGetCallback,
-                                onGetListener, std::placeholders::_1,
-                                std::placeholders::_2, std::placeholders::_3));
+        resource->get(jniInterface.get(), queryParams, callback);
     }
     catch (InvalidArgsException &e)
     {
         throwInvalidArgsException(env, e.code(), e.what());
-        return;
     }
     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;
-    }
-
-    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_nativePut
+(JNIEnv *env, jobject object, jstring resInterface, jobject queryParamsMap,
+ jobject representation, jobject listener)
 {
-    if (!jListener)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
-        return;
-    }
+    VALIDATE_CALLBACK(env, listener)
 
-    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;
-    }
-
-    // Query parameters
-    std::map<std::string, std::string> queryParams;
-    if (jQueryParamsMap)
-        convertJavaMapToQueryParamsMap(env, jQueryParamsMap, queryParams);
+        JniString jniInterface(env, resInterface);
+        std::map<std::string, std::string> queryParams =
+            JniQueryParameter(env).toCpp(queryParamsMap);
 
-    SimulatorResourceModelSP resourceModel =
-        JSimulatorResourceModel::getResourceModelPtr(env, jRepresentation);
+        SimulatorResourceModel resModel;
+        simulatorResourceModelToCpp(env, representation, resModel);
+        SimulatorResourceModelSP resModelSP(new SimulatorResourceModel(resModel));
 
-    // Create listener
-    JNIOnPutListener *onPutListener = new JNIOnPutListener();
-    onPutListener->setJavaOnPutListener(env, jListener);
+        SimulatorRemoteResource::ResponseCallback callback =  std::bind([](
+                    const std::string & uid, int errorCode, SimulatorResourceModelSP representation,
+                    const std::shared_ptr<JniListenerHolder> &listenerRef)
+        {
+            onPutCallback(listenerRef->get(), uid, errorCode, representation);
+        }, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3,
+        JniListenerHolder::create(env, listener));
 
-    try
-    {
-        resource->put(interfaceType,
-                      queryParams,
-                      resourceModel,
-                      std::bind(&JNIOnPutListener::onPutCallback,
-                                onPutListener, std::placeholders::_1,
-                                std::placeholders::_2, std::placeholders::_3));
+        resource->put(jniInterface.get(), queryParams, resModelSP, callback);
     }
     catch (InvalidArgsException &e)
     {
         throwInvalidArgsException(env, e.code(), e.what());
-        return;
     }
     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;
-    }
-
-    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)
+Java_org_oic_simulator_client_SimulatorRemoteResource_nativePost
+(JNIEnv *env, jobject object, jstring resInterface, jobject queryParamsMap,
+ jobject representation, jobject listener)
 {
-    if (!jListener)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
-        return;
-    }
+    VALIDATE_CALLBACK(env, listener)
 
-    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;
-    }
-
-    // Query parameters
-    std::map<std::string, std::string> queryParams;
-    if (jQueryParamsMap)
-        convertJavaMapToQueryParamsMap(env, jQueryParamsMap, queryParams);
+        JniString jniInterface(env, resInterface);
+        std::map<std::string, std::string> queryParams =
+            JniQueryParameter(env).toCpp(queryParamsMap);
 
-    SimulatorResourceModelSP resourceModel =
-        JSimulatorResourceModel::getResourceModelPtr(env, jRepresentation);
+        SimulatorResourceModel resModel;
+        simulatorResourceModelToCpp(env, representation, resModel);
+        SimulatorResourceModelSP resModelSP(new SimulatorResourceModel(resModel));
 
-    // Create listener
-    JNIOnPostListener *onPostListener = new JNIOnPostListener();
-    onPostListener->setJavaOnPostListener(env, jListener);
+        SimulatorRemoteResource::ResponseCallback callback =  std::bind([](
+                    const std::string & uid, int errorCode, SimulatorResourceModelSP representation,
+                    const std::shared_ptr<JniListenerHolder> &listenerRef)
+        {
+            onPostCallback(listenerRef->get(), uid, errorCode, representation);
+        }, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3,
+        JniListenerHolder::create(env, listener));
 
-    try
-    {
-        resource->post(interfaceType,
-                       queryParams,
-                       resourceModel,
-                       std::bind(&JNIOnPostListener::onPostCallback,
-                                 onPostListener, std::placeholders::_1,
-                                 std::placeholders::_2, std::placeholders::_3));
+        resource->post(jniInterface.get(), queryParams, resModelSP, callback);
     }
     catch (InvalidArgsException &e)
     {
         throwInvalidArgsException(env, e.code(), e.what());
-        return;
     }
     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;
     }
-
-    if (interfaceCStr)
-        env->ReleaseStringUTFChars(jResourceInterface, interfaceCStr);
 }
 
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_setConfigInfo
-(JNIEnv *env, jobject thiz, jstring jConfigPath)
+JNIEXPORT jobject JNICALL
+Java_org_oic_simulator_client_SimulatorRemoteResource_setConfigInfo
+(JNIEnv *env, jobject object, jstring configPath)
 {
-    if (!jConfigPath)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM,
-                                  "Configuration file path is null!");
-        return;
-    }
+    VALIDATE_INPUT_RET(env, !configPath, "Path is null!", nullptr)
 
-    SimulatorRemoteResourceSP resource = JniSimulatorRemoteResource::getResourceHandle(env,
-                                         thiz);
-    if (!resource)
+    SimulatorRemoteResourceSP resource = SimulatorRemoteResourceToCpp(env, object);
+    VALIDATE_OBJECT_RET(env, resource, nullptr)
+
+    try
     {
-        throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!");
-        return;
+        JniString jniConfigPath(env, configPath);
+        SimulatorResourceModelSP repSchema = resource->configure(jniConfigPath.get());
+        return simulatorResourceModelToJava(env, *(repSchema.get()));
     }
-
-    // Interface type
-    const char *configCStr = NULL;
-    std::string configPath;
-    if (jConfigPath)
+    catch (InvalidArgsException &e)
     {
-        configCStr = env->GetStringUTFChars(jConfigPath, NULL);
-        configPath = configCStr;
+        throwInvalidArgsException(env, e.code(), e.what());
     }
 
+    return nullptr;
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_client_SimulatorRemoteResource_startObserve
+(JNIEnv *env, jobject object, jobject queryParamsMap, jobject listener)
+{
+    VALIDATE_CALLBACK(env, listener)
+
+    SimulatorRemoteResourceSP resource = SimulatorRemoteResourceToCpp(env, object);
+    VALIDATE_OBJECT(env, resource)
+
     try
     {
-        resource->configure(configPath);
+        std::map<std::string, std::string> queryParams =
+            JniQueryParameter(env).toCpp(queryParamsMap);
+
+        SimulatorRemoteResource::ObserveNotificationCallback callback =  std::bind([](
+                    const std::string & uid, const int errorCode,
+                    SimulatorResourceModelSP representation, const int seq,
+                    const std::shared_ptr<JniListenerHolder> &listenerRef)
+        {
+            onObserveCallback(listenerRef->get(), uid, errorCode, representation, seq);
+        }, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3,
+        std::placeholders::_4, JniListenerHolder::create(env, listener));
+
+        resource->observe(ObserveType::OBSERVE, callback);
     }
     catch (InvalidArgsException &e)
     {
         throwInvalidArgsException(env, e.code(), e.what());
-        return;
     }
-    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_stopObserve
+(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;
+        throwSimulatorException(env, e.code(), e.what());
+    }
+}
 
-        case 2:
-            reqType = RequestType::RQ_TYPE_POST;
-            break;
+JNIEXPORT jint JNICALL
+Java_org_oic_simulator_client_SimulatorRemoteResource_startVerification
+(JNIEnv *env, jobject object, jint reqType, jobject listener)
+{
+    VALIDATE_CALLBACK_RET(env, listener, -1)
 
-        case 3:
-            reqType = RequestType::RQ_TYPE_DELETE;
-            break;
+    SimulatorRemoteResourceSP resource = SimulatorRemoteResourceToCpp(env, object);
+    VALIDATE_OBJECT_RET(env, resource, -1)
 
-        default:
-            return -1;
+    // Convert RequestType
+    RequestType type;
+    switch (reqType)
+    {
+        case 0: type = RequestType::RQ_TYPE_GET; break;
+        case 1: type = RequestType::RQ_TYPE_PUT; break;
+        case 2: type = RequestType::RQ_TYPE_POST; break;
+        case 3: type = RequestType::RQ_TYPE_DELETE; break;
+        default: return -1;
     }
 
-    // Create listener
-    JNIOnVerificationListener *onVerificationListener = new JNIOnVerificationListener();
-    onVerificationListener->setJavaOnVerificationListener(env, jListener);
-
-    int automationId = -1;
-
     try
     {
-        automationId = resource->startVerification(reqType,
-                       std::bind(&JNIOnVerificationListener::onVerificationCallback,
-                                 onVerificationListener, std::placeholders::_1,
-                                 std::placeholders::_2, std::placeholders::_3));
+        SimulatorRemoteResource::StateCallback 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, listener));
+
+        return resource->startVerification(type, callback);
     }
     catch (InvalidArgsException &e)
     {
@@ -841,39 +394,30 @@ Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_startVerificatio
     }
     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");
-    }
 
-    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_stopVerification
+(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->stopVerification(id);
     }
     catch (InvalidArgsException &e)
     {
@@ -881,17 +425,19 @@ Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_stopVerification
     }
     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_dispose
+(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_jni.cpp b/service/simulator/java/jni/simulator_resource_jni.cpp
new file mode 100644 (file)
index 0000000..334b5b5
--- /dev/null
@@ -0,0 +1,470 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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 resourceTypeToJava(JNIEnv *env, SimulatorResource::Type type)
+{
+    static jfieldID single = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResourceTypeCls,
+                             "SINGLE", "Lorg/oic/simulator/server/SimulatorResource$Type;");
+    static jfieldID collection = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResourceTypeCls,
+                                 "COLLECTION", "Lorg/oic/simulator/server/SimulatorResource$Type;");
+
+    switch (type)
+    {
+        case SimulatorResource::Type::SINGLE_RESOURCE:
+            return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResourceTypeCls, single);
+        case SimulatorResource::Type::COLLECTION_RESOURCE:
+            return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResourceTypeCls, collection);
+    }
+
+    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,
+                                  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_getName
+(JNIEnv *env, jobject object)
+{
+    SimulatorResourceSP resource = SimulatorResourceToCpp(env, object);
+    VALIDATE_OBJECT_RET(env, resource, nullptr)
+
+    return env->NewStringUTF(resource->getName().c_str());
+}
+
+JNIEXPORT jobject JNICALL
+Java_org_oic_simulator_server_SimulatorResource_getType
+(JNIEnv *env, jobject object)
+{
+    SimulatorResourceSP resource = SimulatorResourceToCpp(env, object);
+    VALIDATE_OBJECT_RET(env, resource, nullptr)
+
+    return resourceTypeToJava(env, resource->getType());
+}
+
+JNIEXPORT jstring JNICALL
+Java_org_oic_simulator_server_SimulatorResource_getURI
+(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_getResourceType
+(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_getInterface
+(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_isObservable
+(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_isStarted
+(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_getResourceModel
+(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_setName
+(JNIEnv *env, jobject object, jstring name)
+{
+    VALIDATE_INPUT(env, !name, "Name is null!")
+
+    SimulatorResourceSP resource = SimulatorResourceToCpp(env, object);
+    VALIDATE_OBJECT(env, resource)
+
+    try
+    {
+        JniString jniName(env, name);
+        resource->setName(jniName.get());
+    }
+    catch (InvalidArgsException &e)
+    {
+        throwInvalidArgsException(env, e.code(), e.what());
+    }
+    catch (SimulatorException &e)
+    {
+        throwInvalidArgsException(env, e.code(), e.what());
+    }
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_server_SimulatorResource_setURI
+(JNIEnv *env, jobject object, jstring uri)
+{
+    VALIDATE_INPUT(env, !uri, "Uri is null!")
+
+    SimulatorResourceSP resource = SimulatorResourceToCpp(env, object);
+    VALIDATE_OBJECT(env, resource)
+
+    try
+    {
+        JniString jniUri(env, uri);
+        resource->setURI(jniUri.get());
+    }
+    catch (InvalidArgsException &e)
+    {
+        throwInvalidArgsException(env, e.code(), e.what());
+    }
+    catch (SimulatorException &e)
+    {
+        throwInvalidArgsException(env, e.code(), e.what());
+    }
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_server_SimulatorResource_setResourceType
+(JNIEnv *env, jobject object, jstring resourceType)
+{
+    VALIDATE_INPUT(env, !resourceType, "Resource type is null!")
+
+    SimulatorResourceSP resource = SimulatorResourceToCpp(env, object);
+    VALIDATE_OBJECT(env, resource)
+
+    try
+    {
+        JniString jniType(env, resourceType);
+        resource->setResourceType(jniType.get());
+    }
+    catch (InvalidArgsException &e)
+    {
+        throwInvalidArgsException(env, e.code(), e.what());
+    }
+    catch (SimulatorException &e)
+    {
+        throwInvalidArgsException(env, e.code(), e.what());
+    }
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_server_SimulatorResource_addInterface
+(JNIEnv *env, jobject object, jstring interfaceType)
+{
+    VALIDATE_INPUT(env, !interfaceType, "Interface type is null!")
+
+    SimulatorResourceSP resource = SimulatorResourceToCpp(env, object);
+    VALIDATE_OBJECT(env, resource)
+
+    try
+    {
+        JniString jniInterfaceType(env, interfaceType);
+        resource->addInterface(jniInterfaceType.get());
+    }
+    catch (InvalidArgsException &e)
+    {
+        throwInvalidArgsException(env, e.code(), e.what());
+    }
+    catch (NoSupportException &e)
+    {
+        throwNoSupportException(env, e.what());
+    }
+    catch (SimulatorException &e)
+    {
+        throwInvalidArgsException(env, e.code(), e.what());
+    }
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_server_SimulatorResource_setObservable
+(JNIEnv *env, jobject object, jboolean state)
+{
+    SimulatorResourceSP resource = SimulatorResourceToCpp(env, object);
+    VALIDATE_OBJECT(env, resource)
+
+    try
+    {
+        resource->setObservable(static_cast<bool>(state));
+    }
+    catch (SimulatorException &e)
+    {
+        throwInvalidArgsException(env, e.code(), e.what());
+    }
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_server_SimulatorResource_setObserverListener
+(JNIEnv *env, jobject object, jobject listener)
+{
+    VALIDATE_CALLBACK(env, listener)
+
+    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, listener));
+
+    try
+    {
+        resource->setObserverCallback(callback);
+    }
+    catch (InvalidArgsException &e)
+    {
+        throwInvalidArgsException(env, e.code(), e.what());
+    }
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_server_SimulatorResource_setResourceModelChangeListener
+(JNIEnv *env, jobject object, jobject listener)
+{
+    VALIDATE_CALLBACK(env, listener)
+
+    SimulatorResourceSP resource = SimulatorResourceToCpp(env, object);
+    VALIDATE_OBJECT(env, resource)
+
+    SimulatorResource::ResourceModelChangedCallback callback =  std::bind(
+                [](const std::string & uri, SimulatorResourceModel & resModel,
+                   const std::shared_ptr<JniListenerHolder> &listenerRef)
+    {
+        onResourceModelChange(listenerRef->get(), uri, resModel);
+    }, std::placeholders::_1, std::placeholders::_2, JniListenerHolder::create(env, listener));
+
+    try
+    {
+        resource->setModelChangeCallback(callback);
+    }
+    catch (InvalidArgsException &e)
+    {
+        throwInvalidArgsException(env, e.code(), e.what());
+    }
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_server_SimulatorResource_start
+(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_stop
+(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_getObservers
+(JNIEnv *env, jobject object)
+{
+    SimulatorResourceSP resource = SimulatorResourceToCpp(env, object);
+    VALIDATE_OBJECT_RET(env, resource, nullptr)
+
+    return createObserverInfoVector(env, resource->getObserversList());
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_server_SimulatorResource_notifyObserver
+(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_notifyAllObservers
+(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
\ No newline at end of file
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 65b9d9de7c1e2f18c034d025816b17a581f02cfd..d363d0b5292b4650fce4a4aa53684fb5d1a3249e 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_exceptions_jni.h"
+#include "simulator_utils_jni.h"
+#include "jni_string.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:
+        SimulatorResourceModel::ValueType getValueType(jobject jValueType)
+        {
+            static jmethodID ordinalMID = m_env->GetMethodID(
+                                              gSimulatorClassRefs.attributeValueTypeCls, "ordinal", "()I");
+
+            int ordinal = m_env->CallIntMethod(jValueType, ordinalMID);
+            return SimulatorResourceModel::ValueType(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 SimulatorResourceModel::ValueType::INTEGER:
+                    return handleByDepth<int>();
+                case SimulatorResourceModel::ValueType::DOUBLE:
+                    return handleByDepth<double>();
+                case SimulatorResourceModel::ValueType::BOOLEAN:
+                    return handleByDepth<bool>();
+                case SimulatorResourceModel::ValueType::STRING:
+                    return handleByDepth<std::string>();
+                case SimulatorResourceModel::ValueType::RESOURCE_MODEL:
+                    return handleByDepth<SimulatorResourceModel>();
+                case SimulatorResourceModel::ValueType::VECTOR:
+                case SimulatorResourceModel::ValueType::UNKNOWN:
+                    break;
+            }
+        }
+
+        SimulatorResourceModel::ValueVariant 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)
+        {
+        }
+
+        void getValue(jobject &jValue, std::vector<SimulatorResourceModel> &value)
+        {
+        }
+
+        void getValue(jobject &jValue, std::vector<std::vector<SimulatorResourceModel>> &value)
+        {
+        }
+
+        void getValue(jobject &jValue, std::vector<std::vector<std::vector<SimulatorResourceModel>>> &value)
+        {
+        }
+
+        JNIEnv *m_env;
+        SimulatorResourceModel::TypeInfo &m_typeInfo;
+        jobject &m_value;
+        SimulatorResourceModel::ValueVariant m_result;
+};
+
+class JniAttributeValue
 {
-    if (env && thiz && nativeHandle)
-    {
-        env->SetLongField(thiz, GetHandleField(env, thiz), nativeHandle);
-    }
-}
+    public:
+        static jobject toJava(JNIEnv *env, SimulatorResourceModel::Attribute &attribute)
+        {
+            auto value = attribute.getValue();
+            return toJava(env, value);
+        }
+
+        static jobject toJava(JNIEnv *env, SimulatorResourceModel::ValueVariant &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 SimulatorResourceModel::ValueVariant 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();
+        }
+};
+
+class JniAttributeProperty
+{
+    public:
+        static jobject toJava(JNIEnv *env,
+                              SimulatorResourceModel::AttributeProperty &property)
+        {
+            jobject jAttributeProperty = nullptr;
+            if (SimulatorResourceModel::AttributeProperty::Type::RANGE == property.type())
+            {
+                static jmethodID propertyCtor = env->GetMethodID(
+                                                    gSimulatorClassRefs.attributePropertyCls, "<init>", "(DD)V");
+
+                jAttributeProperty = env->NewObject(gSimulatorClassRefs.attributePropertyCls, propertyCtor,
+                                                    property.min(), property.max());
+            }
+            else
+            {
+                static jmethodID propertyCtor = env->GetMethodID(
+                                                    gSimulatorClassRefs.attributePropertyCls, "<init>", "([Lorg/oic/simulator/AttributeValue;)V");
+
+                jobjectArray jValueSet = env->NewObjectArray(property.valueSetSize(),
+                                         gSimulatorClassRefs.attributeValueCls, nullptr);
+                int index = 0;
+                for (auto &value : property.valueSet())
+                {
+                    jobject jValue = JniAttributeValue::toJava(env, value);
+                    env->SetObjectArrayElement(jValueSet, index++, jValue);
+                }
+
+                jAttributeProperty = env->NewObject(gSimulatorClassRefs.attributePropertyCls, propertyCtor,
+                                                    jValueSet);
+            }
+
+            // Add child property
+            if (jAttributeProperty && property.getChildProperty())
+            {
+                SimulatorResourceModel::AttributeProperty childProperty = *(property.getChildProperty());
+                jobject jChildProperty = JniAttributeProperty::toJava(env,  property);
+                if (jChildProperty)
+                {
+                    static jfieldID childPropFID = env->GetFieldID(gSimulatorClassRefs.attributePropertyCls,
+                                                   "mChildProperty", "Lorg/oic/simulator/AttributeProperty;");
+                    env->SetObjectField(jAttributeProperty, childPropFID, jChildProperty);
+                }
+            }
+
+            return jAttributeProperty;
+        }
+
+        static SimulatorResourceModel::AttributeProperty toCpp(JNIEnv *env, jobject jAttributeProperty)
+        {
+            static jfieldID typeFID = env->GetFieldID(gSimulatorClassRefs.attributePropertyCls,
+                                      "mType", "Lorg/oic/simulator/AttributeProperty$Type;");
+            static jfieldID minFID = env->GetFieldID(gSimulatorClassRefs.attributePropertyCls,
+                                     "mMin", "D");
+            static jfieldID maxFID = env->GetFieldID(gSimulatorClassRefs.attributePropertyCls,
+                                     "mMax", "D");
+            static jfieldID valueSetFID = env->GetFieldID(gSimulatorClassRefs.attributePropertyCls,
+                                          "mValueSet", "[Lorg/oic/simulator/AttributeValue;");
+            static jfieldID childPropFID = env->GetFieldID(gSimulatorClassRefs.attributePropertyCls,
+                                           "mChildProperty", "Lorg/oic/simulator/AttributeProperty;");
+            static jmethodID ordinalMID = env->GetMethodID(
+                                              gSimulatorClassRefs.attributePropertyTypeCls, "ordinal", "()I");
+
+            SimulatorResourceModel::AttributeProperty attributeProperty;
+            jobject jType = env->GetObjectField(jAttributeProperty, typeFID);
+            jdouble jMin = env->GetDoubleField(jAttributeProperty, minFID);
+            jdouble jMax = env->GetDoubleField(jAttributeProperty, maxFID);
+            jobjectArray jValueSet = (jobjectArray) env->GetObjectField(jAttributeProperty, valueSetFID);
+            jobject jChildProperty = env->GetObjectField(jAttributeProperty, childPropFID);
+
+            int ordinal = env->CallIntMethod(jType, ordinalMID);
+            switch (SimulatorResourceModel::AttributeProperty::Type(ordinal))
+            {
+                case SimulatorResourceModel::AttributeProperty::Type::RANGE:
+                    {
+                        attributeProperty = SimulatorResourceModel::AttributeProperty(jMin, jMax);
+                    }
+                    break;
+
+                case SimulatorResourceModel::AttributeProperty::Type::VALUE_SET:
+                    {
+                        std::vector<SimulatorResourceModel::ValueVariant> valueSet;
+                        size_t length = env->GetArrayLength(jValueSet);
+                        for (size_t i = 0; i < length; i++)
+                        {
+                            jobject jAttributeValue = env->GetObjectArrayElement(jValueSet, i);
+                            valueSet.push_back(JniAttributeValue::toCpp(env, jAttributeValue));
+                        }
+
+                        attributeProperty = SimulatorResourceModel::AttributeProperty(valueSet);
+                    }
+                    break;
+            }
+
+            // Set child property
+            if (jChildProperty)
+            {
+                SimulatorResourceModel::AttributeProperty childProperty =
+                    JniAttributeProperty::toCpp(env, jAttributeProperty);
+                attributeProperty.setChildProperty(childProperty);
+            }
+
+            return attributeProperty;
+        }
+};
 
 static jobject createHashMap(JNIEnv *env)
 {
-    jobject mapobj = env->NewObject(gSimulatorClassRefs.classHashMap,
-                                    gSimulatorClassRefs.classHashMapCtor);
-    return mapobj;
+    static jmethodID hashMapCtor = env->GetMethodID(
+                                       gSimulatorClassRefs.hashMapCls, "<init>", "()V");
+    return env->NewObject(gSimulatorClassRefs.hashMapCls, hashMapCtor);
 }
 
 static void addEntryToHashMap(JNIEnv *env, jobject mapobj, jobject key, jobject value)
 {
     if (!mapobj || !key || !value)
-    {
         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));
+    static jmethodID hashMapPutMethod = env->GetMethodID(gSimulatorClassRefs.hashMapCls,
+                                        "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
+    env->CallObjectMethod(mapobj, hashMapPutMethod, key, value);
 }
 
-JNIEXPORT jint JNICALL
-Java_org_oic_simulator_SimulatorResourceModel_size
-(JNIEnv *env, jobject thiz)
+jobject simulatorResourceModelToJava(JNIEnv *env, SimulatorResourceModel &resModel)
 {
-    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!");
+    jobject attributesMap = createHashMap(env);
+    jobject propertiesMap = createHashMap(env);
+    if (!attributesMap || !propertiesMap)
         return nullptr;
-    }
 
-    map<string, SimulatorResourceModel::Attribute> attributesMap = resourceModel.getAttributes();
-
-    // Create Java HashMap object
-    jobject jHashMap = NULL;
-    jHashMap = createHashMap(env);
-    if (!jHashMap)
+    for (auto &attributeEntry : resModel.getAttributes())
     {
-        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;
-    }
-
-    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;
-    }
+        jobject jAttributeValue = JniAttributeValue::toJava(env, attributeEntry.second);
+        addEntryToHashMap(env, attributesMap, 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;
+        jobject jAttributeProperty = JniAttributeProperty::toJava(env, attributeEntry.second.getProperty());
+        addEntryToHashMap(env, propertiesMap, jAttrName, jAttributeProperty);
     }
 
-    env->ReleaseStringUTFChars(jAttrName, attrName);
+    static jmethodID simulatorResourceModelCtor = env->GetMethodID(
+                gSimulatorClassRefs.simulatorResourceModelCls, "<init>", "(Ljava/util/Map;Ljava/util/Map;)V");
 
-    // Create a object of ResourceAttribute java class
-    JResourceAttributeConverter converter(attribute);
-    return converter.toJava(env);
+    return env->NewObject(gSimulatorClassRefs.simulatorResourceModelCls,
+                          simulatorResourceModelCtor, attributesMap, propertiesMap);
 }
 
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_SimulatorResourceModel_addAttributeInt
-(JNIEnv *env, jobject thiz, jstring jname, jint jvalue)
+jobject simulatorResourceAttributeToJava(JNIEnv *env, SimulatorResourceModel::Attribute &attribute)
 {
-    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;
-    }
+    static jmethodID simulatorResAttributeCtor = env->GetMethodID(
+                gSimulatorClassRefs.simulatorResourceAttributeCls, "<init>",
+                "(Ljava/lang/String;Lorg/oic/simulator/AttributeValue;Lorg/oic/simulator/AttributeProperty;)V");
 
-    std::string attrName(nameCstr);
-    int value = static_cast<int>(jvalue);
-    resModelPtr->addAttribute(attrName, value);
+    jstring jAttrName = env->NewStringUTF(attribute.getName().c_str());
+    jobject jAttributeValue = JniAttributeValue::toJava(env, attribute);
+    jobject jAttributeProperty = JniAttributeProperty::toJava(env, attribute.getProperty());
 
-    // Release created c string
-    env->ReleaseStringUTFChars(jname, nameCstr);
+    return env->NewObject(gSimulatorClassRefs.simulatorResourceAttributeCls,
+                          simulatorResAttributeCtor, jAttrName, jAttributeValue, jAttributeProperty);
 }
 
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_SimulatorResourceModel_addAttributeDouble
-(JNIEnv *env, jobject thiz, jstring jname, jdouble jvalue)
+bool simulatorResourceModelToCpp(JNIEnv *env, jobject jResModel, SimulatorResourceModel &resModel)
 {
-    if (!jname)
-    {
-        throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid attribute name!");
-        return;
-    }
+    if (!jResModel)
+        return false;
 
-    SimulatorResourceModelSP resModelPtr;
-    resModelPtr = JSimulatorResourceModel::getResourceModelPtr(env, thiz);
-    if (!resModelPtr)
+    static jfieldID valuesFID = env->GetFieldID(gSimulatorClassRefs.simulatorResourceModelCls,
+                                "mValues", "Ljava/util/Map;");
+    static jfieldID propertiesFID = env->GetFieldID(gSimulatorClassRefs.simulatorResourceModelCls,
+                                    "mProperties", "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);
+    jobject jProperties = env->GetObjectField(jResModel, propertiesFID);
+
+    if (jValues)
     {
-        throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "Resource model not found!");
-        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);
+            }
+        }
     }
 
-    const char *nameCstr = env->GetStringUTFChars(jname, NULL);
-    if (!nameCstr)
+    if (jProperties)
     {
-        throwSimulatorException(env, SIMULATOR_ERROR, "String error!");
-        return;
+        jobject entrySet = env->CallObjectMethod(jProperties, 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.setAttributeProperty(JniString(env, key).get(),
+                                              JniAttributeProperty::toCpp(env, value));
+
+                env->DeleteLocalRef(entry);
+                env->DeleteLocalRef(key);
+                env->DeleteLocalRef(value);
+            }
+        }
     }
 
-    std::string attrName(nameCstr);
-    double value = static_cast<double>(jvalue);
-    resModelPtr->addAttribute(attrName, value);
-
-    // Release created c string
-    env->ReleaseStringUTFChars(jname, nameCstr);
+    return true;
 }
 
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_SimulatorResourceModel_addAttributeBoolean
-(JNIEnv *env, jobject thiz, jstring jname, jboolean jvalue)
+bool simulatorResourceAttributeToCpp(JNIEnv *env, jobject jAttribute,
+                                     SimulatorResourceModel::Attribute &attribute)
 {
-    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);
+    if (!jAttribute)
+        return false;
 
-    // Release created c string
-    env->ReleaseStringUTFChars(jname, nameCstr);
-}
+    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;");
 
-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;
-    }
+    jstring jAttributeName = (jstring) env->GetObjectField(jAttribute, nameFID);
+    jobject jAttributeValue = env->GetObjectField(jAttribute, valueFID);
+    jobject jAttributeProperty = env->GetObjectField(jAttribute, propertyFID);
 
-    SimulatorResourceModelSP resModelPtr;
-    resModelPtr = JSimulatorResourceModel::getResourceModelPtr(env, thiz);
-    if (!resModelPtr)
-    {
-        throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "Resource model not found!");
-        return;
-    }
+    if (!jAttributeName || !jAttributeValue)
+        return false;
 
-    const char *nameCstr = env->GetStringUTFChars(jname, NULL);
-    if (!nameCstr)
-    {
-        throwSimulatorException(env, SIMULATOR_ERROR, "String error!");
-        return;
-    }
+    JniString attrName(env, jAttributeName);
+    SimulatorResourceModel::ValueVariant value = JniAttributeValue::toCpp(env, jAttributeValue);
 
-    const char *valueCstr = env->GetStringUTFChars(jvalue, NULL);
-    if (!valueCstr)
+    attribute.setName(attrName.get());
+    attribute.setValue(value);
+    if (jAttributeProperty)
     {
-        env->ReleaseStringUTFChars(jname, nameCstr);
-        throwSimulatorException(env, SIMULATOR_ERROR, "String error!");
-        return;
+        SimulatorResourceModel::AttributeProperty property = JniAttributeProperty::toCpp(env,
+                jAttributeProperty);
+        attribute.setProperty(property);
     }
 
-    std::string attrName(nameCstr);
-    std::string value(valueCstr);
-    resModelPtr->addAttribute(attrName, value);
-
-    // Release created c string
-    env->ReleaseStringUTFChars(jname, nameCstr);
-    env->ReleaseStringUTFChars(jvalue, valueCstr);
+    return true;
 }
 
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_SimulatorResourceModel_dispose
-(JNIEnv *env, jobject thiz)
+bool AttributeValueToCpp(JNIEnv *env, jobject jAttributeValue,
+                         SimulatorResourceModel::ValueVariant &value)
 {
-    JSimulatorResourceModel *resourceModel = GetHandle<JSimulatorResourceModel>(env, thiz);
-    delete resourceModel;
+    if (!jAttributeValue)
+        return false;
+
+    value = JniAttributeValue::toCpp(env, jAttributeValue);
+    return true;
 }
+
index 2e4d35d23c55069f2f41fe9a9d0de047dfe140b3..ca23b3b08bbc0fc73baac8ad54ff595bd8aece0c 100644 (file)
 #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);
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_SimulatorResourceModel_addAttributeString
-(JNIEnv *, jobject, jstring, jstring);
-
-JNIEXPORT void JNICALL
-Java_org_oic_simulator_SimulatorResourceModel_dispose
-(JNIEnv *, jobject);
-
-
-#ifdef __cplusplus
-}
-#endif
+jobject simulatorResourceModelToJava(JNIEnv *env, SimulatorResourceModel &resModel);
+jobject simulatorResourceAttributeToJava(JNIEnv *env, SimulatorResourceModel::Attribute &attribute);
+bool simulatorResourceModelToCpp(JNIEnv *env, jobject jResModel, SimulatorResourceModel &resModel);
+bool simulatorResourceAttributeToCpp(JNIEnv *env, jobject jAttribute,
+                                     SimulatorResourceModel::Attribute &attribute);
+bool AttributeValueToCpp(JNIEnv *env, jobject jAttributeValue,
+                         SimulatorResourceModel::ValueVariant &value);
 
 #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..8a23727
--- /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->getResourceInterfaces();
+    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..bfcb1d6
--- /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..638f816
--- /dev/null
@@ -0,0 +1,248 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_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;}
+
+SimulatorSingleResourceSP simulatorSingleResourceToCpp(JNIEnv *env, jobject object)
+{
+    JniSharedObjectHolder<SimulatorSingleResource> *jniResource =
+        GetHandle<JniSharedObjectHolder<SimulatorSingleResource>>(env, object);
+    if (jniResource)
+        return jniResource->get();
+    return nullptr;
+}
+
+static AutomationType AutomationTypeToCpp(JNIEnv *env, jobject jType)
+{
+    static jmethodID ordinalMID = env->GetMethodID(
+                                      gSimulatorClassRefs.automationTypeCls, "ordinal", "()I");
+
+    int ordinal = env->CallIntMethod(jType, ordinalMID);
+    return AutomationType(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_getAttribute
+(JNIEnv *env, jobject object, jstring attrName)
+{
+    VALIDATE_INPUT_RET(env, !attrName, "Attribute name is null!", nullptr)
+
+    SimulatorSingleResourceSP singleResource = simulatorSingleResourceToCpp(env, object);
+    VALIDATE_OBJECT_RET(env, singleResource, nullptr)
+
+    JniString jniAttrName(env, attrName);
+    SimulatorResourceModel::Attribute attribute;
+    if (singleResource->getAttribute(jniAttrName.get(), attribute))
+        return simulatorResourceAttributeToJava(env, attribute);
+    return nullptr;
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_server_SimulatorSingleResource_addAttribute
+(JNIEnv *env, jobject object, jobject resAttribute)
+{
+    VALIDATE_INPUT(env, !resAttribute, "Resource attribute is null!")
+
+    SimulatorSingleResourceSP singleResource = simulatorSingleResourceToCpp(env, object);
+    VALIDATE_OBJECT(env, singleResource)
+
+    try
+    {
+        SimulatorResourceModel::Attribute attribute;
+        if (!simulatorResourceAttributeToCpp(env, resAttribute, attribute))
+        {
+            throwSimulatorException(env, SIMULATOR_ERROR,
+                                    "Failed to covnert SimulatorResourceAttribute java object!");
+            return;
+        }
+
+        singleResource->addAttribute(attribute);
+    }
+    catch (SimulatorException &e)
+    {
+        throwSimulatorException(env, e.code(), e.what());
+    }
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_server_SimulatorSingleResource_updateAttribute
+(JNIEnv *env, jobject object, jstring attrName, jobject attrValue)
+{
+    VALIDATE_INPUT(env, !attrName, "Attribute name is null!")
+    VALIDATE_INPUT(env, !attrValue, "Attribute value is null!")
+
+    SimulatorSingleResourceSP singleResource = simulatorSingleResourceToCpp(env, object);
+    VALIDATE_OBJECT(env, singleResource)
+
+    SimulatorResourceModel::ValueVariant value;
+    if (!AttributeValueToCpp(env, attrValue, value))
+    {
+        throwSimulatorException(env, SIMULATOR_ERROR,
+                                "Failed to covnert AttributeValue java object!");
+        return;
+    }
+
+    SimulatorResourceModel::Attribute attribute(JniString(env, attrName).get());
+    attribute.setValue(value);
+    singleResource->updateAttributeValue(attribute);
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_server_SimulatorSingleResource_removeAttribute
+(JNIEnv *env, jobject object, jstring attrName)
+{
+    VALIDATE_INPUT(env, !attrName, "Attribute name is null!")
+
+    SimulatorSingleResourceSP singleResource = simulatorSingleResourceToCpp(env, object);
+    VALIDATE_OBJECT(env, singleResource)
+
+    try
+    {
+        JniString jniAttrName(env, attrName);
+        singleResource->removeAttribute(jniAttrName.get());
+    }
+    catch (InvalidArgsException &e)
+    {
+        throwInvalidArgsException(env, e.code(), e.what());
+    }
+}
+
+JNIEXPORT jint JNICALL
+Java_org_oic_simulator_server_SimulatorSingleResource_startResourceUpdation
+(JNIEnv *env, jobject object, jint type, jint interval, jobject listener)
+{
+    VALIDATE_CALLBACK_RET(env, listener, -1)
+
+    SimulatorSingleResourceSP singleResource = simulatorSingleResourceToCpp(env, object);
+    VALIDATE_OBJECT_RET(env, singleResource, -1)
+
+    jobject listenerRef = env->NewGlobalRef(listener);
+    updateCompleteCallback callback =  [listenerRef](const std::string & uri, const int id)
+    {
+        onAutoUpdationComplete(listenerRef, uri, id);
+    };
+
+    try
+    {
+        int id = singleResource->startResourceUpdation((1 == type) ? AutomationType::RECURRENT :
+                 AutomationType::NORMAL, interval, callback);
+        return id;
+    }
+    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_startAttributeUpdation
+(JNIEnv *env, jobject object, jstring attrName, jobject type, jint interval, jobject listener)
+{
+    VALIDATE_INPUT_RET(env, !attrName, "Attribute name is null!", -1)
+    VALIDATE_CALLBACK_RET(env, listener, -1)
+
+    SimulatorSingleResourceSP singleResource = simulatorSingleResourceToCpp(env, object);
+    VALIDATE_OBJECT_RET(env, singleResource, -1)
+
+    jobject listenerRef = env->NewGlobalRef(listener);
+    updateCompleteCallback callback =  [listenerRef](const std::string & uri, const int id)
+    {
+        onAutoUpdationComplete(listenerRef, uri, id);
+    };
+
+    JniString jniAttrName(env, attrName);
+    AutomationType automationType = AutomationTypeToCpp(env, type);
+
+    try
+    {
+        int id = singleResource->startAttributeUpdation(jniAttrName.get(), automationType,
+                 interval, callback);
+        return id;
+    }
+    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_stopUpdation
+(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_dispose
+(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..1f971ce
--- /dev/null
@@ -0,0 +1,293 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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);
+            }
+    }
+
+    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..f3ec682
--- /dev/null
@@ -0,0 +1,113 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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 interfaceTypeCls;
+    jclass simulatorResourceCls;
+    jclass simulatorResourceTypeCls;
+    jclass simulatorSingleResourceCls;
+    jclass simulatorCollectionResourceCls;
+    jclass simulatorResourceModelCls;
+    jclass simulatorResourceAttributeCls;
+    jclass automationTypeCls;
+    jclass attributeValueCls;
+    jclass attributeValueTypeCls;
+    jclass attributeTypeInfoCls;
+    jclass attributePropertyCls;
+    jclass attributePropertyTypeCls;
+    jclass simulatorRemoteResourceCls;
+    jclass observerCls;
+    jclass deviceInfoCls;
+    jclass platformInfoCls;
+    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/AttributeProperty.java b/service/simulator/java/sdk/src/org/oic/simulator/AttributeProperty.java
new file mode 100644 (file)
index 0000000..b555f0e
--- /dev/null
@@ -0,0 +1,169 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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 vaule property.
+ */
+public class AttributeProperty {
+
+    private Type             mType     = Type.UNKNOWN;
+    private double           mMin      = -1;
+    private double           mMax      = -1;
+    private AttributeValue[] mValueSet = null;
+    private AttributeProperty mChildProperty = null;
+
+    /**
+     * Enum to represent propety type.
+     */
+    public enum Type {
+        UNKNOWN, RANGE, VALUESET
+    }
+
+    /**
+     * Constructs {@AttributeProperty} of type
+     * {@AttributeProperty.Type.Range} with min
+     * and max values.
+     *
+     * @param min
+     *            Minimun value the attribute can have.
+     * @param max
+     *            Maximum value the attribute can have.
+     */
+    public AttributeProperty(double min, double max) {
+        mType = Type.RANGE;
+        mMin = min;
+        mMax = max;
+    }
+
+    /**
+     * Constructs {@AttributeProperty} of type
+     * {@AttributeProperty.Type.VALUESET} with
+     * array of integer.
+     *
+     * @param values
+     *            Array of int type values.
+     */
+    public AttributeProperty(int[] values) {
+        mType = Type.VALUESET;
+        mValueSet = new AttributeValue[values.length];
+        for (int i = 0; i < values.length; i++)
+            mValueSet[i] = new AttributeValue(values[i]);
+    }
+
+    /**
+     * Constructs {@AttributeProperty} of type
+     * {@AttributeProperty.Type.VALUESET} with
+     * array of double.
+     *
+     * @param values
+     *            Array of double type values.
+     */
+    public AttributeProperty(double[] values) {
+        mType = Type.VALUESET;
+        mValueSet = new AttributeValue[values.length];
+        for (int i = 0; i < values.length; i++)
+            mValueSet[i] = new AttributeValue(values[i]);
+    }
+
+    /**
+     * Constructs {@AttributeProperty} of type
+     * {@AttributeProperty.Type.VALUESET} with
+     * array of boolean.
+     *
+     * @param values
+     *            Array of boolean type values.
+     */
+    public AttributeProperty(boolean[] values) {
+        mType = Type.VALUESET;
+        mValueSet = new AttributeValue[values.length];
+        for (int i = 0; i < values.length; i++)
+            mValueSet[i] = new AttributeValue(values[i]);
+    }
+
+    /**
+     * Constructs {@AttributeProperty} of type
+     * {@AttributeProperty.Type.VALUESET} with
+     * array of Strings.
+     *
+     * @param values
+     *            Array of strings.
+     */
+    public AttributeProperty(String[] values) {
+        mType = Type.VALUESET;
+        mValueSet = new AttributeValue[values.length];
+        for (int i = 0; i < values.length; i++)
+            mValueSet[i] = new AttributeValue(values[i]);
+    }
+
+    /**
+     * API to get type of property.
+     *
+     * @return {@AttributeProperty.Type}.
+     */
+    public Type type() {
+        return mType;
+    }
+
+    /**
+     * API to get minimum value which was set as property.
+     */
+    public double min() {
+        return mMin;
+    }
+
+    /**
+     * API to get maximum value which was set as property.
+     */
+    public double max() {
+        return mMax;
+    }
+
+    /**
+     * API to get array of values which was set as property.
+     *
+     * @return array of {@AttributeValue}.
+     */
+    public AttributeValue[] valueSet() {
+        return mValueSet;
+    }
+
+    /**
+     * API to set child attribute propety.
+     *
+     * @param childProperty
+     *            Child element property this property used if the
+     *            Attribute value is of array type.
+     */
+    public void setChildProperty(AttributeProperty childProperty) {
+        mChildProperty = childProperty;
+    }
+
+    /**
+     * API to get child attribute propety.
+     *
+     * @return Child element property.
+     */
+    public AttributeProperty getChildProperty() {
+        return mChildProperty;
+    }
+
+    private AttributeProperty(AttributeValue[] values) {
+        mType = Type.VALUESET;
+        mValueSet = values;
+    }
+}
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..76bc72c
--- /dev/null
@@ -0,0 +1,512 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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 provides the value type information in detail.
+     */
+    public class TypeInfo {
+        public ValueType mType;
+        public ValueType mBaseType;
+        public int       mDepth;
+
+        /**
+         * Constructs {@AttributeValue.TypeInfo} with
+         * default values.
+         */
+        TypeInfo() {
+            mType = ValueType.UNKNOWN;
+            mBaseType = ValueType.UNKNOWN;
+            mDepth = 0;
+        }
+
+        /**
+         * Constructs {@AttributeValue.TypeInfo} with
+         * given {AttributeValue.ValueType}.
+         *
+         * @param type
+         *            Value type.
+         */
+        TypeInfo(ValueType type) {
+            mType = type;
+            mBaseType = type;
+            mDepth = 0;
+        }
+
+        /**
+         * Constructs {@AttributeValue.TypeInfo} with
+         * given {AttributeValue.ValueType}s and depth information.
+         *
+         * @param type
+         *            Value type.
+         * @param baseType
+         *            Value base type. This type is useful when vaule is of
+         *            array type.
+         * @param depth
+         *            Depth of array type value. This type is useful when vaule
+         *            is of array type.
+         */
+        TypeInfo(ValueType type, ValueType baseType, int depth) {
+            mType = type;
+            mBaseType = baseType;
+            mDepth = depth;
+        }
+    }
+
+    /**
+     * Constructs {@AttributeValue} with int type value.
+     *
+     * @param value
+     *            int type value.
+     */
+    public AttributeValue(int value) {
+        mValue = new Integer(value);
+    }
+
+    /**
+     * Constructs {@AttributeValue} with double type value.
+     *
+     * @param value
+     *            double type value.
+     */
+    public AttributeValue(double value) {
+        mValue = new Double(value);
+    }
+
+    /**
+     * Constructs {@AttributeValue} with boolean type value.
+     *
+     * @param value
+     *            boolean type value.
+     */
+    public AttributeValue(boolean value) {
+        mValue = new Boolean(value);
+    }
+
+    /**
+     * Constructs {@AttributeValue} with String type value.
+     *
+     * @param value
+     *            String type value.
+     */
+    public AttributeValue(String value) {
+        mValue = value;
+    }
+
+    /**
+     * Constructs {@AttributeValue} with SimulatorResourceModel
+     * type value.
+     *
+     * @param value
+     *            SimulatorResourceModel type value.
+     */
+    public AttributeValue(SimulatorResourceModel value) {
+        mValue = value;
+    }
+
+    /**
+     * Constructs {@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 {@AttributeValue} with array of Integer type
+     * values.
+     *
+     * @param values
+     *            Array of Integer type values.
+     */
+    public AttributeValue(Integer[] values) {
+        mValue = values;
+    }
+
+    /**
+     * Constructs {@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 {@AttributeValue} with array of Double type
+     * values.
+     *
+     * @param values
+     *            Array of Double type values.
+     */
+    public AttributeValue(Double[] values) {
+        mValue = values;
+    }
+
+    /**
+     * Constructs {@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 {@AttributeValue} with array of Boolean type
+     * values.
+     *
+     * @param values
+     *            Array of Boolean type values.
+     */
+    public AttributeValue(Boolean[] values) {
+        mValue = values;
+    }
+
+    /**
+     * Constructs {@AttributeValue} with array of String type
+     * values.
+     *
+     * @param values
+     *            Array of String type values.
+     */
+    public AttributeValue(String[] values) {
+        mValue = values;
+    }
+
+    /**
+     * Constructs {@AttributeValue} with array of
+     * SimulatorResourceModel type values.
+     *
+     * @param values
+     *            Array of SimulatorResourceModel type values.
+     */
+    public AttributeValue(SimulatorResourceModel[] values) {
+        mValue = values;
+    }
+
+    /**
+     * Constructs {@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 {@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 {@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 {@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 {@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 {@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 {@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 {@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 {@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 {@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 {@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 {@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 {@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 {@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 {@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 {@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 {@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/AttributeValueValidation.java b/service/simulator/java/sdk/src/org/oic/simulator/AttributeValueValidation.java
new file mode 100644 (file)
index 0000000..935588f
--- /dev/null
@@ -0,0 +1,323 @@
+package org.oic.simulator;
+
+public class AttributeValueValidation implements AttributeValueVisitor.VisitingMethods<Boolean> {
+    private AttributeProperty mProperty = null;
+
+    public AttributeValueValidation(AttributeProperty property) {
+        mProperty = property;
+    }
+
+    public boolean validate(AttributeValue value) {
+        AttributeValueVisitor visitor = new AttributeValueVisitor(value, this);
+        Boolean result = (Boolean) visitor.visit();
+        return result.booleanValue();
+    }
+
+    @Override
+    public Boolean visitingValue(Integer value) {
+        if (mProperty == null)
+            return false;
+
+        if (checkRange(value.doubleValue()) || checkValueSet(value))
+            return true;
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Double value) {
+        if (mProperty == null)
+            return false;
+
+        if (checkRange(value.doubleValue()) || checkValueSet(value))
+            return true;
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Boolean value) {
+        if (mProperty == null)
+            return false;
+
+        if (checkValueSet(value))
+            return true;
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(String value) {
+        if (mProperty == null)
+            return false;
+
+        if (checkRange(value.length()) || checkValueSet(value))
+            return true;
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(SimulatorResourceModel value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Integer[] values) {
+        if (mProperty == null)
+            return false;
+
+        if (!checkRange(values.length))
+            return false;
+
+        if (mProperty.getChildProperty() != null) {
+            AttributeValueValidation rangeValidation = new AttributeValueValidation(mProperty.getChildProperty());
+            for (Integer value : values) {
+                if (rangeValidation.visitingValue(value) == false)
+                    return false;
+            }
+        }
+
+        return true;
+    }
+
+    @Override
+    public Boolean visitingValue(Double[] values) {
+        if (mProperty == null)
+            return false;
+
+        if (!checkRange(values.length))
+            return false;
+
+        if (mProperty.getChildProperty() != null) {
+            AttributeValueValidation rangeValidation = new AttributeValueValidation(mProperty.getChildProperty());
+            for (Double value : values) {
+                if (rangeValidation.visitingValue(value) == false)
+                    return false;
+            }
+        }
+
+        return true;
+    }
+
+    @Override
+    public Boolean visitingValue(Boolean[] values) {
+        if (mProperty == null)
+            return false;
+
+        if (!checkRange(values.length))
+            return false;
+
+        if (mProperty.getChildProperty() != null) {
+            AttributeValueValidation rangeValidation = new AttributeValueValidation(mProperty.getChildProperty());
+            for (Boolean value : values) {
+                if (rangeValidation.visitingValue(value) == false)
+                    return false;
+            }
+        }
+
+        return true;
+    }
+
+    @Override
+    public Boolean visitingValue(String[] values) {
+        if (mProperty == null)
+            return false;
+
+        if (!checkRange(values.length))
+            return false;
+
+        if (mProperty.getChildProperty() != null) {
+            AttributeValueValidation rangeValidation = new AttributeValueValidation(mProperty.getChildProperty());
+            for (String value : values) {
+                if (rangeValidation.visitingValue(value) == false)
+                    return false;
+            }
+        }
+
+        return true;
+    }
+
+    @Override
+    public Boolean visitingValue(SimulatorResourceModel[] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Integer[][] values) {
+        if (mProperty == null)
+            return false;
+
+        if (!checkRange(values.length))
+            return false;
+
+        if (mProperty.getChildProperty() != null) {
+            AttributeValueValidation rangeValidation = new AttributeValueValidation(mProperty.getChildProperty());
+            for (Integer[] value : values) {
+                if (rangeValidation.visitingValue(value) == false)
+                    return false;
+            }
+        }
+
+        return true;
+    }
+
+    @Override
+    public Boolean visitingValue(Double[][] values) {
+        if (mProperty == null)
+            return false;
+
+        if (!checkRange(values.length))
+            return false;
+
+        if (mProperty.getChildProperty() != null) {
+            AttributeValueValidation rangeValidation = new AttributeValueValidation(mProperty.getChildProperty());
+            for (Double[] value : values) {
+                if (rangeValidation.visitingValue(value) == false)
+                    return false;
+            }
+        }
+
+        return true;
+    }
+
+    @Override
+    public Boolean visitingValue(Boolean[][] values) {
+        if (mProperty == null)
+            return false;
+
+        if (!checkRange(values.length))
+            return false;
+
+        if (mProperty.getChildProperty() != null) {
+            AttributeValueValidation rangeValidation = new AttributeValueValidation(mProperty.getChildProperty());
+            for (Boolean[] value : values) {
+                if (rangeValidation.visitingValue(value) == false)
+                    return false;
+            }
+        }
+
+        return true;
+    }
+
+    @Override
+    public Boolean visitingValue(String[][] values) {
+        if (mProperty == null)
+            return false;
+
+        if (!checkRange(values.length))
+            return false;
+
+        if (mProperty.getChildProperty() != null) {
+            AttributeValueValidation rangeValidation = new AttributeValueValidation(mProperty.getChildProperty());
+            for (String[] value : values) {
+                if (rangeValidation.visitingValue(value) == false)
+                    return false;
+            }
+        }
+
+        return true;
+    }
+
+    @Override
+    public Boolean visitingValue(SimulatorResourceModel[][] value) {
+        return false;
+    }
+
+    @Override
+    public Boolean visitingValue(Integer[][][] values) {
+        if (mProperty == null)
+            return false;
+
+        if (!checkRange(values.length))
+            return false;
+
+        if (mProperty.getChildProperty() != null) {
+            AttributeValueValidation rangeValidation = new AttributeValueValidation(mProperty.getChildProperty());
+            for (Integer[][] value : values) {
+                if (rangeValidation.visitingValue(value) == false)
+                    return false;
+            }
+        }
+
+        return true;
+    }
+
+    @Override
+    public Boolean visitingValue(Double[][][] values) {
+        if (mProperty == null)
+            return false;
+
+        if (!checkRange(values.length))
+            return false;
+
+        if (mProperty.getChildProperty() != null) {
+            AttributeValueValidation rangeValidation = new AttributeValueValidation(mProperty.getChildProperty());
+            for (Double[][] value : values) {
+                if (rangeValidation.visitingValue(value) == false)
+                    return false;
+            }
+        }
+
+        return true;
+    }
+
+    @Override
+    public Boolean visitingValue(Boolean[][][] values) {
+        if (mProperty == null)
+            return false;
+
+        if (!checkRange(values.length))
+            return false;
+
+        if (mProperty.getChildProperty() != null) {
+            AttributeValueValidation rangeValidation = new AttributeValueValidation(mProperty.getChildProperty());
+            for (Boolean[][] value : values) {
+                if (rangeValidation.visitingValue(value) == false)
+                    return false;
+            }
+        }
+
+        return true;
+    }
+
+    @Override
+    public Boolean visitingValue(String[][][] values) {
+        if (mProperty == null)
+            return false;
+
+        if (!checkRange(values.length))
+            return false;
+
+        if (mProperty.getChildProperty() != null) {
+            AttributeValueValidation rangeValidation = new AttributeValueValidation(mProperty.getChildProperty());
+            for (String[][] value : values) {
+                if (rangeValidation.visitingValue(value) == false)
+                    return false;
+            }
+        }
+
+        return true;
+    }
+
+    @Override
+    public Boolean visitingValue(SimulatorResourceModel[][][] value) {
+        return false;
+    }
+
+    private boolean checkRange(double value) {
+        if (AttributeProperty.Type.RANGE == mProperty.type()
+                && (value >= mProperty.min() && value <= mProperty.max())) {
+            return true;
+        }
+
+        return false;
+    }
+
+    private <T> boolean checkValueSet(T value) {
+        if (AttributeProperty.Type.VALUESET == mProperty.type() && null != mProperty.valueSet()) {
+            for (AttributeValue allowedValue : mProperty.valueSet()) {
+                if (allowedValue.get().equals(value))
+                    return true;
+            }
+        }
+
+        return false;
+    }
+}
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..28fc0fb
--- /dev/null
@@ -0,0 +1,118 @@
+package org.oic.simulator;
+
+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[] 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[][] 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[][][] value);
+
+        public T visitingValue(Double[][][] value);
+
+        public T visitingValue(Boolean[][][] value);
+
+        public T visitingValue(String[][][] value);
+
+        public T visitingValue(SimulatorResourceModel[][][] value);
+    }
+
+    public AttributeValueVisitor(AttributeValue value, VisitingMethods listener) {
+        mValue = value;
+        mListener = listener;
+    }
+
+    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;
+    }
+}
index 49e8e39139bb5421cf6e4fa90bf0bbd04201fb4b..66a45ceed9aef799eefbfd423b8cda130a11ac45 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..f6254b0
--- /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 org.oic.simulator;
+
+/**
+ * Listener for getting device information.
+ */
+public interface DeviceListener {
+    /**
+     * Method which provides remote device information.
+     *
+     * @param devInfo
+     *            {@link DeviceInfo} object holding the device information.
+     */
+    public void onDeviceFound(DeviceInfo devInfo);
+}
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 082e59ec5b8c72bb7eae01ab221433f4b3b9aad8..eedc9355dc4f57a26e7ecb4f7686da716bfc4977 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);
-}
index d62fbdd974cee8efd0004fe87f2f242da2b5a517..256e3eb281c0b795b649d6787856685e174c3f20 100644 (file)
@@ -21,7 +21,16 @@ package org.oic.simulator;
  */
 @SuppressWarnings("serial")
 public class InvalidArgsException extends SimulatorException {
-    public InvalidArgsException(int errorCode, String errMessage) {
-        super(errorCode, errMessage);
+
+    public InvalidArgsException(int code, String message) {
+        super(code, message);
+    }
+
+    public InvalidArgsException(SimulatorResult code, String message) {
+        super(code, message);
+    }
+
+    public InvalidArgsException(String message) {
+        super(SimulatorResult.SIMULATOR_INVALID_PARAM, message);
     }
 }
index 914641fad43675f802aee661c81eef9772abb3da..7e6348aa2803d3896a662a90ddc54e77e4655f2e 100644 (file)
@@ -21,7 +21,12 @@ package org.oic.simulator;
  */
 @SuppressWarnings("serial")
 public class NoSupportException extends SimulatorException {
-    public NoSupportException(int errorCode, String errMessage) {
-        super(errorCode, errMessage);
+
+    public NoSupportException(String message) {
+        super(SimulatorResult.SIMULATOR_NOT_SUPPORTED, message);
+    }
+
+    public NoSupportException(SimulatorResult code, String message) {
+        super(code, message);
     }
 }
\ No newline at end of file
index c9127b574ece5f8f7311084ec77861102497894a..e0c259c66ae0615f5ad9f55aa8a20d2b3b808d93 100644 (file)
@@ -22,7 +22,12 @@ package org.oic.simulator;
  */
 @SuppressWarnings("serial")
 public class OperationInProgressException extends SimulatorException {
-    public OperationInProgressException(int errorCode, String errMessage) {
-        super(errorCode, errMessage);
+
+    public OperationInProgressException(String message) {
+        super(SimulatorResult.SIMULATOR_OPERATION_IN_PROGRESS, message);
+    }
+
+    public OperationInProgressException(SimulatorResult code, String message) {
+        super(code, message);
     }
 }
index 7956e925b9c563f8416af6b6c09b14c3c8964e81..8ff3a604bb996961413bfb0f73efbc9a51b3127b 100644 (file)
@@ -22,16 +22,16 @@ package org.oic.simulator;
  */
 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..531729d
--- /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 org.oic.simulator;
+
+/**
+ * Listener for getting platform information.
+ */
+public interface PlatformListener {
+    /**
+     * 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/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 7b4c5c852b2a5cab804f8dc17077158d7560b6de..95e22fab2870418ef63a9286034f01a29e76f2ce 100644 (file)
@@ -23,19 +23,24 @@ 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;
+    public SimulatorException(int code, String message) {
+        this.code = SimulatorResult.get(code);
+        this.message = message;
+    }
+
+    public SimulatorException(SimulatorResult code, String message) {
+        this.code = code;
+        this.message = new String(message);
     }
 
     public SimulatorResult code() {
-        return errorCode;
+        return code;
     }
 
     public String message() {
-        return errorMessage;
+        return message;
     }
 }
\ No newline at end of file
index a16ce671ab7596a19764215c3e2fb8bae57002e7..4f4fb5e831de85790b9d99ed505cef93771e0b14 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,15 +27,14 @@ import org.oic.simulator.serviceprovider.SimulatorResourceServer;
  */
 public class SimulatorManager {
 
+    private 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,
      *         otherwise null.
@@ -44,30 +44,16 @@ public class SimulatorManager {
      * @throws SimulatorException
      *             Thrown for other errors.
      */
-    public static SimulatorResourceServer createResource(String configPath,
-            IResourceModelChangedListener listener)
-            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;
-    }
+    public static native SimulatorResource createResource(String configPath)
+            throws InvalidArgsException, SimulatorException;
 
     /**
-     * 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.
@@ -77,51 +63,34 @@ public class SimulatorManager {
      * @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 createResources(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 configPath
+     *            Path to RAML configuration file.
+     *
+     * @return {@link SimulatorResourceServer} - 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 = null;
+        if (type == SimulatorResource.Type.SINGLE)
+            resource = createSingleResource(name, uri, resourceType);
+        else
+            resource = createCollectionResource(name, uri, resourceType);
+        return resource;
     }
 
     /**
@@ -136,9 +105,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);
+        searchResource(null, listener);
     }
 
     /**
@@ -156,24 +125,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);
+        searchResource(resourceType, listener);
     }
 
     /**
@@ -182,20 +142,17 @@ public class SimulatorManager {
      * @param deviceInfo
      *            Device information.
      */
-    public static void setDeviceInfo(String deviceInfo) {
-        SimulatorManagerNativeInterface.setDeviceInfo(deviceInfo);
-    }
+    public static native void setDeviceInfo(String deviceInfo)
+            throws InvalidArgsException, SimulatorException;
 
     /**
-     * API to get the device information asynchronously via callback
-     * using {@link IDeviceInfo}.
+     * API to search for devices in the network.
      *
      * @param listener
-     *            Interface for receiving the device information.
+     *            Listener for receiving the device information.
      */
-    public static void getDeviceInfo(IDeviceInfo listener) {
-        SimulatorManagerNativeInterface.getDeviceInfo(listener);
-    }
+    public static native void findDevices(DeviceListener listener)
+            throws InvalidArgsException, SimulatorException;
 
     /**
      * API to set the platform information.
@@ -203,18 +160,36 @@ public class SimulatorManager {
      * @param platformInfo
      *            {@link PlatformInfo} - Platform information.
      */
-    public static void setPlatformInfo(PlatformInfo platformInfo) {
-        SimulatorManagerNativeInterface.setPlatformInfo(platformInfo);
-    }
+    public static native void setPlatformInfo(PlatformInfo platformInfo)
+            throws InvalidArgsException, SimulatorException;
 
     /**
-     * API to get the platform information asynchronously via callback
-     * using {@link IPlatformInfo}..
+     * API to find all devices' platform information in the network.
      *
      * @param listener
-     *            Interface for receiving the platform information.
+     *            Listener for receiving the platform information.
      */
-    public static void getPlatformInfo(IPlatformInfo listener) {
-        SimulatorManagerNativeInterface.getPlatformInfo(listener);
-    }
+    public static native void getPlatformInformation(PlatformListener listener)
+            throws InvalidArgsException, SimulatorException;
+
+    /**
+     * API to set the listener for receiving log messages.
+     *
+     * @param logger
+     *            {@link ILogger} to receive the log messages.
+     */
+    public static native void setLogger(ILogger logger)
+            throws SimulatorException;
+
+    private static native Vector<SimulatorResource> createResources(
+            String configPath, int count);
+
+    private static native SimulatorResource createSingleResource(String name,
+            String uri, String resourceType);
+
+    private static native SimulatorResource createCollectionResource(
+            String name, String uri, String resourceType);
+
+    private static native void searchResource(String resourceType,
+            FindResourceListener listener);
 }
\ 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..e2db0f4
--- /dev/null
@@ -0,0 +1,99 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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 {@SimulatorResourceAttribute}
+     * with 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 = new String(name);
+        mValue = value;
+        mProperty = property;
+    }
+
+    /**
+     * Constructs {@SimulatorResourceAttribute}
+     * with attribute name, value.
+     *
+     * @param name
+     *            Name of the attribute.
+     * @param value
+     *            Value of the attribute.
+     */
+    public SimulatorResourceAttribute(String name, AttributeValue value) {
+        mName = new String(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 {@AttributeValue}.
+     */
+    public AttributeValue value() {
+        return mValue;
+    }
+
+    /**
+     * API to get propety of attribute's value.
+     *
+     * @return Attribute's value property        {@AttributeProperty
+     * }.
+     */
+    public AttributeProperty property() {
+        return mProperty;
+    }
+
+    /**
+     * API to set the value of attribute.
+     * 
+     * @param value
+     *            Value of the attribute.
+     */
+    public void setValue(AttributeValue value) {
+        this.mValue = value;
+    }
+}
index 63961e933aacf38e5dc19814de1dfc3ed9836441..04c2de5c8d11e517363d469d02624b9b69edcbcb 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.
  */
 public class SimulatorResourceModel {
 
+    private Map<String, AttributeValue>    mValues     = null;
+    private Map<String, AttributeProperty> mProperties = 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 {@SimulatorResourceModel} object.
      */
     public SimulatorResourceModel() {
-        create();
+        mValues = new HashMap<>();
+        mProperties = new HashMap<>();
     }
 
     /**
-     * API to add an attribute of type integer.
+     * API to add an attribute to resource model.
      *
-     * @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 addAttribute(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 add an attribute to resource model.
      *
-     * @param name
-     *            Name of the attribute
-     * @param value
-     *            Value of the attribute
+     * @param attribute
+     *            {@link SimulatorResourceAttribute} to be add to resource
+     *            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.
+     *             This exception will be thrown on invalid input.
      */
-    public native void addAttributeDouble(String name, double value)
-            throws InvalidArgsException, SimulatorException;
+    public void addAttribute(SimulatorResourceAttribute attribute)
+            throws InvalidArgsException {
+        if (null == attribute || null == attribute.name()
+                || attribute.name().isEmpty() || null == attribute.value())
+            throw new InvalidArgsException("Invalid attribute!");
+
+        mValues.put(attribute.name(), attribute.value());
+    }
 
     /**
-     * API to add an attribute of type boolean.
+     * API to set attribute's property.
      *
-     * @param name
-     *            Name of the attribute
-     * @param value
-     *            Value of the attribute
+     * @param attrName
+     *            Name of the attribute.
+     * @param property
+     *            {@link AttributeProperty} to be set for 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 addAttributeBoolean(String name, boolean value)
-            throws InvalidArgsException, SimulatorException;
+    public void setAttributeProperty(String attrName, AttributeProperty property)
+            throws InvalidArgsException {
+        if (null == attrName || attrName.isEmpty())
+            throw new InvalidArgsException("Invalid attribute!");
+
+        if (null == property)
+            throw new InvalidArgsException("Invalid attribute property!");
+
+        mProperties.put(attrName, property);
+    }
 
     /**
-     * API to add an attribute of type string.
+     * API to set attribute's value.
      *
-     * @param name
-     *            Name of the attribute
+     * @param attrName
+     *            Name of the attribute.
      * @param value
-     *            Value of the attribute
+     *            {@link AttributeValue} to be set for 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 addAttributeString(String name, String value)
-            throws InvalidArgsException, SimulatorException;
+    public void setAttributeValue(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 get number of attributes for this model.
-     *
-     * @return Number of attributes.
+     * API to get all the attributes of resource model.
      *
-     * @throws SimulatorException
-     *             This exception will be thrown either if the resource model is
-     *             not found or for some general errors.
+     * @return Map of attributes with attribute name as key and its
+     *         corresponding {@link SimulatorResourceAttribute} as value.
      */
-    public native int size() throws SimulatorException;
+    public Map<String, SimulatorResourceAttribute> getAttributes() {
+        if (mValues.size() == 0)
+            return null;
+
+        Map<String, SimulatorResourceAttribute> attributes = new HashMap<>();
+        for (Map.Entry<String, AttributeValue> entry : mValues.entrySet()) {
+            SimulatorResourceAttribute attribute = new SimulatorResourceAttribute(
+                    entry.getKey(), entry.getValue(), mProperties.get(entry
+                            .getKey()));
+            attributes.put(entry.getKey(), attribute);
+        }
+
+        return attributes;
+    }
 
     /**
-     * API for getting all attributes.
+     * API to get attribute by name.
      *
-     * @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 {@link SimulatorResourceAttribute}.
      */
-    public native Map<String, ResourceAttribute> getAttributes()
-            throws SimulatorException;
+    public SimulatorResourceAttribute getAttribute(String attrName) {
+        if (mValues.containsKey(attrName)) {
+            SimulatorResourceAttribute attribute = new SimulatorResourceAttribute(
+                    attrName, mValues.get(attrName), mProperties.get(attrName));
+            return attribute;
+        }
+
+        return null;
+    }
 
     /**
-     * API to get attribute by its name.
+     * API to check whether resource model has attribute.
      *
-     * @param name
-     *            Name of the attribute
+     * @param attrName
+     *            Name of the attribute.
      *
-     * @return An object of {@link ResourceAttribute}.
+     * @return true if resource model has an attribute with given name,
+     *         otherwise false.
+     */
+    public boolean containsAttribute(String attrName) {
+        if (mValues.containsKey(attrName))
+            return true;
+        return false;
+    }
+
+    /**
+     * API to get value type information of attribute.
      *
-     * @throws InvalidArgsException
-     *             This exception will be thrown if the attribute does not
-     *             exist.
+     * @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         {@AttributeValue.TypeInfo
+     * }.
      */
-    public native ResourceAttribute getAttribute(String name)
-            throws InvalidArgsException, SimulatorException;
-
-    private SimulatorResourceModel(long nativeHandle) {
-        this.nativeHandle = nativeHandle;
+    public AttributeValue.TypeInfo getAttributeType(String attrName) {
+        if (mValues.containsKey(attrName))
+            return mValues.get(attrName).typeInfo();
+        return null;
     }
 
-    @Override
-    protected void finalize() throws Throwable {
-        try {
-            dispose();
-        } finally {
-            super.finalize();
+    /**
+     * API to remove attribute from resource model.
+     *
+     * @param attrName
+     *            Name of the attribute.
+     *
+     * @return true if resource model has attribute it is removed, otherwise
+     *         false.
+     */
+    public boolean removeAttribute(String attrName) {
+        if (mValues.containsKey(attrName)) {
+            mValues.remove(attrName);
+            if (mProperties.containsKey(attrName))
+                mProperties.remove(attrName);
+            return true;
         }
-    }
 
-    private native void create();
+        return false;
+    }
 
-    private native void dispose();
+    /**
+     * API to get number of attributes present in resource model.
+     *
+     * @return Number of attributes present in resource model.
+     */
+    public int size() {
+        return mValues.size();
+    }
 
-    private long nativeHandle;
-}
\ No newline at end of file
+    // Methods used in native code
+    private SimulatorResourceModel(Map<String, AttributeValue> values,
+            Map<String, AttributeProperty> properties) {
+        mValues = values;
+        mProperties = properties;
+    }
+}
index 8e4b9eb4b9c9b1b035f5f60c9677e27e0118a6e1..f40eaca88c50f36d3e3fd86005e713978cfe9305 100644 (file)
@@ -21,53 +21,15 @@ 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 specific error codes - END */
 
     SIMULATOR_ERROR;
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..be935ae
--- /dev/null
@@ -0,0 +1,33 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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 org.oic.simulator.client.SimulatorRemoteResource;
+
+/**
+ * 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..9812d3d
--- /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;
+
+/**
+ * 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..3e8f8a1
--- /dev/null
@@ -0,0 +1,519 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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;
+
+    private native void dispose();
+
+    private SimulatorRemoteResource(long nativeHandle) {
+        mNativeHandle = nativeHandle;
+    }
+
+    @Override
+    protected void finalize() throws Throwable {
+        try {
+            dispose();
+        } catch (Throwable t) {
+            throw t;
+        } finally {
+            super.finalize();
+        }
+    }
+
+    public enum VerificationType {
+        GET, PUT, POST, DELETE;
+    }
+
+    /**
+     * API to get the URI for this resource.
+     *
+     * @return Resource URI
+     */
+    public String getURI() {
+        return mUri;
+    }
+
+    /**
+     * 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 Array of resource types.
+     */
+    public Vector<String> getResourceTypes() {
+        return mResTypes;
+    }
+
+    /**
+     * API to get the list of resource interfaces.
+     *
+     * @return Array of resource interfaces.
+     */
+    public Vector<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 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 IGetListener}.
+     *
+     * @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 IGetListener}.
+     *
+     * @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 IPutListener}.
+     *
+     * @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 IPutListener}.
+     *
+     * @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 IPostListener}.
+     *
+     * @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 IPostListener}.
+     *
+     * @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 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 native void startObserve(Map<String, String> queryParams,
+            ObserveNotificationListener 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 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 native SimulatorResourceModel 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 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(VerificationType type,
+            VerificationListener onVerifyListener) throws InvalidArgsException,
+            NoSupportException, OperationInProgressException,
+            SimulatorException {
+        return startVerification(type.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 SimulatorException
+     *             Thrown for other errors.
+     */
+    public native void stopVerification(int id) throws InvalidArgsException,
+            SimulatorException;
+
+    /**
+     * 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 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 int startVerification(int type,
+            VerificationListener onVerifyListener);
+}
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..42c7b79
--- /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 org.oic.simulator.server;
+
+import java.util.Vector;
+
+import org.oic.simulator.InvalidArgsException;
+import org.oic.simulator.SimulatorException;
+
+public final class SimulatorCollectionResource extends SimulatorResource {
+
+    private SimulatorCollectionResource(long nativeHandle) {
+        mNativeHandle = nativeHandle;
+    }
+
+    /**
+     * 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 native void addChildResource(SimulatorResource resource)
+            throws InvalidArgsException, SimulatorException;
+
+    /**
+     * 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 native void removeChildResource(SimulatorResource resource)
+            throws InvalidArgsException, SimulatorException;
+
+    /**
+     * 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 native void removeChildResourceByUri(String uri)
+            throws InvalidArgsException, SimulatorException;
+
+    /**
+     * 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 native Vector<SimulatorResource> getChildResource()
+            throws SimulatorException;
+}
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..5120fd8
--- /dev/null
@@ -0,0 +1,362 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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;
+import org.oic.simulator.SimulatorResourceModel;
+
+public class SimulatorResource {
+
+    private native void dispose();
+
+    protected long mNativeHandle;
+
+    protected SimulatorResource() {
+    }
+
+    @Override
+    protected void finalize() throws Throwable {
+        try {
+            dispose();
+        } catch (Throwable t) {
+            throw t;
+        } finally {
+            super.finalize();
+        }
+    }
+
+    public enum Type {
+        SINGLE, COLLECTION
+    }
+
+    public enum AutoUpdateType {
+        ONE_TIME, REPEAT
+    }
+
+    /**
+     * 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 native String getName() throws SimulatorException;
+
+    /**
+     * API to get the type which indicates whether resource is single or
+     * collection resource.
+     *
+     * @return Type of resource.
+     *
+     * @throws SimulatorException
+     *             This exception will be thrown if the native resource object
+     *             does not exist or for some general errors.
+     */
+    public native Type getType() throws SimulatorException;
+
+    /**
+     * 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 native String getURI() throws SimulatorException;
+
+    /**
+     * 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 native String getResourceType() throws SimulatorException;
+
+    /**
+     * API to get the interfaces resource is bound with.
+     *
+     * @return Interface type.
+     *
+     * @throws SimulatorException
+     *             This exception will be thrown if the native resource object
+     *             does not exist or for some general errors.
+     */
+    public native Vector<String> getInterface() throws SimulatorException;
+
+    /**
+     * 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 native boolean isObservable() throws SimulatorException;
+
+    /**
+     * 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 native boolean isStarted() throws SimulatorException;
+
+    /**
+     * 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 getResourceModel()
+            throws SimulatorException;
+
+    /**
+     * 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 native void setName(String name) throws InvalidArgsException,
+            SimulatorException;
+
+    /**
+     * 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
+     *             This exception will be thrown if the native resource object
+     *             does not exist or for some general errors.
+     */
+    public native void setURI(String uri) throws InvalidArgsException,
+            SimulatorException;
+
+    /**
+     * 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 native void setResourceType(String resourceType)
+            throws InvalidArgsException, SimulatorException;
+
+    /**
+     * 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 SimulatorException
+     *             This exception will be thrown if the native resource object
+     *             does not exist or for some general errors.
+     */
+    public native void addInterface(String interfaceType)
+            throws InvalidArgsException, SimulatorException;
+
+    /**
+     * API to make the resource observable or not.
+     *
+     * @param state
+     *            - true make 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 native void setObservable(boolean state) throws SimulatorException;
+
+    /**
+     * 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 native void setObserverListener(ObserverListener listener)
+            throws InvalidArgsException, SimulatorException;
+
+    /**
+     * 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 native void setResourceModelChangeListener(
+            ResourceModelChangeListener listener) throws InvalidArgsException,
+            SimulatorException;
+
+    /**
+     * API to start the resource.
+     *
+     * @throws SimulatorException
+     *             This exception will be thrown if the native resource object
+     *             does not exist or for some general errors.
+     */
+    public native void start() throws SimulatorException;
+
+    /**
+     * API to stop the resource.
+     *
+     * @throws SimulatorException
+     *             This exception will be thrown if the native resource object
+     *             does not exist or for some general errors.
+     */
+    public native void stop() throws SimulatorException;
+
+    /**
+     * 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 native Vector<Observer> getObservers() throws SimulatorException;
+
+    /**
+     * API to notify current resource model to 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 native void notifyObserver(int observerId) throws SimulatorException;
+
+    /**
+     * API to notify all registered observers.
+     *
+     * @throws SimulatorException
+     *             This exception will be thrown if the native resource object
+     *             does not exist or for some general errors.
+     */
+    public native void notifyAllObservers() throws SimulatorException;
+
+    /**
+     * Listener for receiving notification when observer is registered or
+     * unregistered with the resource.
+     */
+    public interface ObserverListener {
+        /**
+         * Method will be invoked when a observer is registered with resource.
+         *
+         * @param uri
+         *            URI of the resource.
+         * @param observer
+         *            {@link ObserverInfo} object containing the details of
+         *            observer.
+         */
+        public void onObserverAdded(String resourceURI, Observer observer);
+
+        /**
+         * Method will be invoked when a observer is Unregistered with resource.
+         *
+         * @param resourceURI
+         *            URI of the resource.
+         * @param observer
+         *            {@link ObserverInfo} 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);
+    }
+}
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..7a1d8ab
--- /dev/null
@@ -0,0 +1,156 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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 org.oic.simulator.AttributeValue;
+import org.oic.simulator.InvalidArgsException;
+import org.oic.simulator.SimulatorException;
+import org.oic.simulator.SimulatorResourceAttribute;
+import org.oic.simulator.SimulatorResourceModel;
+
+public final class SimulatorSingleResource extends SimulatorResource {
+
+    private SimulatorSingleResource(long nativeHandle) {
+        mNativeHandle = nativeHandle;
+    }
+
+    /**
+     * API to get attribute of resource.
+     *
+     * @param attrName
+     *            Name of the attribute
+     *
+     * @return An object of {@link SimulatorResourceAttribute}, or null if
+     *         resource doest 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 native SimulatorResourceAttribute getAttribute(String attrName)
+            throws InvalidArgsException, SimulatorException;
+
+    /**
+     * API to add an attribute to resource's representation model.
+     *
+     * @param attrName
+     *            Name of the attribute.
+     * @param attribute
+     *            Attribute to be added to resource's representation model.
+     *
+     * @throws InvalidArgsException
+     *             This exception will be thrown on invalid input.
+     * @throws SimulatorException
+     *             This exception will be thrown for other errors.
+     */
+    public native void addAttribute(SimulatorResourceAttribute attribute)
+            throws InvalidArgsException, SimulatorException;
+
+    /**
+     * API to update the value of an attribute.
+     *
+     * @param attrName
+     *            Name of the attribute.
+     * @param value
+     *            New value of the attribute.
+     *
+     * @throws InvalidArgsException
+     *             This exception will be thrown on invalid input.
+     * @throws SimulatorException
+     *             This exception will be thrown for other errors.
+     */
+    public native void updateAttribute(String attrName, AttributeValue value)
+            throws InvalidArgsException, SimulatorException;
+
+    /**
+     * API to remove an attribute from the simulated resource.
+     *
+     * @param attrName
+     *            Name of the attribute to be deleted.
+     *
+     * @throws InvalidArgsException
+     *             This exception will be thrown on invalid input.
+     * @throws SimulatorException
+     *             This exception will be thrown for other errors.
+     */
+    public native void removeAttribute(String attrName)
+            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 type
+     *            {@link AutomationType} indicating whether the automation is
+     *            one-time or recursive.
+     * @param interval
+     *            Interval time in milliseconds.
+     * @param listener
+     *            Listener to be notified when value updation 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 native int startResourceUpdation(AutoUpdateType type, int interval,
+            AutoUpdateListener listener) throws InvalidArgsException,
+            SimulatorException;
+
+    /**
+     * 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 AutomationType} 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 native int startAttributeUpdation(String attrName,
+            AutoUpdateType type, int interval, AutoUpdateListener listener)
+            throws InvalidArgsException, SimulatorException;
+
+    /**
+     * 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 native void stopUpdation(int id) throws SimulatorException;
+}
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 38fe3089146446ac86bbc052b90944045ea6924d..efaa23c38b40206eafa635fd8ad73a97417ffbb3 100755 (executable)
@@ -47,4 +47,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 2bd5ab2a6766234c4ed5b195c712eaf68ad454ae..80345b7305a9715f366bf7e2e0740cc99004fd48 100755 (executable)
@@ -29,7 +29,7 @@
 \r
 #include "yaml-cpp/yaml.h"\r
 #include "cJSON.h"\r
-#include "Utils.h"\r
+#include "RamlUtils.h"\r
 #include <fstream>\r
 #include "yaml-cpp/exceptions.h"\r
 #include "RamlExceptions.h"\r
index 38ed45d8c5616e161af8d2bb68bbba611af4a7d9..07a57c9d247ff87ba2832978c55c2aaf89216d4f 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 3949234de197891b23e30296d95c2932d82506b3..2cf1446d1e914d1ffeb390d1fc6a367c2ecef4fa 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 100644 (file)
index 0000000..0fad867
--- /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   Utils.h
+ *
+ * @brief   This file provides utilities for RamlParser.
+ */
+
+#ifndef RAML_UTILS_H
+#define RAML_UTILS_H
+
+#include "yaml-cpp/yaml.h"
+#include "ActionType.h"
+
+namespace RAML
+{
+    namespace Keys
+    {
+        /** Title - Raml title key.*/
+        const std::string Title = "title";
+        /** Version - Raml Version key.*/
+        const std::string Version = "version";
+        /** BaseUri - Raml BaseUri key.*/
+        const std::string BaseUri = "baseUri";
+        /** Protocols - Raml Protocols key.*/
+        const std::string Protocols = "protocols";
+        /** MediaType - Raml MediaType key.*/
+        const std::string MediaType = "mediaType";
+        /** Schemas - Raml Schemas key.*/
+        const std::string Schemas = "schemas";
+        /** ResourceTypes - Raml ResourceTypes key.*/
+        const std::string ResourceTypes = "resourceTypes";
+        /** Traits - Raml Traits key.*/
+        const std::string Traits = "traits";
+        /** IsTrait - Raml is key.*/
+        const std::string IsTrait = "is";
+
+        /** Resource - Raml Resource key.*/
+        const std::string Resource = "/";
+        /** ActionType - Raml allowed ActionType key.*/
+        const std::vector<std::string> ActionType = {"get", "post", "put", "delete",
+                                                     "head", "patch", "options", "trace"
+                                                    };
+
+        /** Responses - Raml Responses key.*/
+        const std::string Responses = "responses";
+        /** Body - Raml Body key.*/
+        const std::string Body = "body";
+        /** Schema - Raml Schema key.*/
+        const std::string Schema = "schema";
+        /** Example - Raml Example key.*/
+        const std::string Example = "example";
+
+        /** BaseUriParameters - Raml BaseUriParameters key.*/
+        const std::string BaseUriParameters = "baseUriParameters";
+        /** UriParameters - Raml UriParameters key.*/
+        const std::string UriParameters = "uriParameters";
+        /** Headers - Raml title Headers.*/
+        const std::string Headers = "headers";
+        /** QueryParameters - Raml QueryParameters key.*/
+        const std::string QueryParameters = "queryParameters";
+        /** FormParameters - Raml FormParameters key.*/
+        const std::string FormParameters = "formParameters";
+        /** DisplayName - Raml DisplayName key.*/
+        const std::string DisplayName = "displayName";
+        /** Description - Raml Description key.*/
+        const std::string Description = "description";
+        /** Type - Raml Type key.*/
+        const std::string Type = "type";
+        /** Enum - Raml Enum key.*/
+        const std::string Enum = "enum";
+        /** Pattern - Raml Pattern key.*/
+        const std::string Pattern = "pattern";
+        /** MinLength - Raml MinLength key.*/
+        const std::string MinLength = "minLength";
+        /** MaxLength - Raml MaxLength key.*/
+        const std::string MaxLength = "maxLength";
+        /** Minimum - Raml Minimum key.*/
+        const std::string Minimum = "minimum";
+        /** Maximum - Raml Maximum key.*/
+        const std::string Maximum = "maximum";
+        /** Repeat - Raml Repeat key.*/
+        const std::string Repeat = "repeat";
+        /** Required - Raml Required key.*/
+        const std::string Required = "required";
+        /** Default - Raml Default key.*/
+        const std::string Default = "default";
+        /** Title - Raml title key.*/
+
+        /** Documentation - Raml Documentation key.*/
+        const std::string Documentation = "documentation";
+        /** Content - Raml Content key.*/
+        const std::string Content = "content";
+
+        /** Json - Raml Json key.*/
+        const std::string Json = "json";
+        /** AllowedRamlYamlTypes - Raml AllowedRamlYamlTypes key.*/
+        const std::vector<std::string> AllowedRamlYamlTypes = {"raml", "yaml", "yml"};
+
+    }
+
+    /**
+    * This macro is reading yamlNode as String.
+    *
+    * @param yamlNode - reference to yamlNode
+    *
+    * @return value as string
+    */
+
+#define READ_NODE_AS_STRING(yamlNode)                   \
+({                                                      \
+(yamlNode).as<std::string>();                           \
+})
+
+    /**
+    * This macro is reading yamlNode as int.
+    *
+    * @param yamlNode - reference to yamlNode
+    *
+    * @return value as int
+    */
+#define READ_NODE_AS_INT(yamlNode)                      \
+({                                                      \
+    (yamlNode).as<int>();                               \
+})
+
+    /**
+    * This macro is reading yamlNode as long.
+    *
+    * @param yamlNode - reference to yamlNode
+    *
+    * @return value as long
+    */
+#define READ_NODE_AS_LONG(yamlNode)                     \
+({                                                      \
+    (yamlNode).as<long>();                              \
+})
+    /**
+     * This macro is reading yamlNode as bool.
+     *
+     * @param yamlNode - reference to yamlNode
+     *
+     * @return value as bool
+      */
+#define READ_NODE_AS_BOOL(yamlNode)                     \
+({                                                      \
+        (yamlNode).as<bool>();                          \
+})
+    /**
+    * This macro is getting ActionType
+    *
+    * @param key - string
+    *
+    * @return ActionType
+    */
+
+#define GET_ACTION_TYPE(key)                            \
+({                                                      \
+    ActionType actionType = ActionType::GET;            \
+    if (key == "get" )                                  \
+        actionType = ActionType::GET;                   \
+    else if (key == "post" )                            \
+        actionType = ActionType::POST;                  \
+    else if (key == "put" )                             \
+        actionType = ActionType::PUT;                   \
+    else if (key == "delete" )                          \
+        actionType = ActionType::DELETE;                \
+    else if (key == "head" )                            \
+        actionType = ActionType::HEAD;                  \
+    else if (key == "patch" )                           \
+        actionType = ActionType::PATCH;                 \
+    else if (key == "options" )                         \
+        actionType = ActionType::OPTIONS;               \
+    else if (key == "trace" )                           \
+        actionType = ActionType::TRACE;                 \
+    actionType;                                         \
+})
+
+}
+#endif
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
index 401e4481610c225fdc304f9bf71a1d8cccb9b435..d2eec8f2e312ad12e517bacfd576f078d26cd8fa 100755 (executable)
@@ -118,7 +118,7 @@ namespace RAML
                     if (*it == reqValue)\r
                         break;\r
                 }\r
-                if (m_required.end() != it)\r
+                if (m_required.end() == it)\r
                 {\r
                     m_required.push_back(reqValue);\r
                 }\r
index b0a0e50a24aac9ba73d8d55a16763e33f02f5327..d2463b2251fdf7f24034b866794e51c405800f77 100755 (executable)
@@ -124,7 +124,7 @@ namespace RAML
                     if (*it == reqValue)\r
                         break;\r
                 }\r
-                if (m_required.end() != it)\r
+                if (m_required.end() == it)\r
                 {\r
                     m_required.push_back(reqValue);\r
                 }\r
index 67968e264b44984e70adf3357e07f477880f8594..0a0c11a1a65a085b4b2b6a4ee295457378d98724 100755 (executable)
@@ -460,12 +460,12 @@ namespace RAML
             if (exclusiveMax)\r
             {\r
                 if (exclusiveMax->type == cJSON_True)\r
-                    property->setMaxDouble( --(Max->valuedouble));\r
+                    property->setMax( --(Max->valuedouble));\r
                 else\r
-                    property->setMaxDouble(Max->valuedouble);\r
+                    property->setMax(Max->valuedouble);\r
             }\r
             else\r
-                property->setMaxDouble(Max->valuedouble);\r
+                property->setMax(Max->valuedouble);\r
         }\r
         cJSON *Min = cJSON_GetObjectItem(childProperties, "minimum");\r
         if (Min)\r
@@ -474,12 +474,12 @@ namespace RAML
             if (exclusiveMin)\r
             {\r
                 if (exclusiveMin->type == cJSON_True)\r
-                    property->setMinDouble( ++(Min->valuedouble));\r
+                    property->setMin( ++(Min->valuedouble));\r
                 else\r
-                    property->setMinDouble(Min->valuedouble);\r
+                    property->setMin(Min->valuedouble);\r
             }\r
             else\r
-                property->setMinDouble(Min->valuedouble);\r
+                property->setMin(Min->valuedouble);\r
         }\r
         cJSON *multipleOf = cJSON_GetObjectItem(childProperties, "multipleOf");\r
         if (multipleOf)\r
index 7291635ef36fc720afee37675b58f3b5680c56f1..c4dda1df0506091090dd67845b45bc953ae1331f 100755 (executable)
@@ -50,7 +50,7 @@ namespace RAML
             /**\r
                   * Constructor of Properties.\r
                   */\r
-            Properties(): m_min(INT_MAX), m_max(INT_MAX), m_doubleMin(INT_MAX), m_doubleMax(INT_MAX),\r
+            Properties(): m_min(INT_MAX), m_max(INT_MAX),\r
                 m_multipleOf(INT_MAX), m_unique(false), m_additionalItems(false) {}\r
 \r
             /**\r
@@ -59,7 +59,7 @@ namespace RAML
                   * @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_multipleOf(INT_MAX),\r
                 m_unique(false), m_additionalItems(false) {}\r
 \r
             /**\r
@@ -188,7 +188,7 @@ namespace RAML
                  * @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
+            inline void getRange(double &min, double &max, int &multipleOf) const\r
             {\r
                 min = m_min;\r
                 max = m_max;\r
@@ -196,24 +196,11 @@ namespace RAML
             }\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
+                 * 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
+            inline void setMin(double min)\r
             {\r
                 m_min = min;\r
             }\r
@@ -223,30 +210,10 @@ namespace RAML
                  *\r
                  * @param max - Maximum value of Properties.\r
                  */\r
-            inline void setMax(const int &max)\r
+            inline void setMax(double max)\r
             {\r
                 m_max = max;\r
             }\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
-\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
@@ -480,10 +447,8 @@ namespace RAML
         private:\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
+            double m_min;\r
+            double m_max;\r
             int m_multipleOf;\r
             AllowedValues m_allowedValues;\r
             std::string m_type;\r
index dd3356495927ef4b43ea39558f31da8d04d3d55e..dafba132d2d72f65744c3f7135ca432d8f4f6f7b 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 6ee2abb3698edfa50b95784a553c4f6050babbe9..ff829c533cbdeb24021cae34d6410a61af4323b4 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 f90fdeadc89b2a2c8d441778d135db75faf95eaa..855d8f4a46597af3a8ca51cd4ac217fa8303a49f 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 cac949dad8db715f105fc49dc206fb89fc342f63..1b4d7486ec6a6c98e6943e097cf9a962f3468046 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 78aaee933c3c465a194182277387e4607c951b96..929f915af24381e69dad96a718925857bd8aae12 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 5d3ed62702bda8eba79f38790a0a5773afddde4e..be4119290538d7bcf3e133c47065bdcd2540dae9 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
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/query_param_generator.cpp b/service/simulator/src/client-controller/query_param_generator.cpp
deleted file mode 100644 (file)
index 1e51e7e..0000000
+++ /dev/null
@@ -1,73 +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 "query_param_generator.h"
-
-QPGenerator::QPGenerator(const std::map<std::string, std::vector<std::string>> &queryParams)
-{
-    for (auto entry : queryParams)
-    {
-        if (entry.second.size())
-        {
-            QPDetail detail;
-            detail.key.assign(entry.first.c_str());
-            detail.values = entry.second;
-            detail.index = 0;
-            m_qpDetails.push_back(detail);
-        }
-    }
-}
-
-bool QPGenerator::hasNext()
-{
-    if (m_qpDetails.size() &&
-        (m_qpDetails[0].index < m_qpDetails[0].values.size()))
-    {
-        return true;
-    }
-
-    return false;
-}
-
-std::map<std::string, std::string> QPGenerator::next()
-{
-    std::map<std::string, std::string> queryParams;
-    if (!hasNext())
-        return queryParams;
-
-    for (auto ele : m_qpDetails)
-        queryParams[ele.key] = ele.values[ele.index];
-
-    for (int index = m_qpDetails.size() - 1; index >= 0; index--)
-    {
-        m_qpDetails[index].index++;
-        if (m_qpDetails[index].index >= m_qpDetails[index].values.size()) // Boundary check
-        {
-            if (index != 0)
-            {
-                m_qpDetails[index].index = 0;
-                continue;
-            }
-        }
-        break;
-    }
-
-    return queryParams;
-}
\ No newline at end of file
diff --git a/service/simulator/src/client-controller/query_param_generator.h b/service/simulator/src/client-controller/query_param_generator.h
deleted file mode 100644 (file)
index 6040ffd..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 QUERY_PARAM_GENERATOR_H_
-#define QUERY_PARAM_GENERATOR_H_
-
-#include <string>
-#include <map>
-#include <vector>
-
-class QPGenerator
-{
-    public:
-        typedef struct
-        {
-            std::string key;
-            std::vector<std::string> values;
-            std::size_t index;
-        } QPDetail;
-
-        QPGenerator() = default;
-        QPGenerator(const std::map<std::string, std::vector<std::string>> &queryParams);
-        bool hasNext();
-        std::map<std::string, std::string> next();
-
-    private:
-        std::vector<QPDetail> m_qpDetails;
-};
-
-#endif
diff --git a/service/simulator/src/client-controller/request_list.h b/service/simulator/src/client-controller/request_list.h
deleted file mode 100644 (file)
index 4992633..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.
- *
- ******************************************************************/
-
-#ifndef REQUEST_LIST_H_
-#define REQUEST_LIST_H_
-
-#include <map>
-#include <mutex>
-
-template <typename T>
-class RequestList
-{
-    public:
-        RequestList() : m_id(0) {}
-
-        int add(T request)
-        {
-            if (!request)
-                return -1;
-
-            std::lock_guard<std::recursive_mutex> lock(m_listMutex);
-            m_requestList[m_id++] = request;
-            return m_id - 1;
-        }
-
-        T get(int id)
-        {
-            std::lock_guard<std::recursive_mutex> lock(m_listMutex);
-            if (m_requestList.end() != m_requestList.find(id))
-                return m_requestList[id];
-
-            return nullptr;
-        }
-
-        T remove(int id)
-        {
-            std::lock_guard<std::recursive_mutex> lock(m_listMutex);
-            if (m_requestList.end() != m_requestList.find(id))
-            {
-                T request = m_requestList[id];
-                m_requestList.erase(m_requestList.find(id));
-                return request;
-            }
-
-            return nullptr;
-        }
-
-        int size()
-        {
-            std::lock_guard<std::recursive_mutex> lock(m_listMutex);
-            return m_requestList.size();
-        }
-
-        void clear()
-        {
-            std::lock_guard<std::recursive_mutex> lock(m_listMutex);
-            m_requestList.clear();
-        }
-
-    private:
-        int m_id;
-        std::recursive_mutex m_listMutex;
-        std::map<int, T> m_requestList;
-};
-
-#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/attribute_generator.cpp b/service/simulator/src/client/attribute_generator.cpp
new file mode 100644 (file)
index 0000000..7a1e140
--- /dev/null
@@ -0,0 +1,183 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_attribute(attribute),
+        m_curValue(INT_MIN),
+        m_valueSetIndex(0)
+{
+    if (m_attribute.getProperty().type() == SimulatorResourceModel::AttributeProperty::Type::RANGE)
+    {
+        m_curValue = m_attribute.getProperty().min();
+    }
+    else if (m_attribute.getProperty().type() ==
+             SimulatorResourceModel::AttributeProperty::Type::VALUE_SET)
+    {
+        m_supportedValues = m_attribute.getProperty().valueSet();
+    }
+}
+
+bool AttributeGenerator::hasNext()
+{
+    if (m_attribute.getProperty().type() == SimulatorResourceModel::AttributeProperty::Type::RANGE
+        && m_curValue <= m_attribute.getProperty().max())
+    {
+        return true;
+    }
+    else if (m_attribute.getProperty().type() ==
+             SimulatorResourceModel::AttributeProperty::Type::VALUE_SET
+             && m_valueSetIndex <= m_supportedValues.size() - 1)
+    {
+        return true;
+    }
+
+    return false;
+}
+
+bool AttributeGenerator::next(SimulatorResourceModel::Attribute &attribute)
+{
+    if (!hasNext())
+        return false;
+
+    attribute.setName(m_attribute.getName());
+    if (m_attribute.getProperty().type() == SimulatorResourceModel::AttributeProperty::Type::RANGE
+        && m_curValue <= m_attribute.getProperty().max())
+    {
+        if (SimulatorResourceModel::ValueType::INTEGER == m_attribute.getType().type())
+            attribute.setValue(static_cast<int>(m_curValue++));
+        else
+            attribute.setValue(m_curValue++);
+    }
+    else if (m_attribute.getProperty().type() ==
+             SimulatorResourceModel::AttributeProperty::Type::VALUE_SET
+             && m_valueSetIndex <= m_supportedValues.size() - 1)
+    {
+        attribute.setValue(m_supportedValues[m_valueSetIndex++]);
+    }
+
+    return true;
+}
+
+SimulatorResourceModel::Attribute AttributeGenerator::current()
+{
+    SimulatorResourceModel::Attribute attribute;
+    attribute.setName(m_attribute.getName());
+
+    if (m_attribute.getProperty().type() == SimulatorResourceModel::AttributeProperty::Type::RANGE
+        && m_curValue <= m_attribute.getProperty().max())
+    {
+        if (SimulatorResourceModel::ValueType::INTEGER == m_attribute.getType().type())
+            attribute.setValue(static_cast<int>(m_curValue));
+        else
+            attribute.setValue(m_curValue);
+    }
+    else if (m_attribute.getProperty().type() ==
+             SimulatorResourceModel::AttributeProperty::Type::VALUE_SET
+             && m_valueSetIndex <= m_supportedValues.size() - 1)
+    {
+        attribute.setValue(m_supportedValues[m_valueSetIndex]);
+    }
+
+    return attribute;
+}
+
+void AttributeGenerator::reset()
+{
+    m_curValue = m_attribute.getProperty().min();
+    m_valueSetIndex = 0;
+}
+
+AttributeCombinationGen::AttributeCombinationGen(
+    const std::vector<SimulatorResourceModel::Attribute> &attributes)
+{
+    for (auto &attr : attributes)
+    {
+        AttributeGenerator attrGen(attr);
+        m_attrGenList.push_back(attr);
+        m_resModel.add(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 (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;
+        return true;
+    }
+    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;
+    }
+
+    return false;
+}
+
+void AttributeCombinationGen::updateAttributeInModel(int index)
+{
+    SimulatorResourceModel::Attribute attribute;
+    if (m_attrGenList[index].next(attribute))
+        m_resModel.updateValue(attribute);
+}
diff --git a/service/simulator/src/client/attribute_generator.h b/service/simulator/src/client/attribute_generator.h
new file mode 100644 (file)
index 0000000..ca0439c
--- /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.
+ *
+ ******************************************************************/
+
+#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:
+        SimulatorResourceModel::Attribute m_attribute;
+        double m_curValue;
+        size_t m_valueSetIndex;
+        std::vector<SimulatorResourceModel::ValueVariant> m_supportedValues;
+};
+
+class AttributeCombinationGen
+{
+    public:
+        AttributeCombinationGen(const std::vector<SimulatorResourceModel::Attribute> &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/client/auto_request_gen.cpp b/service/simulator/src/client/auto_request_gen.cpp
new file mode 100644 (file)
index 0000000..2ab450d
--- /dev/null
@@ -0,0 +1,41 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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/auto_request_gen.h b/service/simulator/src/client/auto_request_gen.h
new file mode 100644 (file)
index 0000000..c296f4e
--- /dev/null
@@ -0,0 +1,51 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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/auto_request_gen_mngr.cpp b/service/simulator/src/client/auto_request_gen_mngr.cpp
new file mode 100644 (file)
index 0000000..10aaf14
--- /dev/null
@@ -0,0 +1,225 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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/auto_request_gen_mngr.h b/service/simulator/src/client/auto_request_gen_mngr.h
new file mode 100644 (file)
index 0000000..ced67a7
--- /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 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/get_request_generator.cpp b/service/simulator/src/client/get_request_generator.cpp
new file mode 100644 (file)
index 0000000..1a6aa17
--- /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.
+ *
+ ******************************************************************/
+
+#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/get_request_generator.h b/service/simulator/src/client/get_request_generator.h
new file mode 100644 (file)
index 0000000..bb23caa
--- /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 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/post_request_generator.cpp b/service/simulator/src/client/post_request_generator.cpp
new file mode 100644 (file)
index 0000000..a8c397d
--- /dev/null
@@ -0,0 +1,145 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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->add(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/post_request_generator.h b/service/simulator/src/client/post_request_generator.h
new file mode 100644 (file)
index 0000000..ddfbac5
--- /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.
+ *
+ ******************************************************************/
+
+#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/put_request_generator.cpp b/service/simulator/src/client/put_request_generator.cpp
new file mode 100644 (file)
index 0000000..d54a52d
--- /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.
+ *
+ ******************************************************************/
+
+#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/put_request_generator.h b/service/simulator/src/client/put_request_generator.h
new file mode 100644 (file)
index 0000000..471af60
--- /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.
+ *
+ ******************************************************************/
+
+#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/query_param_generator.cpp b/service/simulator/src/client/query_param_generator.cpp
new file mode 100644 (file)
index 0000000..1e51e7e
--- /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.
+ *
+ ******************************************************************/
+
+#include "query_param_generator.h"
+
+QPGenerator::QPGenerator(const std::map<std::string, std::vector<std::string>> &queryParams)
+{
+    for (auto entry : queryParams)
+    {
+        if (entry.second.size())
+        {
+            QPDetail detail;
+            detail.key.assign(entry.first.c_str());
+            detail.values = entry.second;
+            detail.index = 0;
+            m_qpDetails.push_back(detail);
+        }
+    }
+}
+
+bool QPGenerator::hasNext()
+{
+    if (m_qpDetails.size() &&
+        (m_qpDetails[0].index < m_qpDetails[0].values.size()))
+    {
+        return true;
+    }
+
+    return false;
+}
+
+std::map<std::string, std::string> QPGenerator::next()
+{
+    std::map<std::string, std::string> queryParams;
+    if (!hasNext())
+        return queryParams;
+
+    for (auto ele : m_qpDetails)
+        queryParams[ele.key] = ele.values[ele.index];
+
+    for (int index = m_qpDetails.size() - 1; index >= 0; index--)
+    {
+        m_qpDetails[index].index++;
+        if (m_qpDetails[index].index >= m_qpDetails[index].values.size()) // Boundary check
+        {
+            if (index != 0)
+            {
+                m_qpDetails[index].index = 0;
+                continue;
+            }
+        }
+        break;
+    }
+
+    return queryParams;
+}
\ No newline at end of file
diff --git a/service/simulator/src/client/query_param_generator.h b/service/simulator/src/client/query_param_generator.h
new file mode 100644 (file)
index 0000000..6040ffd
--- /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.
+ *
+ ******************************************************************/
+
+#ifndef QUERY_PARAM_GENERATOR_H_
+#define QUERY_PARAM_GENERATOR_H_
+
+#include <string>
+#include <map>
+#include <vector>
+
+class QPGenerator
+{
+    public:
+        typedef struct
+        {
+            std::string key;
+            std::vector<std::string> values;
+            std::size_t index;
+        } QPDetail;
+
+        QPGenerator() = default;
+        QPGenerator(const std::map<std::string, std::vector<std::string>> &queryParams);
+        bool hasNext();
+        std::map<std::string, std::string> next();
+
+    private:
+        std::vector<QPDetail> m_qpDetails;
+};
+
+#endif
diff --git a/service/simulator/src/client/request_list.h b/service/simulator/src/client/request_list.h
new file mode 100644 (file)
index 0000000..4992633
--- /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.
+ *
+ ******************************************************************/
+
+#ifndef REQUEST_LIST_H_
+#define REQUEST_LIST_H_
+
+#include <map>
+#include <mutex>
+
+template <typename T>
+class RequestList
+{
+    public:
+        RequestList() : m_id(0) {}
+
+        int add(T request)
+        {
+            if (!request)
+                return -1;
+
+            std::lock_guard<std::recursive_mutex> lock(m_listMutex);
+            m_requestList[m_id++] = request;
+            return m_id - 1;
+        }
+
+        T get(int id)
+        {
+            std::lock_guard<std::recursive_mutex> lock(m_listMutex);
+            if (m_requestList.end() != m_requestList.find(id))
+                return m_requestList[id];
+
+            return nullptr;
+        }
+
+        T remove(int id)
+        {
+            std::lock_guard<std::recursive_mutex> lock(m_listMutex);
+            if (m_requestList.end() != m_requestList.find(id))
+            {
+                T request = m_requestList[id];
+                m_requestList.erase(m_requestList.find(id));
+                return request;
+            }
+
+            return nullptr;
+        }
+
+        int size()
+        {
+            std::lock_guard<std::recursive_mutex> lock(m_listMutex);
+            return m_requestList.size();
+        }
+
+        void clear()
+        {
+            std::lock_guard<std::recursive_mutex> lock(m_listMutex);
+            m_requestList.clear();
+        }
+
+    private:
+        int m_id;
+        std::recursive_mutex m_listMutex;
+        std::map<int, T> m_requestList;
+};
+
+#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..b577a00
--- /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.
+ *
+ ******************************************************************/
+
+#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 resourceModel,
+                                ResponseCallback responseCb, bool verifyResponse)
+{
+    sendRequest(std::string(), queryParam, resourceModel, responseCb, verifyResponse);
+}
+
+void RequestSender::sendRequest(const std::string &interfaceType,
+                                const std::map<std::string, std::string> &queryParam,
+                                SimulatorResourceModelSP resourceModel,
+                                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 = resourceModel;
+    requestDetail->verifyResponse = verifyResponse;
+    requestDetail->responseCb = responseCb;
+
+    int requestId = m_requestList.add(requestDetail);
+
+    OCStackResult ocResult = send(queryParamCpy, resourceModel, 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 received..." << "\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 resourceModel = std::make_shared<SimulatorResourceModel>(
+                SimulatorResourceModel::build(rep));
+    request->responseCb(static_cast<SimulatorResult>(errorCode), resourceModel);
+}
+
+GETRequestSender::GETRequestSender(std::shared_ptr<OC::OCResource> &ocResource)
+    :   RequestSender(RequestType::RQ_TYPE_GET, ocResource) {}
+
+OCStackResult GETRequestSender::send(OC::QueryParamsMap &queryParams,
+                                     SimulatorResourceModelSP &resourceModel, OC::GetCallback callback)
+{
+    SIM_LOG(ILogger::INFO, "Sending GET request..." << "\n**Payload Details**\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 &resourceModel, OC::GetCallback callback)
+{
+    OC::OCRepresentation ocRep;
+    if (resourceModel)
+        ocRep = resourceModel->getOCRepresentation();
+
+    SIM_LOG(ILogger::INFO, "Sending PUT request..." << "\n**Payload Details**\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 &resourceModel, OC::GetCallback callback)
+{
+    OC::OCRepresentation ocRep;
+    if (resourceModel)
+        ocRep = resourceModel->getOCRepresentation();
+
+    SIM_LOG(ILogger::INFO, "Sending POST request..." << "\n**Payload Details**\n" << getRequestString(
+                queryParams, ocRep));
+    return m_ocResource->post(ocRep, queryParams, callback);
+}
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..fa6de91
--- /dev/null
@@ -0,0 +1,113 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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 resourceModel,
+                         ResponseCallback responseCb, bool verifyResponse = false);
+
+        void sendRequest(const std::string &interfaceType,
+                         const std::map<std::string, std::string> &queryParam,
+                         SimulatorResourceModelSP resourceModel,
+                         ResponseCallback responseCb, bool verifyResponse = false);
+
+        void setRequestModel(const RequestModelSP &requestModel);
+
+    protected:
+        virtual OCStackResult send(OC::QueryParamsMap &queryParams,
+                                   SimulatorResourceModelSP &resourceModel, 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 &resourceModel, OC::GetCallback callback);
+};
+
+class PUTRequestSender : public RequestSender
+{
+    public:
+        PUTRequestSender(std::shared_ptr<OC::OCResource> &ocResource);
+
+        OCStackResult send(OC::QueryParamsMap &queryParams,
+                           SimulatorResourceModelSP &resourceModel, OC::GetCallback callback);
+};
+
+class POSTRequestSender : public RequestSender
+{
+    public:
+        POSTRequestSender(std::shared_ptr<OC::OCResource> &ocResource);
+
+        OCStackResult send(OC::QueryParamsMap &queryParams,
+                           SimulatorResourceModelSP &resourceModel, 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/simulator_remote_resource_impl.cpp b/service/simulator/src/client/simulator_remote_resource_impl.cpp
new file mode 100644 (file)
index 0000000..336c3ba
--- /dev/null
@@ -0,0 +1,405 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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"
+
+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)
+{
+    VALIDATE_CALLBACK(callback)
+
+    std::lock_guard<std::mutex> lock(m_observeLock);
+    if (m_observeState)
+    {
+        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, "Observe response received..." << "\n" << getPayloadString(ocRep));
+
+        SimulatorResourceModelSP resourceModel(
+            new  SimulatorResourceModel(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, "OBSERVE request sent");
+    }
+    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));
+
+        SIM_LOG(ILogger::INFO, "OBSERVE CANCEL request sent");
+    }
+    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 std::string &interfaceType,
+                                      const std::map<std::string, std::string> &queryParams,
+                                      ResponseCallback callback)
+{
+    VALIDATE_CALLBACK(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)
+{
+    VALIDATE_CALLBACK(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 resourceModel,
+                                      ResponseCallback callback)
+{
+    VALIDATE_CALLBACK(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,
+                                    resourceModel, std::bind(
+                                        &SimulatorRemoteResourceImpl::onResponseReceived,
+                                        this, std::placeholders::_1, std::placeholders::_2, callback));
+}
+
+void SimulatorRemoteResourceImpl::put(const std::map<std::string, std::string> &queryParams,
+                                      SimulatorResourceModelSP resourceModel,
+                                      ResponseCallback callback)
+{
+    VALIDATE_CALLBACK(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,
+                                    resourceModel, 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 resourceModel,
+                                       ResponseCallback callback)
+{
+    VALIDATE_CALLBACK(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,
+                                     resourceModel, std::bind(
+                                         &SimulatorRemoteResourceImpl::onResponseReceived,
+                                         this, std::placeholders::_1, std::placeholders::_2, callback));
+}
+
+void SimulatorRemoteResourceImpl::post(const std::map<std::string, std::string> &queryParams,
+                                       SimulatorResourceModelSP resourceModel,
+                                       ResponseCallback callback)
+{
+    VALIDATE_CALLBACK(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,
+                                     resourceModel, std::bind(
+                                         &SimulatorRemoteResourceImpl::onResponseReceived,
+                                         this, std::placeholders::_1, std::placeholders::_2, callback));
+}
+
+int SimulatorRemoteResourceImpl::startVerification(RequestType type,
+        StateCallback callback)
+{
+    VALIDATE_CALLBACK(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_postRequestSender,
+                        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);
+}
+
+SimulatorResourceModelSP SimulatorRemoteResourceImpl::configure(const std::string &path)
+{
+    VALIDATE_INPUT(path.empty(), "Path is empty!")
+
+    std::shared_ptr<RAML::RamlParser> ramlParser = std::make_shared<RAML::RamlParser>(path);
+    RAML::RamlPtr raml = ramlParser->getRamlPtr();
+
+    configure(raml);
+
+    if (m_requestModelList.empty())
+        throw InvalidArgsException(SIMULATOR_INVALID_PARAM, "RAML file is invalid for the resource!");
+
+    for (auto &model : m_requestModelList)
+    {
+        SimulatorResourceModelSP schema = (model.second)->getRepSchema();
+        if (schema)
+        {
+            return std::make_shared<SimulatorResourceModel>(*(schema.get()));
+        }
+    }
+
+    return std::make_shared<SimulatorResourceModel>();
+}
+
+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 resourceModel, ResponseCallback clientCallback)
+{
+    clientCallback(m_id, result, resourceModel);
+}
+
+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..9948ea3
--- /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 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 resourceModel,
+                 ResponseCallback callback);
+
+        void put(const std::string &interfaceType,
+                 const std::map<std::string, std::string> &queryParams,
+                 SimulatorResourceModelSP resourceModel,
+                 ResponseCallback callback);
+
+        void post(const std::map<std::string, std::string> &queryParams,
+                  SimulatorResourceModelSP resourceModel,
+                  ResponseCallback callback);
+
+        void post(const std::string &interfaceType,
+                  const std::map<std::string, std::string> &queryParams,
+                  SimulatorResourceModelSP resourceModel,
+                  ResponseCallback callback);
+
+        int startVerification(RequestType type, StateCallback callback);
+        void stopVerification(int id);
+        SimulatorResourceModelSP configure(const std::string &path);
+
+    private:
+        void configure(std::shared_ptr<RAML::Raml> &raml);
+        void onResponseReceived(SimulatorResult result, SimulatorResourceModelSP resourceModel,
+                                ResponseCallback clientCallback);
+        SimulatorConnectivityType convertConnectivityType(OCConnectivityType type) const;
+
+        std::string m_id;
+        std::mutex m_observeLock;
+        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
index 9a2002196d5a44baa7408e587b17449c4b3aa62a..b181433b6ccd8bff24e58ad4c2cdf8b1df72d26d 100644 (file)
@@ -34,14 +34,14 @@ std::map<RequestType, RequestModelSP> RequestModelBuilder::build(const std::stri
         return modelList;
     }
 
-    for (auto  resource : m_raml->getResources())
+    for (auto   &resource : m_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)
@@ -71,9 +71,9 @@ RequestModelSP RequestModelBuilder::createRequestModel(const RAML::ActionPtr &ac
     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);
         }
@@ -84,7 +84,7 @@ RequestModelSP RequestModelBuilder::createRequestModel(const RAML::ActionPtr &ac
     requestModel->setRepSchema(repSchema);
 
     // Corresponsing responses
-    for (auto  responseEntry :  action->getResponses())
+    for (auto   &responseEntry :  action->getResponses())
     {
         std::string codeStr = responseEntry.first;
         int code = boost::lexical_cast<int>(codeStr);
@@ -115,6 +115,7 @@ SimulatorResourceModelSP RequestModelBuilder::createRepSchema(const RAML::Reques
     {
         return nullptr;
     }
+
     RAML::SchemaPtr schema = rep->getSchema();
     if (!schema)
     {
@@ -126,7 +127,7 @@ SimulatorResourceModelSP RequestModelBuilder::createRepSchema(const RAML::Reques
         return nullptr;
 
     SimulatorResourceModelSP repSchema = std::make_shared<SimulatorResourceModel>();
-    for (auto & propertyEntry : properties->getProperties())
+    for (auto &propertyEntry : properties->getProperties())
     {
         std::string propName = propertyEntry.second->getName();
         if ("rt" == propName || "resourceType" == propName || "if" == propName
@@ -139,33 +140,29 @@ SimulatorResourceModelSP RequestModelBuilder::createRepSchema(const RAML::Reques
             case 0: // Integer
                 {
                     // Add the attribute with value
-                    repSchema->addAttribute(propertyEntry.second->getName(), propertyEntry.second->getValue<int>());
+                    repSchema->add(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);
+                    // Convert supported values
+                    std::vector<int> allowedValues = propertyEntry.second->getAllowedValuesInt();
+                    if (allowedValues.size() > 0)
+                    {
+                        SimulatorResourceModel::AttributeProperty attrProp(allowedValues);
+                        repSchema->setAttributeProperty(propName, attrProp);
+                    }
                 }
                 break;
 
             case 1: // Double
                 {
                     // Add the attribute with value
-                    repSchema->addAttribute(propertyEntry.second->getName(), propertyEntry.second->getValue<double>());
+                    repSchema->add(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())
+                    // Convert suppoted values
+                    std::vector<double> allowedValues = propertyEntry.second->getAllowedValuesDouble();
+                    if (allowedValues.size() > 0)
                     {
-                        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);
+                        SimulatorResourceModel::AttributeProperty attrProp(allowedValues);
+                        repSchema->setAttributeProperty(propName, attrProp);
                     }
                 }
                 break;
@@ -173,33 +170,43 @@ SimulatorResourceModelSP RequestModelBuilder::createRepSchema(const RAML::Reques
             case 2: // Boolean
                 {
                     // Add the attribute with value
-                    repSchema->addAttribute(propertyEntry.second->getName(), propertyEntry.second->getValue<bool>());
+                    repSchema->add(propertyEntry.second->getName(), propertyEntry.second->getValue<bool>());
+                    // Convert supported values
+                    std::vector<bool> allowedValues = propertyEntry.second->getAllowedValuesBool();
+                    if (allowedValues.size() > 0)
+                    {
+                        SimulatorResourceModel::AttributeProperty attrProp(allowedValues);
+                        repSchema->setAttributeProperty(propName, attrProp);
+                    }
                 }
                 break;
 
             case 3: // String
                 {
                     // Add the attribute with value
-                    repSchema->addAttribute(propertyEntry.second->getName(),
-                                            propertyEntry.second->getValue<std::string>());
+                    repSchema->add(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())
+                    // Convert suppored values
+                    std::vector<std::string> allowedValues = propertyEntry.second->getAllowedValuesString();
+                    if (allowedValues.size() > 0)
                     {
-                        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);
+                        SimulatorResourceModel::AttributeProperty attrProp(allowedValues);
+                        repSchema->setAttributeProperty(propName, attrProp);
                     }
                 }
                 break;
         }
+
+        // Set the range property if its present
+        double min, max;
+        int multipleof;
+        propertyEntry.second->getRange(min, max, multipleof);
+        if (min != INT_MIN && max != INT_MAX)
+        {
+            SimulatorResourceModel::AttributeProperty attrProp(min, max);
+            repSchema->setAttributeProperty(propName, attrProp);
+        }
     }
 
     return repSchema;
@@ -209,8 +216,6 @@ 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:
@@ -218,5 +223,7 @@ RequestType RequestModelBuilder::getRequestType(RAML::ActionType actionType)
         case RAML::ActionType::DELETE:
             return RequestType::RQ_TYPE_DELETE;
     }
+
+    return RequestType::RQ_TYPE_GET;
 }
 
index 8398a18c64237741ad33db1bb443652761c580ce..9cae27ab74ad55bfd39847340234e89deef4367e 100644 (file)
@@ -27,98 +27,10 @@ void ResponseModel::setRepSchema(SimulatorResourceModelSP &repSchema)
     m_repSchema = repSchema;
 }
 
-SimulatorResult ResponseModel::verifyResponse(const OC::OCRepresentation &rep)
+SimulatorResult ResponseModel::verifyResponse(const OC::OCRepresentation &ocRep)
 {
-    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)
-    {
-        return SIMULATOR_BAD_VALUE;
-    }
-
-    return SIMULATOR_OK;
-}
-
-SimulatorResult ResponseModel::validateAttributeDouble(
-    SimulatorResourceModel::Attribute &attrSchema,
-    const OC::OCRepresentation::AttributeItem &ocAttribute)
-{
-    // Check the value type
-    if (OC::AttributeType::Double != ocAttribute.type())
-    {
-        return SIMULATOR_TYPE_MISMATCH;
-    }
-
-    return SIMULATOR_OK;
+    SimulatorResourceModel resModel = SimulatorResourceModel::build(ocRep);
+    if (m_repSchema->match(resModel))
+        return SIMULATOR_OK;
+    return SIMULATOR_ERROR;
 }
-
-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 77cb2bbf6214e8d934188bfc08933bb9b9a1b1f2..f52626e9bee01b1839d423c68ba42e94afe449f2 100644 (file)
@@ -30,18 +30,11 @@ class ResponseModel
     public:
         friend class RequestModelBuilder;
 
-        SimulatorResult verifyResponse(const OC::OCRepresentation &rep);
+        SimulatorResult verifyResponse(const OC::OCRepresentation &ocRep);
 
     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);
-
         int m_code;
         SimulatorResourceModelSP m_repSchema;
 };
index 2a1a67de84ecdce99ce81a4509313aee8c9716b4..f309ec49a128425f13c6f013019aca847e4eab66 100644 (file)
 #include "simulator_resource_model.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 SimulatorResourceModel::ValueType type =
+        SimulatorResourceModel::ValueType::INTEGER;
 };
 
 template <>
 struct TypeConverter<double>
 {
-    constexpr static SimulatorResourceModel::Attribute::ValueType type =
-            SimulatorResourceModel::Attribute::ValueType::DOUBLE;
+    constexpr static SimulatorResourceModel::ValueType type =
+        SimulatorResourceModel::ValueType::DOUBLE;
 };
 
 template <>
 struct TypeConverter<bool>
 {
-    constexpr static SimulatorResourceModel::Attribute::ValueType type =
-            SimulatorResourceModel::Attribute::ValueType::BOOLEAN;
+    constexpr static SimulatorResourceModel::ValueType type =
+        SimulatorResourceModel::ValueType::BOOLEAN;
 };
 
 template <>
 struct TypeConverter<std::string>
 {
-    constexpr static SimulatorResourceModel::Attribute::ValueType type =
-            SimulatorResourceModel::Attribute::ValueType::STRING;
+    constexpr static SimulatorResourceModel::ValueType type =
+        SimulatorResourceModel::ValueType::STRING;
+};
+
+template <>
+struct TypeConverter<SimulatorResourceModel>
+{
+    constexpr static SimulatorResourceModel::ValueType type =
+        SimulatorResourceModel::ValueType::RESOURCE_MODEL;
+};
+
+template <typename T>
+struct TypeDetails
+{
+    constexpr static SimulatorResourceModel::ValueType type =
+        TypeConverter<T>::type;
+    constexpr static SimulatorResourceModel::ValueType baseType =
+        TypeConverter<T>::type;
+    constexpr static int depth = 0;
+};
+
+template <typename T>
+struct TypeDetails<std::vector<T>>
+{
+    constexpr static SimulatorResourceModel::ValueType type =
+        SimulatorResourceModel::ValueType::VECTOR;
+    constexpr static SimulatorResourceModel::ValueType baseType =
+        TypeDetails<T>::baseType;
+    constexpr static int depth = 1 + TypeDetails<T>::depth;
 };
 
-class attribute_type_visitor : public boost::static_visitor<
-        SimulatorResourceModel::Attribute::ValueType>
+class AttributeTypeVisitor : public boost::static_visitor<>
 {
     public:
+        AttributeTypeVisitor() : m_type(SimulatorResourceModel::ValueType::UNKNOWN),
+            m_baseType(SimulatorResourceModel::ValueType::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;
         }
+
+        SimulatorResourceModel::ValueType m_type;
+        SimulatorResourceModel::ValueType 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 &key)
+                    : m_rep(rep), m_key(key) {}
+
+                template <typename T>
+                void operator ()(const T &value)
+                {
+                    m_rep.setValue(m_key, value);
+                }
+
+                void operator ()(const SimulatorResourceModel &value)
+                {
+                    OC::OCRepresentation ocRep;
+                    for (auto &element : value.getValues())
+                    {
+                        ValueConverter visitor(ocRep, element.first);
+                        boost::apply_visitor(visitor, element.second);
+                    }
+
+                    m_rep.setValue(m_key, ocRep);
+                }
+
+                template <typename T>
+                void operator ()(const std::vector<T> &values)
+                {
+                    m_rep.setValue(m_key, 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].getValues())
+                        {
+                            ValueConverter visitor(ocRepArray[i], element.first);
+                            boost::apply_visitor(visitor, element.second);
+                        }
+                    }
+
+                    m_rep.setValue(m_key, ocRepArray);
+                }
+
+                template <typename T>
+                void operator ()(const std::vector<std::vector<T>> &values)
+                {
+                    m_rep.setValue(m_key, 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].getValues())
+                            {
+                                ValueConverter visitor(ocRepArray[i][j], element.first);
+                                boost::apply_visitor(visitor, element.second);
+                            }
+                        }
+                    }
+
+                    m_rep.setValue(m_key, ocRepArray);
+                }
+
+                template <typename T>
+                void operator ()(const std::vector<std::vector<std::vector<T>>> &values)
+                {
+                    m_rep.setValue(m_key, 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].getValues())
+                                {
+                                    ValueConverter visitor(ocRepArray[i][j][k], element.first);
+                                    boost::apply_visitor(visitor, element.second);
+                                }
+                            }
+                        }
+                    }
+
+                    m_rep.setValue(m_key, ocRepArray);
+                }
+
+            private:
+                OC::OCRepresentation &m_rep;
+                std::string m_key;
+        };
+
+        OC::OCRepresentation build(SimulatorResourceModel &model)
+        {
+            OC::OCRepresentation ocRep;
+            for (auto &element : model.getValues())
             {
-                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) {}
+        SimulatorResourceModel build(const OC::OCRepresentation &ocRep)
+        {
+            SimulatorResourceModel resModel;
+            handleRepresentationType(resModel, ocRep);
+            return std::move(resModel);
+        }
 
-        template <typename T>
-        void operator ()(const T &value)
+    private:
+        void handleRepresentationType(SimulatorResourceModel &resModel,
+                                      const OC::OCRepresentation &ocRep)
         {
-            m_rep.setValue(m_key, value);
+            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);
+                }
+            }
         }
 
-        OC::OCRepresentation &&getRep()
+        void handleVectorType(SimulatorResourceModel &resModel,
+                              const OC::OCRepresentation::AttributeItem &ocAttribute)
         {
-            return std::move(m_rep);
+            if (1 == ocAttribute.depth())
+            {
+                handleVectorTypeDepth1(resModel, ocAttribute);
+            }
+            else if (2 == ocAttribute.depth())
+            {
+                handleVectorTypeDepth2(resModel, ocAttribute);
+            }
+            else if (3 == ocAttribute.depth())
+            {
+                handleVectorTypeDepth3(resModel, ocAttribute);
+            }
         }
 
-    private:
-        OC::OCRepresentation m_rep;
-        std::string m_key;
+        void handleVectorTypeDepth1(SimulatorResourceModel &resModel,
+                                    const OC::OCRepresentation::AttributeItem &ocAttribute)
+        {
+            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())
+            {
+                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);
+            }
+        }
+
+        void handleVectorTypeDepth2(SimulatorResourceModel &resModel,
+                                    const OC::OCRepresentation::AttributeItem &ocAttribute)
+        {
+            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);
+            }
+        }
+
+        void handleVectorTypeDepth3(SimulatorResourceModel &resModel,
+                                    const OC::OCRepresentation::AttributeItem &ocAttribute)
+        {
+            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())
+            {
+                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);
+            }
+        }
 };
 
-class range_validation : public boost::static_visitor<bool>
+class RangeValidator : public boost::static_visitor<bool>
 {
     public:
-        range_validation (SimulatorResourceModel::Attribute &attrItem)
-            : m_attrItem(attrItem) {}
+        RangeValidator(SimulatorResourceModel::AttributeProperty &property) :
+            m_property(property) {}
+
+        bool operator ()(const int &value)
+        {
+            if (checkRange(value) || checkSupportedValueSet(value))
+                return true;
+            return false;
+        }
 
-        bool operator ()(int &value)
+        bool operator ()(const double &value)
         {
-            int min, max;
-            m_attrItem.getRange(min, max);
-            if (value >= min && value <= max)
+            if (checkRange(value) || checkSupportedValueSet(value))
                 return true;
             return false;
         }
 
-        bool operator ()(double &value)
+        bool operator ()(const bool &value)
         {
-            std::vector<SimulatorResourceModel::Attribute::ValueVariant> values
-                = m_attrItem.getAllowedValues();
-            if(0 == values.size())
+            if (checkSupportedValueSet(value))
                 return true;
-            for (SimulatorResourceModel::Attribute::ValueVariant & val : values)
+            return false;
+        }
+
+        bool operator ()(const std::string &value)
+        {
+            int len = value.length();
+            if (checkRange(len) || checkSupportedValueSet(value))
+                return true;
+            return false;
+        }
+
+        bool operator ()(const SimulatorResourceModel &)
+        {
+            return true;
+        }
+
+        template <typename T>
+        bool operator ()(const std::vector<T> &values)
+        {
+            // Verify array property
+            int length = values.size();
+            if (!checkRange(length))
+                return false;
+
+            // Verify array element property
+            if (!m_property.getChildProperty())
+                return true;
+
+            m_property = *(m_property.getChildProperty());
+            for (int index = 0; index < length; index++)
             {
-                SimulatorResourceModel::Attribute::ValueVariant vVal = value;
-                if (val == vVal)
-                    return true;
+                if (!operator ()(values[index]))
+                    return false;
             }
-            return false;
+
+            return true;
         }
 
-        bool operator ()(bool &value)
+        template <typename T>
+        bool operator ()(const std::vector<std::vector<T>> &values)
         {
+            // Verify array property
+            int length = values.size();
+            if (!checkRange(length))
+                return false;
+
+            // Verify array element property
+            if (!m_property.getChildProperty())
+                return true;
+
+            m_property = *(m_property.getChildProperty());
+            for (int index = 0; index < length; index++)
+            {
+                if (!operator ()(values[index]))
+                    return false;
+            }
+
             return true;
         }
 
-        bool operator ()(std::string &value)
+        template <typename T>
+        bool operator ()(const std::vector<std::vector<std::vector<T>>> &values)
         {
-            std::vector<SimulatorResourceModel::Attribute::ValueVariant> values
-                = m_attrItem.getAllowedValues();
-            if(0 == values.size())
+            // Verify array property
+            int length = values.size();
+            if (!checkRange(length))
+                return false;
+
+            // Verify array element property
+            if (!m_property.getChildProperty())
                 return true;
-            for (SimulatorResourceModel::Attribute::ValueVariant & vVal : values)
+
+            m_property = *(m_property.getChildProperty());
+            for (int index = 0; index < length; index++)
             {
-                std::string val = boost::get<std::string>(vVal);
-                if (val == value)
+                if (!operator ()(values[index]))
+                    return false;
+            }
+
+            return true;
+        }
+
+    private:
+        inline bool isValidProperty()
+        {
+            if (SimulatorResourceModel::AttributeProperty::Type::UNKNOWN !=
+                m_property.type())
+                return true;
+            return false;
+        }
+
+        bool checkRange(const double &value)
+        {
+            if (SimulatorResourceModel::AttributeProperty::Type::RANGE ==
+                m_property.type())
+            {
+                if (value >= m_property.min() && value <= m_property.max())
                     return true;
             }
 
             return false;
         }
 
-    private:
-        SimulatorResourceModel::Attribute &m_attrItem;
+        template <typename T>
+        bool checkSupportedValueSet(const T &value)
+        {
+            if (SimulatorResourceModel::AttributeProperty::Type::VALUE_SET ==
+                m_property.type())
+            {
+                for (auto &element : m_property.valueSet())
+                {
+                    T allowedValue = boost::get<T>(element);
+                    if (allowedValue == value)
+                        return true;
+                }
+            }
+
+            return false;
+        }
+
+        SimulatorResourceModel::AttributeProperty m_property;
+};
+
+class ToStringConverter
+{
+    public:
+        class ValueVisitor : public boost::static_visitor<std::string>
+        {
+            public:
+
+                // Single basic type value conversion to string
+                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!";
+                    }
+                }
+
+                // SimulatorResourceModel conversion to string
+                std::string operator ()(const SimulatorResourceModel &value)
+                {
+                    std::ostringstream out;
+                    out << "{ ";
+                    for (auto &element : value.getValues())
+                    {
+                        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;
+            SimulatorResourceModel::ValueVariant value = resModel;
+            return boost::apply_visitor(visitor, value);
+        }
+
+        std::string getStringRepresentation(const SimulatorResourceModel::ValueVariant &value)
+        {
+            ValueVisitor visitor;
+            return boost::apply_visitor(visitor, value);
+        }
 };
 
-SimulatorResourceModel::Attribute::ValueVariant
-&SimulatorResourceModel::Attribute::AllowedValues::at(unsigned int index)
+SimulatorResourceModel::TypeInfo::TypeInfo(
+    SimulatorResourceModel::ValueType type = SimulatorResourceModel::ValueType::UNKNOWN,
+    SimulatorResourceModel::ValueType baseType = SimulatorResourceModel::ValueType::UNKNOWN,
+    int depth = 0)
+    :   m_type (type), m_baseType(baseType), m_depth(depth) {}
+
+SimulatorResourceModel::ValueType SimulatorResourceModel::TypeInfo::type() const
+{
+    return m_type;
+}
+
+SimulatorResourceModel::ValueType SimulatorResourceModel::TypeInfo::baseType() const
+{
+    return m_baseType;
+}
+
+int SimulatorResourceModel::TypeInfo::depth() const
 {
-    return m_values.at(index);
+    return m_depth;
+}
+
+bool SimulatorResourceModel::TypeInfo::operator==(
+    const SimulatorResourceModel::TypeInfo &rhs ) const
+{
+    if (m_type == rhs.type() && m_baseType == rhs.baseType()
+        && m_depth == rhs.depth())
+        return true;
+    return false;
 }
 
-int SimulatorResourceModel::Attribute::AllowedValues::size() const
+bool SimulatorResourceModel::TypeInfo::operator!=(
+    const SimulatorResourceModel::TypeInfo &rhs ) const
 {
-    return m_values.size();
+    if (m_type != rhs.type() || m_baseType != rhs.baseType()
+        || m_depth != rhs.depth())
+        return true;
+    return false;
 }
 
-std::vector<std::string> SimulatorResourceModel::Attribute::AllowedValues::toString() const
+SimulatorResourceModel::AttributeProperty::AttributeProperty()
+    :   m_type(SimulatorResourceModel::AttributeProperty::Type::UNKNOWN),
+        m_min(INT_MIN),
+        m_max(INT_MAX) {}
+
+SimulatorResourceModel::AttributeProperty::AttributeProperty(double min, double max)
+    :   m_type(SimulatorResourceModel::AttributeProperty::Type::RANGE),
+        m_min(min),
+        m_max(max) {}
+
+SimulatorResourceModel::AttributeProperty::AttributeProperty(
+    const std::vector<int> &valueSet)
+    :   m_type(SimulatorResourceModel::AttributeProperty::Type::VALUE_SET),
+        m_min(INT_MIN),
+        m_max(INT_MAX),
+        m_valueSet(valueSet.begin(), valueSet.end()) {}
+
+SimulatorResourceModel::AttributeProperty::AttributeProperty(
+    const std::vector<double> &valueSet)
+    :   m_type(SimulatorResourceModel::AttributeProperty::Type::VALUE_SET),
+        m_min(INT_MIN),
+        m_max(INT_MAX),
+        m_valueSet(valueSet.begin(), valueSet.end()) {}
+
+SimulatorResourceModel::AttributeProperty::AttributeProperty(
+    const std::vector<bool> &valueSet)
+    :   m_type(SimulatorResourceModel::AttributeProperty::Type::VALUE_SET),
+        m_min(INT_MIN),
+        m_max(INT_MAX),
+        m_valueSet(valueSet.begin(), valueSet.end()) {}
+
+SimulatorResourceModel::AttributeProperty::AttributeProperty(
+    const std::vector<std::string> &valueSet)
+    :   m_type(SimulatorResourceModel::AttributeProperty::Type::VALUE_SET),
+        m_min(INT_MIN),
+        m_max(INT_MAX),
+        m_valueSet(valueSet.begin(), valueSet.end()) {}
+
+SimulatorResourceModel::AttributeProperty::AttributeProperty(
+    const std::vector<ValueVariant> &valueSet)
+    :   m_type(SimulatorResourceModel::AttributeProperty::Type::VALUE_SET),
+        m_min(INT_MIN),
+        m_max(INT_MAX),
+        m_valueSet(valueSet.begin(), valueSet.end()) {}
+
+SimulatorResourceModel::AttributeProperty::Type
+SimulatorResourceModel::AttributeProperty::type() const
 {
-    std::vector<std::string> values;
+    return m_type;
+}
 
-    for (auto & value : m_values)
+double SimulatorResourceModel::AttributeProperty::min() const
+{
+    return m_min;
+}
+
+double SimulatorResourceModel::AttributeProperty::max() const
+{
+    return m_max;
+}
+
+int SimulatorResourceModel::AttributeProperty::valueSetSize() const
+{
+    return m_valueSet.size();
+}
+
+std::vector<SimulatorResourceModel::ValueVariant>
+SimulatorResourceModel::AttributeProperty::valueSet() const
+{
+    return m_valueSet;
+}
+
+std::string SimulatorResourceModel::AttributeProperty::valueSetToString() const
+{
+    std::ostringstream out;
+    out << "[ ";
+    for (auto &value : m_valueSet)
     {
-        to_string_visitor visitor;
-        values.push_back(boost::apply_visitor(visitor, value));
+        out << ToStringConverter().getStringRepresentation(value);
+        out << ", ";
     }
-    return values;
+    out << "]";
+    return out.str();
+}
+
+void SimulatorResourceModel::AttributeProperty::setChildProperty(AttributeProperty &childProperty)
+{
+    m_childProperty.reset(new SimulatorResourceModel::AttributeProperty(childProperty));
 }
 
-std::vector<SimulatorResourceModel::Attribute::ValueVariant>
-SimulatorResourceModel::Attribute::AllowedValues::getValues() const
+std::shared_ptr<SimulatorResourceModel::AttributeProperty> SimulatorResourceModel::AttributeProperty::getChildProperty()
 {
-    return m_values;
+    return m_childProperty;
 }
 
-std::string SimulatorResourceModel::Attribute::getName(void) const
+std::string SimulatorResourceModel::Attribute::getName() const
 {
     return m_name;
 }
 
-void SimulatorResourceModel::Attribute::setName(const std::string &name)
+SimulatorResourceModel::TypeInfo SimulatorResourceModel::Attribute::getType() const
 {
-    m_name = name;
+    if (m_value)
+    {
+        AttributeTypeVisitor typeVisitor;
+        boost::apply_visitor(typeVisitor, *(m_value.get()));
+        SimulatorResourceModel::TypeInfo typeInfo(typeVisitor.m_type, typeVisitor.m_baseType,
+                typeVisitor.m_depth);
+        return typeInfo;
+    }
+
+    return SimulatorResourceModel::TypeInfo();
 }
 
-void SimulatorResourceModel::Attribute::getRange(int &min, int &max) const
+const SimulatorResourceModel::AttributeProperty &
+SimulatorResourceModel::Attribute::getProperty() const
 {
-    min = m_min;
-    max = m_max;
+    return m_property;
 }
 
-void SimulatorResourceModel::Attribute::setRange(const int &min, const int &max)
+SimulatorResourceModel::AttributeProperty &SimulatorResourceModel::Attribute::getProperty()
 {
-    m_min = min;
-    m_max = max;
+    return m_property;
 }
 
-int SimulatorResourceModel::Attribute::getAllowedValuesSize() const
+void SimulatorResourceModel::Attribute::setName(const std::string &name)
 {
-    return m_allowedValues.size();
+    m_name = name;
 }
 
-void SimulatorResourceModel::Attribute::setFromAllowedValue(unsigned int index)
+void SimulatorResourceModel::Attribute::setProperty(
+    const SimulatorResourceModel::AttributeProperty &property)
 {
-    m_value = m_allowedValues.at(index);
+    m_property = property;
 }
 
-SimulatorResourceModel::Attribute::ValueType SimulatorResourceModel::Attribute::getValueType() const
+std::string SimulatorResourceModel::Attribute::toString() const
 {
-    attribute_type_visitor typeVisitor;
-    return boost::apply_visitor(typeVisitor, m_value);
+    return ToStringConverter().getStringRepresentation(*m_value);
 }
 
-std::string SimulatorResourceModel::Attribute::valueToString() const
+bool SimulatorResourceModel::add(const SimulatorResourceModel::Attribute &attribute)
 {
-    to_string_visitor visitor;
-    return boost::apply_visitor(visitor, m_value);
+    if (attribute.getName().empty())
+        return false;
+
+    if (m_attributes.end() == m_attributes.find(attribute.getName()))
+    {
+        m_attributes[attribute.getName()] = attribute.getValue();
+        if (SimulatorResourceModel::AttributeProperty::Type::UNKNOWN !=
+            attribute.getProperty().type())
+        {
+            m_attrProperties[attribute.getName()] = attribute.getProperty();
+        }
+        return true;
+    }
+
+    return false;
 }
 
-std::vector<std::string> SimulatorResourceModel::Attribute::allowedValuesToString() const
+bool SimulatorResourceModel::updateValue(const SimulatorResourceModel::Attribute &attribute,
+        bool overwrite)
 {
-    return m_allowedValues.toString();
+    return setAttributeValue(attribute.getName(), attribute.getValue(), false, overwrite);
 }
 
-void SimulatorResourceModel::Attribute::addValuetoRepresentation(OC::OCRepresentation &rep,
-        const std::string &key) const
+bool SimulatorResourceModel::containsAttribute(const std::string &key)
 {
-    add_to_representation visitor(rep, key);
-    boost::apply_visitor(visitor, m_value);
-    rep = visitor.getRep();
+    if (m_attributes.end() != m_attributes.find(key))
+        return true;
+    return false;
 }
 
-bool SimulatorResourceModel::Attribute::compare(SimulatorResourceModel::Attribute &attribute)
+bool SimulatorResourceModel::setAttributeProperty(const std::string &key,
+        const SimulatorResourceModel::AttributeProperty &property)
 {
-    // Check the value types
-    if (m_value.which() != attribute.getValue().which())
+    if (!key.empty() && m_attributes.end() != m_attributes.find(key))
     {
-        return false;
+        m_attrProperties[key] = property;
+        return true;
+    }
+
+    return false;
+}
+
+bool SimulatorResourceModel::getAttributeProperty(const std::string &key,
+        SimulatorResourceModel::AttributeProperty &property)
+{
+    if (m_attrProperties.end() != m_attrProperties.find(key))
+    {
+        property = m_attrProperties[key];
+        return true;
     }
 
-    // Check the value in allowed range
-    range_validation visitor(*this);
-    return boost::apply_visitor(visitor, attribute.getValue());
+    return false;
 }
 
-std::vector<SimulatorResourceModel::Attribute::ValueVariant>
-SimulatorResourceModel::Attribute::getAllowedValues() const
+int SimulatorResourceModel::size() const
 {
-    return m_allowedValues.getValues();
+    return m_attributes.size();
 }
 
-bool SimulatorResourceModel::getAttribute(const std::string &attrName, Attribute &value)
+SimulatorResourceModel::TypeInfo SimulatorResourceModel::getType(const std::string &key)
 {
-    if (m_attributes.end() != m_attributes.find(attrName))
+    if (m_attributes.end() != m_attributes.find(key))
     {
-        value = m_attributes[attrName];
-        return true;
+        return getTypeInfo(m_attributes.find(key)->second);
     }
 
-    return false;
+    return SimulatorResourceModel::TypeInfo();
 }
 
-std::map<std::string, SimulatorResourceModel::Attribute> SimulatorResourceModel::getAttributes()
+SimulatorResourceModel::TypeInfo SimulatorResourceModel::getTypeInfo(const ValueVariant &value)
+const
+{
+    AttributeTypeVisitor typeVisitor;
+    boost::apply_visitor(typeVisitor, value);
+    SimulatorResourceModel::TypeInfo typeInfo(typeVisitor.m_type, typeVisitor.m_baseType,
+            typeVisitor.m_depth);
+    return typeInfo;
+}
+
+std::map<std::string, SimulatorResourceModel::ValueVariant> SimulatorResourceModel::getValues()
 const
 {
     return m_attributes;
 }
 
-void SimulatorResourceModel::addAttribute(const SimulatorResourceModel::Attribute &attribute, bool overwrite)
+std::map<std::string, SimulatorResourceModel::Attribute> SimulatorResourceModel::getAttributes()
 {
-    if (!attribute.getName().empty() &&
-        (m_attributes.end() == m_attributes.find(attribute.getName()) || overwrite))
+    std::map<std::string, SimulatorResourceModel::Attribute> attributes;
+    for (auto &element : m_attributes)
     {
-        m_attributes[attribute.getName()] = attribute;
+        SimulatorResourceModel::Attribute attribute(element.first);
+        attribute.setValue(element.second);
+
+        if (m_attrProperties.end() != m_attrProperties.find(element.first))
+            attribute.setProperty(m_attrProperties[element.first]);
+
+        attributes[element.first] = attribute;
     }
+
+    return attributes;
 }
 
-void SimulatorResourceModel::setRange(const std::string &attrName, const int min, const int max)
+bool SimulatorResourceModel::getAttribute(const std::string &key,
+        SimulatorResourceModel::Attribute &attribute)
 {
-    if (m_attributes.end() != m_attributes.find(attrName))
-        m_attributes[attrName].setRange(min, max);
+    if (m_attributes.end() != m_attributes.find(key))
+    {
+        attribute.setName(m_attributes.find(key)->first);
+        attribute.setValue(m_attributes.find(key)->second);
+
+        if (m_attrProperties.end() != m_attrProperties.find(key))
+            attribute.setProperty(m_attrProperties[key]);
+
+        return true;
+    }
+
+    return false;
 }
 
-void SimulatorResourceModel::setUpdateInterval(const std::string &attrName, int interval)
+bool SimulatorResourceModel::removeAttribute(const std::string &key)
 {
-    if (m_attributes.end() != m_attributes.find(attrName))
-        m_attributes[attrName].setUpdateFrequencyTime(interval);
+    if (m_attributes.end() == m_attributes.find(key))
+    {
+        return false;
+    }
+
+    m_attributes.erase(m_attributes.find(key));
+    return true;
 }
 
-void SimulatorResourceModel::updateAttributeFromAllowedValues(const std::string &attrName,
-        unsigned int index)
+bool SimulatorResourceModel::update(OC::OCRepresentation &ocRep)
 {
-    if (m_attributes.end() != m_attributes.find(attrName))
-        m_attributes[attrName].setFromAllowedValue(index);
+    SimulatorResourceModel resModel = SimulatorResourceModel::build(ocRep);
+    return update(resModel);
 }
 
-void SimulatorResourceModel::removeAttribute(const std::string &attrName)
+OC::OCRepresentation SimulatorResourceModel::getOCRepresentation()
 {
-   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!");
-   }
+    OCRepresentationBuilder ocRepBuilder;
+    return ocRepBuilder.build(*this);
+}
 
-    m_attributes.erase(attrName);
-    return;
+SimulatorResourceModel SimulatorResourceModel::build(const OC::OCRepresentation &ocRep)
+{
+    SimulatorResourceModelBuilder resModelBuilder;
+    return resModelBuilder.build(ocRep);
 }
 
-OC::OCRepresentation SimulatorResourceModel::getOCRepresentation() const
+bool SimulatorResourceModel::update(SimulatorResourceModel &resModel)
 {
-    OC::OCRepresentation rep;
-    for (auto & attribute : m_attributes)
+    if (false == match(resModel))
+    {
+        return false;
+    }
+
+    for (auto &element : resModel.getValues())
     {
-        (attribute.second).addValuetoRepresentation(rep, attribute.first);
+        if (m_attributes.end() != m_attributes.find(element.first))
+        {
+            m_attributes[element.first] = element.second;
+        }
     }
 
-    return rep;
+    return true;
 }
 
-bool SimulatorResourceModel::update(OC::OCRepresentation &ocRep)
+bool SimulatorResourceModel::setAttributeValue(const std::string &key,
+        const ValueVariant &newValue, bool create, bool overwrite)
 {
-    if (0 == ocRep.size())
-        return true;
+    if (key.empty())
+    {
+        OC_LOG(ERROR, TAG, "key is empty!");
+        return false;
+    }
 
-    // Convert OCRepresentation to SimulatorResourceModel
-    SimulatorResourceModelSP resModel = create(ocRep);
+    /*
+     *   Add new entry to attributes map table if key doest not exist,
+     *   othewise check the value update policy before setting value.
+     */
+    if (m_attributes.end() == m_attributes.find(key) && create)
+    {
+        m_attributes[key] = newValue;
+    }
+    else
+    {
+        if (true == match(key, newValue))
+        {
+            m_attributes[key] = newValue;
+        }
+        else if (overwrite)
+        {
+            m_attributes[key] = newValue;
+            m_attrProperties.erase(m_attrProperties.find(key));
+        }
+        else
+        {
+            return false;
+        }
+    }
 
-    return update(resModel);
+    return true;
 }
 
-bool SimulatorResourceModel::update(SimulatorResourceModelSP &repModel)
+bool SimulatorResourceModel::match(const std::string &key,
+                                   const SimulatorResourceModel::ValueVariant &newValue)
 {
-    std::map<std::string, SimulatorResourceModel::Attribute> attributes = repModel->getAttributes();
-    for (auto & attributeItem : attributes)
+    if (m_attributes.end() != m_attributes.find(key))
     {
-        // Check the attribute presence
-        SimulatorResourceModel::Attribute attribute;
-        if (false == getAttribute((attributeItem.second).getName(), attribute))
+        // Check the type of values
+        if (getTypeInfo(m_attributes[key]) != getTypeInfo(newValue))
         {
             return false;
         }
 
-        // Check the validity of the value to be set
-        if (false == attribute.compare(attributeItem.second))
+        // Check the value based on attribute property
+        SimulatorResourceModel::AttributeProperty prop;
+        if (getAttributeProperty(key, prop)
+            && SimulatorResourceModel::AttributeProperty::Type::UNKNOWN != prop.type())
         {
-            return false;
+            RangeValidator rangeValidator(prop);
+            return boost::apply_visitor(rangeValidator, newValue);
         }
-        m_attributes[(attributeItem.second).getName()].setValue((attributeItem.second).getValue());
+
+        return true;
     }
 
-    return true;
+    return false;
 }
 
-SimulatorResourceModelSP SimulatorResourceModel::create(const OC::OCRepresentation &ocRep)
+bool SimulatorResourceModel::match(const SimulatorResourceModel &resModel, bool strict)
 {
-    SimulatorResourceModelSP resModel(new SimulatorResourceModel);
-    for (auto & attributeItem : ocRep)
+    for (auto &element : resModel.getValues())
     {
-        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;
+        // Attribute presence check
+        if (m_attributes.end() == m_attributes.find(element.first) && !strict)
+        {
+            continue;
+        }
+        else if (strict)
+        {
+            return false;
+        }
+
+        // Attribute value type check
+        if (getTypeInfo(m_attributes[element.first]) != getTypeInfo(element.second))
+        {
+            return false;
+        }
+
+        SimulatorResourceModel::AttributeProperty prop;
+        if (getAttributeProperty(element.first, prop)
+            && SimulatorResourceModel::AttributeProperty::Type::UNKNOWN != prop.type())
+        {
+            RangeValidator rangeValidator(prop);
+            return boost::apply_visitor(rangeValidator, element.second);
+        }
     }
-    return resModel;
+
+    return true;
 }
 
+std::string SimulatorResourceModel::toString() const
+{
+    return ToStringConverter().getStringRepresentation(*this);
+}
index 08ca59f5b89c4197bd4a2fd805faa9ec439cd2b1..042f1566ba92d78c2d488fd4ba2297916ee52e6c 100644 (file)
 
 std::string getPayloadString(const OC::OCRepresentation &rep)
 {
-    std::ostringstream data;
     OCRepPayload *payload = rep.getPayload();
     if (!payload)
     {
-        return "Payload: No payload";
+        return "Empty payload";
     }
+    std::ostringstream data;
+    std::ostringstream dummy;
 
-    // URI
-    data << "URI: " << payload->uri << std::endl;
+    std::string payloadType;
+    OCStringLL *types;
+    OCStringLL *interfaces;
+    OCRepPayloadValue *values;
 
-    // Attributes
-    data << "Attributes:" << std::endl;
-    OCRepPayloadValue *values = payload->values;
-    while (NULL != values)
+    // Iterate the payload list
+    while (payload)
     {
-        data << values->name << ":" << rep.getValueToString(values->name) << std::endl;
-        values = values->next;
+        // Payload type
+        payloadType = getPayloadTypeString(payload->base.type);
+        if (!payloadType.empty())
+            data << "Payload type: " << payloadType << std::endl;
+
+        // URI
+        if (NULL != payload->uri && strlen(payload->uri) > 0)
+            data << "URI: " << payload->uri << std::endl;
+
+        // Types
+        types = payload->types;
+        while (types)
+        {
+            if (NULL != types->value && strlen(types->value) > 0)
+            {
+                dummy << types->value;
+                if (types->next)
+                    dummy << ", ";
+            }
+            types = types->next;
+        }
+        if (!dummy.str().empty())
+        {
+            data << "Types: " << dummy.str() << std::endl;
+            dummy.str("");
+        }
+
+        // Interfaces
+        interfaces = payload->interfaces;
+        while (interfaces)
+        {
+            if (NULL != interfaces->value && strlen(interfaces->value) > 0)
+            {
+                dummy << interfaces->value;
+                if (interfaces->next)
+                    dummy << ", ";
+            }
+            interfaces = interfaces->next;
+        }
+        if (!dummy.str().empty())
+        {
+            data << "Interfaces: " << dummy.str() << std::endl;
+            dummy.str("");
+        }
+
+        // Values
+        values = payload->values;
+        while (values)
+        {
+            dummy << "\t" << values->name << ":" << rep.getValueToString(values->name) << std::endl;
+            values = values->next;
+        }
+        if (!dummy.str().empty())
+        {
+            data << "Values:-" << std::endl;
+            data << dummy.str();
+            dummy.str("");
+        }
+        payload = payload->next;
+        if (payload)
+            data << "----------------" << std::endl;
     }
 
     return data.str();
 }
 
+std::string getPayloadTypeString(OCPayloadType type)
+{
+    std::string typeStr;
+    switch (type)
+    {
+        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;
+    }
+    return typeStr;
+}
+
 std::string getRequestString(const std::map<std::string, std::string> &queryParams,
                              const OC::OCRepresentation &rep)
 {
     std::ostringstream data;
-    data << "qp: ";
+    std::ostringstream dummy;
     if (queryParams.size() > 0)
     {
-        for (auto & qp : queryParams)
-            data << qp.second << ",";
+        for (auto &qp : queryParams)
+            dummy << qp.second << ",";
+    }
+    if (!dummy.str().empty())
+    {
+        data << "qp: " << dummy.str() << std::endl;
     }
-
     data << getPayloadString(rep);
     return data.str();
 }
@@ -63,13 +156,16 @@ std::string getRequestString(const std::map<std::string, std::string> &queryPara
 std::string getRequestString(const std::map<std::string, std::string> &queryParams)
 {
     std::ostringstream data;
-    data << "qp: ";
+    std::ostringstream dummy;
     if (queryParams.size() > 0)
     {
-        for (auto & qp : queryParams)
-            data << qp.second << ",";
+        for (auto &qp : queryParams)
+            dummy << qp.second << ",";
+    }
+    if (!dummy.str().empty())
+    {
+        data << "qp: " << dummy.str() << std::endl;
     }
-
     data << "Payload:  No payload";
     return data.str();
-}
\ No newline at end of file
+}
index 23dd47f80ec3f0ae949764619da49098eff5194e..c6fb66e7adf660581644de6a40b9a733ae7fc081 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);
 
+
+#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
\ No newline at end of file
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..766d42f
--- /dev/null
@@ -0,0 +1,181 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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"
+
+#define SLEEP_FOR(X) if (X > 0) std::this_thread::sleep_for(std::chrono::milliseconds(X));
+
+AttributeUpdateAutomation::AttributeUpdateAutomation(int id, SimulatorSingleResource *resource,
+        const SimulatorResourceModel::Attribute &attribute, 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_attributeGen(attribute),
+        m_callback(callback),
+        m_finishedCallback(finishedCallback),
+        m_thread(nullptr)
+{
+    if (m_updateInterval < 0)
+    {
+        m_updateInterval = 0;
+    }
+}
+
+void AttributeUpdateAutomation::start()
+{
+    m_thread = new std::thread(&AttributeUpdateAutomation::updateAttribute, this);
+}
+
+void AttributeUpdateAutomation::stop()
+{
+    m_stopRequested = true;
+    if (m_thread)
+        m_thread->join();
+}
+
+void AttributeUpdateAutomation::updateAttribute()
+{
+    SimulatorSingleResourceImpl *resourceImpl =
+        dynamic_cast<SimulatorSingleResourceImpl *>(m_resource);
+
+    if (!resourceImpl)
+        return;
+
+    do
+    {
+        try
+        {
+            SimulatorResourceModel::Attribute attribute;
+            while (!m_stopRequested && true == m_attributeGen.next(attribute))
+            {
+                if (false == m_resource->updateAttributeValue(attribute))
+                {
+                    OC_LOG_V(ERROR, ATAG, "Failed to update the attribute![%s]", attribute.getName().c_str());
+                    continue;
+                }
+                resourceImpl->notifyApp();
+
+                SLEEP_FOR(m_updateInterval);
+            }
+
+            m_attributeGen.reset();
+        }
+        catch (SimulatorException &e)
+        {
+            break;
+        }
+    }
+    while (!m_stopRequested && 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 through callback
+    if (m_callback)
+        m_callback(m_resource->getURI(), m_id);
+
+    if (m_finishedCallback && !m_stopRequested)
+        m_finishedCallback(m_id);
+}
+
+ResourceUpdateAutomation::ResourceUpdateAutomation(int id, SimulatorSingleResource *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()
+{
+    std::vector<SimulatorResourceModel::Attribute> attributes;
+    for (auto &attributeEntry : m_resource->getResourceModel().getAttributes())
+    {
+        attributes.push_back(attributeEntry.second);
+    }
+
+    if (0 == attributes.size())
+    {
+        OC_LOG(ERROR, RTAG, "Resource has zero attributes!");
+        throw SimulatorException(SIMULATOR_ERROR, "Resource has zero attributes!");
+    }
+
+    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)
+{
+    SimulatorSingleResourceImpl *resourceImpl =
+        dynamic_cast<SimulatorSingleResourceImpl *>(m_resource);
+
+    if (!resourceImpl)
+        return;
+
+    do
+    {
+        AttributeCombinationGen attrCombGen(attributes);
+        SimulatorResourceModel resModel;
+        while (!m_stopRequested && attrCombGen.next(resModel))
+        {
+            for (auto &attributeEntry : resModel.getAttributes())
+            {
+                resourceImpl->updateAttributeValue(attributeEntry.second);
+            }
+
+            resourceImpl->notifyApp();
+            SLEEP_FOR(m_updateInterval);
+        }
+    }
+    while (!m_stopRequested && AutomationType::RECURRENT == m_type);
+
+    // 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/server/resource_update_automation.h b/service/simulator/src/server/resource_update_automation.h
new file mode 100644 (file)
index 0000000..a3dc6d1
--- /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 RESOURCE_UPDATE_AUTOMATION_H_
+#define RESOURCE_UPDATE_AUTOMATION_H_
+
+#include "simulator_single_resource.h"
+#include "attribute_generator.h"
+#include <thread>
+
+class AttributeUpdateAutomation
+{
+    public:
+        AttributeUpdateAutomation(int id, SimulatorSingleResource *resource,
+                                  const SimulatorResourceModel::Attribute &attribute,
+                                  AutomationType type, int interval,
+                                  updateCompleteCallback callback,
+                                  std::function<void (const int)> finishedCallback);
+
+        void start();
+
+        void stop();
+
+    private:
+        void updateAttribute();
+
+        SimulatorSingleResource *m_resource;
+        std::string m_attrName;
+        AutomationType m_type;
+        int m_id;
+        bool m_stopRequested;
+        int m_updateInterval;
+        AttributeGenerator m_attributeGen;
+        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, SimulatorSingleResource *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);
+
+        SimulatorSingleResource *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/server/resource_update_automation_mngr.cpp b/service/simulator/src/server/resource_update_automation_mngr.cpp
new file mode 100644 (file)
index 0000000..1b52c70
--- /dev/null
@@ -0,0 +1,156 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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(SimulatorSingleResource *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(SimulatorSingleResource *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!");
+    }
+
+    // Check the validity of attribute
+    SimulatorResourceModel::Attribute attribute;
+    if (false == resource->getAttribute(attrName, attribute))
+    {
+        OC_LOG_V(ERROR, TAG, "Attribute:%s not present in resource!", attrName.c_str());
+        throw SimulatorException(SIMULATOR_ERROR, "Attribute is not present in resource!");
+    }
+
+    AttributeUpdateAutomationSP attributeAutomation(new AttributeUpdateAutomation(
+                m_id, resource, attribute, 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;
+    }
+}
+
+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..68227fd
--- /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 RESOURCE_UPDATE_AUTOMATION_MNGR_H_
+#define RESOURCE_UPDATE_AUTOMATION_MNGR_H_
+
+#include "simulator_single_resource.h"
+#include "resource_update_automation.h"
+
+class UpdateAutomationMngr
+{
+    public:
+        UpdateAutomationMngr();
+
+        int startResourceAutomation(SimulatorSingleResource *resource,
+                                    AutomationType type, int interval, updateCompleteCallback callback);
+
+        int startAttributeAutomation(SimulatorSingleResource *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/server/simulator_collection_resource_impl.cpp b/service/simulator/src/server/simulator_collection_resource_impl.cpp
new file mode 100644 (file)
index 0000000..ef74e41
--- /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.
+ *
+ ******************************************************************/
+
+#include "simulator_collection_resource_impl.h"
+#include "simulator_utils.h"
+#include "simulator_logger.h"
+#include "logger.h"
+
+#define TAG "SIM_COLLECTION_RESOURCE"
+
+SimulatorCollectionResourceImpl::SimulatorCollectionResourceImpl()
+    :   m_type(SimulatorResource::Type::COLLECTION_RESOURCE),
+        m_interfaces {OC::DEFAULT_INTERFACE, OC::LINK_INTERFACE},
+        m_resourceHandle(NULL)
+{
+    m_property = static_cast<OCResourceProperty>(OC_DISCOVERABLE | OC_OBSERVABLE);
+}
+
+std::string SimulatorCollectionResourceImpl::getName() const
+{
+    return m_name;
+}
+
+SimulatorResource::Type SimulatorCollectionResourceImpl::getType() const
+{
+    return m_type;
+}
+
+std::string SimulatorCollectionResourceImpl::getURI() const
+{
+    return m_uri;
+}
+
+std::string SimulatorCollectionResourceImpl::getResourceType() const
+{
+    return m_resourceType;
+}
+
+std::vector<std::string> SimulatorCollectionResourceImpl::getInterface() const
+{
+    return m_interfaces;
+}
+
+void SimulatorCollectionResourceImpl::setInterface(const std::vector<std::string> &interfaces)
+{
+    m_interfaces = interfaces;
+}
+
+void SimulatorCollectionResourceImpl::setName(const std::string &name)
+{
+    VALIDATE_INPUT(name.empty(), "Name is empty!")
+
+    std::lock_guard<std::recursive_mutex> lock(m_objectLock);
+    if (m_resourceHandle)
+    {
+        throw SimulatorException(SIMULATOR_OPERATION_NOT_ALLOWED,
+                                 "Name can not be set when collection is started!");
+    }
+
+    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 collection 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 collection is started!");
+    }
+
+    m_resourceType = resourceType;
+}
+
+void SimulatorCollectionResourceImpl::addInterface(std::string interfaceType)
+{
+    VALIDATE_INPUT(interfaceType.empty(), "Interface type is empty!")
+
+    if (interfaceType == OC::GROUP_INTERFACE)
+    {
+        throw NoSupportException("Collection resource does not support this interface type!");
+    }
+
+    std::lock_guard<std::recursive_mutex> lock(m_objectLock);
+    if (m_resourceHandle)
+    {
+        throw SimulatorException(SIMULATOR_OPERATION_NOT_ALLOWED,
+                                 "Interface type can not be set when resource is started!");
+    }
+
+    auto found = std::find(m_interfaces.begin(), m_interfaces.end(), interfaceType);
+    if (found != m_interfaces.end())
+        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 (true == state)
+        m_property = static_cast<OCResourceProperty>(m_property | OC_OBSERVABLE);
+    else
+        m_property = static_cast<OCResourceProperty>(m_property ^ OC_OBSERVABLE);
+}
+
+void SimulatorCollectionResourceImpl::setObserverCallback(ObserverCallback callback)
+{
+    VALIDATE_CALLBACK(callback)
+    m_observeCallback = callback;
+}
+
+void SimulatorCollectionResourceImpl::setModelChangeCallback(ResourceModelChangedCallback callback)
+{
+    VALIDATE_CALLBACK(callback)
+    m_modelCallback = callback;
+}
+
+bool SimulatorCollectionResourceImpl::isObservable()
+{
+    return (m_property & OC_OBSERVABLE);
+}
+
+bool SimulatorCollectionResourceImpl::isStarted()
+{
+    return (nullptr != m_resourceHandle);
+}
+
+void SimulatorCollectionResourceImpl::start()
+{
+    std::lock_guard<std::recursive_mutex> lock(m_objectLock);
+    if (m_resourceHandle)
+    {
+        throw SimulatorException(SIMULATOR_ERROR, "Collection already registered!");
+    }
+
+    if (m_uri.empty() || m_resourceType.empty())
+    {
+        throw SimulatorException(SIMULATOR_ERROR, "Found 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)
+        return;
+
+    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;
+}
+
+void SimulatorCollectionResourceImpl::setResourceModel(const SimulatorResourceModel &resModel)
+{
+    std::lock_guard<std::mutex> lock(m_modelLock);
+    m_resModel = resModel;
+}
+
+std::vector<ObserverInfo> SimulatorCollectionResourceImpl::getObserversList()
+{
+    return m_observersList;
+}
+
+void SimulatorCollectionResourceImpl::notify(int id)
+{
+    std::lock_guard<std::recursive_mutex> lock(m_objectLock);
+    if (!m_resourceHandle)
+        return;
+
+    OC::ObservationIds observers {static_cast<OCObservationId>(id)};
+    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(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(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;
+}
+
+OCEntityHandlerResult SimulatorCollectionResourceImpl::handleRequests(
+    std::shared_ptr<OC::OCResourceRequest> request)
+{
+    if (!request)
+        return OC_EH_ERROR;
+
+    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)
+        }
+
+        // Handover the request to appropriate interface handler
+        std::string interfaceType(OC::DEFAULT_INTERFACE);
+        OC::QueryParamsMap queryParams = request->getQueryParameters();
+        if (queryParams.end() != queryParams.find("if"))
+            interfaceType = queryParams["if"];
+
+        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 << "] 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);
+
+            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.getOCRepresentation();
+        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)
+    }
+
+    // TODO: Handle PUT, POST and DELETE requests
+
+    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>)
+{
+    // TODO: Handle this interface
+    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.getOCRepresentation();
+    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(SimulatorResourceSP &resource)
+{
+    std::lock_guard<std::mutex> lock(m_modelLock);
+    if (!m_resModel.containsAttribute("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())
+        {
+            break;
+            found = true;
+        }
+    }
+
+    if (false ==  found)
+    {
+        links.push_back(newLink);
+        m_resModel.updateValue("links", links);
+    }
+}
+
+void SimulatorCollectionResourceImpl::removeLink(std::string uri)
+{
+    std::lock_guard<std::mutex> lock(m_modelLock);
+    if (!m_resModel.containsAttribute("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.updateValue("links", links);
+            break;
+        }
+    }
+}
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 100644 (file)
index 0000000..0b11440
--- /dev/null
@@ -0,0 +1,96 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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"
+
+class SimulatorResourceFactory;
+class SimulatorCollectionResourceImpl : public SimulatorCollectionResource
+{
+    public:
+        friend class SimulatorResourceFactory;
+
+        std::string getName() const;
+        SimulatorResource::Type getType() const;
+        std::string getURI() const;
+        std::string getResourceType() const;
+        std::vector<std::string> getInterface() const;
+        bool isObservable();
+        bool isStarted();
+        SimulatorResourceModel getResourceModel();
+        void setInterface(const std::vector<std::string> &interfaces);
+        void setName(const std::string &name);
+        void setURI(const std::string &uri);
+        void setResourceType(const std::string &resourceType);
+        void addInterface(std::string interfaceType);
+        void setObservable(bool state);
+        void setObserverCallback(ObserverCallback callback);
+        void setModelChangeCallback(ResourceModelChangedCallback callback);
+        void start();
+        void stop();
+        std::vector<ObserverInfo> getObserversList();
+        void notify(int id);
+        void notifyAll();
+
+        std::vector<std::string> getSupportedResources();
+        void addChildResource(SimulatorResourceSP &resource);
+        void removeChildResource(SimulatorResourceSP &resource);
+        void removeChildResource(const std::string &uri);
+        std::vector<SimulatorResourceSP> getChildResources();
+
+        void setResourceModel(const SimulatorResourceModel &resModel);
+
+    private:
+        SimulatorCollectionResourceImpl();
+
+        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);
+        void sendNotification(OC::ObservationIds &observers);
+        void addLink(SimulatorResourceSP &resource);
+        void removeLink(std::string uri);
+
+        SimulatorResource::Type m_type;
+        std::string m_name;
+        std::string m_uri;
+        std::string m_resourceType;
+        std::vector<std::string> m_interfaces;
+
+        std::mutex m_modelLock;
+        SimulatorResourceModel m_resModel;
+        std::recursive_mutex m_objectLock;
+        std::mutex m_childResourcesLock;
+        std::map<std::string, SimulatorResourceSP> m_childResources;
+        std::vector<std::string> m_supportedTypes;
+        std::vector<ObserverInfo> m_observersList;
+        ObserverCallback m_observeCallback;
+        ResourceModelChangedCallback m_modelCallback;
+
+        OCResourceProperty m_property;
+        OCResourceHandle m_resourceHandle;
+};
+
+#endif
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..be3b19c
--- /dev/null
@@ -0,0 +1,429 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_factory.h"
+#include "simulator_single_resource_impl.h"
+#include "simulator_collection_resource_impl.h"
+#include "simulator_logger.h"
+#include "logger.h"
+
+#define TAG "SIM_RESOURCE_FACTORY"
+
+SimulatorResourceFactory *SimulatorResourceFactory::getInstance()
+{
+    static SimulatorResourceFactory s_instance;
+    return &s_instance;
+}
+
+std::shared_ptr<SimulatorResource> SimulatorResourceFactory::createResource(
+    const std::string &configPath)
+{
+    // Parse the RAML file
+    std::shared_ptr<RAML::RamlParser> ramlParser = std::make_shared<RAML::RamlParser>(configPath);
+    RAML::RamlPtr raml = ramlParser->getRamlPtr();
+
+    // Get the first resource model from RAML
+    RAML::RamlResourcePtr ramlResource;
+    if (0 == raml->getResources().size()
+        || nullptr == (ramlResource = raml->getResources().begin()->second))
+    {
+        OC_LOG(ERROR, TAG, "Zero resources detected from RAML!");
+        return nullptr;
+    }
+
+    return buildResource(ramlResource);
+}
+
+std::vector<std::shared_ptr<SimulatorResource> > SimulatorResourceFactory::createResource(
+    const std::string &configPath, unsigned int count)
+{
+    std::vector<std::shared_ptr<SimulatorResource>> resources;
+
+    // Parse the RAML file
+    std::shared_ptr<RAML::RamlParser> ramlParser = std::make_shared<RAML::RamlParser>(configPath);
+    RAML::RamlPtr raml = ramlParser->getRamlPtr();
+
+    // Get the first resource model from RAML
+    RAML::RamlResourcePtr ramlResource;
+    if (0 == raml->getResources().size()
+        || nullptr == (ramlResource = raml->getResources().begin()->second))
+    {
+        OC_LOG(ERROR, TAG, "Zero resources detected from RAML!");
+        return resources;
+    }
+
+    while (count--)
+    {
+        std::shared_ptr<SimulatorResource> resource = buildResource(ramlResource);
+        if (!resource)
+        {
+            OC_LOG(ERROR, TAG, "Failed to create resource!");
+            return resources;
+        }
+
+        resources.push_back(resource);
+    }
+
+    return resources;
+}
+
+std::shared_ptr<SimulatorSingleResource> SimulatorResourceFactory::createSingleResource(
+    const std::string &name, const std::string &uri, const std::string &resourceType)
+{
+    SimulatorSingleResourceImpl *simpleResource = new SimulatorSingleResourceImpl();
+    simpleResource->setName(name);
+    simpleResource->setURI(uri);
+    simpleResource->setResourceType(resourceType);
+    return std::shared_ptr<SimulatorSingleResource>(simpleResource);
+}
+
+std::shared_ptr<SimulatorCollectionResource> SimulatorResourceFactory::createCollectionResource(
+    const std::string &name, const std::string &uri, const std::string &resourceType)
+{
+    SimulatorCollectionResourceImpl *collectionResource = new SimulatorCollectionResourceImpl();
+    collectionResource->setName(name);
+    collectionResource->setURI(uri);
+    collectionResource->setResourceType(resourceType);
+    return std::shared_ptr<SimulatorCollectionResource>(collectionResource);
+}
+
+SimulatorResourceModel::Attribute SimulatorResourceFactory::buildAttribute(
+    std::shared_ptr<RAML::Properties> propertyElement)
+{
+    std::string propName = propertyElement->getName();
+
+    // Build representation attribute
+    SimulatorResourceModel::Attribute attribute(propName);
+    switch (propertyElement->getVariantType())
+    {
+        case RAML::VariantType::INT:
+            {
+                attribute.setValue(propertyElement->getValue<int>());
+
+                // Convert suppoted values
+                std::vector<int> allowedValues = propertyElement->getAllowedValuesInt();
+                if (allowedValues.size() > 0)
+                {
+                    SimulatorResourceModel::AttributeProperty attrProp(allowedValues);
+                    attribute.setProperty(attrProp);
+                }
+            }
+            break;
+
+        case RAML::VariantType::DOUBLE:
+            {
+                attribute.setValue(propertyElement->getValue<double>());
+
+                // Convert suppoted values
+                std::vector<double> allowedValues = propertyElement->getAllowedValuesDouble();
+                if (allowedValues.size() > 0)
+                {
+                    SimulatorResourceModel::AttributeProperty attrProp(allowedValues);
+                    attribute.setProperty(attrProp);
+                }
+            }
+            break;
+
+        case RAML::VariantType::BOOL:
+            {
+                attribute.setValue(propertyElement->getValue<bool>());
+
+                std::vector<bool> allowedValues = {true, false};
+                SimulatorResourceModel::AttributeProperty attrProp(allowedValues);
+                attribute.setProperty(attrProp);
+            }
+            break;
+
+        case RAML::VariantType::STRING:
+            {
+                attribute.setValue(propertyElement->getValue<std::string>());
+
+                // Convert suppoted values
+                std::vector<std::string> allowedValues = propertyElement->getAllowedValuesString();
+                if (allowedValues.size() > 0)
+                {
+                    SimulatorResourceModel::AttributeProperty attrProp(allowedValues);
+                    attribute.setProperty(attrProp);
+                }
+            }
+            break;
+    }
+
+    // Set the range property if its present
+    double min, max;
+    int multipleof;
+    propertyElement->getRange(min, max, multipleof);
+    if (min != INT_MIN && max != INT_MAX)
+    {
+        SimulatorResourceModel::AttributeProperty attrProp(min, max);
+        attribute.setProperty(attrProp);
+    }
+    return attribute;
+}
+
+SimulatorResourceModel SimulatorResourceFactory::buildResourceModel(
+    std::shared_ptr<RAML::Items> item)
+{
+    SimulatorResourceModel itemModel;
+    for ( auto &propElement : item->getProperties())
+    {
+        if (!propElement.second)
+            continue;
+
+        std::string propName = propElement.second->getName();
+        if ("p" == propName || "n" == propName || "id" == propName)
+        {
+            continue;
+        }
+
+        if ("array" == propElement.second->getType())
+        {
+            std::vector<SimulatorResourceModel> arrayResModel;
+            for ( auto &propertyItem : propElement.second->getItems())
+            {
+                arrayResModel.push_back(buildResourceModel(propertyItem));
+            }
+            itemModel.add(propName, arrayResModel);
+        }
+        else
+        {
+            itemModel.add(buildAttribute(propElement.second));
+        }
+    }
+    return itemModel;
+}
+
+RAML::RequestResponseBodyPtr SimulatorResourceFactory::getRAMLResponseBody(
+    std::shared_ptr<RAML::RamlResource> ramlResource, RAML::ActionType type, std::string responseCode)
+{
+    // Get the resource representation schema from response body
+    RAML::ActionPtr action = ramlResource->getAction(type);
+    if (!action)
+    {
+        OC_LOG(ERROR, TAG, "Resource does not possess the request!");
+        return nullptr;
+    }
+
+    RAML::ResponsePtr response = action->getResponse(responseCode);
+    if (!response)
+    {
+        OC_LOG(ERROR, TAG, "Resource does not provide valid GET response!");
+        return nullptr;
+    }
+
+    RAML::RequestResponseBodyPtr responseBody = response->getResponseBody("application/json");
+    if (!responseBody)
+    {
+        OC_LOG(ERROR, TAG, "GET response is not of type \"application/json\" ");
+        return nullptr;
+    }
+
+    return responseBody;
+}
+
+SimulatorResourceModel SimulatorResourceFactory::buildModelFromResponseBody(
+    RAML::RequestResponseBodyPtr responseBody, std::string &resourceType, std::vector<std::string> &interfaceType)
+{
+    SimulatorResourceModel resModel;
+
+    if (!responseBody)
+        return resModel;
+
+    // Iterate throgh all resource property and extract information needed for simulating resource.
+    RAML::JsonSchemaPtr resourceProperties = responseBody->getSchema()->getProperties();
+
+
+    for ( auto &propertyElement : resourceProperties->getProperties())
+    {
+        if (!propertyElement.second)
+            continue;
+
+        std::string propName = propertyElement.second->getName();
+
+        // Resource type
+        if ("rt" == propName || "resourceType" == propName)
+        {
+            resourceType = propertyElement.second->getValueString();
+            continue;
+        }
+
+        // Interface type
+        if ("if" == propName)
+        {
+            if ("string" == propertyElement.second->getType())
+            {
+                interfaceType.push_back(propertyElement.second->getValueString());
+            }
+            else if ("array" == propertyElement.second->getType())
+            {
+                for (auto &item : propertyElement.second->getItems())
+                {
+                    if ("string" == item->getType())
+                    {
+                        interfaceType = item->getAllowedValuesString();
+                        break;
+                    }
+                }
+            }
+            continue;
+        }
+
+        // Other Standard properties which should not be part of resource model
+        if ("p" == propName || "n" == propName || "id" == propName)
+        {
+            continue;
+        }
+
+        // Add the attribute to resource model
+        if ("array" == propertyElement.second->getType())
+        {
+            std::vector<SimulatorResourceModel> arrayResModel;
+            for ( auto &propertyItem : propertyElement.second->getItems())
+            {
+                arrayResModel.push_back(buildResourceModel(propertyItem));
+            }
+            resModel.add(propName, arrayResModel);
+        }
+        else
+        {
+            resModel.add(buildAttribute(propertyElement.second));
+        }
+    }
+
+    if ("array" == resourceProperties->getType())
+    {
+        std::vector<SimulatorResourceModel> arrayResModel;
+        for ( auto &propertyItem : resourceProperties->getItems())
+        {
+            arrayResModel.push_back(buildResourceModel(propertyItem));
+        }
+        resModel.add("links", arrayResModel);
+    }
+
+    return resModel;
+}
+
+std::shared_ptr<SimulatorResource> SimulatorResourceFactory::buildResource(
+    std::shared_ptr<RAML::RamlResource> ramlResource)
+{
+    std::string name;
+    std::string uri;
+    std::string resourceType, rt;
+    std::vector<std::string> interfaceType, ifType;
+
+    name = ramlResource->getDisplayName();
+    uri = ramlResource->getResourceUri();
+
+    RAML::RequestResponseBodyPtr successResponseBody = getRAMLResponseBody(
+        ramlResource, RAML::ActionType::GET, "200");
+    RAML::RequestResponseBodyPtr putErrorResponseBody = getRAMLResponseBody(
+        ramlResource, RAML::ActionType::PUT, "403");
+    RAML::RequestResponseBodyPtr postErrorResponseBody = getRAMLResponseBody(
+        ramlResource, RAML::ActionType::POST, "403");
+
+    SimulatorResourceModel successResponseModel = buildModelFromResponseBody(
+        successResponseBody, resourceType, interfaceType);
+    SimulatorResourceModel putErrorResponseModel = buildModelFromResponseBody(
+        putErrorResponseBody, rt, ifType);
+    SimulatorResourceModel postErrorResponseModel = buildModelFromResponseBody(
+        postErrorResponseBody, rt, ifType);
+
+    // Create simple/collection resource
+    std::shared_ptr<SimulatorResource> simResource;
+    if (successResponseModel.containsAttribute("links"))
+    {
+        try
+        {
+            std::shared_ptr<SimulatorCollectionResourceImpl> collectionRes(
+                new SimulatorCollectionResourceImpl());
+
+            collectionRes->setName(name);
+            collectionRes->setResourceType(resourceType);
+            collectionRes->setInterface(interfaceType);
+            collectionRes->setURI(ResourceURIFactory::getInstance()->constructURI(uri));
+
+            collectionRes->setResourceModel(successResponseModel);
+            simResource = std::dynamic_pointer_cast<SimulatorResource>(collectionRes);
+        }
+        catch (InvalidArgsException &e) {}
+    }
+    else
+    {
+        try
+        {
+            std::shared_ptr<SimulatorSingleResourceImpl> singleRes(
+                new SimulatorSingleResourceImpl());
+
+            singleRes->setName(name);
+            singleRes->setResourceType(resourceType);
+            singleRes->setInterface(interfaceType);
+            singleRes->setURI(ResourceURIFactory::getInstance()->constructURI(uri));
+
+            singleRes->setResourceModel(successResponseModel);
+            singleRes->setPutErrorResponseModel(putErrorResponseModel);
+            singleRes->setPostErrorResponseModel(postErrorResponseModel);
+
+            simResource = std::dynamic_pointer_cast<SimulatorResource>(singleRes);
+        }
+        catch (InvalidArgsException &e) {}
+    }
+
+    return simResource;
+}
+
+ResourceURIFactory *ResourceURIFactory::getInstance()
+{
+    static ResourceURIFactory s_instance;
+    return &s_instance;
+}
+
+ResourceURIFactory::ResourceURIFactory()
+    : m_id(0) {}
+
+std::string ResourceURIFactory::constructURI(const std::string &uri)
+{
+    std::lock_guard<std::mutex> lock(m_lock);
+    if (isUnique(uri))
+    {
+        updateUri(uri);
+        return uri;
+    }
+    std::ostringstream os;
+    os << uri;
+    if (!uri.empty() && '/' != uri[uri.length() - 1])
+        os << '/';
+    os << m_id++;
+    updateUri(os.str());
+    return os.str();
+}
+
+void ResourceURIFactory::updateUri(const std::string &uri)
+{
+    m_uriList.insert(std::pair<std::string, bool>(uri, true));
+}
+
+bool ResourceURIFactory::isUnique(const std::string &uri)
+{
+    if (m_uriList.end() == m_uriList.find(uri))
+        return true;
+    else
+        return false;
+}
+
diff --git a/service/simulator/src/server/simulator_resource_factory.h b/service/simulator/src/server/simulator_resource_factory.h
new file mode 100644 (file)
index 0000000..242385e
--- /dev/null
@@ -0,0 +1,142 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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 Items;
+}
+
+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:
+        SimulatorResourceModel::Attribute buildAttribute(
+            std::shared_ptr<RAML::Properties> propertyElement);
+        SimulatorResourceModel buildResourceModel(std::shared_ptr<RAML::Items> item);
+        SimulatorResourceModel buildModelFromResponseBody(
+            RAML::RequestResponseBodyPtr responseBody, std::string &resourceType, std::vector<std::string> &interfaceType);
+        RAML::RequestResponseBodyPtr getRAMLResponseBody(
+            std::shared_ptr<RAML::RamlResource> ramlResource, RAML::ActionType type, std::string responseCode);
+        std::shared_ptr<SimulatorResource> buildResource(
+            std::shared_ptr<RAML::RamlResource> ramlResource);
+
+        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 constructURI(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 100644 (file)
index 0000000..5d5df1d
--- /dev/null
@@ -0,0 +1,598 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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 "simulator_logger.h"
+#include "logger.h"
+
+#define TAG "SIM_SINGLE_RESOURCE"
+
+SimulatorSingleResourceImpl::SimulatorSingleResourceImpl()
+    :   m_type(SimulatorResource::Type::SINGLE_RESOURCE),
+        m_interfaces {OC::DEFAULT_INTERFACE},
+        m_resourceHandle(NULL)
+{
+    m_property = static_cast<OCResourceProperty>(OC_DISCOVERABLE | OC_OBSERVABLE);
+}
+
+std::string SimulatorSingleResourceImpl::getName() const
+{
+    return m_name;
+}
+
+SimulatorResource::Type SimulatorSingleResourceImpl::getType() const
+{
+    return m_type;
+}
+
+std::string SimulatorSingleResourceImpl::getURI() const
+{
+    return m_uri;
+}
+
+std::string SimulatorSingleResourceImpl::getResourceType() const
+{
+    return m_resourceType;
+}
+
+std::vector<std::string> SimulatorSingleResourceImpl::getInterface() const
+{
+    return m_interfaces;
+}
+
+void SimulatorSingleResourceImpl::setInterface(const std::vector<std::string> &interfaces)
+{
+    m_interfaces = interfaces;
+}
+
+void SimulatorSingleResourceImpl::setName(const std::string &name)
+{
+    VALIDATE_INPUT(name.empty(), "Name is empty!")
+
+    std::lock_guard<std::recursive_mutex> lock(m_objectLock);
+    if (m_resourceHandle)
+    {
+        throw SimulatorException(SIMULATOR_OPERATION_NOT_ALLOWED,
+                                 "Name can not be set when resource is started!");
+    }
+
+    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 can not be set when resource is started!");
+    }
+
+    m_resourceType = resourceType;
+}
+
+void SimulatorSingleResourceImpl::addInterface(std::string interfaceType)
+{
+    VALIDATE_INPUT(interfaceType.empty(), "Interface type is empty!")
+
+    if (interfaceType == OC::LINK_INTERFACE
+        || interfaceType == OC::BATCH_INTERFACE
+        || interfaceType == OC::GROUP_INTERFACE)
+    {
+        throw NoSupportException("Single type resource does not support this interface!");
+    }
+
+    std::lock_guard<std::recursive_mutex> lock(m_objectLock);
+    if (m_resourceHandle)
+    {
+        throw SimulatorException(SIMULATOR_OPERATION_NOT_ALLOWED,
+                                 "Interface type can not be set when resource is started!");
+    }
+
+    auto found = std::find(m_interfaces.begin(), m_interfaces.end(), interfaceType);
+    if (found != m_interfaces.end())
+        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 (true == state)
+        m_property = static_cast<OCResourceProperty>(m_property | OC_OBSERVABLE);
+    else
+        m_property = static_cast<OCResourceProperty>(m_property ^ OC_OBSERVABLE);
+}
+
+void SimulatorSingleResourceImpl::setObserverCallback(ObserverCallback callback)
+{
+    VALIDATE_CALLBACK(callback)
+    m_observeCallback = callback;
+}
+
+bool SimulatorSingleResourceImpl::isObservable()
+{
+    return (m_property & OC_OBSERVABLE);
+}
+
+bool SimulatorSingleResourceImpl::isStarted()
+{
+    return (nullptr != m_resourceHandle);
+}
+
+void SimulatorSingleResourceImpl::start()
+{
+    std::lock_guard<std::recursive_mutex> lock(m_objectLock);
+    if (m_resourceHandle)
+    {
+        SIM_LOG(ILogger::INFO, "[" << m_name << "] " << "Resource already registered!")
+    }
+
+    if (m_uri.empty() || m_resourceType.empty())
+    {
+        throw SimulatorException(SIMULATOR_ERROR, "Found 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)
+        return;
+
+    typedef OCStackResult (*UnregisterResource)(const OCResourceHandle &);
+
+    invokeocplatform(static_cast<UnregisterResource>(OC::OCPlatform::unregisterResource),
+                     m_resourceHandle);
+
+    m_resourceHandle = nullptr;
+}
+
+std::vector<ObserverInfo> SimulatorSingleResourceImpl::getObserversList()
+{
+    return m_observersList;
+}
+
+void SimulatorSingleResourceImpl::notify(int id, SimulatorResourceModel &resModel)
+{
+    std::lock_guard<std::recursive_mutex> lock(m_objectLock);
+    if (!m_resourceHandle)
+        return;
+
+    std::shared_ptr<OC::OCResourceResponse> resourceResponse =
+    {std::make_shared<OC::OCResourceResponse>()};
+
+    resourceResponse->setErrorCode(200);
+    resourceResponse->setResponseResult(OC_EH_OK);
+    resourceResponse->setResourceRepresentation(resModel.getOCRepresentation(),
+            OC::DEFAULT_INTERFACE);
+
+    OC::ObservationIds observers;
+    observers.push_back(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 SimulatorSingleResourceImpl::notifyAll(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> resourceResponse =
+    {std::make_shared<OC::OCResourceResponse>()};
+
+    resourceResponse->setErrorCode(200);
+    resourceResponse->setResponseResult(OC_EH_OK);
+    resourceResponse->setResourceRepresentation(resModel.getOCRepresentation(),
+            OC::DEFAULT_INTERFACE);
+
+    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, resourceResponse);
+}
+
+void SimulatorSingleResourceImpl::notify(int id)
+{
+    notify(id, m_resModel);
+}
+
+void SimulatorSingleResourceImpl::notifyAll()
+{
+    notifyAll(m_resModel);
+}
+
+bool SimulatorSingleResourceImpl::getAttribute(const std::string &attrName,
+        SimulatorResourceModel::Attribute &attribute)
+{
+    VALIDATE_INPUT(attrName.empty(), "Attribute name is empty!")
+
+    std::lock_guard<std::mutex> lock(m_modelLock);
+    return m_resModel.getAttribute(attrName, attribute);
+}
+
+void SimulatorSingleResourceImpl::addAttribute(const SimulatorResourceModel::Attribute &attribute,
+        bool notify)
+{
+    std::lock_guard<std::mutex> lock(m_modelLock);
+    if (m_resModel.containsAttribute(attribute.getName()))
+        throw SimulatorException(SIMULATOR_ERROR, "Attribute exist with same name!");
+
+    if (!m_resModel.add(attribute))
+        throw SimulatorException(SIMULATOR_ERROR, "Failed to add attribute!");
+
+    if (notify && isStarted())
+        notifyAll();
+}
+
+bool SimulatorSingleResourceImpl::getAttributeProperty(const std::string &attrName,
+        SimulatorResourceModel::AttributeProperty &property)
+{
+    VALIDATE_INPUT(attrName.empty(), "Attribute name is empty!")
+
+    std::lock_guard<std::mutex> lock(m_modelLock);
+    return m_resModel.getAttributeProperty(attrName, property);
+}
+
+bool SimulatorSingleResourceImpl::setAttributeProperty(const std::string &attrName,
+        const SimulatorResourceModel::AttributeProperty &property)
+{
+    VALIDATE_INPUT(attrName.empty(), "Attribute name is empty!")
+
+    std::lock_guard<std::mutex> lock(m_modelLock);
+    return m_resModel.setAttributeProperty(attrName, property);
+}
+
+bool SimulatorSingleResourceImpl::updateAttributeValue(
+    const SimulatorResourceModel::Attribute &attribute,
+    bool notify)
+{
+    std::lock_guard<std::mutex> lock(m_modelLock);
+    if (m_resModel.updateValue(attribute))
+    {
+        if (notify && isStarted())
+            notifyAll();
+        return true;
+    }
+
+    return false;
+}
+
+bool SimulatorSingleResourceImpl::removeAttribute(const std::string &attrName, bool notify)
+{
+    VALIDATE_INPUT(attrName.empty(), "Attribute name is empty!")
+
+    std::lock_guard<std::mutex> lock(m_modelLock);
+    if (m_resModel.removeAttribute(attrName))
+    {
+        if (notify && isStarted())
+            notifyAll();
+        return true;
+    }
+
+    return false;
+}
+
+SimulatorResourceModel SimulatorSingleResourceImpl::getResourceModel()
+{
+    std::lock_guard<std::mutex> lock(m_modelLock);
+    return m_resModel;
+}
+
+void SimulatorSingleResourceImpl::setModelChangeCallback(ResourceModelChangedCallback callback)
+{
+    VALIDATE_CALLBACK(callback)
+    m_modelCallback = callback;
+}
+
+int SimulatorSingleResourceImpl::startResourceUpdation(AutomationType type,
+        int updateInterval, updateCompleteCallback callback)
+{
+    VALIDATE_CALLBACK(callback)
+
+    std::lock_guard<std::recursive_mutex> lock(m_objectLock);
+    if (!m_resourceHandle)
+        throw SimulatorException(SIMULATOR_NO_RESOURCE, "Resource is not registered!");
+
+    return m_updateAutomationMgr.startResourceAutomation(this, type, updateInterval, callback);
+}
+
+int SimulatorSingleResourceImpl::startAttributeUpdation(const std::string &attrName,
+        AutomationType type, int updateInterval, updateCompleteCallback callback)
+{
+    VALIDATE_CALLBACK(callback)
+
+    std::lock_guard<std::recursive_mutex> lock(m_objectLock);
+    if (!m_resourceHandle)
+        throw SimulatorException(SIMULATOR_NO_RESOURCE, "Resource is not registered!");
+
+    return m_updateAutomationMgr.startAttributeAutomation(this, attrName, type,
+            updateInterval, callback);
+}
+
+std::vector<int> SimulatorSingleResourceImpl::getResourceUpdationIds()
+{
+    return m_updateAutomationMgr.getResourceAutomationIds();
+}
+
+std::vector<int> SimulatorSingleResourceImpl::getAttributeUpdationIds()
+{
+    return m_updateAutomationMgr.getAttributeAutomationIds();
+}
+
+void SimulatorSingleResourceImpl::stopUpdation(const int id)
+{
+    m_updateAutomationMgr.stop(id);
+}
+
+void SimulatorSingleResourceImpl::setResourceModel(const SimulatorResourceModel &resModel)
+{
+    std::lock_guard<std::mutex> lock(m_modelLock);
+    m_resModel = resModel;
+}
+
+void SimulatorSingleResourceImpl::setPutErrorResponseModel(const SimulatorResourceModel &resModel)
+{
+    m_putErrorResModel = resModel;
+}
+
+void SimulatorSingleResourceImpl::setPostErrorResponseModel(const SimulatorResourceModel &resModel)
+{
+    m_postErrorResModel = resModel;
+}
+
+void SimulatorSingleResourceImpl::notifyApp(SimulatorResourceModel &resModel)
+{
+    if (m_modelCallback)
+    {
+        m_modelCallback(m_uri, resModel);
+    }
+}
+
+void SimulatorSingleResourceImpl::notifyApp()
+{
+    notifyApp(m_resModel);
+}
+
+bool SimulatorSingleResourceImpl::updateResourceModel(OC::OCRepresentation &ocRep,
+        SimulatorResourceModel &resModel)
+{
+    std::lock_guard<std::mutex> lock(m_modelLock);
+    if (m_resModel.update(ocRep))
+    {
+        resModel = m_resModel;
+        return true;
+    }
+    return false;
+}
+
+OCEntityHandlerResult SimulatorSingleResourceImpl::handleRequests(
+    std::shared_ptr<OC::OCResourceRequest> request)
+{
+    OCEntityHandlerResult errCode = OC_EH_ERROR;
+    if (!request)
+        return OC_EH_ERROR;
+
+    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)
+        }
+
+        // Handover the request to appropriate interface handler
+        std::string interfaceType(OC::DEFAULT_INTERFACE);
+        OC::QueryParamsMap queryParams = request->getQueryParameters();
+        if (queryParams.end() != queryParams.find("if"))
+            interfaceType = queryParams["if"];
+
+        std::shared_ptr<OC::OCResourceResponse> response;
+        if (interfaceType == OC::DEFAULT_INTERFACE)
+        {
+            response = requestOnBaseLineInterface(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 (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);
+
+            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);
+        }
+        errCode = OC_EH_OK;
+    }
+
+    return errCode;
+}
+
+std::shared_ptr<OC::OCResourceResponse> SimulatorSingleResourceImpl::requestOnBaseLineInterface(
+    std::shared_ptr<OC::OCResourceRequest> request)
+{
+    std::shared_ptr<OC::OCResourceResponse> response;
+    if ("GET" == request->getRequestType())
+    {
+        OC::OCRepresentation ocRep = m_resModel.getOCRepresentation();
+        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)
+    }
+    else if ("PUT" == request->getRequestType()
+             || "POST" == request->getRequestType())
+    {
+        OC::OCRepresentation requestRep = request->getResourceRepresentation();
+        SimulatorResourceModel resModel;
+        if (true == updateResourceModel(requestRep, resModel))
+        {
+            notifyAll(resModel);
+            notifyApp(resModel);
+
+            response = std::make_shared<OC::OCResourceResponse>();
+            response->setErrorCode(200);
+            response->setResponseResult(OC_EH_OK);
+            response->setResourceRepresentation(resModel.getOCRepresentation());
+            std::string resPayload = getPayloadString(resModel.getOCRepresentation());
+            SIM_LOG(ILogger::INFO, "[" << m_uri <<
+                    "] Sending response for " << request->getRequestType() << " request. \n**Payload details**" <<
+                    resPayload)
+        }
+        else
+        {
+            response = std::make_shared<OC::OCResourceResponse>();
+            response->setErrorCode(400);
+            response->setResponseResult(OC_EH_ERROR);
+            if ("PUT" == request->getRequestType())
+            {
+                if (m_putErrorResModel.getOCRepresentation().empty())
+                    response->setResourceRepresentation(m_resModel.getOCRepresentation());
+                else
+                    response->setResourceRepresentation(m_putErrorResModel.getOCRepresentation());
+            }
+            else
+            {
+                if (m_postErrorResModel.getOCRepresentation().empty())
+                    response->setResourceRepresentation(m_resModel.getOCRepresentation());
+                else
+                    response->setResourceRepresentation(m_postErrorResModel.getOCRepresentation());
+            }
+        }
+    }
+    else if ("DELETE" == request->getRequestType())
+    {
+        // TODO: Handle this request
+    }
+
+    if (response)
+    {
+        response->setRequestHandle(request->getRequestHandle());
+        response->setResourceHandle(request->getResourceHandle());
+    }
+
+    return response;
+}
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 100644 (file)
index 0000000..6aa6a4a
--- /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.
+ *
+ ******************************************************************/
+
+#ifndef SIMULATOR_SINGLE_RESOURCE_IMPL_H_
+#define SIMULATOR_SINGLE_RESOURCE_IMPL_H_
+
+#include "simulator_single_resource.h"
+#include "resource_update_automation_mngr.h"
+
+class SimulatorResourceFactory;
+class SimulatorSingleResourceImpl : public SimulatorSingleResource
+{
+    public:
+        friend class SimulatorResourceFactory;
+
+        std::string getName() const;
+        SimulatorResource::Type getType() const;
+        std::string getURI() const;
+        std::string getResourceType() const;
+        std::vector<std::string> getInterface() const;
+        void setInterface(const std::vector<std::string> &interfaces);
+        void setName(const std::string &name);
+        void setURI(const std::string &uri);
+        void setResourceType(const std::string &resourceType);
+        void addInterface(std::string interfaceType);
+        void setObservable(bool state);
+        void setObserverCallback(ObserverCallback callback);
+        bool isObservable();
+        bool isStarted();
+        void start();
+        void stop();
+        std::vector<ObserverInfo> getObserversList();
+        void notify(int id);
+        void notifyAll();
+        void notify(int id, SimulatorResourceModel &resModel);
+        void notifyAll(SimulatorResourceModel &resModel);
+
+        bool getAttribute(const std::string &attrName,
+                          SimulatorResourceModel::Attribute &attribute);
+        void addAttribute(const SimulatorResourceModel::Attribute &attribute, bool notify = true);
+        bool getAttributeProperty(const std::string &attrName,
+                                  SimulatorResourceModel::AttributeProperty &property);
+        bool setAttributeProperty(const std::string &attrName,
+                                  const SimulatorResourceModel::AttributeProperty &property);
+        bool updateAttributeValue(const SimulatorResourceModel::Attribute &attribute,
+                                  bool notify = true);
+        bool removeAttribute(const std::string &attrName, bool notify = true);
+        SimulatorResourceModel getResourceModel();
+        void setModelChangeCallback(ResourceModelChangedCallback callback);
+        int startResourceUpdation(AutomationType type, int updateInterval,
+                                  updateCompleteCallback callback);
+        int startAttributeUpdation(const std::string &attrName, AutomationType type,
+                                   int updateInterval, updateCompleteCallback callback);
+        std::vector<int> getResourceUpdationIds();
+        std::vector<int> getAttributeUpdationIds();
+        void stopUpdation(const int id);
+        void setResourceModel(const SimulatorResourceModel &resModel);
+        void setPutErrorResponseModel(const SimulatorResourceModel &resModel);
+        void setPostErrorResponseModel(const SimulatorResourceModel &resModel);
+        void notifyApp();
+        void notifyApp(SimulatorResourceModel &resModel);
+
+    private:
+        SimulatorSingleResourceImpl();
+        OCEntityHandlerResult handleRequests(std::shared_ptr<OC::OCResourceRequest> request);
+        std::shared_ptr<OC::OCResourceResponse> requestOnBaseLineInterface(
+            std::shared_ptr<OC::OCResourceRequest> request);
+        void resourceModified();
+        bool updateResourceModel(OC::OCRepresentation &ocRep, SimulatorResourceModel &resModel);
+
+        SimulatorResource::Type m_type;
+        std::string m_name;
+        std::string m_uri;
+        std::string m_resourceType;
+        std::vector<std::string> m_interfaces;
+
+        std::recursive_mutex m_objectLock;
+        std::mutex m_modelLock;
+        SimulatorResourceModel m_resModel;
+        SimulatorResourceModel m_putErrorResModel;
+        SimulatorResourceModel m_postErrorResModel;
+        ResourceModelChangedCallback m_modelCallback;
+        ObserverCallback m_observeCallback;
+        UpdateAutomationMngr m_updateAutomationMgr;
+        std::vector<ObserverInfo> m_observersList;
+
+        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 38e5269155e064b8bb3639a3bfc69d74316d66ba..001cbb3d90021a526eff625c73ff3a3f653e39d7 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,102 @@ 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 =
+            SimulatorResourceFactory::getInstance()->createResource(configPath);
+    if (!resource)
+        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 =
+            SimulatorResourceFactory::getInstance()->createResource(configPath, count);
+    if (!resources.size())
+        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(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(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;
+
+        SimulatorRemoteResourceSP simulatorResource(new SimulatorRemoteResourceImpl(ocResource));
+        callback(simulatorResource);
+    }, 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;
+
+        SimulatorRemoteResourceSP simulatorResource(new SimulatorRemoteResourceImpl(ocResource));
+        callback(simulatorResource);
+    }, 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)
 {
-    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, DeviceInfoCallback callback)
     {
         std::string deviceName = rep.getValue<std::string>("n");
         std::string deviceID = rep.getValue<std::string>("di");
@@ -99,7 +147,7 @@ void SimulatorManager::getDeviceInfo(DeviceInfoCallback callback)
 
         DeviceInfo deviceInfo(deviceName, deviceID, deviceSpecVersion, deviceDMV);
         callback(deviceInfo);
-    };
+    }, std::placeholders::_1, callback);
 
     std::ostringstream uri;
     uri << OC_MULTICAST_PREFIX << OC_RSRVD_DEVICE_URI;
@@ -108,16 +156,12 @@ void SimulatorManager::getDeviceInfo(DeviceInfoCallback callback)
                                            OCConnectivityType, OC::FindDeviceCallback);
 
     invokeocplatform(static_cast<GetDeviceInfo>(OC::OCPlatform::getDeviceInfo), "",
-                     uri.str(),
-                     CT_DEFAULT,
-                     deviceCallback);
+                     uri.str(), 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);
 
@@ -129,10 +173,10 @@ void SimulatorManager::setDeviceInfo(const std::string &deviceName)
 
 void SimulatorManager::getPlatformInfo(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, PlatformInfoCallback callback)
     {
         PlatformInfo platformInfo;
         platformInfo.setPlatformID(rep.getValue<std::string>("pi"));
@@ -148,7 +192,7 @@ void SimulatorManager::getPlatformInfo(PlatformInfoCallback callback)
         platformInfo.setSystemTime(rep.getValue<std::string>("st"));
 
         callback(platformInfo);
-    };
+    }, std::placeholders::_1, callback);
 
     std::ostringstream uri;
     uri << OC_MULTICAST_PREFIX << OC_RSRVD_PLATFORM_URI;
@@ -157,9 +201,7 @@ void SimulatorManager::getPlatformInfo(PlatformInfoCallback callback)
             OCConnectivityType, OC::FindPlatformCallback);
 
     invokeocplatform(static_cast<GetPlatformInfo>(OC::OCPlatform::getPlatformInfo), "",
-                     uri.str(),
-                     CT_DEFAULT,
-                     platformCallback);
+                     uri.str(), 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..0687158
--- /dev/null
@@ -0,0 +1,1148 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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;
+
+    static {
+        System.loadLibrary("SimulatorManager");
+        System.loadLibrary("RamlParser");
+        System.loadLibrary("oc");
+        System.loadLibrary("oc_logger");
+        System.loadLibrary("octbstack");
+    }
+
+    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 {
+            SimulatorResourceModel resModel = singleResource.getResourceModel();
+            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 {
+            SimulatorResourceModel resModel = singleResource.getResourceModel();
+            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.startObserve(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.startObserve(null, 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.startObserve(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.startObserve(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.VerificationType.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.VerificationType.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.VerificationType.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.VerificationType.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.VerificationType.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..475b708
--- /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.
+ */
+
+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 {
+    static {
+        System.loadLibrary("SimulatorManager");
+        System.loadLibrary("RamlParser");
+        System.loadLibrary("oc");
+        System.loadLibrary("oc_logger");
+        System.loadLibrary("octbstack");
+    }
+
+    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.getChildResource();
+        } 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.getChildResource();
+        } 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.getChildResource();
+        } 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.getChildResource();
+        } 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.getChildResource();
+        } 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.getChildResource();
+        } 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.getChildResource();
+        } 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..33cde70
--- /dev/null
@@ -0,0 +1,419 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.SimulatorException;
+import org.oic.simulator.SimulatorManager;
+import org.oic.simulator.client.FindResourceListener;
+import org.oic.simulator.client.SimulatorRemoteResource;
+import org.oic.simulator.server.SimulatorResource;
+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;
+
+    static {
+        System.loadLibrary("SimulatorManager");
+        System.loadLibrary("RamlParser");
+        System.loadLibrary("oc");
+        System.loadLibrary("oc_logger");
+        System.loadLibrary("octbstack");
+    }
+
+    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 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;
+
+        try {
+            type = resource.getType();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        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 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 testIsObservable_P01() {
+        boolean state = false;
+
+        try {
+            state = resource.isObservable();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertEquals(true, state);
+    }
+
+    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..b6bcc94
--- /dev/null
@@ -0,0 +1,649 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+import org.oic.simulator.AttributeProperty;
+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.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 {
+    static {
+        System.loadLibrary("SimulatorManager");
+        System.loadLibrary("RamlParser");
+        System.loadLibrary("oc");
+        System.loadLibrary("oc_logger");
+        System.loadLibrary("octbstack");
+    }
+
+    private static final String     SINGLE_RES_RAML = "./ramls/oic.r.light.raml";
+    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";
+    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;
+    }
+
+    SimulatorSingleResource createResourceFromRAML() {
+        try {
+            return (SimulatorSingleResource) SimulatorManager
+                    .createResource(SINGLE_RES_RAML);
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        return null;
+    }
+
+    public void testGetResourceModel_P01() {
+        SimulatorResourceModel resModel = null;
+
+        try {
+            SimulatorSingleResource resource = createResourceFromRAML();
+            resModel = resource.getResourceModel();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertNotNull(resModel);
+        assertTrue(resModel.size() > 0);
+    }
+
+    public void testAddAttributeInteger_P01() {
+        int result = -1;
+
+        try {
+            SimulatorResourceAttribute attribute = new SimulatorResourceAttribute(
+                    INT_KEY, new AttributeValue(2), null);
+            singleResource.addAttribute(attribute);
+            result = ((Integer) singleResource.getAttribute(INT_KEY).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 {
+            SimulatorResourceAttribute attribute = new SimulatorResourceAttribute(
+                    DOUBLE_KEY, new AttributeValue(4.0), null);
+            singleResource.addAttribute(attribute);
+            result = ((Double) singleResource.getAttribute(DOUBLE_KEY).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 {
+            SimulatorResourceAttribute attribute = new SimulatorResourceAttribute(
+                    BOOL_KEY, new AttributeValue(true), null);
+            singleResource.addAttribute(attribute);
+            result = ((Boolean) singleResource.getAttribute(BOOL_KEY).value()
+                    .get()).booleanValue();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertEquals(true, result);
+    }
+
+    public void testaddAttributeString_P01() {
+        String result = null;
+
+        try {
+            SimulatorResourceAttribute attribute = new SimulatorResourceAttribute(
+                    STRING_KEY, new AttributeValue("string-value"), null);
+            singleResource.addAttribute(attribute);
+            result = (String) singleResource.getAttribute(STRING_KEY).value()
+                    .get();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertEquals("string-value", result);
+    }
+
+    public void testUpdateAttributeInteger_P01() {
+        int result = -1;
+
+        try {
+            SimulatorResourceAttribute attribute = new SimulatorResourceAttribute(
+                    INT_KEY, new AttributeValue(10), null);
+            singleResource.addAttribute(attribute);
+            singleResource.updateAttribute(INT_KEY, new AttributeValue(12));
+            result = ((Integer) singleResource.getAttribute(INT_KEY).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 {
+            SimulatorResourceAttribute attribute = new SimulatorResourceAttribute(
+                    DOUBLE_KEY, new AttributeValue(22.0), null);
+            singleResource.addAttribute(attribute);
+            singleResource
+                    .updateAttribute(DOUBLE_KEY, new AttributeValue(25.3));
+            result = ((Double) singleResource.getAttribute(DOUBLE_KEY).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 {
+            SimulatorResourceAttribute attribute = new SimulatorResourceAttribute(
+                    BOOL_KEY, new AttributeValue(true), null);
+            singleResource.addAttribute(attribute);
+            singleResource.updateAttribute(BOOL_KEY, new AttributeValue(false));
+            result = ((Boolean) singleResource.getAttribute(BOOL_KEY).value()
+                    .get()).booleanValue();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertEquals(false, result);
+    }
+
+    public void testupdateAttributeString_P01() {
+        String result = null;
+
+        try {
+            SimulatorResourceAttribute attribute = new SimulatorResourceAttribute(
+                    STRING_KEY, new AttributeValue("old-value"), null);
+            singleResource.addAttribute(attribute);
+            singleResource.updateAttribute(STRING_KEY, new AttributeValue(
+                    "new-value"));
+            result = (String) singleResource.getAttribute(STRING_KEY).value()
+                    .get();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertEquals("new-value", result);
+    }
+
+    public void testSetRange_P01() {
+        int result = -1;
+
+        try {
+            SimulatorResourceAttribute attribute = new SimulatorResourceAttribute(
+                    INT_KEY, new AttributeValue(10), new AttributeProperty(1,
+                            12));
+            singleResource.addAttribute(attribute);
+            singleResource.updateAttribute(INT_KEY, new AttributeValue(3));
+            result = ((Integer) singleResource.getAttribute(INT_KEY).value()
+                    .get()).intValue();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertEquals(3, result);
+    }
+
+    public void testSetRange_N01() {
+        int result = -1;
+
+        try {
+            SimulatorResourceAttribute attribute = new SimulatorResourceAttribute(
+                    INT_KEY, new AttributeValue(10), new AttributeProperty(1,
+                            12));
+            singleResource.addAttribute(attribute);
+            singleResource.updateAttribute(INT_KEY, new AttributeValue(13));
+            result = ((Integer) singleResource.getAttribute(INT_KEY).value()
+                    .get()).intValue();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertEquals(10, result);
+    }
+
+    public void testSetAllowedValuesInteger_P01() {
+        int result = -1;
+
+        try {
+            int[] values = { 1, 10, 20, 50 };
+            SimulatorResourceAttribute attribute = new SimulatorResourceAttribute(
+                    INT_KEY, new AttributeValue(10), new AttributeProperty(
+                            values));
+            singleResource.addAttribute(attribute);
+            singleResource.updateAttribute(INT_KEY, new AttributeValue(20));
+            result = ((Integer) singleResource.getAttribute(INT_KEY).value()
+                    .get()).intValue();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertEquals(20, result);
+    }
+
+    public void testSetAllowedValuesInteger_N01() {
+        int result = -1;
+
+        try {
+            int[] values = { 1, 10, 20, 50 };
+            SimulatorResourceAttribute attribute = new SimulatorResourceAttribute(
+                    INT_KEY, new AttributeValue(10), new AttributeProperty(
+                            values));
+            singleResource.addAttribute(attribute);
+            singleResource.updateAttribute(INT_KEY, new AttributeValue(15));
+            result = ((Integer) singleResource.getAttribute(INT_KEY).value()
+                    .get()).intValue();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertEquals(10, result);
+    }
+
+    public void testSetAllowedValuesDouble_P01() {
+        double result = 0.0;
+
+        try {
+            double[] values = { 11.5, 10.5, 20.5, 50.5 };
+            SimulatorResourceAttribute attribute = new SimulatorResourceAttribute(
+                    DOUBLE_KEY, new AttributeValue(11.5),
+                    new AttributeProperty(values));
+            singleResource.addAttribute(attribute);
+            singleResource
+                    .updateAttribute(DOUBLE_KEY, new AttributeValue(10.5));
+            result = ((Double) singleResource.getAttribute(DOUBLE_KEY).value()
+                    .get()).doubleValue();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertEquals(10.5, result);
+    }
+
+    public void testSetAllowedValuesDouble_N01() {
+        double result = 0.0;
+
+        try {
+            double[] values = { 11.5, 10.5, 20.5, 50.5 };
+            SimulatorResourceAttribute attribute = new SimulatorResourceAttribute(
+                    DOUBLE_KEY, new AttributeValue(11.5),
+                    new AttributeProperty(values));
+            singleResource.addAttribute(attribute);
+            singleResource.updateAttribute(DOUBLE_KEY, new AttributeValue(2.2));
+            result = ((Double) singleResource.getAttribute(DOUBLE_KEY).value()
+                    .get()).doubleValue();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertEquals(11.5, result);
+    }
+
+    public void testsetAllowedValuesString_P01() {
+        String result = null;
+
+        try {
+            String[] values = { "monday", "tuesday", "wednesday" };
+            SimulatorResourceAttribute attribute = new SimulatorResourceAttribute(
+                    STRING_KEY, new AttributeValue("monday"),
+                    new AttributeProperty(values));
+            singleResource.addAttribute(attribute);
+            singleResource.updateAttribute(STRING_KEY, new AttributeValue(
+                    "tuesday"));
+            result = (String) singleResource.getAttribute(STRING_KEY).value()
+                    .get();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertEquals("tuesday", result);
+    }
+
+    public void testsetAllowedValuesString_N01() {
+        String result = null;
+
+        try {
+            String[] values = { "monday", "tuesday", "wednesday" };
+            SimulatorResourceAttribute attribute = new SimulatorResourceAttribute(
+                    STRING_KEY, new AttributeValue("monday"),
+                    new AttributeProperty(values));
+            singleResource.addAttribute(attribute);
+            singleResource.updateAttribute(STRING_KEY, new AttributeValue(
+                    "friday"));
+            result = (String) singleResource.getAttribute(STRING_KEY).value()
+                    .get();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        assertEquals("monday", result);
+    }
+
+    public void testRemoveAttribute_P01() {
+        SimulatorResourceAttribute result = null;
+
+        try {
+            SimulatorResourceAttribute attribute = new SimulatorResourceAttribute(
+                    STRING_KEY, new AttributeValue("friday"), null);
+            singleResource.addAttribute(attribute);
+            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 {
+            SimulatorResourceAttribute attribute = new SimulatorResourceAttribute(
+                    STRING_KEY, new AttributeValue("friday"), null);
+            singleResource.addAttribute(attribute);
+            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() {
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
+            singleResource.removeAttribute("");
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
+        }
+
+        assertEquals(ExceptionType.INVALID_ARGS, exType);
+    }
+
+    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(10, TimeUnit.SECONDS);
+            } catch (InterruptedException e) {
+                e.printStackTrace();
+            }
+
+            resource.stopUpdation(id);
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        } catch (SimulatorException e) {
+            e.printStackTrace();
+        }
+
+        try {
+            resource.stop();
+            resource.stopUpdation(id);
+        } 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 (SimulatorResourceAttribute resAttribute : resource
+                    .getResourceModel().getAttributes().values())
+                attributeName = resAttribute.name();
+        } 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, 100,
+                    automationListener);
+
+            try {
+                lockObject.await(10, 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);
+    }
+}
+
+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/AttributeValueTest.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/AttributeValueTest.java
new file mode 100644 (file)
index 0000000..f382716
--- /dev/null
@@ -0,0 +1,478 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.addAttribute(INT_KEY, new AttributeValue(1));
+            model.addAttribute(DOUBLE_KEY, new AttributeValue(1.00));
+            model.addAttribute(BOOL_KEY, new AttributeValue(true));
+            model.addAttribute(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.addAttribute(INT_KEY, new AttributeValue(1));
+            childModel.addAttribute(DOUBLE_KEY, new AttributeValue(1.00));
+            childModel.addAttribute(BOOL_KEY, new AttributeValue(true));
+            childModel.addAttribute(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.addAttribute(INT_KEY, new AttributeValue(1));
+            childModel.addAttribute(DOUBLE_KEY, new AttributeValue(1.00));
+            childModel.addAttribute(BOOL_KEY, new AttributeValue(true));
+            childModel.addAttribute(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.addAttribute(INT_KEY, new AttributeValue(1));
+            childModel.addAttribute(DOUBLE_KEY, new AttributeValue(1.00));
+            childModel.addAttribute(BOOL_KEY, new AttributeValue(true));
+            childModel.addAttribute(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/AttributeValueValidationTest.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/AttributeValueValidationTest.java
new file mode 100644 (file)
index 0000000..96618f4
--- /dev/null
@@ -0,0 +1,253 @@
+package org.oic.simulator.test;
+
+import org.oic.simulator.AttributeProperty;
+import org.oic.simulator.AttributeValue;
+import org.oic.simulator.AttributeValueValidation;
+
+import junit.framework.TestCase;
+
+public class AttributeValueValidationTest extends TestCase {
+    protected void setUp() throws Exception {
+        super.setUp();
+    }
+
+    protected void tearDown() throws Exception {
+        super.tearDown();
+    }
+
+    public void testValidateInt_P01() {
+        AttributeProperty property = new AttributeProperty(1, 10);
+        AttributeValueValidation validation = new AttributeValueValidation(
+                property);
+        assertTrue(validation.validate(new AttributeValue(5)));
+    }
+
+    public void testValidateInt_P02() {
+        int[] valueSet = { 1, 5, 7 };
+        AttributeProperty property = new AttributeProperty(valueSet);
+        AttributeValueValidation validation = new AttributeValueValidation(
+                property);
+        assertTrue(validation.validate(new AttributeValue(5)));
+    }
+
+    public void testValidateInt_N01() {
+        AttributeProperty property = new AttributeProperty(1, 10);
+        AttributeValueValidation validation = new AttributeValueValidation(
+                property);
+        assertFalse(validation.validate(new AttributeValue(15)));
+    }
+
+    public void testValidateInt_N02() {
+        int[] valueSet = { 1, 5, 7 };
+        AttributeProperty property = new AttributeProperty(valueSet);
+        AttributeValueValidation validation = new AttributeValueValidation(
+                property);
+        assertFalse(validation.validate(new AttributeValue(6)));
+    }
+
+    public void testValidateInt_N03() {
+        AttributeValueValidation validation = new AttributeValueValidation(
+                null);
+        assertFalse(validation.validate(new AttributeValue(6)));
+    }
+
+    public void testValidateInt1DArray_P01() {
+        AttributeProperty arrayProp = new AttributeProperty(1, 2);
+        arrayProp.setChildProperty(new AttributeProperty(1, 10));
+
+        int[] value = { 1, 5 };
+        AttributeValueValidation validation = new AttributeValueValidation(
+                arrayProp);
+        assertTrue(validation.validate(new AttributeValue(value)));
+    }
+
+    public void testValidateInt1DArray_N01() {
+        AttributeProperty arrayProp = new AttributeProperty(1, 2);
+        arrayProp.setChildProperty(new AttributeProperty(1, 10));
+
+        int[] value = { 1, 5, 7 };
+        AttributeValueValidation validation = new AttributeValueValidation(
+                arrayProp);
+        assertFalse(validation.validate(new AttributeValue(value)));
+    }
+
+    public void testValidateInt1DArray_N02() {
+        AttributeProperty arrayProp = new AttributeProperty(1, 2);
+        arrayProp.setChildProperty(new AttributeProperty(1, 10));
+
+        int[] value = { 1, 15 };
+        AttributeValueValidation validation = new AttributeValueValidation(
+                arrayProp);
+        assertFalse(validation.validate(new AttributeValue(value)));
+    }
+
+    public void testValidateInt2DArray_P01() {
+        AttributeProperty array1Prop = new AttributeProperty(1, 1);
+        AttributeProperty array2Prop = new AttributeProperty(1, 1);
+        AttributeProperty valueProp = new AttributeProperty(1, 10);
+        array1Prop.setChildProperty(array2Prop);
+        array2Prop.setChildProperty(valueProp);
+
+        int[][] value = { { 1 } };
+        AttributeValueValidation validation = new AttributeValueValidation(
+                array1Prop);
+        assertTrue(validation.validate(new AttributeValue(value)));
+    }
+
+    public void testValidateInt2DArray_N01() {
+        AttributeProperty array1Prop = new AttributeProperty(1, 1);
+        AttributeProperty array2Prop = new AttributeProperty(1, 1);
+        AttributeProperty valueProp = new AttributeProperty(1, 10);
+        array1Prop.setChildProperty(array2Prop);
+        array2Prop.setChildProperty(valueProp);
+
+        int[][] value = { { 1 }, { 2 } };
+        AttributeValueValidation validation = new AttributeValueValidation(
+                array1Prop);
+        assertFalse(validation.validate(new AttributeValue(value)));
+    }
+
+    public void testValidateInt2DArray_N02() {
+        AttributeProperty array1Prop = new AttributeProperty(1, 1);
+        AttributeProperty array2Prop = new AttributeProperty(1, 1);
+        AttributeProperty valueProp = new AttributeProperty(1, 10);
+        array1Prop.setChildProperty(array2Prop);
+        array2Prop.setChildProperty(valueProp);
+
+        int[][] value = { { 1, 2 } };
+        AttributeValueValidation validation = new AttributeValueValidation(
+                array1Prop);
+        assertFalse(validation.validate(new AttributeValue(value)));
+    }
+
+    public void testValidateInt2DArray_N03() {
+        AttributeProperty array1Prop = new AttributeProperty(1, 1);
+        AttributeProperty array2Prop = new AttributeProperty(1, 1);
+        AttributeProperty valueProp = new AttributeProperty(1, 10);
+        array1Prop.setChildProperty(array2Prop);
+        array2Prop.setChildProperty(valueProp);
+
+        int[][] value = { { 15 } };
+        AttributeValueValidation validation = new AttributeValueValidation(
+                array1Prop);
+        assertFalse(validation.validate(new AttributeValue(value)));
+    }
+
+    public void testValidateDouble_P01() {
+        AttributeProperty property = new AttributeProperty(1, 10);
+        AttributeValueValidation validation = new AttributeValueValidation(
+                property);
+        assertTrue(validation.validate(new AttributeValue(5.12)));
+    }
+
+    public void testValidateDouble_P02() {
+        double[] valueSet = { 1.0, 5.12, 7.0 };
+        AttributeProperty property = new AttributeProperty(valueSet);
+        AttributeValueValidation validation = new AttributeValueValidation(
+                property);
+        assertTrue(validation.validate(new AttributeValue(5.12)));
+    }
+
+    public void testValidateDouble_N01() {
+        AttributeProperty property = new AttributeProperty(1, 10);
+        AttributeValueValidation validation = new AttributeValueValidation(
+                property);
+        assertFalse(validation.validate(new AttributeValue(15.23)));
+    }
+
+    public void testValidateDouble_N02() {
+        double[] valueSet = { 1.0, 5.12, 7.0 };
+        AttributeProperty property = new AttributeProperty(valueSet);
+        AttributeValueValidation validation = new AttributeValueValidation(
+                property);
+        assertFalse(validation.validate(new AttributeValue(6.0)));
+    }
+
+    public void testValidateDouble_N03() {
+        AttributeValueValidation validation = new AttributeValueValidation(
+                null);
+        assertFalse(validation.validate(new AttributeValue(6.0)));
+    }
+
+    public void testValidateDouble1DArray_P01() {
+        AttributeProperty arrayProp = new AttributeProperty(1, 2);
+        arrayProp.setChildProperty(new AttributeProperty(1, 10));
+
+        double[] value = { 1.2, 5.2 };
+        AttributeValueValidation validation = new AttributeValueValidation(
+                arrayProp);
+        assertTrue(validation.validate(new AttributeValue(value)));
+    }
+
+    public void testValidateDouble1DArray_N01() {
+        AttributeProperty arrayProp = new AttributeProperty(1, 2);
+        arrayProp.setChildProperty(new AttributeProperty(1, 10));
+
+        double[] value = { 1.2, 5.2, 7.2 };
+        AttributeValueValidation validation = new AttributeValueValidation(
+                arrayProp);
+        assertFalse(validation.validate(new AttributeValue(value)));
+    }
+
+    public void testValidateDouble1DArray_N02() {
+        AttributeProperty arrayProp = new AttributeProperty(1, 2);
+        arrayProp.setChildProperty(new AttributeProperty(1, 10));
+
+        double[] value = { 1.2, 15.2 };
+        AttributeValueValidation validation = new AttributeValueValidation(
+                arrayProp);
+        assertFalse(validation.validate(new AttributeValue(value)));
+    }
+
+    public void testValidateDouble2DArray_P01() {
+        AttributeProperty array1Prop = new AttributeProperty(1, 1);
+        AttributeProperty array2Prop = new AttributeProperty(1, 1);
+        AttributeProperty valueProp = new AttributeProperty(1, 10);
+        array1Prop.setChildProperty(array2Prop);
+        array2Prop.setChildProperty(valueProp);
+
+        double[][] value = { { 1.2 } };
+        AttributeValueValidation validation = new AttributeValueValidation(
+                array1Prop);
+        assertTrue(validation.validate(new AttributeValue(value)));
+    }
+
+    public void testValidateDouble2DArray_N01() {
+        AttributeProperty array1Prop = new AttributeProperty(1, 1);
+        AttributeProperty array2Prop = new AttributeProperty(1, 1);
+        AttributeProperty valueProp = new AttributeProperty(1, 10);
+        array1Prop.setChildProperty(array2Prop);
+        array2Prop.setChildProperty(valueProp);
+
+        double[][] value = { { 1.2 }, { 2.2 } };
+        AttributeValueValidation validation = new AttributeValueValidation(
+                array1Prop);
+        assertFalse(validation.validate(new AttributeValue(value)));
+    }
+
+    public void testValidateDouble2DArray_N02() {
+        AttributeProperty array1Prop = new AttributeProperty(1, 1);
+        AttributeProperty array2Prop = new AttributeProperty(1, 1);
+        AttributeProperty valueProp = new AttributeProperty(1, 10);
+        array1Prop.setChildProperty(array2Prop);
+        array2Prop.setChildProperty(valueProp);
+
+        double[][] value = { { 1.2, 2.2 } };
+        AttributeValueValidation validation = new AttributeValueValidation(
+                array1Prop);
+        assertFalse(validation.validate(new AttributeValue(value)));
+    }
+
+    public void testValidateDouble2DArray_N03() {
+        AttributeProperty array1Prop = new AttributeProperty(1, 1);
+        AttributeProperty array2Prop = new AttributeProperty(1, 1);
+        AttributeProperty valueProp = new AttributeProperty(1, 10);
+        array1Prop.setChildProperty(array2Prop);
+        array2Prop.setChildProperty(valueProp);
+
+        double[][] value = { { 15.2 } };
+        AttributeValueValidation validation = new AttributeValueValidation(
+                array1Prop);
+        assertFalse(validation.validate(new AttributeValue(value)));
+    }
+}
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/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 7fb25db73aead8d52be9dfa7fe2e3633789cb016..c63170a744d9464d04be80c5e3cb7fddc469f209 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;
+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";
 
-
-    static
-    {
+    static {
         System.loadLibrary("SimulatorManager");
+        System.loadLibrary("RamlParser");
+        System.loadLibrary("oc");
+        System.loadLibrary("oc_logger");
+        System.loadLibrary("octbstack");
     }
 
     @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 = "";
+            SimulatorResource resource = 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 {
+            SimulatorResource resource = 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 = "";
+            Vector<SimulatorResource> resource = 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 {
+            Vector<SimulatorResource> resource = 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 {
+            Vector<SimulatorResource> resource = 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 {
+            Vector<SimulatorResource> resource = 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";
+
+            SimulatorResource 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";
+
+            SimulatorResource 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;
+
+        try {
+            String name = "test-resource";
+            String uri = "";
+            String resourceType = "test.resource";
 
-        SimulatorResourceServer[] simulatorResourceServers = createResources(count);
+            SimulatorResource 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);
+        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);
+            SimulatorResource 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  );
+        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;
+            SimulatorResource resource = 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]);
-        }
-        catch (Exception e)
-        {
-            result = false;
+            SimulatorResource resource = SimulatorManager.createResource(
+                    SimulatorResource.Type.SINGLE, name, uri, resourceType);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
         }
 
-        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;
+
+        try {
+            String resourceType = "test.singleresource";
+            SimulatorManager.findResource(resourceType, null);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
+        }
 
-        SimulatorResourceServer simulatorResourceServer = createResource();
+        assertTrue(exType == ExceptionType.INVALID_ARGS);
+    }
 
-        SimulatorRemoteResourceObject simulatorRemoteResource = new SimulatorRemoteResourceObject();
+    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);
+    }
 
-        FindResourceListener findResourceListener = new FindResourceListener(lockObject, simulatorRemoteResource);
+    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);
+    }
 
-        try
-        {
-            SimulatorManager.findResource(findResourceListener);
-        }
-        catch (Exception e)
-        {
-            result = false;
+    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());
+    }
 
-        try
-        {
+    public void testFindResourceAll_N01() {
+        ExceptionType exType = ExceptionType.UNKNOWN;
+
+        try {
             SimulatorManager.findResource(null);
-            result = false;
-        }
-        catch (Exception e)
-        {
-            result = true;
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
         }
 
-        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(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;
 
-        SimulatorManager.setPlatformInfo(platformInfo);
+        try {
+            SimulatorManager.findDevices(null);
+        } catch (InvalidArgsException e) {
+            exType = ExceptionType.INVALID_ARGS;
+        } catch (SimulatorException e) {
+            exType = ExceptionType.SIMULATOR;
+        }
+
+        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(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);
+        } 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(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(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 2748e09eba4ba356e3c0f22a91cda1572a3a00fd..76ae00eed3b7d0a9699cabb50dd2f4ba5db2dd8e 100644 (file)
@@ -18,317 +18,234 @@ package org.oic.simulator.test;
 
 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.SimulatorResourceAttribute;
 import org.oic.simulator.SimulatorResourceModel;
 
+import junit.framework.TestCase;
+
 /**
- * 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 testAddAttributeInt_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;
+        SimulatorResourceModel resModel = new SimulatorResourceModel();
+        SimulatorResourceAttribute attribute = new SimulatorResourceAttribute(
+                INT_KEY, new AttributeValue(10), null);
+        try {
+            resModel.addAttribute(attribute);
+            result = ((Integer) resModel.getAttribute(INT_KEY).value().get())
+                    .intValue();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
         }
 
-        assertTrue(result);
+        assertEquals(10, result);
     }
 
-    public void testAddAttributeInt_N02()
-    {
-        int val = 666666;
+    public void testAddAttributeInt_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;
+        SimulatorResourceModel resModel = new SimulatorResourceModel();
+        SimulatorResourceAttribute attribute = new SimulatorResourceAttribute(
+                INT_KEY, new AttributeValue(-10), null);
+        try {
+            resModel.addAttribute(attribute);
+            result = ((Integer) resModel.getAttribute(INT_KEY).value().get())
+                    .intValue();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
         }
 
-        assertTrue(result);
+        assertEquals(-10, result);
     }
 
-    public void testAddAttributeDouble_P01()
-    {
-        double val = 10.11;
+    public void testAddAttributeDouble_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;
+        SimulatorResourceModel resModel = new SimulatorResourceModel();
+        SimulatorResourceAttribute attribute = new SimulatorResourceAttribute(
+                DOUBLE_KEY, new AttributeValue(4.0), null);
+        try {
+            resModel.addAttribute(attribute);
+            result = ((Double) resModel.getAttribute(DOUBLE_KEY).value().get())
+                    .doubleValue();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
         }
 
-        assertTrue(result);
+        assertEquals(4.0, result);
     }
 
-    public void testAddAttributeDouble_N01()
-    {
-        double val = -11.12;
+    public void testAddAttributeDouble_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;
+        SimulatorResourceModel resModel = new SimulatorResourceModel();
+        SimulatorResourceAttribute attribute = new SimulatorResourceAttribute(
+                DOUBLE_KEY, new AttributeValue(-4.0), null);
+        try {
+            resModel.addAttribute(attribute);
+            result = ((Double) resModel.getAttribute(DOUBLE_KEY).value().get())
+                    .doubleValue();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
         }
 
-        assertTrue(result);
+        assertEquals(-4.0, result);
     }
 
-    public void testAddAttributeDouble_N02()
-    {
-        double val = 0.0044444444444;
+    public void testAddAttributeBoolean_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;
+        SimulatorResourceModel resModel = new SimulatorResourceModel();
+        SimulatorResourceAttribute attribute = new SimulatorResourceAttribute(
+                BOOL_KEY, new AttributeValue(true), null);
+        try {
+            resModel.addAttribute(attribute);
+            result = ((Boolean) resModel.getAttribute(BOOL_KEY).value().get())
+                    .booleanValue();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
         }
 
-        assertTrue(result);
+        assertEquals(true, result);
     }
 
-    public void testAddAttributeString_P01()
-    {
-        String val = "asdf";
+    public void testAddAttributeString_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;
+        SimulatorResourceModel resModel = new SimulatorResourceModel();
+        SimulatorResourceAttribute attribute = new SimulatorResourceAttribute(
+                STRING_KEY, new AttributeValue("string-value"), null);
+        try {
+            resModel.addAttribute(attribute);
+            result = (String) resModel.getAttribute(STRING_KEY).value().get();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
         }
 
-        assertTrue(result);
+        assertEquals("string-value", result);
     }
 
-    public void testAddAttributeString_N01()
-    {
-        String val = "";
+    public void testAddAttributeString_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;
+        SimulatorResourceModel resModel = new SimulatorResourceModel();
+        SimulatorResourceAttribute attribute = new SimulatorResourceAttribute(
+                STRING_KEY, new AttributeValue(""), null);
+        try {
+            resModel.addAttribute(attribute);
+            result = (String) resModel.getAttribute(STRING_KEY).value().get();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
         }
 
-        assertTrue(result);
+        assertEquals("", result);
     }
 
-   public void testAddAttributeString_N02() {
-        String val = null;
+    public void testAddAttributeString_P03() {
+        String result = null;
 
-        boolean result = false;
+        SimulatorResourceModel resModel = new SimulatorResourceModel();
+        SimulatorResourceAttribute attribute = new SimulatorResourceAttribute(
+                STRING_KEY, new AttributeValue("@#$$&^*^(*^&"), null);
         try {
-
-            simulatorResourceModel.addAttributeString(KEY, val);
-
-            result = result && simulatorResourceModel.getAttribute(KEY).getValue().toString().equals(val);
-
-        } catch(Exception e) {
-            result = true;
+            resModel.addAttribute(attribute);
+            result = (String) resModel.getAttribute(STRING_KEY).value().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);
+    public void testSize_P02() {
+        int result = -1;
 
-            result = result && ((Boolean.parseBoolean(simulatorResourceModel.getAttribute(KEY).getValue().toString()+"")));
-
-            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.addAttribute(new SimulatorResourceAttribute(INT_KEY,
+                    new AttributeValue(1234), null));
+            resModel.addAttribute(new SimulatorResourceAttribute(DOUBLE_KEY,
+                    new AttributeValue(1.234), null));
+            resModel.addAttribute(new SimulatorResourceAttribute(BOOL_KEY,
+                    new AttributeValue(true), null));
+            resModel.addAttribute(new SimulatorResourceAttribute(STRING_KEY,
+                    new AttributeValue("string-value"), null));
+            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);
+    public void testGetAttribute_P01() {
+        SimulatorResourceAttribute result = null;
 
-            simulatorResourceModel.addAttributeString("test2", "asdf");
-            simulatorResourceModel.addAttributeBoolean("test3", Boolean.parseBoolean("true"));
-            simulatorResourceModel.addAttributeDouble("test4", 22.435234);
-
-            result = result && (simulatorResourceModel.size() == 4);
-        }
-        catch(Exception e)
-        {
-            result = false;
+        SimulatorResourceModel resModel = new SimulatorResourceModel();
+        try {
+            resModel.addAttribute(new SimulatorResourceAttribute(INT_KEY,
+                    new AttributeValue(10), null));
+            result = resModel.getAttribute(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 testGetAttributes_P01() {
+        Map<String, SimulatorResourceAttribute> result = null;
 
-            result = result && Integer.parseInt(simulatorResourceModel.getAttribute(KEY).getValue().toString()) == val;
-        }
-        catch(Exception e)
-        {
-            result = false;
-        }
-        assertTrue(result);
+        SimulatorResourceModel resModel = new SimulatorResourceModel();
+        try {
+            resModel.addAttribute(new SimulatorResourceAttribute(INT_KEY,
+                    new AttributeValue(1234), null));
+            resModel.addAttribute(new SimulatorResourceAttribute(DOUBLE_KEY,
+                    new AttributeValue(1.234), null));
+            resModel.addAttribute(new SimulatorResourceAttribute(BOOL_KEY,
+                    new AttributeValue(true), null));
+            resModel.addAttribute(new SimulatorResourceAttribute(STRING_KEY,
+                    new AttributeValue("string-value"), null));
+            result = resModel.getAttributes();
+        } catch (InvalidArgsException e) {
+            e.printStackTrace();
+        }
+
+        assertNotNull(result);
+        assertEquals(4, result.size());
     }
 }
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;
+    }
+}