Merge branch 'master' into simulator
authorHarish Kumara Marappa <h.marappa@samsung.com>
Fri, 18 Sep 2015 14:37:25 +0000 (20:07 +0530)
committerHarish Kumara Marappa <h.marappa@samsung.com>
Fri, 18 Sep 2015 14:37:25 +0000 (20:07 +0530)
Change-Id: I76a7d8c501e2122a3c4eddd73ede9f7195fe1055
Signed-off-by: Harish Kumara Marappa <h.marappa@samsung.com>
309 files changed:
extlibs/yaml/SConscript [new file with mode: 0755]
resource/include/OCApi.h
resource/include/OCResourceRequest.h
resource/src/InProcServerWrapper.cpp
service/SConscript
service/simulator/SConscript [new file with mode: 0755]
service/simulator/examples/README.txt [new file with mode: 0755]
service/simulator/examples/client-controller/SConscript [new file with mode: 0644]
service/simulator/examples/client-controller/client_controller.cpp [new file with mode: 0644]
service/simulator/examples/server/SConscript [new file with mode: 0644]
service/simulator/examples/server/service_provider.cpp [new file with mode: 0644]
service/simulator/inc/simulator_client_types.h [new file with mode: 0644]
service/simulator/inc/simulator_device_info.h [new file with mode: 0644]
service/simulator/inc/simulator_error_codes.h [new file with mode: 0644]
service/simulator/inc/simulator_exceptions.h [new file with mode: 0644]
service/simulator/inc/simulator_logger.h [new file with mode: 0644]
service/simulator/inc/simulator_manager.h [new file with mode: 0644]
service/simulator/inc/simulator_platform_info.h [new file with mode: 0644]
service/simulator/inc/simulator_remote_resource.h [new file with mode: 0644]
service/simulator/inc/simulator_resource_model.h [new file with mode: 0644]
service/simulator/inc/simulator_resource_server.h [new file with mode: 0644]
service/simulator/inc/simulator_server_types.h [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/.classpath [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/.project [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/META-INF/MANIFEST.MF [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/build.properties [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/checked.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/clear_d.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/clear_e.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/debug_log.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/delete_d.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/delete_e.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/error_log.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/export_log_d.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/export_log_e.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/filter_d.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/filter_e.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/info_log.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/light_16x16.png [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/lock_d.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/lock_e.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/log_details_e.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/oic_logo_16x16.png [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/oic_logo_32x32.png [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/oic_logo_64x64.png [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/prop_d.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/prop_e.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/sample.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/trash_e.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/tree_mode_d.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/tree_mode_e.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/unchecked.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/unknown_log.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/warning_log.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/plugin.xml [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/Activator.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/listener/IConfigurationUpload.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/listener/IFindResourceUIListener.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/listener/IGetUIListener.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/listener/ILogUIListener.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/listener/IObserveUIListener.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/listener/IPostUIListener.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/listener/IPutUIListener.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/listener/IResourceSelectionChangedUIListener.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/listener/IVerificationUIListener.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/manager/ImageManager.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/manager/LogManager.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/manager/ResourceManager.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/perspective/PerspectiveFactory.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/remoteresource/MetaProperty.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/remoteresource/PutPostAttributeModel.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/remoteresource/RemoteResource.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/remoteresource/RemoteResourceAttribute.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/utils/Constants.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/utils/Utility.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/AttributeView.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/LogView.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/MetaPropertiesView.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/MultiResourceOrchestrationView.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/ResourceManagerView.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/FilterDialog.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/FindResourcePage.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/FindResourceWizard.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/LoadRAMLDialog.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/LogDetailsDialog.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/PostRequestDialog.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/PutRequestDialog.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/ResourceWizardDialog.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/VerificationDialog.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/logger/LogContentProvider.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/logger/LogEntry.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/logger/LogLabelProvider.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/logger/LoggerCallback.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/README.txt [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/.classpath [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/.project [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/META-INF/MANIFEST.MF [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/build.properties [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/button_free.PNG [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/button_pressed.PNG [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/checked.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/clear_d.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/clear_e.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/debug_log.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/delete_d.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/delete_e.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/error_log.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/export_log_d.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/export_log_e.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/filter_d.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/filter_e.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/info_log.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/light_16x16.png [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/lock_d.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/lock_e.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/log_details_e.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/oic_logo_16x16.png [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/oic_logo_32x32.png [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/oic_logo_64x64.png [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/prop_d.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/prop_e.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/sample.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/trash_e.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/tree_mode_d.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/tree_mode_e.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/unchecked.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/unknown_log.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/warning_log.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/plugin.xml [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/resource/Light/simple-light-error.json [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/resource/Light/simple-light.json [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/resource/Light/simple-light.raml [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/logger/LogContentProvider.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/logger/LogEntry.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/logger/LogLabelProvider.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/logger/LoggerCallback.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/Activator.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IAutomationUIListener.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/ILogUIListener.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IObserverListChangedUIListener.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IResourceListChangedUIListener.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IResourceModelChangedUIListener.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IResourceSelectionChangedUIListener.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/manager/ImageManager.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/manager/LogManager.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/manager/ResourceManager.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/perspective/PerspectiveFactory.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/AutomationSettingHelper.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/DeleteCategory.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/LocalResourceAttribute.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/MetaProperty.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/ModelChangeNotificationType.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/ObserverDetail.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/SimulatorResource.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/StandardConfiguration.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/utils/Constants.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/utils/Utility.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/AttributeEditingSupport.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/AttributeView.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/LogView.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/MetaPropertiesView.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/MultiResourceOrchestrationView.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/ResourceManagerView.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/ResourceObserverView.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/AutomationSettingDialog.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/CreateResourcePage.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/CreateResourceWizard.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/DeleteResourcePage.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/DeleteResourceWizard.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/FilterDialog.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/LogDetailsDialog.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/ResourceWizardDialog.java [new file with mode: 0644]
service/simulator/java/jni/resource_attributes_jni.cpp [new file with mode: 0644]
service/simulator/java/jni/resource_attributes_jni.h [new file with mode: 0644]
service/simulator/java/jni/simulator_common_jni.h [new file with mode: 0644]
service/simulator/java/jni/simulator_device_info_jni.cpp [new file with mode: 0644]
service/simulator/java/jni/simulator_device_info_jni.h [new file with mode: 0644]
service/simulator/java/jni/simulator_jni_utils.cpp [new file with mode: 0644]
service/simulator/java/jni/simulator_jni_utils.h [new file with mode: 0644]
service/simulator/java/jni/simulator_manager_jni.cpp [new file with mode: 0644]
service/simulator/java/jni/simulator_manager_jni.h [new file with mode: 0644]
service/simulator/java/jni/simulator_platform_info_jni.cpp [new file with mode: 0644]
service/simulator/java/jni/simulator_platform_info_jni.h [new file with mode: 0644]
service/simulator/java/jni/simulator_remote_resource_jni.cpp [new file with mode: 0644]
service/simulator/java/jni/simulator_remote_resource_jni.h [new file with mode: 0644]
service/simulator/java/jni/simulator_resource_jni_util.cpp [new file with mode: 0644]
service/simulator/java/jni/simulator_resource_jni_util.h [new file with mode: 0644]
service/simulator/java/jni/simulator_resource_model_jni.cpp [new file with mode: 0644]
service/simulator/java/jni/simulator_resource_model_jni.h [new file with mode: 0644]
service/simulator/java/jni/simulator_resource_server_jni.cpp [new file with mode: 0644]
service/simulator/java/jni/simulator_resource_server_jni.h [new file with mode: 0644]
service/simulator/java/sdk/.classpath [new file with mode: 0644]
service/simulator/java/sdk/.gitignore [new file with mode: 0644]
service/simulator/java/sdk/.project [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/DeviceInfo.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/IAutomation.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/IDeviceInfo.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/ILogger.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/IPlatformInfo.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/InvalidArgsException.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/NoSupportException.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/OperationInProgressException.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/PlatformInfo.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/ResourceAttribute.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/SimulatorException.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/SimulatorManager.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/SimulatorManagerNativeInterface.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/SimulatorResourceModel.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/SimulatorResult.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IFindResourceListener.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IGetListener.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IObserveListener.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IPostListener.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IPutListener.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IVerificationListener.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/SimulatorConnectivityType.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/SimulatorObserveType.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/SimulatorRemoteResource.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/SimulatorVerificationType.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/serviceprovider/AutomationType.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/serviceprovider/IObserver.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/serviceprovider/IResourceModelChangedListener.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/serviceprovider/ObserverInfo.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/serviceprovider/SimulatorResourceServer.java [new file with mode: 0644]
service/simulator/ramlparser/SConscript [new file with mode: 0755]
service/simulator/ramlparser/example/SConscript [new file with mode: 0755]
service/simulator/ramlparser/example/raml_parser.cpp [new file with mode: 0755]
service/simulator/ramlparser/raml/IncludeResolver.cpp [new file with mode: 0755]
service/simulator/ramlparser/raml/IncludeResolver.h [new file with mode: 0755]
service/simulator/ramlparser/raml/RamlErrorCodes.h [new file with mode: 0755]
service/simulator/ramlparser/raml/RamlExceptions.cpp [new file with mode: 0755]
service/simulator/ramlparser/raml/RamlExceptions.h [new file with mode: 0755]
service/simulator/ramlparser/raml/RamlParser.cpp [new file with mode: 0755]
service/simulator/ramlparser/raml/RamlParser.h [new file with mode: 0755]
service/simulator/ramlparser/raml/Utils.h [new file with mode: 0755]
service/simulator/ramlparser/raml/jsonSchemaParser/AllowedValues.h [new file with mode: 0755]
service/simulator/ramlparser/raml/jsonSchemaParser/Definitions.h [new file with mode: 0755]
service/simulator/ramlparser/raml/jsonSchemaParser/Helpers.h [new file with mode: 0755]
service/simulator/ramlparser/raml/jsonSchemaParser/Items.h [new file with mode: 0755]
service/simulator/ramlparser/raml/jsonSchemaParser/JsonSchema.cpp [new file with mode: 0755]
service/simulator/ramlparser/raml/jsonSchemaParser/JsonSchema.h [new file with mode: 0755]
service/simulator/ramlparser/raml/jsonSchemaParser/Properties.h [new file with mode: 0755]
service/simulator/ramlparser/raml/model/AbstractParam.cpp [new file with mode: 0755]
service/simulator/ramlparser/raml/model/AbstractParam.h [new file with mode: 0755]
service/simulator/ramlparser/raml/model/Action.cpp [new file with mode: 0755]
service/simulator/ramlparser/raml/model/Action.h [new file with mode: 0755]
service/simulator/ramlparser/raml/model/ActionType.h [new file with mode: 0755]
service/simulator/ramlparser/raml/model/DocumentationItem.cpp [new file with mode: 0755]
service/simulator/ramlparser/raml/model/DocumentationItem.h [new file with mode: 0755]
service/simulator/ramlparser/raml/model/FormParameter.h [new file with mode: 0755]
service/simulator/ramlparser/raml/model/Header.h [new file with mode: 0755]
service/simulator/ramlparser/raml/model/QueryParameter.h [new file with mode: 0755]
service/simulator/ramlparser/raml/model/Raml.cpp [new file with mode: 0755]
service/simulator/ramlparser/raml/model/Raml.h [new file with mode: 0755]
service/simulator/ramlparser/raml/model/RamlResource.cpp [new file with mode: 0755]
service/simulator/ramlparser/raml/model/RamlResource.h [new file with mode: 0755]
service/simulator/ramlparser/raml/model/RequestResponseBody.cpp [new file with mode: 0755]
service/simulator/ramlparser/raml/model/RequestResponseBody.h [new file with mode: 0755]
service/simulator/ramlparser/raml/model/Response.cpp [new file with mode: 0755]
service/simulator/ramlparser/raml/model/Response.h [new file with mode: 0755]
service/simulator/ramlparser/raml/model/Schema.cpp [new file with mode: 0755]
service/simulator/ramlparser/raml/model/Schema.h [new file with mode: 0755]
service/simulator/ramlparser/raml/model/UriParameter.h [new file with mode: 0755]
service/simulator/src/client-controller/attribute_generator.cpp [new file with mode: 0644]
service/simulator/src/client-controller/attribute_generator.h [new file with mode: 0644]
service/simulator/src/client-controller/auto_request_gen.cpp [new file with mode: 0644]
service/simulator/src/client-controller/auto_request_gen.h [new file with mode: 0644]
service/simulator/src/client-controller/auto_request_gen_mngr.cpp [new file with mode: 0644]
service/simulator/src/client-controller/auto_request_gen_mngr.h [new file with mode: 0644]
service/simulator/src/client-controller/get_request_generator.cpp [new file with mode: 0644]
service/simulator/src/client-controller/get_request_generator.h [new file with mode: 0644]
service/simulator/src/client-controller/post_request_generator.cpp [new file with mode: 0644]
service/simulator/src/client-controller/post_request_generator.h [new file with mode: 0644]
service/simulator/src/client-controller/put_request_generator.cpp [new file with mode: 0644]
service/simulator/src/client-controller/put_request_generator.h [new file with mode: 0644]
service/simulator/src/client-controller/query_param_generator.cpp [new file with mode: 0644]
service/simulator/src/client-controller/query_param_generator.h [new file with mode: 0644]
service/simulator/src/client-controller/request_list.h [new file with mode: 0644]
service/simulator/src/client-controller/request_sender.cpp [new file with mode: 0644]
service/simulator/src/client-controller/request_sender.h [new file with mode: 0644]
service/simulator/src/client-controller/simulator_client.cpp [new file with mode: 0644]
service/simulator/src/client-controller/simulator_client.h [new file with mode: 0644]
service/simulator/src/client-controller/simulator_remote_resource_impl.cpp [new file with mode: 0644]
service/simulator/src/client-controller/simulator_remote_resource_impl.h [new file with mode: 0644]
service/simulator/src/common/request_model.cpp [new file with mode: 0644]
service/simulator/src/common/request_model.h [new file with mode: 0644]
service/simulator/src/common/request_model_builder.cpp [new file with mode: 0644]
service/simulator/src/common/request_model_builder.h [new file with mode: 0644]
service/simulator/src/common/response_model.cpp [new file with mode: 0644]
service/simulator/src/common/response_model.h [new file with mode: 0644]
service/simulator/src/common/simulator_exceptions.cpp [new file with mode: 0644]
service/simulator/src/common/simulator_logger.cpp [new file with mode: 0644]
service/simulator/src/common/simulator_resource_model.cpp [new file with mode: 0644]
service/simulator/src/common/simulator_utils.cpp [new file with mode: 0644]
service/simulator/src/common/simulator_utils.h [new file with mode: 0644]
service/simulator/src/service-provider/resource_manager.cpp [new file with mode: 0644]
service/simulator/src/service-provider/resource_manager.h [new file with mode: 0644]
service/simulator/src/service-provider/resource_update_automation.cpp [new file with mode: 0644]
service/simulator/src/service-provider/resource_update_automation.h [new file with mode: 0644]
service/simulator/src/service-provider/resource_update_automation_mngr.cpp [new file with mode: 0644]
service/simulator/src/service-provider/resource_update_automation_mngr.h [new file with mode: 0644]
service/simulator/src/service-provider/simulator_resource_creator.cpp [new file with mode: 0644]
service/simulator/src/service-provider/simulator_resource_creator.h [new file with mode: 0644]
service/simulator/src/service-provider/simulator_resource_server.cpp [new file with mode: 0644]
service/simulator/src/service-provider/simulator_resource_server_impl.cpp [new file with mode: 0644]
service/simulator/src/service-provider/simulator_resource_server_impl.h [new file with mode: 0644]
service/simulator/src/simulator_device_info.cpp [new file with mode: 0644]
service/simulator/src/simulator_manager.cpp [new file with mode: 0644]
service/simulator/src/simulator_platform_info.cpp [new file with mode: 0644]

diff --git a/extlibs/yaml/SConscript b/extlibs/yaml/SConscript
new file mode 100755 (executable)
index 0000000..4cd8948
--- /dev/null
@@ -0,0 +1,54 @@
+#******************************************************************\r
+#\r
+# Copyright 2014 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
+import os\r
+Import('env')\r
+\r
+yaml_env = env.Clone()\r
+src_dir = env.get('SRC_DIR')\r
+\r
+yamlDir = os.path.join(src_dir, 'extlibs','yaml','yaml')\r
+\r
+if not os.path.exists(yamlDir):\r
+    print '''\r
+*********************************** Error: ****************************************\r
+* Please download yaml using the following command:                               *\r
+*     $ git clone https://github.com/jbeder/yaml-cpp.git extlibs/yaml/yaml *\r
+***********************************************************************************\r
+'''\r
+    Exit(1)\r
+\r
+######################################################################\r
+# Build flags\r
+######################################################################\r
+yaml_env.AppendUnique(CPPPATH = ['yaml/src' , 'yaml/include'])\r
+yaml_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])\r
+yaml_env.AppendUnique(CPPDEFINES = ['LINUX'])\r
+yaml_env.AppendUnique(LIBS = ['pthread'])\r
+\r
+yaml_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x'])\r
+\r
+######################################################################\r
+# Source files and Targets\r
+######################################################################\r
+yaml_src = [env.Glob('yaml/src/*.cpp'), env.Glob('yaml/src/contrib/*.cpp')]\r
+yamlsdk = yaml_env.StaticLibrary('YamlParser', yaml_src)\r
+\r
+yaml_env.InstallTarget(yamlsdk, 'libYaml')\r
index 21d56e7..5dacc85 100644 (file)
@@ -229,6 +229,12 @@ namespace OC
         ObserveAction action;
         // Identifier for observation being registered/unregistered
         OCObservationId obsId;
+        // Connectivity type
+        OCConnectivityType connectivityType;
+        // Addresss
+        std::string address;
+        // Port
+        uint16_t port;
     } ObservationInfo;
 
     // const strings for different interfaces
index 004adf1..962ddb2 100644 (file)
@@ -52,7 +52,7 @@ namespace OC
             m_queryParameters{},
             m_requestHandlerFlag{},
             m_representation{},
-            m_observationInfo{ObserveAction::ObserveRegister, 0},
+            m_observationInfo{},
             m_headerOptions{},
             m_requestHandle{nullptr},
             m_resourceHandle{nullptr}
index a25839f..522ef82 100644 (file)
@@ -128,6 +128,12 @@ void formResourceRequest(OCEntityHandlerFlag flag,
             OC::ObservationInfo observationInfo;
             observationInfo.action = (OC::ObserveAction) entityHandlerRequest->obsInfo.action;
             observationInfo.obsId = entityHandlerRequest->obsInfo.obsId;
+
+            observationInfo.connectivityType = static_cast<OCConnectivityType>(
+                    (entityHandlerRequest->devAddr.adapter << CT_ADAPTER_SHIFT) |
+                    (entityHandlerRequest->devAddr.flags & CT_MASK_FLAGS));
+            observationInfo.address = entityHandlerRequest->devAddr.addr;
+            observationInfo.port = entityHandlerRequest->devAddr.port;
             pRequest->setObservationInfo(observationInfo);
         }
     }
index be349be..9fb8020 100644 (file)
@@ -45,3 +45,8 @@ if target_os not in ['arduino','darwin']:
        if target_os not in ['tizen']:
                SConscript('resource-encapsulation/SConscript')
 
+       # Build simulator module
+       if target_os in ['linux']:
+               SConscript('simulator/SConscript')
+
+
diff --git a/service/simulator/SConscript b/service/simulator/SConscript
new file mode 100755 (executable)
index 0000000..260cb0b
--- /dev/null
@@ -0,0 +1,89 @@
+#******************************************************************
+#
+# Copyright 2014 Samsung Electronics All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+##
+# Simulator build script
+##
+
+import os, sys
+Import('env')
+
+lib_env = env.Clone()
+SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env')
+simulator_env = lib_env.Clone()
+
+#Raml Parser
+SConscript('ramlparser/SConscript')
+
+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 = [
+               '../../resource/include/',
+               '../../resource/csdk/stack/include',
+               '../../resource/csdk/ocrandom/include',
+               '../../resource/csdk/logger/include',
+               '../../resource/oc_logger/include',
+               './ramlparser/raml',
+               './ramlparser/raml/model',              
+               './ramlparser/raml/jsonSchemaParser',   
+               '../../extlibs/yaml/yaml/include'
+               ])
+
+# Including Java path for building JNI files
+try:
+       os.environ['JAVA_HOME']
+except KeyError:
+       print '''
+*************************************** Error *********************************
+* JAVA_HOME environment variable not set                                      
+* Simulator has dependency on java, Please set environment variable JAVA_HOME
+*******************************************************************************
+       '''
+       sys.exit(1)
+       
+java_headers = [os.path.join(os.environ['JAVA_HOME'], 'include')]
+java_headers.append(os.path.join(java_headers[0], 'win32'))
+java_headers.append(os.path.join(java_headers[0], 'linux'))
+java_headers.append(os.path.join(java_headers[0], 'solaris'))
+simulator_env.AppendUnique(CPPPATH = java_headers)
+
+simulator_env.AppendUnique(CPPPATH = ['../../extlibs/cjson'])
+simulator_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'libcoap','RamlParser','YamlParser'])
+simulator_env.AppendUnique(LIBS = ['pthread'])
+
+simulator_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x'])
+
+######################################################################
+# Source files and Targets
+######################################################################
+simulator_src = [env.Glob('src/*.cpp')
+                 ,env.Glob('src/*/*.cpp')
+                 ,env.Glob('java/jni/*.cpp')
+                ]
+simulatorsdk = simulator_env.SharedLibrary('SimulatorManager', simulator_src)
+
+simulator_env.InstallTarget(simulatorsdk, 'libSimulator')
+
+#Build sample application
+SConscript('examples/server/SConscript')
+SConscript('examples/client-controller/SConscript')
diff --git a/service/simulator/examples/README.txt b/service/simulator/examples/README.txt
new file mode 100755 (executable)
index 0000000..f0ab383
--- /dev/null
@@ -0,0 +1,3 @@
+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
new file mode 100644 (file)
index 0000000..7149b6b
--- /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
+######################################################################
+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
new file mode 100644 (file)
index 0000000..ff9556c
--- /dev/null
@@ -0,0 +1,632 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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()->findResources(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::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 notificatoin 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
+            {
+                resource->configure("../../../../../../../../service/simulator/ramlparser/example/oic.r.light.raml");
+                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()->setDefaultConsoleLogger())
+                    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()->setDefaultFileLogger(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/server/SConscript b/service/simulator/examples/server/SConscript
new file mode 100644 (file)
index 0000000..9a5b38e
--- /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
+######################################################################
+simulatorserver = sim_env.Program('simulator-server', 'service_provider.cpp')
+
+Alias("simulatorserver", simulatorserver)
+env.AppendTarget('simulatorserver')
diff --git a/service/simulator/examples/server/service_provider.cpp b/service/simulator/examples/server/service_provider.cpp
new file mode 100644 (file)
index 0000000..b0a82ec
--- /dev/null
@@ -0,0 +1,586 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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(std::string &configPath)
+        {
+            printMenu();
+            bool cont = true;
+            while (cont)
+            {
+                int choice = -1;
+                std::cout << "Enter your choice: ";
+                std::cin >> choice;
+                if (choice < 0 || choice > 9)
+                {
+                    std::cout << "Invaild choice !" << std::endl; continue;
+                }
+
+                switch (choice)
+                {
+                    case 1 : simulateResource(configPath); 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(std::string &configPath)
+        {
+            SimulatorResourceServer::ResourceModelChangedCB callback = std::bind(
+                        &SimLightResource::onResourceModelChanged, this, std::placeholders::_1, std::placeholders::_2);
+            SimulatorResourceServerSP resource = SimulatorManager::getInstance()->createResource(configPath,
+                                                  callback);
+            if (NULL == resource.get())
+                std::cout << "Failed to create resource" << std::endl;
+
+            m_resources.push_back(resource);
+            std::cout << "Resource created successfully! URI= " << resource->getURI().c_str() << 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;
+                        }
+
+                        SimulatorManager::getInstance()->deleteResources(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++;
+                        }
+                    } break;
+                case 3:
+                    {
+                        SimulatorManager::getInstance()->deleteResources();
+                        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 continue the attribute values changing process? (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 continue the attribute values changing process? (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,
+                                    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 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,
+                                    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 <<
+              "To set the Resource from RAML file, run the service provider with argument of Path of Raml File."
+              << std::endl;
+    std::cout <<
+              "Example: ./simulator-server PATH-TO-RAML-FILE"
+              << 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()->setDefaultConsoleLogger())
+                    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()->setDefaultFileLogger(filePath))
+                    std::cout << "Failed to set default file logger" << std::endl;
+            } break;
+        case 3: SimulatorManager::getInstance()->setLogger(gAppLogger);
+    }
+}
+
+int main(int argc, char *argv[])
+{
+    std::string configPath = "";
+
+    if (argc == 2)
+    {
+        char *value = argv[1];
+        configPath.append(value);
+    }
+    else
+    {
+        configPath = "";
+    }
+    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(configPath);
+                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/inc/simulator_client_types.h b/service/simulator/inc/simulator_client_types.h
new file mode 100644 (file)
index 0000000..21c7faa
--- /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.
+ *
+ ******************************************************************/
+
+#ifndef SIMULATOR_CLIENT_TYPES_H_
+#define SIMULATOR_CLIENT_TYPES_H_
+
+#include <iostream>
+#include <functional>
+#include <memory>
+#include "simulator_error_codes.h"
+
+enum class ObserveType
+{
+    OBSERVE,
+    OBSERVE_ALL
+};
+
+enum class RequestType
+{
+    RQ_TYPE_GET,
+    RQ_TYPE_PUT,
+    RQ_TYPE_POST,
+    RQ_TYPE_DELETE
+};
+
+typedef struct
+{
+    bool isVerified;
+    SimulatorResult errorCode;
+} ValidationStatus;
+
+typedef enum
+{
+    OP_START,
+    OP_COMPLETE,
+    OP_ABORT
+} OperationState;
+
+typedef enum
+{
+    /** use when defaults are ok. */
+    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),
+
+#ifdef RA_ADAPTER
+    /** Remote Access over XMPP.*/
+    SIMULATOR_CT_ADAPTER_REMOTE_ACCESS = (1 << 19),
+#endif
+
+    /** 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,
+} SimulatorConnectivityType;
+
+class SimulatorRemoteResource;
+typedef std::function<void(std::shared_ptr<SimulatorRemoteResource>)>
+ResourceFindCallback;
+
+#endif
diff --git a/service/simulator/inc/simulator_device_info.h b/service/simulator/inc/simulator_device_info.h
new file mode 100644 (file)
index 0000000..b9fb11b
--- /dev/null
@@ -0,0 +1,71 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#ifndef SIMULATOR_DEVICE_INFO_H_
+#define SIMULATOR_DEVICE_INFO_H_
+
+#include <iostream>
+
+/**
+ * @class   DeviceInfo
+ *
+ * @brief   This class contains remote device information and provide APIs access it.
+ */
+class DeviceInfo
+{
+    public:
+        DeviceInfo(const std::string &, const std::string &, const std::string &, const std::string &);
+
+        /**
+         * This method is for getting device name.
+         *
+         * @return Device name.
+         */
+        std::string getName() const;
+
+        /**
+         * This method is for getting device id.
+         *
+         * @return Device id.
+         */
+        std::string getID() const;
+
+        /**
+         * This method is for getting device specification version.
+         *
+         * @return Device id.
+         */
+        std::string getSpecVersion() const;
+
+        /**
+         * This method is for getting device data model version.
+         *
+         * @return Device data model version.
+         */
+        std::string getDataModelVersion() const;
+
+    private:
+        std::string m_name;
+        std::string m_id;
+        std::string m_specVersion;
+        std::string m_DMV;
+};
+
+#endif
diff --git a/service/simulator/inc/simulator_error_codes.h b/service/simulator/inc/simulator_error_codes.h
new file mode 100644 (file)
index 0000000..ae802f3
--- /dev/null
@@ -0,0 +1,81 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#ifndef SIMULATOR_ERROR_CODES_H_
+#define SIMULATOR_ERROR_CODES_H_
+
+#include <iostream>
+
+typedef enum
+{
+    /** STACK error codes - START */
+    SIMULATOR_OK = 0,
+    SIMULATOR_RESOURCE_CREATED,
+    SIMULATOR_RESOURCE_DELETED,
+    SIMULATOR_CONTINUE,
+    SIMULATOR_INVALID_URI = 20,
+    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,
+#ifdef WITH_PRESENCE
+    SIMULATOR_PRESENCE_STOPPED = 128,
+    SIMULATOR_PRESENCE_TIMEOUT,
+    SIMULATOR_PRESENCE_DO_NOT_HANDLE,
+#endif
+    /** 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_RESPONSE_CODE,
+    SIMULATOR_UKNOWN_PROPERTY,
+    SIMULATOR_TYPE_MISMATCH,
+    SIMULATOR_BAD_VALUE,
+    /** Simulator specific error codes - START */
+
+    SIMULATOR_ERROR = 255
+} SimulatorResult;
+#endif //SIMULATOR_ERROR_CODES_H_
\ No newline at end of file
diff --git a/service/simulator/inc/simulator_exceptions.h b/service/simulator/inc/simulator_exceptions.h
new file mode 100644 (file)
index 0000000..cfb1207
--- /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_exceptions.h
+ *
+ * @brief This file provides exceptions which would be thrown from simualtor module.
+ *
+ */
+
+#ifndef SIMULATOR_EXCEPTIONS_H_
+#define SIMULATOR_EXCEPTIONS_H_
+
+#include <exception>
+#include "simulator_error_codes.h"
+
+/**
+ * @class SimulatorException
+ * @brief This is the base exception of all type of exception thrown from simulator module.
+ */
+class SimulatorException : public std::exception
+{
+    public:
+        /**
+         * Constructor of SimulatorException.
+         *
+         * @param errorCode - Error code.
+         * @param message - String describing the error messsage.
+         */
+        SimulatorException(SimulatorResult errorCode, const std::string &message);
+
+        /**
+         * API to get error message describing exception reason.
+         *
+         * @return Null terminated string.
+         */
+        virtual const char *what() const noexcept;
+
+        /**
+         * API to get error code with which exception is thrown.
+         *
+         * @return SimulatorResult - Error code.
+         */
+        virtual SimulatorResult code() const;
+        virtual ~SimulatorException() throw() {}
+
+    private:
+        SimulatorResult m_errorCode;
+        std::string m_message;
+};
+
+/**
+ * @class InvalidArgsException
+ * @brief This exception will be thrown to indicate invalid arguments case.
+ */
+class InvalidArgsException : public SimulatorException
+{
+    public:
+        InvalidArgsException(SimulatorResult errorCode, const std::string &message);
+};
+
+/**
+ * @class NoSupportException
+ * @brief This exception will be thrown to indicate not supported operation cases.
+ */
+class NoSupportException : public SimulatorException
+{
+    public:
+        NoSupportException(const std::string &message);
+};
+
+/**
+ * @class OperationInProgressException
+ * @brief This exception will be thrown to indicate requested operation is not allowed as other operation
+ *              is in progress state.
+ */
+class OperationInProgressException : public SimulatorException
+{
+    public:
+        OperationInProgressException(const std::string &message);
+};
+
+#endif
diff --git a/service/simulator/inc/simulator_logger.h b/service/simulator/inc/simulator_logger.h
new file mode 100644 (file)
index 0000000..8a0c028
--- /dev/null
@@ -0,0 +1,79 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file   simulator_logger.h
+ *
+ * @brief   This file provides the interface for logging messages to different targets (console/file).
+ */
+
+#ifndef SIMULATOR_LOGGER_H_
+#define SIMULATOR_LOGGER_H_
+
+#include <iostream>
+#include <memory>
+
+class ILogger
+{
+    public:
+        enum Level
+        {
+            INFO = 0,
+            DEBUG,
+            WARNING,
+            ERROR
+        };
+
+        static const char *getString(Level level)
+        {
+            switch (level)
+            {
+                case Level::INFO: return "INFO";
+                case Level::DEBUG: return "DEBUG";
+                case Level::WARNING: return "WARNING";
+                case Level::ERROR: return "ERROR";
+                default: return "UNKNOWN";
+            }
+        }
+
+        virtual void write(std::string, Level, std::string) = 0;
+};
+
+class Logger
+{
+    public:
+        bool setDefaultConsoleTarget();
+        bool setDefaultFileTarget(const std::string &path);
+        void setCustomTarget(const std::shared_ptr<ILogger> &target);
+        void write(ILogger::Level level, std::ostringstream &str);
+
+    private:
+        std::shared_ptr<ILogger> m_target;
+};
+
+auto simLogger() -> Logger &;
+
+#ifndef SIM_LOG
+#define SIM_LOG(LEVEL, MSG) { \
+        simLogger().write(LEVEL, static_cast<std::ostringstream&>(std::ostringstream()<<MSG)); \
+    }
+#endif
+
+#endif
\ No newline at end of file
diff --git a/service/simulator/inc/simulator_manager.h b/service/simulator/inc/simulator_manager.h
new file mode 100644 (file)
index 0000000..69c2ee0
--- /dev/null
@@ -0,0 +1,222 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+  * @file   simulator_manager.h
+  *
+  * @brief   This file contains the declaration of SimulatorManager class which has the methods
+  *              for configuring the platform and creation/deletion of resources.
+  */
+
+#ifndef SIMULATOR_MANAGER_H_
+#define SIMULATOR_MANAGER_H_
+
+#include "simulator_server_types.h"
+#include "simulator_client_types.h"
+#include "simulator_device_info.h"
+#include "simulator_platform_info.h"
+#include "simulator_resource_server.h"
+#include "simulator_remote_resource.h"
+#include "simulator_exceptions.h"
+#include "simulator_logger.h"
+
+typedef std::function<void(DeviceInfo &deviceInfo)> DeviceInfoCallback;
+typedef std::function<void(PlatformInfo &platformInfo)> PlatformInfoCallback;
+
+/**
+ * @class   SimulatorManager
+ *
+ * @brief   This class provides a set of methods for platform configuration,
+ *              and creation/deletion of resources.
+ *
+ */
+class SimulatorManager
+{
+    public:
+        static SimulatorManager *getInstance();
+
+        /**
+         * 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.
+         *
+         *  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);
+
+        /**
+         * 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.
+         *
+         * 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 = "");
+
+        /**
+          * 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);
+
+        /**
+          * 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 deleteResources(const std::string &resourceType = "");
+
+        /**
+         * 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 would throw @InvalidArgsException when invalid arguments passed, and
+         * @SimulatorException if any other error occured.
+         */
+        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 would throw @InvalidArgsException when invalid arguments passed, and
+         * @SimulatorException if any other error occured.
+         */
+        void findResources(const std::string &resourceType, ResourceFindCallback callback);
+
+        /**
+         * API for getting device information from remote device.
+         * Received device information will be notified through the callback set using
+         * @callback parameter.
+         *
+         * @param callback - Method of type @DeviceInfoCallback through which device information
+         *                                   will be notified.
+         *
+         * NOTE: API throws @InvalidArgsException and @SimulatorException on error.
+         */
+        void getDeviceInfo(DeviceInfoCallback callback);
+
+        /**
+         * API for registering device information with stack.
+         *
+         * @param deviceName - Device name to be registered.
+         *
+         * NOTE: API throws @InvalidArgsException and @SimulatorException on error.
+         */
+        void setDeviceInfo(const std::string &deviceName);
+
+        /**
+         * API for getting platform information from remote device.
+         * Received platform information will be notified through the callback set using
+         * @callback parameter.
+         *
+         * @param callback - Method of type @PlatformInfoCallback through which platform
+         *                                   information will be notified.
+         *
+         * NOTE: API throws @InvalidArgsException and @SimulatorException on error.
+         */
+        void getPlatformInfo(PlatformInfoCallback callback);
+
+        /**
+         * API for registering platform information with stack.
+         *
+         * @param platformInfo - PlatformInfo contains all platform related information.
+         *
+         * NOTE: API throws @SimulatorException on error.
+         */
+        void setPlatformInfo(PlatformInfo &platformInfo);
+
+        /**
+         * API for setting logger target for receiving the log messages.
+         *
+         * @param logger - ILogger interface for handling the log messages.
+         *
+         */
+        void setLogger(const std::shared_ptr<ILogger> &logger);
+
+        /**
+         * API for setting console as logger target.
+         *
+         * @return true if console set as logger target,
+         *         otherwise false.
+         *
+         */
+        bool setDefaultConsoleLogger();
+
+        /**
+         * API for setting file as logger target.
+         *
+         * @param path - File to which log messages to be saved.
+         *
+         * @return true if console set as logger target,
+         *         otherwise false.
+         *
+         */
+        bool setDefaultFileLogger(const std::string &path);
+
+    private:
+        SimulatorManager();
+        ~SimulatorManager() = default;
+        SimulatorManager(const SimulatorManager &) = delete;
+        SimulatorManager &operator=(const SimulatorManager &) = delete;
+        SimulatorManager(const SimulatorManager &&) = delete;
+        SimulatorManager &operator=(const SimulatorManager && ) = delete;
+};
+
+#endif
diff --git a/service/simulator/inc/simulator_platform_info.h b/service/simulator/inc/simulator_platform_info.h
new file mode 100644 (file)
index 0000000..fb12caf
--- /dev/null
@@ -0,0 +1,136 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+#ifndef SIMULATOR_PLATFORM_INFO_H_
+#define SIMULATOR_PLATFORM_INFO_H_
+
+#include <iostream>
+
+/**
+ * @class   PlatformInfo
+ *
+ * @brief   This class contains remote device platform information and provide APIs access it.
+ */
+class PlatformInfo
+{
+    public:
+        /**
+         * This method is for getting platfom id.
+         *
+         * @return Platform id.
+         */
+        std::string getPlatformID() const;
+
+        /**
+         * This method is for getting platform version.
+         *
+         * @return Platform version.
+         */
+        std::string getPlatformVersion() const;
+
+        /**
+         * This method is for getting manufacturer name.
+         *
+         * @return manufacturer name.
+         */
+        std::string getManufacturerName() const;
+
+        /**
+         * This method is for getting manufacturer URL.
+         *
+         * @return manufacturer URL.
+         */
+        std::string getManufacturerUrl() const;
+
+        /**
+         * This method is for getting model number.
+         *
+         * @return Model number.
+         */
+        std::string getModelNumber() const;
+
+        /**
+         * This method is for getting date of manufacture.
+         *
+         * @return Date of manufacture.
+         */
+        std::string getDateOfManfacture() const;
+
+        /**
+         * This method is for getting operating system version.
+         *
+         * @return Operating system version.
+         */
+        std::string getOSVersion() const;
+
+        /**
+         * This method is for getting hardware version.
+         *
+         * @return Hardware version.
+         */
+        std::string getHardwareVersion() const;
+
+        /**
+         * This method is for getting firmware version.
+         *
+         * @return Firmware version.
+         */
+        std::string getFirmwareVersion() const;
+
+        /**
+         * This method is for getting support link URL.
+         *
+         * @return URL of support link.
+         */
+        std::string getSupportUrl() const;
+
+        /**
+         * This method is for getting system time.
+         *
+         * @return System time.
+         */
+        std::string getSystemTime() const;
+
+        void setPlatformID(const std::string &platformId);
+        void setPlatformVersion(const std::string &platformVersion);
+        void setManufacturerName(const std::string &manufacturerName);
+        void setManufacturerUrl(const std::string &manufacturerUrl);
+        void setModelNumber(const std::string &modelNumber);
+        void setDateOfManfacture(const std::string &dateOfManufacture);
+        void setOSVersion(const std::string &osVersion);
+        void setHardwareVersion(const std::string &hwVersion);
+        void setFirmwareVersion(const std::string &firmwareVersion);
+        void setSupportUrl(const std::string &supportUrl);
+        void setSystemTime(const std::string &systemTime);
+
+    private:
+        std::string m_platformID;
+        std::string m_manufacturerName;
+        std::string m_manufacturerUrl;
+        std::string m_modelNumber;
+        std::string m_dateOfManufacture;
+        std::string m_platformVersion;
+        std::string m_operationSystemVersion;
+        std::string m_hardwareVersion;
+        std::string m_firmwareVersion;
+        std::string m_supportUrl;
+        std::string m_systemTime;
+};
+
+#endif
diff --git a/service/simulator/inc/simulator_remote_resource.h b/service/simulator/inc/simulator_remote_resource.h
new file mode 100644 (file)
index 0000000..5388bcc
--- /dev/null
@@ -0,0 +1,159 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file simulator_remote_resource.h
+ *
+ * @brief This file provides a class for handling discovered resources.
+ *
+ */
+
+#ifndef SIMULATOR_REMOTE_RESOURCE_H_
+#define SIMULATOR_REMOTE_RESOURCE_H_
+
+#include "simulator_client_types.h"
+#include "simulator_resource_model.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
+{
+    public:
+
+        /**
+         * Callback method for receiving response for GET, PUT and POST requests.
+         *
+         */
+        typedef std::function<void (std::string, SimulatorResult, SimulatorResourceModelSP)>
+        ResponseCallback;
+
+        /**
+         * Callback method for receiving model change notifications from remote resource.
+         *
+         */
+        typedef std::function<void (std::string, SimulatorResult, SimulatorResourceModelSP, int)>
+        ObserveNotificationCallback;
+
+        /**
+         * Callback method for receiving auto request generation and verifiction progress state.
+         *
+         */
+        typedef std::function<void(std::string, int, OperationState)>
+        StateCallback;
+
+        /**
+         * API for getting URI of resource.
+         *
+         * @return URI of resource.
+         *
+         */
+        virtual std::string getURI() const = 0;
+
+        /**
+         * API for getting host address of resource.
+         *
+         * @return Host address of resource.
+         *
+         */
+        virtual std::string getHost() const = 0;
+
+        /**
+         * API for getting unique id of resource.
+         *
+         * @return ID of resource.
+         *
+         */
+        virtual std::string getID() const = 0;
+
+
+        /**
+         * API for getting connectivity type of resource.
+         *
+         * @return enum SimulatorConnectivityType value
+         *
+         */
+        virtual SimulatorConnectivityType getConnectivityType() const = 0;
+
+        /**
+         * API for getting resource types bound with the resource.
+         *
+         * @return vector of strings representing resource types.
+         *
+         */
+        virtual std::vector < std::string > getResourceTypes() const = 0;
+
+        /**
+         * API for getting interface types bound with the resource.
+         *
+         * @return vector of strings representing interface types.
+         *
+         */
+        virtual std::vector < std::string > getResourceInterfaces() const = 0;
+
+        /**
+         * API to check whether resource can be observed or not.
+         *
+         * @return true if resource is observable, otherwise false.
+         *
+         */
+        virtual bool isObservable() const = 0;
+
+        virtual void observe(ObserveType type, ObserveNotificationCallback callback) = 0;
+
+        virtual void cancelObserve() = 0;
+
+        virtual void get(const std::map<std::string, std::string> &queryParams,
+                         ResponseCallback callback) = 0;
+
+        virtual void get(const std::string &interfaceType,
+                         const std::map<std::string, std::string> &queryParams,
+                         ResponseCallback callback) = 0;
+
+        virtual void put(const std::map<std::string, std::string> &queryParams,
+                         SimulatorResourceModelSP representation,
+                         ResponseCallback callback) = 0;
+
+        virtual void put(const std::string &interfaceType,
+                         const std::map<std::string, std::string> &queryParams,
+                         SimulatorResourceModelSP representation,
+                         ResponseCallback callback) = 0;
+
+        virtual void post(const std::map<std::string, std::string> &queryParams,
+                          SimulatorResourceModelSP representation,
+                          ResponseCallback callback) = 0;
+
+        virtual void post(const std::string &interfaceType,
+                          const std::map<std::string, std::string> &queryParams,
+                          SimulatorResourceModelSP representation,
+                          ResponseCallback callback) = 0;
+
+        virtual int startVerification(RequestType type, StateCallback callback) = 0;
+
+        virtual void stopVerification(int id) = 0;
+
+        virtual void configure(const std::string &path) = 0;
+};
+
+typedef std::shared_ptr<SimulatorRemoteResource> SimulatorRemoteResourceSP;
+
+#endif
+
diff --git a/service/simulator/inc/simulator_resource_model.h b/service/simulator/inc/simulator_resource_model.h
new file mode 100644 (file)
index 0000000..d4757e9
--- /dev/null
@@ -0,0 +1,337 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_model.h
+ *
+ * @brief   This file contains a class which represents the resource model for simulator
+ *             resources and provides a set of functions for updating the model.
+ */
+
+#ifndef SIMULATOR_RESOURCE_MODEL_H_
+#define SIMULATOR_RESOURCE_MODEL_H_
+
+#include <string>
+#include <vector>
+#include "OCPlatform.h"
+#include <climits>
+
+/**
+ * @class   SimulatorResourceModel
+ * @brief   This class provides a set of functions for accessing and manipulating the resource model.
+ */
+class SimulatorResourceModel
+{
+    public:
+        SimulatorResourceModel() = default;
+        SimulatorResourceModel(SimulatorResourceModel &&) = default;
+        SimulatorResourceModel(const SimulatorResourceModel &) = default;
+        SimulatorResourceModel &operator=(const SimulatorResourceModel &) = default;
+        SimulatorResourceModel &operator=(SimulatorResourceModel && ) = default;
+
+        /**
+          * @class   Attribute
+          * @brief   This class represents a resource attribute whose values can be generic.
+          */
+        class Attribute
+        {
+            public:
+                typedef boost::variant <
+                int,
+                double,
+                bool,
+                std::string
+                > ValueVariant;
+
+                Attribute()
+                {
+                    m_min = INT_MIN;
+                    m_max = INT_MAX;
+                    m_updateInterval = -1;
+                }
+
+                Attribute(const std::string &attrName)
+                {
+                    m_name = attrName;
+                    m_min = INT_MIN;
+                    m_max = INT_MAX;
+                    m_updateInterval = -1;
+                }
+
+                /**
+                 * 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);
+                }
+
+                /**
+                 * API to get attribute's value.
+                 *
+                 * @return value of attribute as ValueVariant.
+                 */
+                ValueVariant &getValue()
+                {
+                    return m_value;
+                }
+
+                /**
+                 * API to get attribute's value type.
+                 *
+                 * @return type of value.
+                 */
+                int getValueType() const
+                {
+                    return m_value.which();
+                }
+
+                /**
+                 * API to set the attribute's value.
+                 *
+                 * @param value - value to be set.
+                 */
+                template <typename T>
+                void setValue(const T &value)
+                {
+                    m_value = value;
+                }
+
+                /**
+                 * API to set the attribute's value from allowed values container.
+                 *
+                 * @param allowedValueIndex - Index of value to be set from allowed vaules container.
+                 */
+                void setFromAllowedValue(unsigned int index);
+
+                /**
+                 * API to get range of attribute's value.
+                 */
+                void getRange(int &min, int &max) const;
+
+                /**
+                 * API to set range of attribute's value.
+                 *
+                 * @param min - minimum value could be set as attribute value.
+                 * @param max - maximum value could be set as attribute value.
+                 */
+                void setRange(const int &min, const int &max);
+
+                /**
+                 * API to set the values to allowed values set.
+                 *
+                 * @param values - vector of values which will be set as allowed values.
+                 */
+                template <typename T>
+                bool setAllowedValues(const std::vector<T> &values)
+                {
+                    ValueVariant temp = values.at(0);
+                    if (temp.which() != m_value.which())
+                    {
+                        return false;
+                    }
+
+                    m_allowedValues.addValues(values);
+                    return true;
+                }
+
+                /**
+                 * API to get the number of values present in allowed values set.
+                 *
+                 * @return Size of the allowed values.
+                 */
+                int getAllowedValuesSize() const;
+
+                /**
+                 * 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();
+
+                int getUpdateFrequencyTime() {return m_updateInterval;}
+                void setUpdateFrequencyTime(int interval) {m_updateInterval = interval;}
+
+            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();
+                    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;
+        };
+
+        /**
+         * API to get the number of attributes in the resource model.
+         *
+         * @return Number of attributes.
+         */
+        int size() const { return m_attributes.size(); }
+
+        /**
+         * API to get the value of an attribute.
+         *
+         * @param attrName - Attribute name
+         * @param value - Attribute value
+         *
+         * @return true if attribute exists, otherwise false.
+         */
+        bool getAttribute(const std::string &attrName, Attribute &value);
+
+        /**
+         * API to get the entire list of attributes in the form of key-value pair.
+         * Attribute name is the key and an instance of Attribute is the value.
+         *
+         * @return A map of all the attributes
+         */
+        std::map<std::string, Attribute> getAttributes() const;
+
+        /**
+         * API to add new attribute to resource model.
+         *
+         * @param attrName - Attribute name
+         * @param attrValue - Attribute value
+         */
+        template <typename T>
+        void addAttribute(const std::string &attrName, const T &attrValue)
+        {
+            if (m_attributes.end() == m_attributes.find(attrName))
+            {
+                m_attributes[attrName] = Attribute(attrName);
+                m_attributes[attrName].setValue(attrValue);
+            }
+        }
+
+        /**
+          * API to add new attribute to resource model.
+          *
+          * @param attr  - Attribute pointer
+          *
+          */
+        void addAttribute(Attribute &attr)
+        {
+            std::string attrName = attr.getName();
+            m_attributes[attrName] = Attribute(attr);
+        }
+
+        /**
+         * 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);
+
+        template <typename T>
+        void setAllowedValues(const std::string &attrName, const std::vector<T> &values)
+        {
+            if (m_attributes.end() != m_attributes.find(attrName))
+                m_attributes[attrName].setAllowedValues(values);
+        }
+
+        bool update(OC::OCRepresentation &ocRep);
+
+        bool update(std::shared_ptr<SimulatorResourceModel> &repModel);
+
+        template <typename T>
+        void updateAttribute(const std::string &attrName, const T &value)
+        {
+            if (m_attributes.end() != m_attributes.find(attrName))
+                m_attributes[attrName].setValue(value);
+        }
+
+        void updateAttributeFromAllowedValues(const std::string &attrName, unsigned int index);
+
+        void removeAttribute(const std::string &attrName);
+
+        void setUpdateInterval(const std::string &attrName, int interval);
+
+    private:
+        std::map<std::string, Attribute> m_attributes;
+};
+
+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
new file mode 100644 (file)
index 0000000..d72d1d0
--- /dev/null
@@ -0,0 +1,286 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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);
+        }
+
+        /**
+         * 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,
+                                          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 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,
+                                          updateCompleteCallback callback) = 0;
+
+        /**
+         * API to get the Ids of all ongoing resource update automation .
+         *
+         * @return vector of resource automation ids.
+         */
+        virtual std::vector<int> getResourceAutomationIds() = 0;
+
+        /**
+         * API to get the Ids of all ongoing attribute update automation .
+         *
+         * @return vector of attribute automation ids.
+         */
+        virtual std::vector<int> getAttributeAutomationIds() = 0;
+
+        /**
+        * API to stop the resource/attribute automation.
+        *
+        * @param id - Identifier for automation.
+        */
+        virtual void stopUpdateAutomation(const int id) = 0;
+
+        /**
+         * API to set the callback for receiving the notifications when the
+         * resource model changes.
+         *
+         * @param callback - Callback to be set for receiving the notifications.
+         */
+        virtual void setModelChangeCallback(ResourceModelChangedCB callback) = 0;
+
+        /**
+         * API to set the callback for receiving the notifications when
+         * observer is registered or unregistered with resource.
+         *
+         * @param callback - Callback to be set for receiving the notifications.
+         */
+        virtual void setObserverCallback(ObserverCB callback) = 0;
+
+        /**
+         * API to get observers which are registered with resource.
+         *
+         * @return vector of ObserverInfo.
+         */
+        virtual std::vector<ObserverInfo> getObserversList() = 0;
+
+        /**
+         * API to notify current resource model to specific observer.
+         *
+         * NOTE: API throws @SimulatorException exception.
+         */
+        virtual void notify(uint8_t id) = 0;
+
+        /**
+         * API to notify all registered observers.
+         *
+         * NOTE: API throws @SimulatorException exception.
+         */
+        virtual void notifyAll() = 0;
+
+    protected:
+        std::string m_name;
+        std::string m_uri;
+        std::string m_resourceType;
+        std::string m_interfaceType;
+        SimulatorResourceModel m_resModel;
+};
+
+typedef std::shared_ptr<SimulatorResourceServer> SimulatorResourceServerSP;
+
+#endif
diff --git a/service/simulator/inc/simulator_server_types.h b/service/simulator/inc/simulator_server_types.h
new file mode 100644 (file)
index 0000000..2449d0a
--- /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_SERVER_TYPES_H_
+#define SIMULATOR_SERVER_TYPES_H_
+
+#include <iostream>
+#include <functional>
+
+enum class AutomationType
+{
+    NORMAL,
+    RECURRENT
+};
+
+typedef std::function<void (const std::string &, const int)> updateCompleteCallback;
+
+#endif
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/.classpath b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/.classpath
new file mode 100644 (file)
index 0000000..cd0df03
--- /dev/null
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+       <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
+       <classpathentry kind="src" path="src"/>
+       <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
+       <classpathentry kind="lib" path="libs/Simulator.jar"/>
+       <classpathentry kind="output" path="bin"/>
+</classpath>
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/.project b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/.project
new file mode 100644 (file)
index 0000000..39567c3
--- /dev/null
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+       <name>ClientControllerPlugin</name>
+       <comment></comment>
+       <projects>
+       </projects>
+       <buildSpec>
+               <buildCommand>
+                       <name>org.eclipse.jdt.core.javabuilder</name>
+                       <arguments>
+                       </arguments>
+               </buildCommand>
+               <buildCommand>
+                       <name>org.eclipse.pde.ManifestBuilder</name>
+                       <arguments>
+                       </arguments>
+               </buildCommand>
+               <buildCommand>
+                       <name>org.eclipse.pde.SchemaBuilder</name>
+                       <arguments>
+                       </arguments>
+               </buildCommand>
+       </buildSpec>
+       <natures>
+               <nature>org.eclipse.pde.PluginNature</nature>
+               <nature>org.eclipse.jdt.core.javanature</nature>
+       </natures>
+</projectDescription>
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/META-INF/MANIFEST.MF b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/META-INF/MANIFEST.MF
new file mode 100644 (file)
index 0000000..4366174
--- /dev/null
@@ -0,0 +1,13 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: ClientControllerPlugin
+Bundle-SymbolicName: ClientControllerPlugin;singleton:=true
+Bundle-Version: 0.1.0
+Bundle-Activator: oic.simulator.clientcontroller.Activator
+Require-Bundle: org.eclipse.ui,
+ org.eclipse.core.runtime
+Bundle-RequiredExecutionEnvironment: JavaSE-1.7
+Bundle-ActivationPolicy: lazy
+Bundle-NativeCode: libs/libSimulatorManager.so
+Bundle-ClassPath: libs/Simulator.jar,
+ .
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/build.properties b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/build.properties
new file mode 100644 (file)
index 0000000..100c21d
--- /dev/null
@@ -0,0 +1,8 @@
+source.. = src/
+output.. = bin/
+bin.includes = META-INF/,\
+               .,\
+               plugin.xml,\
+               icons/,\
+               libs/Simulator.jar,\
+               libs/libSimulatorManager.so
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/checked.gif b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/checked.gif
new file mode 100644 (file)
index 0000000..e556e7d
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/checked.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/clear_d.gif b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/clear_d.gif
new file mode 100644 (file)
index 0000000..6775edf
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/clear_d.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/clear_e.gif b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/clear_e.gif
new file mode 100644 (file)
index 0000000..af30a42
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/clear_e.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/debug_log.gif b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/debug_log.gif
new file mode 100644 (file)
index 0000000..d90a29f
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/debug_log.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/delete_d.gif b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/delete_d.gif
new file mode 100644 (file)
index 0000000..9e14298
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/delete_d.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/delete_e.gif b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/delete_e.gif
new file mode 100644 (file)
index 0000000..b6922ac
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/delete_e.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/error_log.gif b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/error_log.gif
new file mode 100644 (file)
index 0000000..9b048d6
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/error_log.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/export_log_d.gif b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/export_log_d.gif
new file mode 100644 (file)
index 0000000..030b93e
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/export_log_d.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/export_log_e.gif b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/export_log_e.gif
new file mode 100644 (file)
index 0000000..5a0837d
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/export_log_e.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/filter_d.gif b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/filter_d.gif
new file mode 100644 (file)
index 0000000..ba6d891
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/filter_d.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/filter_e.gif b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/filter_e.gif
new file mode 100644 (file)
index 0000000..1492b4e
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/filter_e.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/info_log.gif b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/info_log.gif
new file mode 100644 (file)
index 0000000..3679f84
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/info_log.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/light_16x16.png b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/light_16x16.png
new file mode 100644 (file)
index 0000000..8b3abbd
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/light_16x16.png differ
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/lock_d.gif b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/lock_d.gif
new file mode 100644 (file)
index 0000000..b776478
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/lock_d.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/lock_e.gif b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/lock_e.gif
new file mode 100644 (file)
index 0000000..68fd6cf
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/lock_e.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/log_details_e.gif b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/log_details_e.gif
new file mode 100644 (file)
index 0000000..7ccc6a7
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/log_details_e.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/oic_logo_16x16.png b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/oic_logo_16x16.png
new file mode 100644 (file)
index 0000000..e6bbc36
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/oic_logo_16x16.png differ
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/oic_logo_32x32.png b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/oic_logo_32x32.png
new file mode 100644 (file)
index 0000000..d02a216
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/oic_logo_32x32.png differ
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/oic_logo_64x64.png b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/oic_logo_64x64.png
new file mode 100644 (file)
index 0000000..4fe3cbb
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/oic_logo_64x64.png differ
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/prop_d.gif b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/prop_d.gif
new file mode 100644 (file)
index 0000000..ec394d6
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/prop_d.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/prop_e.gif b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/prop_e.gif
new file mode 100644 (file)
index 0000000..d11c996
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/prop_e.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/sample.gif b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/sample.gif
new file mode 100644 (file)
index 0000000..34fb3c9
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/sample.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/trash_e.gif b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/trash_e.gif
new file mode 100644 (file)
index 0000000..bf961b3
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/trash_e.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/tree_mode_d.gif b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/tree_mode_d.gif
new file mode 100644 (file)
index 0000000..62bdbe2
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/tree_mode_d.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/tree_mode_e.gif b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/tree_mode_e.gif
new file mode 100644 (file)
index 0000000..dda8bae
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/tree_mode_e.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/unchecked.gif b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/unchecked.gif
new file mode 100644 (file)
index 0000000..342fa9d
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/unchecked.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/unknown_log.gif b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/unknown_log.gif
new file mode 100644 (file)
index 0000000..a54ccfe
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/unknown_log.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/warning_log.gif b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/warning_log.gif
new file mode 100644 (file)
index 0000000..14009e9
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/warning_log.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/plugin.xml b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/plugin.xml
new file mode 100644 (file)
index 0000000..1bc294b
--- /dev/null
@@ -0,0 +1,80 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<?eclipse version="3.4"?>
+<plugin>
+   <extension
+         point="org.eclipse.ui.perspectives">
+        <perspective
+             class="oic.simulator.clientcontroller.perspective.PerspectiveFactory"
+             icon="icons/oic_logo_16x16.png"
+             id="oic.simulator.clientcontroller.perspective"
+             name="Client Controller">
+        </perspective>
+   </extension>
+   <extension
+         point="org.eclipse.ui.views">
+        <category
+            id="oic.simulator.clientcontroller.category"
+            name="Client Controller">
+        </category>
+        <view category="oic.simulator.clientcontroller.category"
+            class="oic.simulator.clientcontroller.view.ResourceManagerView"
+            icon="icons/oic_logo_16x16.png"
+            id="oic.simulator.clientcontroller.view.resourcemanager"
+            name="Resource Manager"
+            restorable="true">
+        </view>
+        <view category="oic.simulator.clientcontroller.category"
+            class="oic.simulator.clientcontroller.view.MetaPropertiesView"
+            icon="icons/oic_logo_16x16.png"
+            id="oic.simulator.clientcontroller.view.metaproperties"
+            name="Properties"
+            restorable="true">
+        </view>
+        <view category="oic.simulator.clientcontroller.category"
+            class="oic.simulator.clientcontroller.view.AttributeView"
+            icon="icons/oic_logo_16x16.png"
+            id="oic.simulator.clientcontroller.view.attribute"
+            name="Attribute Manager"
+            restorable="true">
+        </view>
+        <view category="oic.simulator.clientcontroller.category"
+            class="oic.simulator.clientcontroller.view.MultiResourceOrchestrationView"
+            icon="icons/oic_logo_16x16.png"
+            id="oic.simulator.clientcontroller.view.orchestration"
+            name="Multi-Resource Automation"
+            restorable="true">
+        </view>
+        <view category="oic.simulator.clientcontroller.category"
+            class="oic.simulator.clientcontroller.view.LogView"
+            icon="icons/oic_logo_16x16.png"
+            id="oic.simulator.clientcontroller.view.log"
+            name="Simulator Log"
+            restorable="true">
+        </view>
+   </extension>
+   <extension
+         point="org.eclipse.ui.perspectiveExtensions">
+        <perspectiveExtension targetID="*">
+            <perspectiveShortcut 
+                 id="oic.simulator.clientcontroller.perspective">
+             </perspectiveShortcut>
+        </perspectiveExtension>
+        <perspectiveExtension targetID="oic.simulator.clientcontroller.perspective">
+            <viewShortcut
+                id="oic.simulator.clientcontroller.view.resourcemanager">
+            </viewShortcut>
+            <viewShortcut
+                id="oic.simulator.clientcontroller.view.metaproperties">
+            </viewShortcut>
+            <viewShortcut
+                id="oic.simulator.clientcontroller.view.attribute">
+            </viewShortcut>
+            <viewShortcut
+                id="oic.simulator.clientcontroller.view.orchestration">
+            </viewShortcut>
+            <viewShortcut
+                id="oic.simulator.clientcontroller.view.log">
+            </viewShortcut>
+        </perspectiveExtension>
+   </extension>
+</plugin>
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/Activator.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/Activator.java
new file mode 100644 (file)
index 0000000..5f22400
--- /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.
+ */
+
+package oic.simulator.clientcontroller;
+
+import oic.simulator.clientcontroller.manager.ImageManager;
+import oic.simulator.clientcontroller.manager.LogManager;
+import oic.simulator.clientcontroller.manager.ResourceManager;
+
+import org.eclipse.ui.plugin.AbstractUIPlugin;
+import org.osgi.framework.BundleContext;
+
+/**
+ * The activator class controls the plug-in life cycle.
+ */
+public class Activator extends AbstractUIPlugin {
+
+    // The plug-in ID
+    public static final String     PLUGIN_ID = "ClientControllerPlugin";
+
+    // The shared instance
+    private static Activator       plugin;
+
+    private static ResourceManager resourceManager;
+
+    private static LogManager      logManager;
+
+    private static ImageManager    imageManager;
+
+    static {
+        System.loadLibrary("SimulatorManager");
+    }
+
+    public Activator() {
+    }
+
+    public void start(BundleContext context) throws Exception {
+        super.start(context);
+        plugin = this;
+        setResourceManager(new ResourceManager());
+        setLogManager(new LogManager());
+        imageManager = ImageManager.getInstance();
+    }
+
+    public void stop(BundleContext context) throws Exception {
+        plugin = null;
+        // Stopping Resource Manager
+        if (null != resourceManager) {
+            resourceManager.shutdown();
+            resourceManager = null;
+        }
+        // Stopping Log Manager
+        if (null != logManager) {
+            logManager.shutdown();
+            logManager = null;
+        }
+        super.stop(context);
+    }
+
+    public static Activator getDefault() {
+        return plugin;
+    }
+
+    public ResourceManager getResourceManager() {
+        return resourceManager;
+    }
+
+    private static void setResourceManager(ResourceManager manager) {
+        Activator.resourceManager = manager;
+    }
+
+    public LogManager getLogManager() {
+        return logManager;
+    }
+
+    private static void setLogManager(LogManager logManager) {
+        Activator.logManager = logManager;
+    }
+
+    public ImageManager getImageManager() {
+        return imageManager;
+    }
+}
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/listener/IConfigurationUpload.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/listener/IConfigurationUpload.java
new file mode 100644 (file)
index 0000000..3b8f6fd
--- /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.clientcontroller.listener;
+
+import oic.simulator.clientcontroller.remoteresource.RemoteResource;
+
+/**
+ * Interface through which the configuration uploaded event is notified to the
+ * UI listeners.
+ */
+public interface IConfigurationUpload {
+    public void onConfigurationUploaded(RemoteResource resource);
+}
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/listener/IFindResourceUIListener.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/listener/IFindResourceUIListener.java
new file mode 100644 (file)
index 0000000..684fe89
--- /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.clientcontroller.listener;
+
+import oic.simulator.clientcontroller.remoteresource.RemoteResource;
+
+/**
+ * Interface through which the resource found notification is sent to the UI
+ * listeners.
+ */
+public interface IFindResourceUIListener {
+    public void onNewResourceFound(RemoteResource resource);
+}
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/listener/IGetUIListener.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/listener/IGetUIListener.java
new file mode 100644 (file)
index 0000000..6d752c5
--- /dev/null
@@ -0,0 +1,28 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package oic.simulator.clientcontroller.listener;
+
+import oic.simulator.clientcontroller.remoteresource.RemoteResource;
+
+/**
+ * Interface through which the GET responses are notified to the UI listeners.
+ */
+public interface IGetUIListener {
+    public void onGetCompleted(RemoteResource resource);
+
+    public void onGetFailed(RemoteResource resource);
+}
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/listener/ILogUIListener.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/listener/ILogUIListener.java
new file mode 100644 (file)
index 0000000..0afea77
--- /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.clientcontroller.listener;
+
+import java.util.List;
+
+import oic.simulator.logger.LogEntry;
+
+/**
+ * Interface through which the log events are notified to the UI listeners.
+ */
+public interface ILogUIListener {
+    public void logAdded(LogEntry added);
+
+    public void logChanged(List<LogEntry> entry);
+}
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/listener/IObserveUIListener.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/listener/IObserveUIListener.java
new file mode 100644 (file)
index 0000000..ca5f838
--- /dev/null
@@ -0,0 +1,29 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package oic.simulator.clientcontroller.listener;
+
+import oic.simulator.clientcontroller.remoteresource.RemoteResource;
+
+/**
+ * Interface through which the observe responses are notified to the UI
+ * listeners.
+ */
+public interface IObserveUIListener {
+    public void onObserveCompleted(RemoteResource resource);
+
+    public void onObserveFailed(RemoteResource resource);
+}
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/listener/IPostUIListener.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/listener/IPostUIListener.java
new file mode 100644 (file)
index 0000000..793eb76
--- /dev/null
@@ -0,0 +1,28 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package oic.simulator.clientcontroller.listener;
+
+import oic.simulator.clientcontroller.remoteresource.RemoteResource;
+
+/**
+ * Interface through which the POST responses are notified to the UI listeners.
+ */
+public interface IPostUIListener {
+    public void onPostCompleted(RemoteResource resource);
+
+    public void onPostFailed(RemoteResource resource);
+}
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/listener/IPutUIListener.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/listener/IPutUIListener.java
new file mode 100644 (file)
index 0000000..28eb3ff
--- /dev/null
@@ -0,0 +1,28 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package oic.simulator.clientcontroller.listener;
+
+import oic.simulator.clientcontroller.remoteresource.RemoteResource;
+
+/**
+ * Interface through which the PUT responses are notified to the UI listeners.
+ */
+public interface IPutUIListener {
+    public void onPutCompleted(RemoteResource resource);
+
+    public void onPutFailed(RemoteResource resource);
+}
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/listener/IResourceSelectionChangedUIListener.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/listener/IResourceSelectionChangedUIListener.java
new file mode 100644 (file)
index 0000000..51586cd
--- /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.clientcontroller.listener;
+
+import oic.simulator.clientcontroller.remoteresource.RemoteResource;
+
+/**
+ * Interface through which the resource selection UI event is notified to the UI
+ * listeners.
+ */
+public interface IResourceSelectionChangedUIListener {
+    public void onResourceSelectionChange(RemoteResource resource);
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/listener/IVerificationUIListener.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/listener/IVerificationUIListener.java
new file mode 100644 (file)
index 0000000..0956a68
--- /dev/null
@@ -0,0 +1,31 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package oic.simulator.clientcontroller.listener;
+
+import oic.simulator.clientcontroller.remoteresource.RemoteResource;
+
+/**
+ * Interface through which the automatic verification status events are sent to
+ * the UI listeners.
+ */
+public interface IVerificationUIListener {
+    public void onVerificationStarted(RemoteResource resource, int autoType);
+
+    public void onVerificationAborted(RemoteResource resource, int autoType);
+
+    public void onVerificationCompleted(RemoteResource resource, int autoType);
+}
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/manager/ImageManager.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/manager/ImageManager.java
new file mode 100644 (file)
index 0000000..b0b1f6c
--- /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.clientcontroller.manager;
+
+import java.net.URL;
+
+import oic.simulator.clientcontroller.Activator;
+import oic.simulator.clientcontroller.utils.Constants;
+
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.jface.resource.ImageRegistry;
+import org.eclipse.swt.graphics.Image;
+import org.osgi.framework.Bundle;
+
+/**
+ * Class which loads the icons/images into the image registry, and has methods
+ * to handle the image related requests from other UI modules.
+ */
+public class ImageManager {
+
+    private static ImageManager imageManager;
+
+    public static ImageManager getInstance() {
+        if (null == imageManager) {
+            imageManager = new ImageManager();
+        }
+        return imageManager;
+    }
+
+    static {
+        ImageRegistry r = Activator.getDefault().getImageRegistry();
+        Bundle bundle = Activator.getDefault().getBundle();
+
+        r.put(Constants.CHECKED, ImageDescriptor.createFromURL(bundle
+                .getEntry("icons/checked.gif")));
+        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")));
+        r.put(Constants.INFO_LOG, ImageDescriptor.createFromURL(bundle
+                .getEntry("/icons/info_log.gif")));
+        r.put(Constants.WARNING_LOG, ImageDescriptor.createFromURL(bundle
+                .getEntry("/icons/warning_log.gif")));
+        r.put(Constants.ERROR_LOG, ImageDescriptor.createFromURL(bundle
+                .getEntry("/icons/error_log.gif")));
+        r.put(Constants.UNKNOWN_LOG, ImageDescriptor.createFromURL(bundle
+                .getEntry("/icons/unknown_log.gif")));
+    }
+
+    public static Image getImage(String imagePath) {
+        if (null == imagePath || imagePath.length() < 1) {
+            return null;
+        }
+        URL imageURL = Activator.getDefault().getBundle().getEntry(imagePath);
+        ImageDescriptor descriptor = ImageDescriptor.createFromURL(imageURL);
+        return descriptor.createImage();
+    }
+}
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/manager/LogManager.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/manager/LogManager.java
new file mode 100644 (file)
index 0000000..03700e4
--- /dev/null
@@ -0,0 +1,256 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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.manager;
+
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.LinkedList;
+
+import oic.simulator.clientcontroller.Activator;
+import oic.simulator.clientcontroller.listener.ILogUIListener;
+import oic.simulator.clientcontroller.utils.Constants;
+import oic.simulator.logger.LogEntry;
+import oic.simulator.logger.LoggerCallback;
+
+import org.eclipse.jface.resource.ImageRegistry;
+import org.eclipse.swt.graphics.Image;
+import org.oic.simulator.ILogger;
+import org.oic.simulator.ILogger.Level;
+import org.oic.simulator.SimulatorManager;
+
+/**
+ * Class which handles the native logs, maintains log entries and updates the
+ * UI.
+ */
+public class LogManager {
+    private LinkedList<LogEntry>         entries           = new LinkedList<LogEntry>();
+    private ArrayList<ILogUIListener>    listeners         = new ArrayList<ILogUIListener>();
+    private LinkedList<LogEntry>         visibleEntries    = new LinkedList<LogEntry>();
+    private HashMap<Integer, Boolean>    visibleSeverities = new HashMap<Integer, Boolean>();
+
+    private ILogger                      logger;
+    private LogManagerSynchronizerThread synchronizerThread;
+    private Thread                       threadHandle;
+
+    public LogManager() {
+        synchronizerThread = new LogManagerSynchronizerThread();
+        threadHandle = new Thread(synchronizerThread);
+        threadHandle.setName("OIC Simulator event queue");
+        threadHandle.start();
+
+        // Set the logger callback with the native layer
+        logger = new LoggerCallback();
+        SimulatorManager.setLogger(logger);
+    }
+
+    private static class LogManagerSynchronizerThread implements Runnable {
+
+        LinkedList<Runnable> eventQueue = new LinkedList<Runnable>();
+
+        @Override
+        public void run() {
+            while (!Thread.interrupted()) {
+
+                synchronized (this) {
+                    try {
+                        while (eventQueue.isEmpty()) {
+                            this.wait();
+                            break;
+                        }
+                    } catch (InterruptedException e) {
+                        return;
+                    }
+                }
+
+                Runnable pop;
+                synchronized (this) {
+                    pop = eventQueue.pop();
+                }
+                try {
+                    pop.run();
+                } catch (Exception e) {
+                    if (e instanceof InterruptedException) {
+                        return;
+                    }
+                    e.printStackTrace();
+                }
+            }
+        }
+
+        public void addToQueue(Runnable event) {
+            synchronized (this) {
+                eventQueue.add(event);
+                this.notify();
+            }
+        }
+    }
+
+    public void log(int severity, Date date, String msg) {
+        final LogEntry logEntry = new LogEntry(severity, date, msg);
+        synchronizerThread.addToQueue(new Runnable() {
+            @Override
+            public void run() {
+                boolean notify = false;
+                synchronized (entries) {
+                    entries.add(logEntry);
+                    Boolean showEntry = LogManager.this.visibleSeverities
+                            .get(logEntry.getSeverity());
+                    if (showEntry != null) {
+                        if (showEntry) {
+                            visibleEntries.add(logEntry);
+                            notify = true;
+                        }
+                    }
+                    if (entries.size() > Constants.LOG_SIZE) {
+                        entries.pop();
+                    }
+                    if (visibleEntries.size() > Constants.LOG_SIZE) {
+                        visibleEntries.pop();
+                        notify = true;
+                    }
+                }
+                if (notify) {
+                    notifyListeners(logEntry);
+                }
+            }
+        });
+    }
+
+    public void applyFilter(final HashMap<Integer, Boolean> visibleSeverities) {
+        synchronizerThread.addToQueue(new Runnable() {
+
+            @Override
+            public void run() {
+                LinkedList<LogEntry> newLogs = new LinkedList<LogEntry>();
+                synchronized (entries) {
+                    LogManager.this.visibleSeverities = visibleSeverities;
+                    for (LogEntry logEntry : entries) {
+                        if (LogManager.this.visibleSeverities.get(logEntry
+                                .getSeverity())) {
+                            newLogs.add(logEntry);
+                        }
+                    }
+                }
+                visibleEntries = newLogs;
+                notifyListeners();
+            }
+        });
+
+    }
+
+    private void notifyListeners() {
+        for (ILogUIListener l : listeners) {
+            l.logChanged(new ArrayList<LogEntry>(visibleEntries));
+        }
+    }
+
+    private void notifyListeners(LogEntry added) {
+        for (ILogUIListener l : listeners) {
+            l.logAdded(added);
+        }
+    }
+
+    public void clearLog() {
+        synchronizerThread.addToQueue(new Runnable() {
+
+            @Override
+            public void run() {
+                synchronized (entries) {
+                    entries = new LinkedList<LogEntry>();
+                    visibleEntries = new LinkedList<LogEntry>();
+                }
+                notifyListeners();
+            }
+        });
+    }
+
+    public void removeEntry(final LogEntry element) {
+        synchronizerThread.addToQueue(new Runnable() {
+
+            @Override
+            public void run() {
+                synchronized (entries) {
+                    entries.remove(element);
+                    visibleEntries.remove(element);
+                }
+                notifyListeners();
+            }
+        });
+    }
+
+    public ArrayList<LogEntry> getLogEntries() {
+        synchronized (entries) {
+            return new ArrayList<LogEntry>(entries);
+        }
+    }
+
+    public void addLogListener(final ILogUIListener listener) {
+        synchronizerThread.addToQueue(new Runnable() {
+            @Override
+            public void run() {
+                if (!listeners.contains(listener)) {
+                    listeners.add(listener);
+                }
+            }
+        });
+    }
+
+    public void removeLogListener(final ILogUIListener listener) {
+        synchronizerThread.addToQueue(new Runnable() {
+            @Override
+            public void run() {
+                if (!listeners.contains(listener)) {
+                    listeners.remove(listener);
+                }
+            }
+        });
+    }
+
+    public void shutdown() {
+        threadHandle.interrupt();
+    }
+
+    public static String getSeverityName(int severity) {
+        if (severity == Level.INFO.ordinal()) {
+            return Constants.INFO;
+        } else if (severity == Level.WARNING.ordinal()) {
+            return Constants.WARNING;
+        } else if (severity == Level.ERROR.ordinal()) {
+            return Constants.ERROR;
+        } else if (severity == Level.DEBUG.ordinal()) {
+            return Constants.DEBUG;
+        } else {
+            return Constants.UNKNOWN;
+        }
+    }
+
+    public static Image getSeverityIcon(int severity) {
+        ImageRegistry r = Activator.getDefault().getImageRegistry();
+        if (severity == Level.INFO.ordinal()) {
+            return r.get(Constants.INFO_LOG);
+        } else if (severity == Level.WARNING.ordinal()) {
+            return r.get(Constants.WARNING_LOG);
+        } else if (severity == Level.ERROR.ordinal()) {
+            return r.get(Constants.ERROR_LOG);
+        } else if (severity == Level.DEBUG.ordinal()) {
+            return r.get(Constants.DEBUG_LOG);
+        } else {
+            return r.get(Constants.UNKNOWN_LOG);
+        }
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/manager/ResourceManager.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/manager/ResourceManager.java
new file mode 100644 (file)
index 0000000..20e7d6c
--- /dev/null
@@ -0,0 +1,1507 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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.manager;
+
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import oic.simulator.clientcontroller.Activator;
+import oic.simulator.clientcontroller.listener.IConfigurationUpload;
+import oic.simulator.clientcontroller.listener.IFindResourceUIListener;
+import oic.simulator.clientcontroller.listener.IGetUIListener;
+import oic.simulator.clientcontroller.listener.IObserveUIListener;
+import oic.simulator.clientcontroller.listener.IPostUIListener;
+import oic.simulator.clientcontroller.listener.IPutUIListener;
+import oic.simulator.clientcontroller.listener.IResourceSelectionChangedUIListener;
+import oic.simulator.clientcontroller.listener.IVerificationUIListener;
+import oic.simulator.clientcontroller.remoteresource.MetaProperty;
+import oic.simulator.clientcontroller.remoteresource.PutPostAttributeModel;
+import oic.simulator.clientcontroller.remoteresource.RemoteResource;
+import oic.simulator.clientcontroller.remoteresource.RemoteResourceAttribute;
+import oic.simulator.clientcontroller.utils.Constants;
+import oic.simulator.clientcontroller.utils.Utility;
+
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.swt.graphics.Image;
+import org.oic.simulator.ILogger.Level;
+import org.oic.simulator.ResourceAttribute;
+import org.oic.simulator.ResourceAttribute.Range;
+import org.oic.simulator.ResourceAttribute.Type;
+import org.oic.simulator.SimulatorException;
+import org.oic.simulator.SimulatorManager;
+import org.oic.simulator.SimulatorResourceModel;
+import org.oic.simulator.clientcontroller.IFindResourceListener;
+import org.oic.simulator.clientcontroller.IGetListener;
+import org.oic.simulator.clientcontroller.IObserveListener;
+import org.oic.simulator.clientcontroller.IPostListener;
+import org.oic.simulator.clientcontroller.IPutListener;
+import org.oic.simulator.clientcontroller.IVerificationListener;
+import org.oic.simulator.clientcontroller.SimulatorObserveType;
+import org.oic.simulator.clientcontroller.SimulatorRemoteResource;
+import org.oic.simulator.clientcontroller.SimulatorVerificationType;
+
+/**
+ * This class acts as an interface between the simulator java SDK and the
+ * various UI modules. It maintains all the details of resources and provides
+ * other UI modules with the information required. It also handles responses for
+ * find, GET, PUT, POST, Observe and automatic verification operations from
+ * native layer and propagates those events to the registered UI listeners.
+ */
+public class ResourceManager {
+
+    private Set<String>                               lastKnownSearchTypes;
+
+    private RemoteResource                            currentResourceInSelection;
+
+    private IFindResourceListener                     findResourceListener;
+    private IGetListener                              getListener;
+    private IPutListener                              putListener;
+    private IPostListener                             postListener;
+    private IObserveListener                          observeListener;
+    private IVerificationListener                     verifyListener;
+
+    private ResponseSynchronizerThread                synchronizerThread;
+
+    private Thread                                    threadHandle;
+
+    private List<IFindResourceUIListener>             findResourceUIListeners;
+    private List<IResourceSelectionChangedUIListener> resourceSelectionChangedUIListeners;
+    private List<IGetUIListener>                      getUIListeners;
+    private List<IPutUIListener>                      putUIListeners;
+    private List<IPostUIListener>                     postUIListeners;
+    private List<IObserveUIListener>                  observeUIListeners;
+    private List<IVerificationUIListener>             verificationUIListeners;
+    private List<IConfigurationUpload>                configUploadUIListeners;
+
+    // Map with Server ID as key and the complete object as the value
+    private Map<String, RemoteResource>               resourceMap;
+    private List<RemoteResource>                      favoriteResources;
+    // TODO: Temporarily maintaining a list of favorite resource URIs.
+    private List<String>                              favoriteURIList;
+
+    public ResourceManager() {
+        resourceMap = new HashMap<String, RemoteResource>();
+        favoriteResources = new ArrayList<RemoteResource>();
+        favoriteURIList = new ArrayList<String>();
+        findResourceUIListeners = new ArrayList<IFindResourceUIListener>();
+        resourceSelectionChangedUIListeners = new ArrayList<IResourceSelectionChangedUIListener>();
+        getUIListeners = new ArrayList<IGetUIListener>();
+        putUIListeners = new ArrayList<IPutUIListener>();
+        postUIListeners = new ArrayList<IPostUIListener>();
+        observeUIListeners = new ArrayList<IObserveUIListener>();
+        verificationUIListeners = new ArrayList<IVerificationUIListener>();
+        configUploadUIListeners = new ArrayList<IConfigurationUpload>();
+
+        findResourceListener = new IFindResourceListener() {
+
+            @Override
+            public void onResourceCallback(
+                    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.
+                        String uid = resourceN.getId();
+                        if (null == uid) {
+                            return;
+                        }
+                        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);
+
+                        // Add the resource in local data structure
+                        addResourceDetails(resource);
+
+                        // Add resource to favorite list
+                        String uri = resource.getResourceURI();
+                        if (null != uri) {
+                            if (favoriteURIList.contains(uri)) {
+                                addResourcetoFavorites(resource);
+                            }
+                        }
+                        // Notify the UI listener
+                        newResourceFoundNotification(resource);
+
+                        // Send an initial GET request to get the resource
+                        // attributes
+                        try {
+                            resourceN.get(null, getListener);
+                        } catch (SimulatorException e) {
+                            Activator
+                                    .getDefault()
+                                    .getLogManager()
+                                    .log(Level.ERROR.ordinal(),
+                                            new Date(),
+                                            "[" + e.getClass().getSimpleName()
+                                                    + "]" + e.code().toString()
+                                                    + "-" + e.message());
+                        }
+                    }
+                });
+            }
+        };
+
+        getListener = new IGetListener() {
+            @Override
+            public void onGetCompleted(final String uid,
+                    final SimulatorResourceModel resourceModelN) {
+                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);
+                        }
+                    }
+                });
+            }
+
+            @Override
+            public void onGetFailed(Throwable th) {
+                synchronizerThread.addToQueue(new Runnable() {
+                    @Override
+                    public void run() {
+                    }
+                });
+            }
+        };
+
+        putListener = new IPutListener() {
+
+            @Override
+            public void onPutCompleted(final String uid,
+                    final SimulatorResourceModel resourceModelN) {
+                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);
+                        }
+                    }
+                });
+            }
+
+            @Override
+            public void onPutFailed(Throwable th) {
+                synchronizerThread.addToQueue(new Runnable() {
+                    @Override
+                    public void run() {
+                    }
+                });
+            }
+        };
+
+        postListener = new IPostListener() {
+            @Override
+            public void onPostCompleted(final String uid,
+                    final SimulatorResourceModel resourceModelN) {
+                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
+                            postCompleteNotification(resource);
+                        }
+                    }
+                });
+            }
+
+            @Override
+            public void onPostFailed(Throwable th) {
+                synchronizerThread.addToQueue(new Runnable() {
+                    @Override
+                    public void run() {
+                    }
+                });
+            }
+        };
+
+        observeListener = new IObserveListener() {
+
+            @Override
+            public void onObserveCompleted(final String uid,
+                    final SimulatorResourceModel resourceModelN, final int seq) {
+                System.out.println("ResourceManager: onObserveCallback()");
+                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
+                            observeCompleteNotification(resource);
+                        }
+                    }
+                });
+            }
+
+            @Override
+            public void onObserveFailed(Throwable th) {
+                // TODO Auto-generated method stub
+            }
+        };
+
+        verifyListener = new IVerificationListener() {
+
+            @Override
+            public void onVerificationStarted(final String uid, final int autoId) {
+                System.out.println("onVefificationStarted: " + autoId);
+                synchronizerThread.addToQueue(new Runnable() {
+                    @Override
+                    public void run() {
+                        RemoteResource resource = getResource(uid);
+                        if (null == resource) {
+                            return;
+                        }
+                        // Update the automation status.
+                        resource.updateAutomationStatus(autoId, true);
+
+                        int autoType = resource.getAutomationtype(autoId);
+
+                        // Notify the listeners.
+                        verificationStartedNotification(resource, autoType);
+                    }
+                });
+            }
+
+            @Override
+            public void onVerificationCompleted(final String uid,
+                    final int autoId) {
+                System.out.println("onVefificationCompleted: " + autoId);
+                synchronizerThread.addToQueue(new Runnable() {
+                    @Override
+                    public void run() {
+                        RemoteResource resource = getResource(uid);
+                        if (null == resource) {
+                            return;
+                        }
+                        // Update the automation status.
+                        resource.updateAutomationStatus(autoId, false);
+
+                        int autoType = resource.getAutomationtype(autoId);
+
+                        // Notify the listeners.
+                        verificationCompletedNotification(resource, autoType);
+                    }
+                });
+            }
+
+            @Override
+            public void onVerificationAborted(final String uid, final int autoId) {
+                System.out.println("onVefificationAborted: " + autoId);
+                synchronizerThread.addToQueue(new Runnable() {
+                    @Override
+                    public void run() {
+                        RemoteResource resource = getResource(uid);
+                        if (null == resource) {
+                            return;
+                        }
+                        // Update the automation status.
+                        resource.updateAutomationStatus(autoId, false);
+
+                        int autoType = resource.getAutomationtype(autoId);
+
+                        // Notify the listeners.
+                        verificationAbortedNotification(resource, autoType);
+                    }
+                });
+            }
+        };
+
+        synchronizerThread = new ResponseSynchronizerThread();
+        threadHandle = new Thread(synchronizerThread);
+        threadHandle.setName("Simulator Client Controller Event Queue");
+        threadHandle.start();
+    }
+
+    private RemoteResource handleResponse(String uid,
+            SimulatorResourceModel resourceModelN) {
+        if (null == uid || null == resourceModelN) {
+            return null;
+        }
+
+        // Update the local model
+        RemoteResource resource;
+        resource = getResource(uid);
+        if (null == resource) {
+            return null;
+        }
+
+        resource.setResourceModel(resourceModelN);
+        Map<String, RemoteResourceAttribute> attributeMap = fetchResourceAttributesFromModel(resourceModelN);
+
+        // TODO: For debugging
+        if (null != attributeMap) {
+            RemoteResourceAttribute.printAttributes(attributeMap);
+            System.out.println("Attributes found: " + (null != attributeMap));
+            System.out.println("No of attributes: " + attributeMap.size());
+
+            resource.setResourceAttributesMap(attributeMap);
+        }
+        return resource;
+    }
+
+    private static class ResponseSynchronizerThread implements Runnable {
+
+        LinkedList<Runnable> responseQueue = new LinkedList<Runnable>();
+
+        @Override
+        public void run() {
+            while (!Thread.interrupted()) {
+                synchronized (this) {
+                    try {
+                        while (responseQueue.isEmpty()) {
+                            this.wait();
+                            break;
+                        }
+                    } catch (InterruptedException e) {
+                        return;
+                    }
+                }
+
+                Runnable thread;
+                synchronized (this) {
+                    thread = responseQueue.pop();
+                }
+                try {
+                    thread.run();
+                } catch (Exception e) {
+                    if (e instanceof InterruptedException) {
+                        return;
+                    }
+                    e.printStackTrace();
+                }
+            }
+        }
+
+        public void addToQueue(Runnable event) {
+            synchronized (this) {
+                responseQueue.add(event);
+                this.notify();
+            }
+        }
+    }
+
+    public void addResourceSelectionChangedUIListener(
+            IResourceSelectionChangedUIListener resourceSelectionChangedUIListener) {
+        synchronized (resourceSelectionChangedUIListeners) {
+            resourceSelectionChangedUIListeners
+                    .add(resourceSelectionChangedUIListener);
+        }
+    }
+
+    public void addGetUIListener(IGetUIListener getUIListener) {
+        synchronized (getUIListeners) {
+            getUIListeners.add(getUIListener);
+        }
+    }
+
+    public void addPutUIListener(IPutUIListener putUIListener) {
+        synchronized (putUIListeners) {
+            putUIListeners.add(putUIListener);
+        }
+    }
+
+    public void addPostUIListener(IPostUIListener postUIListener) {
+        synchronized (postUIListeners) {
+            postUIListeners.add(postUIListener);
+        }
+    }
+
+    public void addObserveUIListener(IObserveUIListener observeUIListener) {
+        synchronized (observeUIListeners) {
+            observeUIListeners.add(observeUIListener);
+        }
+    }
+
+    public void addVerificationUIListener(
+            IVerificationUIListener verificationUIListener) {
+        synchronized (verificationUIListeners) {
+            verificationUIListeners.add(verificationUIListener);
+        }
+    }
+
+    public void addConfigUploadUIListener(IConfigurationUpload configListener) {
+        synchronized (configUploadUIListeners) {
+            configUploadUIListeners.add(configListener);
+        }
+    }
+
+    public void removeResourceSelectionChangedUIListener(
+            IResourceSelectionChangedUIListener listener) {
+        synchronized (resourceSelectionChangedUIListeners) {
+            if (null != listener
+                    && resourceSelectionChangedUIListeners.size() > 0) {
+                resourceSelectionChangedUIListeners.remove(listener);
+            }
+        }
+    }
+
+    public void removeGetUIListener(IGetUIListener getUIListener) {
+        synchronized (getUIListeners) {
+            getUIListeners.remove(getUIListener);
+        }
+    }
+
+    public void removePutUIListener(IPutUIListener putUIListener) {
+        synchronized (putUIListeners) {
+            putUIListeners.remove(putUIListener);
+        }
+    }
+
+    public void removePostUIListener(IPostUIListener postUIListener) {
+        synchronized (postUIListeners) {
+            postUIListeners.remove(postUIListener);
+        }
+    }
+
+    public void removeObserveUIListener(IObserveUIListener observeUIListener) {
+        synchronized (observeUIListeners) {
+            observeUIListeners.remove(observeUIListener);
+        }
+    }
+
+    public void removeVerificationUIListener(
+            IVerificationUIListener verificationUIListener) {
+        synchronized (verificationUIListeners) {
+            verificationUIListeners.remove(verificationUIListener);
+        }
+    }
+
+    public void removeConfigUploadUIListener(IConfigurationUpload configListener) {
+        synchronized (configUploadUIListeners) {
+            configUploadUIListeners.remove(configListener);
+        }
+    }
+
+    public void addResourcetoFavorites(RemoteResource resource) {
+        if (null == resource) {
+            return;
+        }
+        resource.setFavorite(true);
+        synchronized (favoriteResources) {
+            favoriteResources.add(resource);
+            favoriteURIList.add(resource.getResourceURI());
+        }
+    }
+
+    public void removeResourceFromFavorites(RemoteResource resource) {
+        if (null == resource) {
+            return;
+        }
+        resource.setFavorite(false);
+        synchronized (favoriteResources) {
+            favoriteResources.remove(resource);
+        }
+    }
+
+    public void removeResourceURIFromFavorites(RemoteResource resource) {
+        if (null == resource) {
+            return;
+        }
+        synchronized (favoriteURIList) {
+            favoriteURIList.remove(resource.getResourceURI());
+        }
+    }
+
+    public synchronized RemoteResource getCurrentResourceInSelection() {
+        return currentResourceInSelection;
+    }
+
+    public synchronized void setCurrentResourceInSelection(
+            RemoteResource resource) {
+        this.currentResourceInSelection = resource;
+    }
+
+    private void addResourceDetails(RemoteResource remoteResource) {
+        if (null != remoteResource) {
+            synchronized (resourceMap) {
+                resourceMap.put(remoteResource.getuId(), remoteResource);
+            }
+        }
+    }
+
+    public void addFindresourceUIListener(IFindResourceUIListener listener) {
+        if (null == listener) {
+            return;
+        }
+        synchronized (findResourceUIListeners) {
+            findResourceUIListeners.add(listener);
+        }
+    }
+
+    public void removeFindresourceUIListener(IFindResourceUIListener listener) {
+        if (null == listener) {
+            return;
+        }
+        synchronized (findResourceUIListeners) {
+            findResourceUIListeners.remove(listener);
+        }
+    }
+
+    private RemoteResource fetchResourceDetails(
+            SimulatorRemoteResource remoteResourceN) {
+        if (null == remoteResourceN) {
+            return null;
+        }
+        RemoteResource remoteResource = new RemoteResource();
+        remoteResource.setuId(remoteResourceN.getId());
+        remoteResource.setResourceURI(remoteResourceN.getUri());
+        remoteResource.setHost(remoteResourceN.getHost());
+        remoteResource.setResourceTypes(remoteResourceN.getResourceTypes());
+        remoteResource.setResourceInterfaces(remoteResourceN
+                .getResourceInterfaces());
+        remoteResource.setConnectivityType(remoteResourceN
+                .getConnectivityType());
+        remoteResource.setObservable(remoteResourceN.getIsObservable());
+        return remoteResource;
+    }
+
+    private boolean isUidExist(String uid) {
+        boolean exist;
+        synchronized (resourceMap) {
+            exist = resourceMap.containsKey(uid);
+        }
+        return exist;
+    }
+
+    private RemoteResource getResource(String uid) {
+        if (null == uid) {
+            return null;
+        }
+        RemoteResource resource;
+        synchronized (resourceMap) {
+            resource = resourceMap.get(uid);
+        }
+        return resource;
+    }
+
+    private Map<String, RemoteResourceAttribute> fetchResourceAttributesFromModel(
+            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;
+            }
+            if (null != attributeMapN) {
+                resourceAttributeMap = new HashMap<String, RemoteResourceAttribute>();
+
+                Set<String> attNameSet = attributeMapN.keySet();
+                String attName;
+                Object attValueObj;
+                ResourceAttribute attributeN;
+                RemoteResourceAttribute attribute;
+                Iterator<String> attNameItr = attNameSet.iterator();
+                while (attNameItr.hasNext()) {
+                    attName = attNameItr.next();
+                    attributeN = attributeMapN.get(attName);
+                    if (null != attributeN) {
+                        attribute = new RemoteResourceAttribute();
+                        attribute.setResourceAttribute(attributeN);
+                        attribute.setAttributeName(attName);
+
+                        attValueObj = attributeN.getValue();
+                        if (null != attValueObj) {
+                            attribute.setAttributeValue(attValueObj);
+                        }
+
+                        // Set the attribute type
+                        attribute.setAttValBaseType(attributeN.getBaseType());
+                        attribute.setAttValType(attributeN.getType());
+
+                        // Set the range and allowed values
+                        Range range = attributeN.getRange();
+                        if (null != range) {
+                            attribute.setMinValue(range.getMin());
+                            attribute.setMaxValue(range.getMax());
+                        } else {
+                            Object[] values = attributeN.getAllowedValues();
+                            if (null != values && values.length > 0) {
+                                List<Object> valueList = new ArrayList<Object>();
+                                for (Object obj : values) {
+                                    valueList.add(obj);
+                                }
+                                attribute.setAllowedValues(valueList);
+                            }
+                            /*
+                             * Type baseType = attribute.getAttValBaseType();
+                             * 
+                             * if(baseType == Type.INT) { //int[] values =
+                             * attributeN.getAllowedValues();
+                             * attribute.setAllowedValues
+                             * (attributeN.getAllowedValues()); } else
+                             * if(baseType == Type.DOUBLE) { double[] values =
+                             * attributeN.getAllowedValues();
+                             * attribute.setAllowedValues
+                             * (Utility.converArrayToList(values)); } else
+                             * if(baseType == Type.BOOL) { //boolean[] values =
+                             * attributeN.getAllowedValues(); List<Object> obj =
+                             * new ArrayList<Object>(); obj.add(true);
+                             * obj.add(false); attribute.setAllowedValues(obj);
+                             * } else if(baseType == Type.STRING) { String[]
+                             * values = attributeN.getAllowedValues();
+                             * attribute.
+                             * setAllowedValues(Utility.converArrayToList
+                             * (values)); }
+                             */
+                        }
+                        resourceAttributeMap.put(attName, attribute);
+                    }
+                }
+            }
+        }
+        return resourceAttributeMap;
+    }
+
+    private void newResourceFoundNotification(RemoteResource resource) {
+        synchronized (findResourceUIListeners) {
+            if (findResourceUIListeners.size() > 0) {
+                IFindResourceUIListener listener;
+                Iterator<IFindResourceUIListener> listenerItr = findResourceUIListeners
+                        .iterator();
+                while (listenerItr.hasNext()) {
+                    listener = listenerItr.next();
+                    if (null != listener) {
+                        listener.onNewResourceFound(resource);
+                    }
+                }
+            }
+        }
+    }
+
+    private void resourceSelectionChangedUINotification(RemoteResource resource) {
+        synchronized (resourceSelectionChangedUIListeners) {
+            if (resourceSelectionChangedUIListeners.size() > 0) {
+                IResourceSelectionChangedUIListener listener;
+                Iterator<IResourceSelectionChangedUIListener> listenerItr = resourceSelectionChangedUIListeners
+                        .iterator();
+                while (listenerItr.hasNext()) {
+                    listener = listenerItr.next();
+                    if (null != listener) {
+                        listener.onResourceSelectionChange(resource);
+                    }
+                }
+            }
+        }
+    }
+
+    private void getCompleteNotification(RemoteResource resource) {
+        synchronized (getUIListeners) {
+            if (getUIListeners.size() > 0) {
+                IGetUIListener listener;
+                Iterator<IGetUIListener> listenerItr = getUIListeners
+                        .iterator();
+                while (listenerItr.hasNext()) {
+                    listener = listenerItr.next();
+                    if (null != listener) {
+                        listener.onGetCompleted(resource);
+                    }
+                }
+            }
+        }
+    }
+
+    private void putCompleteNotification(RemoteResource resource) {
+        synchronized (putUIListeners) {
+            if (putUIListeners.size() > 0) {
+                IPutUIListener listener;
+                Iterator<IPutUIListener> listenerItr = putUIListeners
+                        .iterator();
+                while (listenerItr.hasNext()) {
+                    listener = listenerItr.next();
+                    if (null != listener) {
+                        listener.onPutCompleted(resource);
+                    }
+                }
+            }
+        }
+    }
+
+    private void postCompleteNotification(RemoteResource resource) {
+        synchronized (postUIListeners) {
+            if (postUIListeners.size() > 0) {
+                IPostUIListener listener;
+                Iterator<IPostUIListener> listenerItr = postUIListeners
+                        .iterator();
+                while (listenerItr.hasNext()) {
+                    listener = listenerItr.next();
+                    if (null != listener) {
+                        listener.onPostCompleted(resource);
+                    }
+                }
+            }
+        }
+    }
+
+    private void observeCompleteNotification(RemoteResource resource) {
+        synchronized (observeUIListeners) {
+            if (observeUIListeners.size() > 0) {
+                IObserveUIListener listener;
+                Iterator<IObserveUIListener> listenerItr = observeUIListeners
+                        .iterator();
+                while (listenerItr.hasNext()) {
+                    listener = listenerItr.next();
+                    if (null != listener) {
+                        listener.onObserveCompleted(resource);
+                    }
+                }
+            }
+        }
+    }
+
+    private void verificationStartedNotification(RemoteResource resource,
+            int autoType) {
+        synchronized (verificationUIListeners) {
+            if (verificationUIListeners.size() > 0) {
+                IVerificationUIListener listener;
+                Iterator<IVerificationUIListener> listenerItr = verificationUIListeners
+                        .iterator();
+                while (listenerItr.hasNext()) {
+                    listener = listenerItr.next();
+                    if (null != listener) {
+                        listener.onVerificationStarted(resource, autoType);
+                    }
+                }
+            }
+        }
+    }
+
+    private void verificationAbortedNotification(RemoteResource resource,
+            int autoType) {
+        synchronized (verificationUIListeners) {
+            if (verificationUIListeners.size() > 0) {
+                IVerificationUIListener listener;
+                Iterator<IVerificationUIListener> listenerItr = verificationUIListeners
+                        .iterator();
+                while (listenerItr.hasNext()) {
+                    listener = listenerItr.next();
+                    if (null != listener) {
+                        listener.onVerificationAborted(resource, autoType);
+                    }
+                }
+            }
+        }
+    }
+
+    private void verificationCompletedNotification(RemoteResource resource,
+            int autoType) {
+        synchronized (verificationUIListeners) {
+            if (verificationUIListeners.size() > 0) {
+                IVerificationUIListener listener;
+                Iterator<IVerificationUIListener> listenerItr = verificationUIListeners
+                        .iterator();
+                while (listenerItr.hasNext()) {
+                    listener = listenerItr.next();
+                    if (null != listener) {
+                        listener.onVerificationCompleted(resource, autoType);
+                    }
+                }
+            }
+        }
+    }
+
+    private void configUploadedNotification(RemoteResource resource) {
+        synchronized (configUploadUIListeners) {
+            if (configUploadUIListeners.size() > 0) {
+                IConfigurationUpload listener;
+                Iterator<IConfigurationUpload> listenerItr = configUploadUIListeners
+                        .iterator();
+                while (listenerItr.hasNext()) {
+                    listener = listenerItr.next();
+                    if (null != listener) {
+                        listener.onConfigurationUploaded(resource);
+                    }
+                }
+            }
+        }
+    }
+
+    // TODO: Temporarily used to display the resource in the UI
+    public List<String> getURIList() {
+        List<String> list = new ArrayList<String>();
+        synchronized (resourceMap) {
+            /*
+             * Set<String> idSet = resourceMap.keySet(); Iterator<String> idItr
+             * = idSet.iterator(); String sId; RemoteResource resource;
+             * while(idItr.hasNext()) { sId = idItr.next(); resource =
+             * resourceMap.get(sId); if(null == resource) { continue; }
+             * list.add(resource.getResourceURI()); }
+             */
+            Set<String> uriSet = resourceMap.keySet();
+            Iterator<String> uriItr = uriSet.iterator();
+            String uri;
+            while (uriItr.hasNext()) {
+                uri = uriItr.next();
+                if (null != uri) {
+                    list.add(uri);
+                }
+            }
+
+            // Sort the types
+            Collections.sort(list);
+        }
+        return list;
+    }
+
+    public synchronized Set<String> getLastKnownSearchTypes() {
+        return lastKnownSearchTypes;
+    }
+
+    public synchronized void setLastKnownSearchTypes(
+            Set<String> lastKnownSearchTypes) {
+        this.lastKnownSearchTypes = lastKnownSearchTypes;
+    }
+
+    public boolean findResourceRequest(Set<String> searchTypes) {
+        if (null == searchTypes || searchTypes.size() < 1) {
+            return false;
+        }
+        boolean result = false;
+        Iterator<String> searchItr = searchTypes.iterator();
+        String rType;
+        while (searchItr.hasNext()) {
+            rType = searchItr.next();
+            try {
+                SimulatorManager.findResources(rType, findResourceListener);
+                result = true;
+            } catch (SimulatorException e) {
+                Activator
+                        .getDefault()
+                        .getLogManager()
+                        .log(Level.ERROR.ordinal(),
+                                new Date(),
+                                "[" + e.getClass().getSimpleName() + "]"
+                                        + e.code().toString() + "-"
+                                        + e.message());
+            }
+        }
+        return result;
+    }
+
+    public void deleteResources(final Set<String> searchTypes) {
+        if (null == searchTypes || searchTypes.size() < 1) {
+            return;
+        }
+        new Thread() {
+            public void run() {
+                Iterator<String> typeItr = searchTypes.iterator();
+                String resType;
+                while (typeItr.hasNext()) {
+                    resType = typeItr.next();
+                    deleteResourcesByType(resType);
+
+                    // Change the current resource in selection
+                    updateCurrentResourceInSelection(searchTypes);
+                }
+            }
+        }.start();
+    }
+
+    private void updateCurrentResourceInSelection(Set<String> searchTypes) {
+        if (null == searchTypes || searchTypes.size() < 1) {
+            return;
+        }
+        RemoteResource resourceInSelection = getCurrentResourceInSelection();
+        if (null == resourceInSelection) {
+            return;
+        }
+        List<String> typesOfSelection = resourceInSelection.getResourceTypes();
+        if (null == typesOfSelection || typesOfSelection.size() < 1) {
+            return;
+        }
+        Iterator<String> itr = typesOfSelection.iterator();
+        String type;
+        while (itr.hasNext()) {
+            type = itr.next();
+            if (searchTypes.contains(type)) {
+                setCurrentResourceInSelection(null);
+                resourceSelectionChangedUINotification(null);
+                break;
+            }
+        }
+    }
+
+    private void deleteResourcesByType(String resourceType) {
+        if (null == resourceType) {
+            return;
+        }
+        synchronized (resourceMap) {
+            Set<String> keySet = resourceMap.keySet();
+            if (null == keySet) {
+                return;
+            }
+            Iterator<String> keyItr = keySet.iterator();
+            String uId;
+            RemoteResource resource;
+            boolean exist;
+            List<String> types;
+            while (keyItr.hasNext()) {
+                uId = keyItr.next();
+                resource = resourceMap.get(uId);
+                if (null == resource) {
+                    continue;
+                }
+                types = resource.getResourceTypes();
+                if (null != types) {
+                    exist = types.contains(resourceType);
+                    if (exist) {
+                        // Remove the resource
+                        keyItr.remove();
+                        removeResourceFromFavorites(resource);
+                    }
+                }
+            }
+        }
+    }
+
+    public void resourceSelectionChanged(final RemoteResource resource) {
+        new Thread() {
+            @Override
+            public void run() {
+                setCurrentResourceInSelection(resource);
+                // Notify all observers for resource selection change event
+                resourceSelectionChangedUINotification(resource);
+            }
+        }.start();
+    }
+
+    public List<MetaProperty> getMetaProperties(RemoteResource resource) {
+        if (null != resource) {
+            String propName;
+            String propValue;
+
+            List<MetaProperty> metaPropertyList = new ArrayList<MetaProperty>();
+
+            for (int index = 0; index < Constants.META_PROPERTY_COUNT; index++) {
+                propName = Constants.META_PROPERTIES[index];
+                if (propName.equals(Constants.RESOURCE_URI)) {
+                    propValue = resource.getResourceURI();
+                } else if (propName.equals(Constants.CONNECTIVITY_TYPE)) {
+                    propValue = resource.getConnectivityType().toString();
+                } else if (propName.equals(Constants.OBSERVABLE)) {
+                    propValue = Utility.getObservableInString(resource
+                            .isObservable());
+                    // see in UI
+                } else if (propName.equals(Constants.RESOURCE_TYPES)) {
+                    List<String> types = resource.getResourceTypes();
+                    if (null != types) {
+                        propValue = types.toString();
+                    } else {
+                        propValue = Constants.NOT_AVAILABLE;
+                    }
+                } else if (propName.equals(Constants.RESOURCE_INTERFACES)) {
+                    List<String> interfaces = resource.getResourceInterfaces();
+                    if (null != interfaces) {
+                        propValue = interfaces.toString();
+                    } else {
+                        propValue = Constants.NOT_AVAILABLE;
+                    }
+                } else {
+                    propValue = null;
+                }
+                if (null != propValue) {
+                    metaPropertyList.add(new MetaProperty(propName, propValue));
+                }
+            }
+
+            return metaPropertyList;
+        }
+        return null;
+    }
+
+    public Map<String, Boolean> getAutomationStatus(RemoteResource resource) {
+        if (null == resource) {
+            return null;
+        }
+        Map<String, Boolean> autoStatus = new HashMap<String, Boolean>();
+        autoStatus.put(Constants.GET, resource.isGetAutomtnInProgress());
+        autoStatus.put(Constants.PUT, resource.isPutAutomtnInProgress());
+        autoStatus.put(Constants.POST, resource.isPostAutomtnInProgress());
+        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) {
+            Set<String> idSet = resourceMap.keySet();
+            Iterator<String> idItr = idSet.iterator();
+            RemoteResource resource;
+            while (idItr.hasNext()) {
+                resource = resourceMap.get(idItr.next());
+                if (null != resource) {
+                    resourceList.add(resource);
+                }
+            }
+        }
+        // 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 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);
+            }
+        });
+
+        return resourceList;
+    }
+
+    public List<RemoteResource> getFavResourceList() {
+        List<RemoteResource> resourceList;
+        synchronized (favoriteResources) {
+            resourceList = new ArrayList<RemoteResource>(favoriteResources);
+        }
+        return resourceList;
+    }
+
+    public String getAttributeValue(RemoteResource res, String attName) {
+        if (null == res || null == attName) {
+            return null;
+        }
+        return res.getAttributeValue(attName);
+    }
+
+    public void sendGetRequest(RemoteResource resource) {
+        if (null == resource) {
+            return;
+        }
+        SimulatorRemoteResource resourceN = resource.getResource();
+        if (null == resourceN) {
+            return;
+        }
+        try {
+            resourceN.get(null, getListener);
+        } catch (SimulatorException e) {
+            Activator
+                    .getDefault()
+                    .getLogManager()
+                    .log(Level.ERROR.ordinal(),
+                            new Date(),
+                            "[" + e.getClass().getSimpleName() + "]"
+                                    + e.code().toString() + "-" + e.message());
+        }
+    }
+
+    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();
+        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) {
+            Activator
+                    .getDefault()
+                    .getLogManager()
+                    .log(Level.ERROR.ordinal(),
+                            new Date(),
+                            "[" + e.getClass().getSimpleName() + "]"
+                                    + e.code().toString() + "-" + e.message());
+        }
+        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();
+        if (null == resourceN) {
+            return;
+        }
+        Map<String, RemoteResourceAttribute> attMap = resource
+                .getResourceAttributesMap();
+        if (null == attMap || attMap.size() < 1) {
+            return;
+        }
+        // Filter out the attributes whose modification status is true.
+        Iterator<PutPostAttributeModel> itr = putPostModelList.iterator();
+        PutPostAttributeModel model;
+        while (itr.hasNext()) {
+            model = itr.next();
+            if (!model.isModified()) {
+                itr.remove();
+            }
+        }
+        SimulatorResourceModel resourceModel = getUpdatedResourceModel(attMap,
+                putPostModelList);
+        try {
+            resourceN.post(resourceModel, null, postListener);
+        } catch (SimulatorException e) {
+            Activator
+                    .getDefault()
+                    .getLogManager()
+                    .log(Level.ERROR.ordinal(),
+                            new Date(),
+                            "[" + e.getClass().getSimpleName() + "]"
+                                    + e.code().toString() + "-" + e.message());
+        }
+    }
+
+    private SimulatorResourceModel getUpdatedResourceModel(
+            Map<String, RemoteResourceAttribute> attMap,
+            List<PutPostAttributeModel> putPostModelList) {
+        String attName;
+        SimulatorResourceModel resourceModel = new SimulatorResourceModel();
+        PutPostAttributeModel model;
+        RemoteResourceAttribute attribute;
+        Type attType;
+        Iterator<PutPostAttributeModel> itr = putPostModelList.iterator();
+        while (itr.hasNext()) {
+            model = itr.next();
+            attName = model.getAttName();
+            attribute = attMap.get(attName);
+            if (null == attribute) {
+                continue;
+            }
+            attType = attribute.getAttValBaseType();
+            if (attType == Type.INT) {
+                int attValue;
+                try {
+                    attValue = Integer.parseInt(model.getAttValue());
+                    resourceModel.addAttributeInt(attName, attValue);
+                } catch (NumberFormatException e) {
+                    Activator
+                            .getDefault()
+                            .getLogManager()
+                            .log(Level.ERROR.ordinal(), new Date(),
+                                    e.getMessage());
+                } catch (SimulatorException e) {
+                    Activator
+                            .getDefault()
+                            .getLogManager()
+                            .log(Level.ERROR.ordinal(),
+                                    new Date(),
+                                    "[" + e.getClass().getSimpleName() + "]"
+                                            + e.code().toString() + "-"
+                                            + e.message());
+                }
+            } else if (attType == Type.DOUBLE) {
+                double attValue;
+                try {
+                    attValue = Double.parseDouble(model.getAttValue());
+                    resourceModel.addAttributeDouble(attName, attValue);
+                } catch (NumberFormatException e) {
+                    Activator
+                            .getDefault()
+                            .getLogManager()
+                            .log(Level.ERROR.ordinal(), new Date(),
+                                    e.getMessage());
+                } catch (SimulatorException e) {
+                    Activator
+                            .getDefault()
+                            .getLogManager()
+                            .log(Level.ERROR.ordinal(),
+                                    new Date(),
+                                    "[" + e.getClass().getSimpleName() + "]"
+                                            + e.code().toString() + "-"
+                                            + e.message());
+                }
+            } else if (attType == Type.BOOL) {
+                boolean attValue;
+                attValue = Boolean.parseBoolean(model.getAttValue());
+                try {
+                    resourceModel.addAttributeBoolean(attName, attValue);
+                } catch (SimulatorException e) {
+                    Activator
+                            .getDefault()
+                            .getLogManager()
+                            .log(Level.ERROR.ordinal(),
+                                    new Date(),
+                                    "[" + e.getClass().getSimpleName() + "]"
+                                            + e.code().toString() + "-"
+                                            + e.message());
+                }
+            } else if (attType == Type.STRING) {
+                String attValue;
+                attValue = model.getAttValue();
+                try {
+                    resourceModel.addAttributeString(attName, attValue);
+                } catch (SimulatorException e) {
+                    Activator
+                            .getDefault()
+                            .getLogManager()
+                            .log(Level.ERROR.ordinal(),
+                                    new Date(),
+                                    "[" + e.getClass().getSimpleName() + "]"
+                                            + e.code().toString() + "-"
+                                            + e.message());
+                }
+            }
+        }
+        return resourceModel;
+    }
+
+    public void sendObserveRequest(RemoteResource resource) {
+        System.out.println("sendObserverRequest() entry");
+        if (null == resource) {
+            return;
+        }
+        System.out.println("Resource is null:" + (resource == null));
+        resource.setObserved(true);
+        SimulatorRemoteResource resourceN = resource.getResource();
+        if (null == resourceN) {
+            return;
+        }
+        try {
+            resourceN.observe(SimulatorObserveType.OBSERVE, null,
+                    observeListener);
+        } catch (SimulatorException e) {
+            Activator
+                    .getDefault()
+                    .getLogManager()
+                    .log(Level.ERROR.ordinal(),
+                            new Date(),
+                            "[" + e.getClass().getSimpleName() + "]"
+                                    + e.code().toString() + "-" + e.message());
+        }
+        System.out.println("Observer called.");
+    }
+
+    public void sendCancelObserveRequest(RemoteResource resource) {
+        if (null == resource) {
+            return;
+        }
+        resource.setObserved(false);
+        SimulatorRemoteResource resourceN = resource.getResource();
+        if (null == resourceN) {
+            return;
+        }
+        try {
+            resourceN.cancelObserve();
+        } catch (SimulatorException e) {
+            Activator
+                    .getDefault()
+                    .getLogManager()
+                    .log(Level.ERROR.ordinal(),
+                            new Date(),
+                            "[" + e.getClass().getSimpleName() + "]"
+                                    + e.code().toString() + "-" + e.message());
+        }
+    }
+
+    public void startAutomationRequest(int reqType, RemoteResource resource) {
+        if (null == resource) {
+            return;
+        }
+        SimulatorRemoteResource resourceN = resource.getResource();
+        if (null == resourceN) {
+            return;
+        }
+        SimulatorVerificationType type = SimulatorVerificationType
+                .getVerificationType(reqType);
+        if (null == type) {
+            return;
+        }
+        System.out.println("Before calling startVerification: " + reqType);
+        int autoId;
+        try {
+            autoId = resourceN.startVerification(type, verifyListener);
+            System.out.println("After calling startVerification: " + autoId);
+            if (autoId != -1) {
+                if (reqType == Constants.GET_AUTOMATION_INDEX) {
+                    // resource.setGetAutomtnInProgress(true);
+                    resource.setGetAutomtnId(autoId);
+                } else if (reqType == Constants.PUT_AUTOMATION_INDEX) {
+                    // resource.setPutAutomtnInProgress(true);
+                    resource.setPutAutomtnId(autoId);
+                } else {// if(reqType == Constants.POST_AUTOMATION_INDEX) {
+                        // resource.setPostAutomtnInProgress(true);
+                    resource.setPostAutomtnId(autoId);
+                }
+            }
+        } catch (SimulatorException e) {
+            Activator
+                    .getDefault()
+                    .getLogManager()
+                    .log(Level.ERROR.ordinal(),
+                            new Date(),
+                            "[" + e.getClass().getSimpleName() + "]"
+                                    + e.code().toString() + "-" + e.message());
+        }
+    }
+
+    public void stopAutomationRequest(int reqType, RemoteResource resource) {
+        if (null == resource) {
+            return;
+        }
+        SimulatorRemoteResource resourceN = resource.getResource();
+        if (null == resourceN) {
+            return;
+        }
+        int autoId;
+        if (reqType == Constants.GET_AUTOMATION_INDEX) {
+            resource.setGetAutomtnInProgress(false);
+            autoId = resource.getGetAutomtnId();
+        } else if (reqType == Constants.PUT_AUTOMATION_INDEX) {
+            resource.setPutAutomtnInProgress(false);
+            autoId = resource.getPutAutomtnId();
+        } else {// if(reqType == Constants.POST_AUTOMATION_INDEX) {
+            resource.setPostAutomtnInProgress(false);
+            autoId = resource.getPostAutomtnId();
+        }
+        try {
+            resourceN.stopVerification(autoId);
+        } catch (SimulatorException e) {
+            Activator
+                    .getDefault()
+                    .getLogManager()
+                    .log(Level.ERROR.ordinal(),
+                            new Date(),
+                            "[" + e.getClass().getSimpleName() + "]"
+                                    + e.code().toString() + "-" + e.message());
+        }
+    }
+
+    public void setConfigFilePath(RemoteResource resource, String configFilePath) {
+        if (null == resource) {
+            return;
+        }
+        SimulatorRemoteResource resourceN = resource.getResource();
+        if (null == resourceN) {
+            return;
+        }
+        try {
+            resourceN.configureRAMLPath(configFilePath);
+        } catch (SimulatorException e) {
+            Activator
+                    .getDefault()
+                    .getLogManager()
+                    .log(Level.ERROR.ordinal(),
+                            new Date(),
+                            "[" + e.getClass().getSimpleName() + "]"
+                                    + e.code().toString() + "-" + e.message());
+            return;
+        }
+        // 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";
+    }
+
+    public void shutdown() {
+        // TODO: To be implemented for clean-up activities.
+    }
+}
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/perspective/PerspectiveFactory.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/perspective/PerspectiveFactory.java
new file mode 100644 (file)
index 0000000..527e460
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package oic.simulator.clientcontroller.perspective;
+
+import oic.simulator.clientcontroller.view.AttributeView;
+import oic.simulator.clientcontroller.view.LogView;
+import oic.simulator.clientcontroller.view.MetaPropertiesView;
+import oic.simulator.clientcontroller.view.MultiResourceOrchestrationView;
+import oic.simulator.clientcontroller.view.ResourceManagerView;
+
+import org.eclipse.ui.IPageLayout;
+import org.eclipse.ui.IPerspectiveFactory;
+
+/**
+ * This class creates a new eclipse perspective for client controller and
+ * positions the different views inside.
+ */
+public class PerspectiveFactory implements IPerspectiveFactory {
+
+    public static final String PERSPECTIVE_ID = "oic.simulator.clientcontroller.perspective";
+    private IPageLayout        factory;
+
+    @Override
+    public void createInitialLayout(IPageLayout factory) {
+        this.factory = factory;
+        factory.setEditorAreaVisible(false);
+        addViews();
+        factory.setFixed(false);
+    }
+
+    private void addViews() {
+        factory.addView(ResourceManagerView.VIEW_ID, IPageLayout.LEFT, 0.3f,
+                factory.getEditorArea());
+        factory.addView(MetaPropertiesView.VIEW_ID, IPageLayout.BOTTOM, 0.65f,
+                ResourceManagerView.VIEW_ID);
+        factory.addView(AttributeView.VIEW_ID, IPageLayout.LEFT, 0.7f,
+                factory.getEditorArea());
+        factory.addView(LogView.VIEW_ID, IPageLayout.BOTTOM, 0.65f,
+                AttributeView.VIEW_ID);
+        factory.addView(MultiResourceOrchestrationView.VIEW_ID,
+                IPageLayout.RIGHT, 0.6f, AttributeView.VIEW_ID);
+    }
+}
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/remoteresource/MetaProperty.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/remoteresource/MetaProperty.java
new file mode 100644 (file)
index 0000000..b2fde06
--- /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.clientcontroller.remoteresource;
+
+/**
+ * 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/ClientControllerPlugin/src/oic/simulator/clientcontroller/remoteresource/PutPostAttributeModel.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/remoteresource/PutPostAttributeModel.java
new file mode 100644 (file)
index 0000000..0b566a0
--- /dev/null
@@ -0,0 +1,83 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package oic.simulator.clientcontroller.remoteresource;
+
+import java.util.List;
+
+/**
+ * This is a helper class for showing the resource attributes in PUT and POST
+ * dialogs.
+ */
+public class PutPostAttributeModel {
+
+    private String       attName;
+    private String       attValue;
+    private List<String> values;
+    boolean              modified;
+
+    public String getAttName() {
+        return attName;
+    }
+
+    public void setAttName(String attName) {
+        this.attName = attName;
+    }
+
+    public String getAttValue() {
+        return attValue;
+    }
+
+    public void setAttValue(String attValue) {
+        this.attValue = attValue;
+    }
+
+    public List<String> getValues() {
+        return values;
+    }
+
+    public void setValues(List<String> values) {
+        this.values = values;
+    }
+
+    public boolean isModified() {
+        return modified;
+    }
+
+    public void setModified(boolean modified) {
+        this.modified = modified;
+    }
+
+    public static PutPostAttributeModel getModel(
+            RemoteResourceAttribute attribute) {
+        PutPostAttributeModel putPostModel = null;
+        if (null != attribute) {
+            putPostModel = new PutPostAttributeModel();
+            putPostModel.setAttName(attribute.getAttributeName());
+            putPostModel.setAttValue(String.valueOf(attribute
+                    .getAttributeValue()));
+            putPostModel.setValues(attribute.getAllValues());
+            putPostModel.setModified(false);
+        }
+        return putPostModel;
+    }
+
+    @Override
+    public String toString() {
+        return attName + "," + attValue + "\n";
+    }
+
+}
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/remoteresource/RemoteResource.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/remoteresource/RemoteResource.java
new file mode 100644 (file)
index 0000000..17a052e
--- /dev/null
@@ -0,0 +1,264 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package oic.simulator.clientcontroller.remoteresource;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.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;
+
+/**
+ * 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 Map<String, RemoteResourceAttribute> resourceAttributesMap;
+
+    private boolean                              configUploaded;
+
+    private boolean                              getAutomtnInProgress;
+    private boolean                              putAutomtnInProgress;
+    private boolean                              postAutomtnInProgress;
+
+    private int                                  getAutomtnId;
+    private int                                  putAutomtnId;
+    private int                                  postAutomtnId;
+
+    private boolean                              isFavorite;
+
+    public SimulatorResourceModel getResourceModel() {
+        return resourceModel;
+    }
+
+    public void setResourceModel(SimulatorResourceModel resourceModel) {
+        this.resourceModel = resourceModel;
+    }
+
+    public Map<String, RemoteResourceAttribute> getResourceAttributesMap() {
+        return resourceAttributesMap;
+    }
+
+    public void setResourceAttributesMap(
+            Map<String, RemoteResourceAttribute> resourceAttributesMap) {
+        this.resourceAttributesMap = resourceAttributesMap;
+    }
+
+    public int getGetAutomtnId() {
+        return getAutomtnId;
+    }
+
+    public void setGetAutomtnId(int getAutomtnId) {
+        this.getAutomtnId = getAutomtnId;
+    }
+
+    public int getPutAutomtnId() {
+        return putAutomtnId;
+    }
+
+    public void setPutAutomtnId(int putAutomtnId) {
+        this.putAutomtnId = putAutomtnId;
+    }
+
+    public int getPostAutomtnId() {
+        return postAutomtnId;
+    }
+
+    public void setPostAutomtnId(int postAutomtnId) {
+        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;
+    }
+
+    public void setGetAutomtnInProgress(boolean getAutomtnInProgress) {
+        this.getAutomtnInProgress = getAutomtnInProgress;
+    }
+
+    public boolean isPutAutomtnInProgress() {
+        return putAutomtnInProgress;
+    }
+
+    public void setPutAutomtnInProgress(boolean putAutomtnInProgress) {
+        this.putAutomtnInProgress = putAutomtnInProgress;
+    }
+
+    public boolean isPostAutomtnInProgress() {
+        return postAutomtnInProgress;
+    }
+
+    public void setPostAutomtnInProgress(boolean postAutomtnInProgress) {
+        this.postAutomtnInProgress = postAutomtnInProgress;
+    }
+
+    public boolean isConfigUploaded() {
+        return configUploaded;
+    }
+
+    public void setConfigUploaded(boolean configUploaded) {
+        this.configUploaded = configUploaded;
+    }
+
+    public SimulatorRemoteResource getResource() {
+        return resourceN;
+    }
+
+    public void setResource(SimulatorRemoteResource resource) {
+        this.resourceN = resource;
+    }
+
+    public boolean isObserved() {
+        return observed;
+    }
+
+    public void setObserved(boolean observed) {
+        this.observed = observed;
+    }
+
+    public List<PutPostAttributeModel> getPutPostModel() {
+        Map<String, RemoteResourceAttribute> attMap = getResourceAttributesMap();
+        if (null == attMap || attMap.size() < 1) {
+            return null;
+        }
+        List<PutPostAttributeModel> putPostModelList = new ArrayList<PutPostAttributeModel>();
+        String attName;
+        RemoteResourceAttribute attribute;
+        PutPostAttributeModel putPostModel;
+        Iterator<String> attItr = attMap.keySet().iterator();
+        while (attItr.hasNext()) {
+            attName = attItr.next();
+            attribute = attMap.get(attName);
+            putPostModel = PutPostAttributeModel.getModel(attribute);
+            if (null != putPostModel) {
+                putPostModelList.add(putPostModel);
+            }
+        }
+        return putPostModelList;
+    }
+
+    public String getAttributeValue(String attName) {
+        RemoteResourceAttribute attribute = resourceAttributesMap.get(attName);
+        if (null == attribute) {
+            return null;
+        }
+        return String.valueOf(attribute.getAttributeValue());
+    }
+
+    public String getuId() {
+        return uId;
+    }
+
+    public void setuId(String uId) {
+        this.uId = uId;
+    }
+
+    public int getAutomationtype(int autoId) {
+        if (getAutomtnId == autoId) {
+            return Constants.GET_AUTOMATION_INDEX;
+        } else if (putAutomtnId == autoId) {
+            return Constants.PUT_AUTOMATION_INDEX;
+        } else {// if(postAutomtnId == autoId) {
+            return Constants.POST_AUTOMATION_INDEX;
+        }
+    }
+
+    public void updateAutomationStatus(int autoId, boolean status) {
+        if (getAutomtnId == autoId) {
+            getAutomtnInProgress = status;
+        } else if (putAutomtnId == autoId) {
+            putAutomtnInProgress = status;
+        } else {// if(postAutomtnId == autoId) {
+            postAutomtnInProgress = status;
+        }
+    }
+
+    public boolean isFavorite() {
+        return isFavorite;
+    }
+
+    public void setFavorite(boolean isFavorite) {
+        this.isFavorite = isFavorite;
+    }
+}
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/remoteresource/RemoteResourceAttribute.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/remoteresource/RemoteResourceAttribute.java
new file mode 100644 (file)
index 0000000..27cbdc8
--- /dev/null
@@ -0,0 +1,185 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package oic.simulator.clientcontroller.remoteresource;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import org.oic.simulator.ResourceAttribute;
+import org.oic.simulator.ResourceAttribute.Type;
+
+/**
+ * This class represents an attribute in the remote resource.
+ */
+public class RemoteResourceAttribute {
+
+    // Native object reference
+    private ResourceAttribute resourceAttribute;
+
+    private String            attributeName;
+    private Object            attributeValue;
+    private Type              attValType;
+    private Type              attValBaseType;
+    private List<Object>      allowedValues;
+
+    private Object            minValue;
+    private Object            maxValue;
+
+    public ResourceAttribute getResourceAttribute() {
+        return resourceAttribute;
+    }
+
+    public void setResourceAttribute(ResourceAttribute resourceAttribute) {
+        this.resourceAttribute = resourceAttribute;
+    }
+
+    public String getAttributeName() {
+        return attributeName;
+    }
+
+    public void setAttributeName(String attributeName) {
+        this.attributeName = attributeName;
+    }
+
+    public Object getAttributeValue() {
+        return attributeValue;
+    }
+
+    public void setAttributeValue(Object attributeValue) {
+        this.attributeValue = attributeValue;
+    }
+
+    public List<Object> getAllowedValues() {
+        return allowedValues;
+    }
+
+    public void setAllowedValues(List<Object> allowedValues) {
+        this.allowedValues = allowedValues;
+    }
+
+    public void setAllowedValues(String[] allowedValues) {
+        List<Object> allowedValueList = null;
+        if (null != allowedValues && allowedValues.length > 0) {
+            allowedValueList = new ArrayList<Object>();
+            for (String value : allowedValues) {
+                allowedValueList.add(value);
+            }
+        }
+        this.allowedValues = allowedValueList;
+    }
+
+    public Object getMinValue() {
+        return minValue;
+    }
+
+    public void setMinValue(Object minValue) {
+        this.minValue = minValue;
+    }
+
+    public Object getMaxValue() {
+        return maxValue;
+    }
+
+    public void setMaxValue(Object maxValue) {
+        this.maxValue = maxValue;
+    }
+
+    public static RemoteResourceAttribute clone(
+            RemoteResourceAttribute attribute) {
+        RemoteResourceAttribute clone = null;
+        if (null != attribute) {
+            clone = new RemoteResourceAttribute();
+            clone.setAttributeName(attribute.getAttributeName());
+            clone.setAttributeValue(attribute.getAttributeValue());
+            clone.setAllowedValues(attribute.getAllowedValues());
+            clone.setAttValBaseType(attribute.getAttValBaseType());
+            clone.setAttValType(attribute.getAttValType());
+            clone.setMinValue(attribute.getMinValue());
+            clone.setMaxValue(attribute.getMaxValue());
+            clone.setResourceAttribute(null);
+        }
+        return clone;
+    }
+
+    // This method gives all known possible values of the attribute in string
+    // format.
+    // It takes allowed values or range of values whichever is available
+    public List<String> getAllValues() {
+        List<String> valueList = new ArrayList<String>();
+        if (null != allowedValues) {
+            Iterator<Object> values = allowedValues.iterator();
+            Object value;
+            while (values.hasNext()) {
+                value = values.next();
+                if (null != value) {
+                    valueList.add(String.valueOf(value));
+                }
+            }
+        } else if (null != minValue && null != maxValue) {
+            if (attributeValue.getClass() == Integer.class) {
+                int min = (Integer) minValue;
+                int max = (Integer) maxValue;
+                for (int value = min; value <= max; value++) {
+                    valueList.add(String.valueOf(value));
+                }
+            } else if (attributeValue.getClass() == Double.class) {
+                double min = (Double) minValue;
+                double max = (Double) maxValue;
+                for (double value = min; value <= max; value++) {
+                    valueList.add(String.valueOf(value));
+                }
+            }
+        }
+        if (valueList.size() < 1 && null != attributeValue) {
+            valueList.add(String.valueOf(attributeValue));
+        }
+        return valueList;
+    }
+
+    public static void printAttributes(
+            Map<String, RemoteResourceAttribute> attributeMap) {
+        Iterator<String> itr = attributeMap.keySet().iterator();
+        String attName;
+        RemoteResourceAttribute att;
+        while (itr.hasNext()) {
+            attName = itr.next();
+            att = attributeMap.get(attName);
+            System.out.println("AttributeName:" + attName);
+            System.out.println("AttributeValue:"
+                    + att.getAttributeValue().toString());
+            System.out.println("Allowed Values:" + att.getAllValues());
+        }
+    }
+
+    public Type getAttValType() {
+        return attValType;
+    }
+
+    public void setAttValType(Type attValType) {
+        this.attValType = attValType;
+    }
+
+    public Type getAttValBaseType() {
+        return attValBaseType;
+    }
+
+    public void setAttValBaseType(Type attValBaseType) {
+        this.attValBaseType = attValBaseType;
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/utils/Constants.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/utils/Constants.java
new file mode 100644 (file)
index 0000000..3fe81ac
--- /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.
+ */
+
+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";
+}
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/utils/Utility.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/utils/Utility.java
new file mode 100644 (file)
index 0000000..8baed7c
--- /dev/null
@@ -0,0 +1,79 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package oic.simulator.clientcontroller.utils;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * This class has common utility methods.
+ */
+public class Utility {
+    public static List<String> convertSetToList(Set<String> typeSet) {
+        if (null == typeSet) {
+            return null;
+        }
+        List<String> list = new ArrayList<String>();
+        Iterator<String> typeItr = typeSet.iterator();
+        while (typeItr.hasNext()) {
+            list.add(typeItr.next());
+        }
+        return list;
+    }
+
+    public static String getObservableInString(boolean observable) {
+        if (observable) {
+            return Constants.YES;
+        } else {
+            return Constants.NO;
+        }
+    }
+
+    public static String[] convertListToString(List<String> valueList) {
+        String[] strArr;
+        if (null != valueList && valueList.size() > 0) {
+            strArr = valueList.toArray(new String[1]);
+        } else {
+            strArr = new String[1];
+        }
+        return strArr;
+    }
+
+    /*
+     * public static 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; }
+     */
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/AttributeView.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/AttributeView.java
new file mode 100644 (file)
index 0000000..f91a752
--- /dev/null
@@ -0,0 +1,806 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package oic.simulator.clientcontroller.view;
+
+import java.util.List;
+import java.util.Map;
+
+import oic.simulator.clientcontroller.Activator;
+import oic.simulator.clientcontroller.listener.IConfigurationUpload;
+import oic.simulator.clientcontroller.listener.IGetUIListener;
+import oic.simulator.clientcontroller.listener.IObserveUIListener;
+import oic.simulator.clientcontroller.listener.IPostUIListener;
+import oic.simulator.clientcontroller.listener.IPutUIListener;
+import oic.simulator.clientcontroller.listener.IResourceSelectionChangedUIListener;
+import oic.simulator.clientcontroller.listener.IVerificationUIListener;
+import oic.simulator.clientcontroller.manager.ResourceManager;
+import oic.simulator.clientcontroller.remoteresource.PutPostAttributeModel;
+import oic.simulator.clientcontroller.remoteresource.RemoteResource;
+import oic.simulator.clientcontroller.remoteresource.RemoteResourceAttribute;
+import oic.simulator.clientcontroller.utils.Constants;
+import oic.simulator.clientcontroller.view.dialogs.VerificationDialog;
+import oic.simulator.clientcontroller.view.dialogs.PostRequestDialog;
+import oic.simulator.clientcontroller.view.dialogs.PutRequestDialog;
+
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.viewers.IStructuredContentProvider;
+import org.eclipse.jface.viewers.StyledCellLabelProvider;
+import org.eclipse.jface.viewers.TableViewer;
+import org.eclipse.jface.viewers.TableViewerColumn;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.jface.viewers.ViewerCell;
+import org.eclipse.jface.window.Window;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.CTabFolder;
+import org.eclipse.swt.custom.CTabFolder2Adapter;
+import org.eclipse.swt.custom.CTabFolderEvent;
+import org.eclipse.swt.custom.CTabItem;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.graphics.Color;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Group;
+import org.eclipse.swt.widgets.Table;
+import org.eclipse.swt.widgets.Text;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.part.ViewPart;
+
+/**
+ * This class manages and shows the attribute view in the perspective.
+ */
+public class AttributeView extends ViewPart {
+
+    public static final String                  VIEW_ID        = "oic.simulator.clientcontroller.view.attribute";
+
+    private TableViewer                         attTblViewer;
+
+    private Button                              getButton;
+    private Button                              putButton;
+    private Button                              postButton;
+    private Button                              automateButton;
+    private Button                              observeResButton;
+
+    private CTabFolder                          payloadFolder;
+    private CTabItem                            requestPayloadTab;
+    private CTabItem                            responsePayloadTab;
+    private Text                                requestPayloadTxt;
+    private Text                                responsePayloadTxt;
+
+    private final String[]                      attTblHeaders  = {
+            "Attribute Name", "Attribute Value"               };
+    private final Integer[]                     attTblColWidth = { 200, 200 };
+
+    private ResourceManager                     resourceManager;
+
+    private IResourceSelectionChangedUIListener resourceSelectionChangedListener;
+    private IGetUIListener                      getUIListener;
+    private IPutUIListener                      putUIListener;
+    private IPostUIListener                     postUIListener;
+    private IObserveUIListener                  observeUIListener;
+    private IVerificationUIListener             verificationUIListener;
+    private IConfigurationUpload                configUploadUIListener;
+
+    private RemoteResource                      resourceInSelection;
+
+    public AttributeView() {
+        resourceManager = Activator.getDefault().getResourceManager();
+
+        resourceSelectionChangedListener = new IResourceSelectionChangedUIListener() {
+
+            @Override
+            public void onResourceSelectionChange(final RemoteResource resource) {
+                Display.getDefault().asyncExec(new Runnable() {
+
+                    @Override
+                    public void run() {
+                        System.out
+                                .println("AttributeView: onResourceSelectionChange");
+                        resourceInSelection = resource;
+
+                        // Set visibility of manual and automation controls
+                        setVisibility((resource == null) ? false : true);
+
+                        // Update the attribute table
+                        if (null != attTblViewer
+                                && !attTblViewer.getControl().isDisposed()) {
+                            System.out.println("viewer is alive");
+                            updateViewer(getData(resource));
+                        }
+
+                        // Update the observe status
+                        updateObserve(resource);
+
+                        // Update the pay-load details if any
+                    }
+                });
+            }
+        };
+
+        getUIListener = new IGetUIListener() {
+
+            @Override
+            public void onGetCompleted(final RemoteResource resource) {
+                Display.getDefault().asyncExec(new Runnable() {
+
+                    @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() {
+
+            @Override
+            public void onPutCompleted(final RemoteResource resource) {
+                Display.getDefault().asyncExec(new Runnable() {
+
+                    @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() {
+
+            @Override
+            public void onPostCompleted(final RemoteResource resource) {
+                Display.getDefault().asyncExec(new Runnable() {
+
+                    @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() {
+
+            @Override
+            public void onObserveCompleted(final RemoteResource resource) {
+                Display.getDefault().asyncExec(new Runnable() {
+
+                    @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() {
+
+            @Override
+            public void onVerificationStarted(final RemoteResource resource,
+                    final int autoType) {
+                Display.getDefault().asyncExec(new Runnable() {
+
+                    @Override
+                    public void run() {
+                        changeReqBtnVisibility(autoType, false);
+                    }
+                });
+            }
+
+            @Override
+            public void onVerificationCompleted(final RemoteResource resource,
+                    final int autoType) {
+                Display.getDefault().asyncExec(new Runnable() {
+
+                    @Override
+                    public void run() {
+                        changeReqBtnVisibility(autoType, true);
+                    }
+                });
+            }
+
+            @Override
+            public void onVerificationAborted(final RemoteResource resource,
+                    final int autoType) {
+                Display.getDefault().asyncExec(new Runnable() {
+
+                    @Override
+                    public void run() {
+                        changeReqBtnVisibility(autoType, true);
+                    }
+                });
+            }
+        };
+
+        configUploadUIListener = new IConfigurationUpload() {
+
+            @Override
+            public void onConfigurationUploaded(final RemoteResource resource) {
+                Display.getDefault().asyncExec(new Runnable() {
+
+                    @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()) {
+                            automateButton.setEnabled(true);
+                        }
+                    }
+                });
+            }
+        };
+    }
+
+    private void changeReqBtnVisibility(int reqType, boolean visibility) {
+        if (reqType == Constants.GET_AUTOMATION_INDEX) {
+            if (!getButton.isDisposed()) {
+                getButton.setEnabled(visibility);
+            }
+        } else if (reqType == Constants.PUT_AUTOMATION_INDEX) {
+            if (!putButton.isDisposed()) {
+                putButton.setEnabled(visibility);
+            }
+        } else {// if(reqType == Constants.POST_AUTOMATION_INDEX) {
+            if (!postButton.isDisposed()) {
+                postButton.setEnabled(visibility);
+            }
+        }
+    }
+
+    private Map<String, RemoteResourceAttribute> getData(RemoteResource resource) {
+        if (null == resource) {
+            return null;
+        }
+        Map<String, RemoteResourceAttribute> attMap = resource
+                .getResourceAttributesMap();
+        System.out.println("AttributeView: \n" + attMap);
+        return attMap;
+    }
+
+    private void updateViewer(Map<String, RemoteResourceAttribute> attMap) {
+        if (null != attTblViewer) {
+            Table tbl = attTblViewer.getTable();
+            if (null != attMap) {
+                attTblViewer.setInput(attMap.entrySet().toArray());
+                if (!tbl.isDisposed()) {
+                    tbl.setLinesVisible(true);
+                }
+            } else {
+                if (!tbl.isDisposed()) {
+                    tbl.removeAll();
+                    tbl.setLinesVisible(false);
+                }
+            }
+        }
+    }
+
+    private void updateObserve(RemoteResource resource) {
+        if (null == resource) {
+            return;
+        }
+        boolean observed = resource.isObserved();
+        if (!observeResButton.isDisposed()) {
+            observeResButton.setSelection(observed);
+        }
+    }
+
+    @Override
+    public void createPartControl(Composite parent) {
+        Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE);
+
+        parent.setLayout(new GridLayout(2, false));
+        GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        parent.setLayoutData(gd);
+
+        Group attGroup = new Group(parent, SWT.NONE);
+        attGroup.setLayout(new GridLayout());
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.horizontalSpan = 2;
+        gd.heightHint = 175;
+        attGroup.setLayoutData(gd);
+        attGroup.setText("Attributes");
+        attGroup.setBackground(color);
+
+        setupAttributeTable(attGroup);
+
+        setupMessageArea(parent);
+
+        setupResourceLevelOpsArea(parent);
+
+        setupTabArea(parent);
+
+        setUIListeners();
+
+        addManagerListeners();
+
+        setVisibility(false);
+
+        // Updating the data in the UI as per the resource in selection.
+        if (null != attTblViewer && !attTblViewer.getControl().isDisposed()) {
+            updateViewer(getData(resourceManager
+                    .getCurrentResourceInSelection()));
+        }
+    }
+
+    private void setupMessageArea(Composite parent) {
+        GridData gd;
+        Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE);
+        Group msgTypesGrp = new Group(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);
+
+        getButton = new Button(msgTypesGrp, SWT.PUSH);
+        getButton.setText("GET");
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.widthHint = 50;
+        getButton.setLayoutData(gd);
+
+        putButton = new Button(msgTypesGrp, SWT.PUSH);
+        putButton.setText("PUT");
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.widthHint = 50;
+        putButton.setLayoutData(gd);
+
+        postButton = new Button(msgTypesGrp, 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);
+        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);
+
+        automateButton = new Button(resOpsGrp, 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 setupTabArea(final Composite parent) {
+        GridData gd;
+        payloadFolder = new CTabFolder(parent, SWT.BORDER);
+        gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        gd.horizontalSpan = 2;
+        payloadFolder.setLayoutData(gd);
+        payloadFolder.setSimple(false);
+        payloadFolder.setUnselectedCloseVisible(false);
+        payloadFolder.setUnselectedImageVisible(false);
+        // payloadFolder.setMaximizeVisible(true);
+        // payloadFolder.setMinimizeVisible(true);
+
+        requestPayloadTab = new CTabItem(payloadFolder, SWT.NULL);
+        requestPayloadTab.setText("Request Payload");
+
+        requestPayloadTxt = new Text(payloadFolder, SWT.MULTI | SWT.V_SCROLL
+                | SWT.H_SCROLL | SWT.READ_ONLY | SWT.WRAP);
+        requestPayloadTab.setControl(requestPayloadTxt);
+
+        responsePayloadTab = new CTabItem(payloadFolder, SWT.NULL);
+        responsePayloadTab.setText("Response Payload");
+
+        responsePayloadTxt = new Text(payloadFolder, SWT.MULTI | SWT.V_SCROLL
+                | SWT.H_SCROLL | SWT.READ_ONLY | SWT.WRAP);
+        responsePayloadTab.setControl(responsePayloadTxt);
+
+        // Add Listeners
+
+        payloadFolder.addCTabFolder2Listener(new CTabFolder2Adapter() {
+            @Override
+            public void minimize(CTabFolderEvent event) {
+                payloadFolder.setMinimized(true);
+                GridData gd = new GridData(SWT.FILL, SWT.FILL, true, false);
+                gd.horizontalSpan = 2;
+                payloadFolder.setLayoutData(gd);
+                parent.layout(true);
+            }
+
+            @Override
+            public void maximize(CTabFolderEvent event) {
+                payloadFolder.setMaximized(true);
+                GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+                gd.horizontalSpan = 2;
+                payloadFolder.setLayoutData(gd);
+                parent.layout(true);
+            }
+
+            @Override
+            public void restore(CTabFolderEvent event) {
+                payloadFolder.setMaximized(false);
+                payloadFolder.setMinimized(false);
+                GridData gd = new GridData(SWT.FILL, SWT.FILL, true, false);
+                gd.horizontalSpan = 2;
+                payloadFolder.setLayoutData(gd);
+                parent.layout(true);
+            }
+        });
+    }
+
+    private void setupAttributeTable(Group attGroup) {
+        attTblViewer = new TableViewer(attGroup, SWT.SINGLE | 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 element = cell.getElement();
+                if (element instanceof Map.Entry) {
+                    @SuppressWarnings("unchecked")
+                    Map.Entry<String, RemoteResourceAttribute> entry = (Map.Entry<String, RemoteResourceAttribute>) element;
+                    cell.setText(entry.getKey());
+                }
+            }
+        });
+
+        TableViewerColumn attValue = new TableViewerColumn(tableViewer,
+                SWT.NONE);
+        attValue.getColumn().setWidth(attTblColWidth[1]);
+        attValue.getColumn().setText(attTblHeaders[1]);
+        attValue.setLabelProvider(new StyledCellLabelProvider() {
+            @Override
+            public void update(ViewerCell cell) {
+                Object element = cell.getElement();
+                if (element instanceof Map.Entry) {
+                    @SuppressWarnings("unchecked")
+                    Map.Entry<String, RemoteResourceAttribute> entry = (Map.Entry<String, RemoteResourceAttribute>) element;
+                    Object value = entry.getValue().getAttributeValue();
+                    if (null == value) {
+                        cell.setText("");
+                    } else {
+                        cell.setText(String.valueOf(value));
+                    }
+                }
+            }
+        });
+    }
+
+    private void setUIListeners() {
+
+        getButton.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                if (resourceInSelection.isGetAutomtnInProgress()) {
+                    MessageDialog
+                            .openInformation(Display.getDefault()
+                                    .getActiveShell(), "GET Request",
+                                    "GET Automation is in progress. Please wait or stop the automation.");
+                } else {
+                    resourceManager.sendGetRequest(resourceInSelection);
+                }
+            }
+        });
+
+        putButton.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                PlatformUI.getWorkbench().getDisplay().syncExec(new Thread() {
+                    @Override
+                    public void run() {
+                        if (resourceInSelection.isPutAutomtnInProgress()) {
+                            MessageDialog
+                                    .openInformation(Display.getDefault()
+                                            .getActiveShell(), "PUT Request",
+                                            "PUT Automation is in progress. Please wait or stop the automation.");
+                            return;
+                        }
+                        List<PutPostAttributeModel> putPostModelList;
+                        putPostModelList = resourceInSelection
+                                .getPutPostModel();
+                        if (null == putPostModelList) {
+                            MessageDialog
+                                    .openInformation(Display.getDefault()
+                                            .getActiveShell(), "PUT Request",
+                                            "No attributes exist in the resource model.");
+                            return;
+                        }
+                        PutRequestDialog putDialog = new PutRequestDialog(
+                                Display.getDefault().getActiveShell(),
+                                putPostModelList);
+                        if (putDialog.open() == Window.OK) {
+                            // Call the native PUT method
+                            resourceManager.sendPutRequest(resourceInSelection,
+                                    putPostModelList);
+                        }
+                    }
+                });
+            }
+        });
+
+        postButton.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                PlatformUI.getWorkbench().getDisplay().syncExec(new Thread() {
+                    @Override
+                    public void run() {
+                        if (resourceInSelection.isPostAutomtnInProgress()) {
+                            MessageDialog
+                                    .openInformation(Display.getDefault()
+                                            .getActiveShell(), "POST Request",
+                                            "POST Automation is in progress. Please wait or stop the automation.");
+                            return;
+                        }
+                        List<PutPostAttributeModel> putPostModelList;
+                        putPostModelList = resourceInSelection
+                                .getPutPostModel();
+                        if (null == putPostModelList) {
+                            MessageDialog
+                                    .openInformation(Display.getDefault()
+                                            .getActiveShell(), "PUT Request",
+                                            "No attributes exist in the resource model.");
+                            return;
+                        }
+
+                        PostRequestDialog postDialog = new PostRequestDialog(
+                                Display.getDefault().getActiveShell(),
+                                putPostModelList);
+                        if (postDialog.open() == Window.OK) {
+                            // Call the native POST method
+                            resourceManager.sendPostRequest(
+                                    resourceInSelection, putPostModelList);
+                        }
+                    }
+                });
+            }
+        });
+
+        observeResButton.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                boolean checked = observeResButton.getSelection();
+                if (checked) {
+                    resourceManager.sendObserveRequest(resourceInSelection);
+                } else {
+                    resourceManager
+                            .sendCancelObserveRequest(resourceInSelection);
+                }
+            }
+        });
+
+        automateButton.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                PlatformUI.getWorkbench().getDisplay().syncExec(new Thread() {
+                    @Override
+                    public void run() {
+                        RemoteResource resource = resourceManager
+                                .getCurrentResourceInSelection();
+                        if (null == resource) {
+                            return;
+                        }
+                        Map<String, Boolean> autoStatus = resourceManager
+                                .getAutomationStatus(resource);
+                        if (null == autoStatus) {
+                            return;
+                        }
+                        VerificationDialog ad = new VerificationDialog(Display
+                                .getDefault().getActiveShell(), autoStatus);
+                        ad.open();
+                    }
+                });
+            }
+        });
+    }
+
+    private void addManagerListeners() {
+        resourceManager
+                .addResourceSelectionChangedUIListener(resourceSelectionChangedListener);
+        resourceManager.addGetUIListener(getUIListener);
+        resourceManager.addPutUIListener(putUIListener);
+        resourceManager.addPostUIListener(postUIListener);
+        resourceManager.addObserveUIListener(observeUIListener);
+        resourceManager.addVerificationUIListener(verificationUIListener);
+        resourceManager.addConfigUploadUIListener(configUploadUIListener);
+    }
+
+    private void setVisibility(boolean visibility) {
+        if (!getButton.isDisposed())
+            getButton.setEnabled(visibility);
+        if (!putButton.isDisposed())
+            putButton.setEnabled(visibility);
+        if (!postButton.isDisposed())
+            postButton.setEnabled(visibility);
+        if (!automateButton.isDisposed()) {
+            if (visibility && null != resourceInSelection
+                    && resourceInSelection.isConfigUploaded()) {
+                automateButton.setEnabled(true);
+            } else {
+                automateButton.setEnabled(false);
+            }
+        }
+        if (!observeResButton.isDisposed())
+            observeResButton.setEnabled(visibility);
+    }
+
+    class AttributeContentProvider implements IStructuredContentProvider {
+
+        @Override
+        public void dispose() {
+        }
+
+        @Override
+        public void inputChanged(Viewer viewer, Object arg1, Object arg2) {
+        }
+
+        @Override
+        public Object[] getElements(Object element) {
+            return (Object[]) element;
+        }
+
+    }
+
+    @Override
+    public void dispose() {
+        // Unregister the selection listener
+        if (null != resourceSelectionChangedListener) {
+            resourceManager
+                    .removeResourceSelectionChangedUIListener(resourceSelectionChangedListener);
+        }
+
+        // Unregister the GET listener
+        if (null != getUIListener) {
+            resourceManager.removeGetUIListener(getUIListener);
+        }
+
+        super.dispose();
+    }
+
+    @Override
+    public void setFocus() {
+    }
+
+}
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/LogView.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/LogView.java
new file mode 100644 (file)
index 0000000..3c4d76e
--- /dev/null
@@ -0,0 +1,724 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package oic.simulator.clientcontroller.view;
+
+import java.io.BufferedWriter;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+import java.util.HashMap;
+import java.util.List;
+
+import oic.simulator.clientcontroller.Activator;
+import oic.simulator.clientcontroller.listener.ILogUIListener;
+import oic.simulator.clientcontroller.manager.LogManager;
+import oic.simulator.clientcontroller.utils.Constants;
+import oic.simulator.clientcontroller.view.dialogs.FilterDialog;
+import oic.simulator.clientcontroller.view.dialogs.LogDetailsDialog;
+import oic.simulator.logger.LogContentProvider;
+import oic.simulator.logger.LogEntry;
+import oic.simulator.logger.LogLabelProvider;
+
+import org.eclipse.jface.action.Action;
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.action.IContributionItem;
+import org.eclipse.jface.action.IMenuManager;
+import org.eclipse.jface.action.IToolBarManager;
+import org.eclipse.jface.action.MenuManager;
+import org.eclipse.jface.action.Separator;
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.jface.viewers.DoubleClickEvent;
+import org.eclipse.jface.viewers.IDoubleClickListener;
+import org.eclipse.jface.viewers.ISelectionChangedListener;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.SelectionChangedEvent;
+import org.eclipse.jface.viewers.StructuredSelection;
+import org.eclipse.jface.viewers.TreeViewer;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.jface.viewers.ViewerComparator;
+import org.eclipse.jface.window.Window;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.KeyEvent;
+import org.eclipse.swt.events.KeyListener;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.FileDialog;
+import org.eclipse.swt.widgets.Text;
+import org.eclipse.swt.widgets.Tree;
+import org.eclipse.swt.widgets.TreeColumn;
+import org.eclipse.swt.widgets.TreeItem;
+import org.eclipse.ui.IActionBars;
+import org.eclipse.ui.IWorkbenchActionConstants;
+import org.eclipse.ui.IWorkbenchPage;
+import org.eclipse.ui.dialogs.FilteredTree;
+import org.eclipse.ui.dialogs.PatternFilter;
+import org.eclipse.ui.part.ViewPart;
+import org.oic.simulator.ILogger.Level;
+
+/**
+ * This class manages and shows the log view in the perspective.
+ */
+public class LogView extends ViewPart {
+
+    public static final String        VIEW_ID              = "oic.simulator.clientcontroller.view.log";
+
+    private LogManager                logManager;
+    private ILogUIListener            logListener;
+
+    private LogContentProvider        treeContentProvider;
+
+    private FilteredTree              tree;
+    private TreeColumn                severityColumn;
+    private TreeColumn                dateColumn;
+    private TreeColumn                messageColumn;
+
+    private IAction                   exportLogAction;
+    private IAction                   clearLogAction;
+    private IAction                   deleteLogAction;
+    private IAction                   scrollLockAction;
+    private IAction                   logDetailsAction;
+    private IAction                   filterAction;
+    private IAction                   activateViewAction;
+    private IAction                   showTextFilter;
+    private IContributionItem         groupByAction;
+
+    private HashMap<Integer, Boolean> shownSeverities      = new HashMap<Integer, Boolean>();
+
+    private boolean                   activateOnChange     = false;
+
+    private boolean                   hideTextFilter       = false;
+
+    private boolean                   scrollLockDisabled;
+
+    public static final int           ORDER_BY_TIME        = 0;
+    public static final int           ORDER_BY_SEVERITY    = 1;
+    public static final int           ORDER_BY_MESSAGE     = 2;
+
+    int                               sortCandidate        = ORDER_BY_TIME;
+
+    SortAction                        sortByTimeAction     = new SortAction(
+                                                                   "Order by Time",
+                                                                   ORDER_BY_TIME);
+    SortAction                        sortBySeverityAction = new SortAction(
+                                                                   "Order by Severity",
+                                                                   ORDER_BY_SEVERITY);
+    SortAction                        sortByMessageAction  = new SortAction(
+                                                                   "Order by Message",
+                                                                   ORDER_BY_MESSAGE);
+
+    private ViewerComparator          dateComparator;
+    private ViewerComparator          severityComparator;
+    private ViewerComparator          messageComparator;
+
+    private TreeColumn                sortColumn           = null;
+    private static int                DOWN                 = 1;
+    private static int                UP                   = -1;
+    private int                       sortDirection        = DOWN;
+
+    public LogView() {
+
+        logListener = new ILogUIListener() {
+
+            @Override
+            public void logChanged(final List<LogEntry> entry) {
+                Display.getDefault().asyncExec(new Runnable() {
+
+                    @Override
+                    public void run() {
+                        TreeViewer viewer = tree.getViewer();
+                        if (viewer.getControl().isDisposed()) {
+                            return;
+                        }
+                        viewer.setInput(entry);
+                        updateTree(false);
+                    }
+                });
+            }
+
+            @Override
+            public void logAdded(final LogEntry added) {
+                Display.getDefault().asyncExec(new Runnable() {
+
+                    @Override
+                    public void run() {
+                        TreeViewer viewer = tree.getViewer();
+                        if (viewer.getControl().isDisposed()) {
+                            return;
+                        }
+                        LogContentProvider provider = (LogContentProvider) viewer
+                                .getContentProvider();
+                        provider.addLog(added);
+                        tree.getViewer().add(viewer.getInput(), added);
+                        @SuppressWarnings("unchecked")
+                        List<LogEntry> input = (List<LogEntry>) viewer
+                                .getInput();
+                        if (input.size() > Constants.LOG_SIZE) {
+                            viewer.remove(viewer.getInput(), 0);
+                        }
+                        updateTree(true);
+                    }
+                });
+            }
+
+            private void updateTree(boolean needscroll) {
+                if (activateOnChange) {
+                    IWorkbenchPage page = Activator.getDefault().getWorkbench()
+                            .getActiveWorkbenchWindow().getActivePage();
+                    if (page != null) {
+                        page.bringToTop(LogView.this);
+                    }
+                }
+                if (scrollLockDisabled && needscroll) {
+                    Tree tree2 = tree.getViewer().getTree();
+                    if (tree2.getItemCount() > 0) {
+                        TreeItem item = tree2.getItem(tree2.getItemCount() - 1);
+                        tree2.setTopItem(item);
+                        deleteLogAction.setEnabled(true);
+                    }
+                }
+            }
+        };
+
+        logManager = Activator.getDefault().getLogManager();
+
+        // Initially state of scroll lock
+        scrollLockDisabled = true;
+    }
+
+    @Override
+    public void createPartControl(Composite parent) {
+        PatternFilter filter = new PatternFilter() {
+
+            DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss.SSS");
+
+            @Override
+            protected boolean isLeafMatch(Viewer viewer, Object element) {
+                if (element instanceof LogEntry) {
+                    LogEntry logEntry = (LogEntry) element;
+                    String severity = LogManager.getSeverityName(logEntry
+                            .getSeverity());
+                    String date = dateFormat.format(logEntry.getDate());
+                    String message = logEntry.getMessage();
+                    return wordMatches(severity) || wordMatches(date)
+                            || wordMatches(message);
+                }
+                return false;
+            }
+        };
+        filter.setIncludeLeadingWildcard(true);
+        tree = new FilteredTree(parent, SWT.SINGLE | SWT.H_SCROLL
+                | SWT.V_SCROLL | SWT.FULL_SELECTION, filter, true);
+
+        setupFilteredTree();
+
+        createColumnComparators();
+
+        createActions();
+
+        setDefaultShownSeverities();
+
+        IActionBars actionBars = getViewSite().getActionBars();
+        IToolBarManager toolBarManager = actionBars.getToolBarManager();
+        toolBarManager.add(exportLogAction);
+        toolBarManager.add(clearLogAction);
+        toolBarManager.add(deleteLogAction);
+        toolBarManager.add(scrollLockAction);
+        toolBarManager
+                .add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
+
+        IMenuManager mgr = actionBars.getMenuManager();
+        mgr.add(groupByAction);
+        mgr.add(new Separator());
+        mgr.add(filterAction);
+        mgr.add(new Separator());
+        mgr.add(activateViewAction);
+        mgr.add(showTextFilter);
+
+        addManagerListeners();
+
+        if (sortCandidate == ORDER_BY_TIME) {
+            sortByTimeAction.run();
+        } else if (sortCandidate == ORDER_BY_SEVERITY) {
+            sortBySeverityAction.run();
+        } else { // order_selected == ORDER_BY_NONE
+            sortByMessageAction.run();
+        }
+
+    }
+
+    private void setupFilteredTree() {
+        tree.setLayoutData(new GridData(GridData.FILL_BOTH));
+        final Tree innerTree = tree.getViewer().getTree();
+        innerTree.setLinesVisible(true);
+
+        severityColumn = new TreeColumn(innerTree, SWT.LEFT);
+        severityColumn.setText("Severity");
+        severityColumn.setWidth(110);
+        severityColumn.addSelectionListener(new SelectionAdapter() {
+
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                sortBySeverityAction.run();
+            }
+        });
+        dateColumn = new TreeColumn(innerTree, SWT.LEFT);
+        dateColumn.setText("Time");
+        dateColumn.setWidth(110);
+        dateColumn.addSelectionListener(new SelectionAdapter() {
+
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                sortByTimeAction.run();
+            }
+        });
+        messageColumn = new TreeColumn(innerTree, SWT.LEFT);
+        messageColumn.setText("Message");
+        messageColumn.setWidth(180);
+        messageColumn.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                sortByMessageAction.run();
+            }
+        });
+
+        innerTree.setHeaderVisible(true);
+
+        treeContentProvider = new LogContentProvider();
+
+        tree.getViewer().setContentProvider(treeContentProvider);
+        tree.getViewer().setLabelProvider(new LogLabelProvider());
+
+        tree.getViewer().setInput(logManager.getLogEntries());
+
+        tree.getViewer().addSelectionChangedListener(
+                new ISelectionChangedListener() {
+
+                    @Override
+                    public void selectionChanged(SelectionChangedEvent event) {
+                        deleteLogAction.setEnabled(!tree.getViewer()
+                                .getSelection().isEmpty());
+                        logDetailsAction.setEnabled(!tree.getViewer()
+                                .getSelection().isEmpty());
+                    }
+                });
+
+        tree.getViewer().getTree().addKeyListener(new KeyListener() {
+
+            @Override
+            public void keyReleased(KeyEvent e) {
+            }
+
+            @Override
+            public void keyPressed(KeyEvent e) {
+                if (e.character == (char) 127) { // If delete key is pressed
+                    if (deleteLogAction.isEnabled()) {
+                        deleteLogAction.run();
+                    }
+                }
+            }
+        });
+
+        tree.getViewer().addDoubleClickListener(new IDoubleClickListener() {
+
+            @Override
+            public void doubleClick(DoubleClickEvent event) {
+                logDetailsAction.run();
+            }
+        });
+    }
+
+    private void createColumnComparators() {
+        dateComparator = new ViewerComparator() {
+
+            @Override
+            public int compare(Viewer viewer, Object e1, Object e2) {
+                LogEntry l1 = (LogEntry) e1;
+                LogEntry l2 = (LogEntry) e2;
+                return l1.getDate().compareTo(l2.getDate()) * sortDirection;
+            }
+        };
+
+        severityComparator = new ViewerComparator() {
+
+            @Override
+            public int compare(Viewer viewer, Object e1, Object e2) {
+                LogEntry l1 = (LogEntry) e1;
+                LogEntry l2 = (LogEntry) e2;
+                if (l1.getSeverity() < l2.getSeverity()) {
+                    return -1 * sortDirection;
+                }
+                if (l1.getSeverity() > l2.getSeverity()) {
+                    return 1 * sortDirection;
+                }
+                return 0;
+            }
+        };
+
+        messageComparator = new ViewerComparator() {
+
+            @Override
+            public int compare(Viewer viewer, Object e1, Object e2) {
+                LogEntry l1 = (LogEntry) e1;
+                LogEntry l2 = (LogEntry) e2;
+                return l1.getMessage().compareTo(l2.getMessage())
+                        * sortDirection;
+            }
+        };
+
+    }
+
+    private void setDefaultShownSeverities() {
+        shownSeverities.put(Level.INFO.ordinal(), true);
+        shownSeverities.put(Level.DEBUG.ordinal(), true);
+        shownSeverities.put(Level.WARNING.ordinal(), true);
+        shownSeverities.put(Level.ERROR.ordinal(), true);
+    }
+
+    private void addManagerListeners() {
+        logManager.addLogListener(logListener);
+        logManager.applyFilter(shownSeverities);
+    }
+
+    private void createActions() {
+        exportLogAction = createExportLogAction();
+        clearLogAction = createClearLogAction();
+        deleteLogAction = createDeleteLogAction();
+        scrollLockAction = createScrollLockAction();
+        logDetailsAction = createLogDetailsAction();
+
+        filterAction = createFilterAction();
+        activateViewAction = createActivateViewAction();
+        showTextFilter = createShowTextFilter();
+        groupByAction = createGroupByAction();
+    }
+
+    private IAction createExportLogAction() {
+        Action action = new Action("Export log") {
+            @Override
+            public void run() {
+                FileDialog fd = new FileDialog(Display.getDefault()
+                        .getActiveShell(), SWT.SAVE);
+                fd.setOverwrite(true);
+                fd.setFileName("OIC_Simulator_ServerLog.log");
+                fd.setFilterExtensions(Constants.SAVE_LOG_FILTER_EXTENSIONS);
+                String name = fd.open();
+                List<LogEntry> logEntries = logManager.getLogEntries();
+                StringBuilder sb = new StringBuilder();
+                for (LogEntry entry : logEntries) {
+                    sb.append(entry.toString());
+                }
+                String data = sb.toString();
+                BufferedWriter out = null;
+                try {
+                    out = new BufferedWriter(new FileWriter(name));
+                    out.write(data);
+                } catch (IOException e) {
+                    e.printStackTrace();
+                    MessageDialog.openError(
+                            Display.getDefault().getActiveShell(),
+                            "Export error",
+                            "Could not export log. IO exception: "
+                                    + e.getMessage());
+                } finally {
+                    try {
+                        if (null != out) {
+                            out.close();
+                        }
+                    } catch (IOException e) {
+                        System.out.println("Error occurred during close.");
+                    }
+                }
+            }
+        };
+        action.setToolTipText("Export log");
+
+        action.setImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/export_log_e.gif"));
+        action.setDisabledImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/export_log_d.gif"));
+        action.setEnabled(true);
+
+        return action;
+    }
+
+    private IAction createClearLogAction() {
+        Action action = new Action("Clear log") {
+
+            @Override
+            public void run() {
+                logManager.clearLog();
+            }
+        };
+        action.setToolTipText("Clear log");
+
+        action.setImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/clear_e.gif"));
+        action.setDisabledImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/clear_d.gif"));
+        action.setEnabled(true);
+        return action;
+    }
+
+    private IAction createDeleteLogAction() {
+        Action action = new Action("Delete log entry") {
+
+            @Override
+            @SuppressWarnings("unchecked")
+            public void run() {
+                IStructuredSelection selection = (IStructuredSelection) tree
+                        .getViewer().getSelection();
+                List<LogEntry> entries = (List<LogEntry>) tree.getViewer()
+                        .getInput();
+                LogEntry selectedEntry = (LogEntry) selection.getFirstElement();
+                if (null != selectedEntry) {
+                    LogEntry toBeShownEntry = null;
+                    for (LogEntry entry : entries) {
+                        if (entry.equals(selectedEntry)) {
+                            int size = entries.size();
+                            int index = entries.indexOf(selectedEntry);
+                            if (index + 1 < size) {
+                                toBeShownEntry = entries.get(index + 1);
+                            } else if (index > 0) {
+                                toBeShownEntry = entries.get(index - 1);
+                            }
+                            break;
+                        }
+                    }
+                    logManager.removeEntry(selectedEntry);
+                    if (null != toBeShownEntry) {
+                        tree.getViewer().setSelection(
+                                new StructuredSelection(toBeShownEntry));
+                    }
+                }
+            }
+        };
+        action.setToolTipText("Delete log entry");
+        action.setImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/delete_e.gif"));
+        action.setDisabledImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/delete_d.gif"));
+        action.setEnabled(false);
+        return action;
+    }
+
+    private IAction createScrollLockAction() {
+        Action action = new Action("Scroll lock") {
+
+            @Override
+            public void run() {
+                scrollLockDisabled = !this.isChecked();
+            };
+
+            @Override
+            public int getStyle() {
+                return IAction.AS_CHECK_BOX;
+            }
+        };
+        action.setToolTipText("Scroll lock");
+        action.setImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/lock_e.gif"));
+        action.setDisabledImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/lock_d.gif"));
+        action.setEnabled(true);
+        return action;
+    }
+
+    private IAction createLogDetailsAction() {
+        Action action = new Action("Details...") {
+
+            @Override
+            public void run() {
+                Display.getDefault().asyncExec(new Runnable() {
+
+                    @Override
+                    public void run() {
+                        LogEntry x = (LogEntry) ((IStructuredSelection) tree
+                                .getViewer().getSelection()).getFirstElement();
+
+                        new LogDetailsDialog(Display.getDefault()
+                                .getActiveShell(), LogManager.getSeverityName(x
+                                .getSeverity()), LogManager.getSeverityIcon(x
+                                .getSeverity()), x.getDate(), x.getMessage())
+                                .open();
+                    }
+                });
+            }
+        };
+        action.setToolTipText("Details...");
+        action.setImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/log_details_e.gif"));
+        action.setDisabledImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/log_details_e.gif"));
+        action.setEnabled(false);
+        return action;
+    }
+
+    private IAction createFilterAction() {
+        Action action = new Action("Filters ...") {
+
+            @Override
+            public void run() {
+                FilterDialog fd = new FilterDialog(Display.getDefault()
+                        .getActiveShell(), shownSeverities);
+                if (fd.open() == Window.OK) {
+                    logManager.applyFilter(shownSeverities);
+                }
+                tree.getViewer().refresh();
+            }
+        };
+        action.setToolTipText("Filters ...");
+
+        action.setImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/filter_e.gif"));
+        action.setDisabledImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/filter_d.gif"));
+        action.setEnabled(true);
+        return action;
+    }
+
+    private IAction createActivateViewAction() {
+        Action action = new Action("Activate view on new events",
+                IAction.AS_CHECK_BOX) {
+
+            @Override
+            public void run() {
+                activateOnChange = this.isChecked();
+            }
+        };
+        action.setChecked(activateOnChange);
+        action.setToolTipText("Activate view on new events");
+
+        action.setImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/prop_e.gif"));
+        action.setDisabledImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/prop_d.gif"));
+        action.setEnabled(true);
+        return action;
+    }
+
+    private IAction createShowTextFilter() {
+        Action action = new Action("Show text filter", IAction.AS_CHECK_BOX) {
+
+            @Override
+            public void run() {
+                Text filterControl = tree.getFilterControl();
+                Composite filterComposite = filterControl.getParent();
+                GridData gd = (GridData) filterComposite.getLayoutData();
+                boolean visible = isChecked();
+                gd.exclude = !visible;
+                filterComposite.setVisible(visible);
+                filterControl.setText("");
+                if (visible) {
+                    filterControl.selectAll();
+                    setFocus();
+                }
+                tree.layout(false);
+                hideTextFilter = !visible;
+            }
+        };
+        action.setToolTipText("Show text filter");
+
+        action.setImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/tree_mode_e.gif"));
+        action.setDisabledImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/tree_mode_d.gif"));
+        action.setEnabled(true);
+        action.setChecked(!hideTextFilter);
+        if (hideTextFilter) {
+            action.run();
+        }
+        return action;
+    }
+
+    private IContributionItem createGroupByAction() {
+        IMenuManager manager = new MenuManager("Order by");
+        manager.add(sortByTimeAction);
+        manager.add(sortBySeverityAction);
+        manager.add(sortByMessageAction);
+        return manager;
+    }
+
+    class SortAction extends Action {
+
+        private final int sortBy;
+
+        public SortAction(String text, int sortBy) {
+            super(text, IAction.AS_RADIO_BUTTON);
+            this.sortBy = sortBy;
+
+            if (sortCandidate == sortBy) {
+                setChecked(true);
+            }
+        }
+
+        @Override
+        public void run() {
+            sortBySeverityAction.setChecked(false);
+            sortByTimeAction.setChecked(false);
+            sortCandidate = sortBy;
+            setChecked(true);
+
+            ViewerComparator comparator;
+            TreeColumn column;
+            if (sortBy == ORDER_BY_SEVERITY) {
+                comparator = severityComparator;
+                column = severityColumn;
+            } else if (sortBy == ORDER_BY_TIME) {
+                comparator = dateComparator;
+                column = dateColumn;
+            } else { // Order by message
+                comparator = messageComparator;
+                column = messageColumn;
+            }
+            TreeViewer viewer = tree.getViewer();
+            viewer.setComparator(comparator);
+            viewer.getTree().setSortColumn(column);
+            if (column.equals(sortColumn)) { // reverse sorting order
+                sortDirection = viewer.getTree().getSortDirection() == SWT.UP ? DOWN
+                        : UP;
+                viewer.getTree().setSortDirection(
+                        sortDirection == UP ? SWT.UP : SWT.DOWN);
+                viewer.refresh();
+            } else { // set this column as the one to sort by
+                sortDirection = DOWN;
+                viewer.getTree().setSortDirection(SWT.DOWN);
+            }
+            sortColumn = column;
+            refresh();
+        }
+    }
+
+    private void refresh() {
+        tree.getViewer().refresh();
+    }
+
+    @Override
+    public void setFocus() {
+        tree.setFocus();
+    }
+
+    @Override
+    public void dispose() {
+        logManager.removeLogListener(logListener);
+        super.dispose();
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/MetaPropertiesView.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/MetaPropertiesView.java
new file mode 100644 (file)
index 0000000..ae9fa40
--- /dev/null
@@ -0,0 +1,202 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package oic.simulator.clientcontroller.view;
+
+import java.util.List;
+
+import oic.simulator.clientcontroller.Activator;
+import oic.simulator.clientcontroller.listener.IResourceSelectionChangedUIListener;
+import oic.simulator.clientcontroller.manager.ResourceManager;
+import oic.simulator.clientcontroller.remoteresource.MetaProperty;
+import oic.simulator.clientcontroller.remoteresource.RemoteResource;
+
+import org.eclipse.jface.viewers.ColumnLabelProvider;
+import org.eclipse.jface.viewers.IStructuredContentProvider;
+import org.eclipse.jface.viewers.TableViewer;
+import org.eclipse.jface.viewers.TableViewerColumn;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.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.Table;
+import org.eclipse.ui.part.ViewPart;
+
+/**
+ * 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.clientcontroller.view.metaproperties";
+
+    private TableViewer                         tableViewer;
+
+    private final String[]                      columnHeaders = { "Property",
+            "Value"                                          };
+
+    private final Integer[]                     columnWidth   = { 150, 150 };
+
+    private IResourceSelectionChangedUIListener resourceSelectionChangedListener;
+
+    private ResourceManager                     resourceManager;
+
+    public MetaPropertiesView() {
+
+        resourceManager = Activator.getDefault().getResourceManager();
+
+        resourceSelectionChangedListener = new IResourceSelectionChangedUIListener() {
+
+            @Override
+            public void onResourceSelectionChange(final RemoteResource resource) {
+                Display.getDefault().asyncExec(new Runnable() {
+
+                    @Override
+                    public void run() {
+                        if (null != tableViewer) {
+                            updateViewer(getData(resource));
+                        }
+                    }
+                });
+            }
+        };
+    }
+
+    @Override
+    public void createPartControl(Composite parent) {
+        parent.setLayout(new GridLayout(1, false));
+
+        tableViewer = new TableViewer(parent, SWT.SINGLE | SWT.H_SCROLL
+                | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER);
+
+        createColumns(tableViewer);
+
+        // make lines and header visible
+        final Table table = tableViewer.getTable();
+        table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+        table.setHeaderVisible(true);
+        table.setLinesVisible(true);
+
+        tableViewer.setContentProvider(new PropertycontentProvider());
+
+        addManagerListeners();
+
+        // Check whether there is any resource selected already
+        List<MetaProperty> propertyList = getData(null);
+        if (null != propertyList) {
+            updateViewer(propertyList);
+        }
+
+    }
+
+    private List<MetaProperty> getData(RemoteResource resource) {
+        if (null == resource) {
+            resource = Activator.getDefault().getResourceManager()
+                    .getCurrentResourceInSelection();
+        }
+        List<MetaProperty> metaPropertyList = resourceManager
+                .getMetaProperties(resource);
+        return metaPropertyList;
+    }
+
+    private void updateViewer(List<MetaProperty> metaPropertyList) {
+        if (null != tableViewer) {
+            Table tbl = tableViewer.getTable();
+            if (null != metaPropertyList) {
+                tableViewer.setInput(metaPropertyList.toArray());
+                if (!tbl.isDisposed()) {
+                    tbl.setLinesVisible(true);
+                }
+            } else {
+                if (!tbl.isDisposed()) {
+                    tbl.removeAll();
+                    tbl.setLinesVisible(false);
+                }
+            }
+        }
+    }
+
+    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 ColumnLabelProvider() {
+            @Override
+            public String getText(Object element) {
+                MetaProperty prop = (MetaProperty) element;
+                if (null != prop) {
+                    return prop.getPropName();
+                } else {
+                    return "";
+                }
+            }
+        });
+
+        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 "";
+                }
+            }
+        });
+    }
+
+    private void addManagerListeners() {
+        resourceManager
+                .addResourceSelectionChangedUIListener(resourceSelectionChangedListener);
+    }
+
+    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;
+        }
+
+    }
+
+    @Override
+    public void dispose() {
+        // Unregister the listener
+        if (null != resourceSelectionChangedListener) {
+            resourceManager
+                    .removeResourceSelectionChangedUIListener(resourceSelectionChangedListener);
+        }
+        super.dispose();
+    }
+
+    @Override
+    public void setFocus() {
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/MultiResourceOrchestrationView.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/MultiResourceOrchestrationView.java
new file mode 100644 (file)
index 0000000..67ae7ce
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package oic.simulator.clientcontroller.view;
+
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.ui.part.ViewPart;
+
+/**
+ * This class manages and shows the multi-resource automation view in the
+ * perspective.
+ */
+public class MultiResourceOrchestrationView extends ViewPart {
+
+    public static final String VIEW_ID = "oic.simulator.clientcontroller.view.orchestration";
+
+    @Override
+    public void createPartControl(Composite arg0) {
+        // TODO Auto-generated method stub
+
+    }
+
+    @Override
+    public void setFocus() {
+        // TODO Auto-generated method stub
+
+    }
+
+}
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/ResourceManagerView.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/ResourceManagerView.java
new file mode 100644 (file)
index 0000000..2082a42
--- /dev/null
@@ -0,0 +1,766 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package oic.simulator.clientcontroller.view;
+
+import java.util.List;
+import java.util.Set;
+
+import oic.simulator.clientcontroller.Activator;
+import oic.simulator.clientcontroller.listener.IFindResourceUIListener;
+import oic.simulator.clientcontroller.manager.ResourceManager;
+import oic.simulator.clientcontroller.remoteresource.RemoteResource;
+import oic.simulator.clientcontroller.utils.Constants;
+import oic.simulator.clientcontroller.view.dialogs.FindResourceWizard;
+import oic.simulator.clientcontroller.view.dialogs.LoadRAMLDialog;
+import oic.simulator.clientcontroller.view.dialogs.ResourceWizardDialog;
+
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.viewers.ISelectionChangedListener;
+import org.eclipse.jface.viewers.IStructuredSelection;
+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;
+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.Menu;
+import org.eclipse.swt.widgets.MenuItem;
+import org.eclipse.swt.widgets.Tree;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.dialogs.FilteredTree;
+import org.eclipse.ui.dialogs.PatternFilter;
+import org.eclipse.ui.part.ViewPart;
+
+/**
+ * This class manages and shows the resource manager view in the perspective.
+ */
+public class ResourceManagerView extends ViewPart {
+
+    public static final String      VIEW_ID = "oic.simulator.clientcontroller.view.resourcemanager";
+
+    private Button                  findResButton;
+    private Button                  refreshButton;
+
+    private TreeViewer              treeViewer;
+    private TreeViewer              favTreeViewer;
+
+    private CTabFolder              folder;
+    private CTabItem                foundResTab;
+    private CTabItem                favResTab;
+
+    private ResourceManager         resourceManager;
+
+    private IFindResourceUIListener findListener;
+
+    private Boolean                 foundResource;
+
+    private MessageDialog           findDialog;
+
+    private MessageDialog           refreshDialog;
+
+    private Thread                  sleepThreadHandle;
+
+    public ResourceManagerView() {
+        resourceManager = Activator.getDefault().getResourceManager();
+
+        findListener = new IFindResourceUIListener() {
+
+            @Override
+            public void onNewResourceFound(final RemoteResource resource) {
+                System.out.println("View: onNewResourceFound");
+                if (null == resource) {
+                    return;
+                }
+                // Changing the status of the find operation.
+                setFoundResource(true);
+
+                // Interrupt the sleep thread.
+                if (null != sleepThreadHandle && sleepThreadHandle.isAlive()) {
+                    sleepThreadHandle.interrupt();
+                }
+
+                // Update the tree viewer
+                Display.getDefault().asyncExec(new Runnable() {
+                    @Override
+                    public void run() {
+                        if (!treeViewer.getControl().isDisposed()) {
+                            treeViewer.refresh();
+                        }
+
+                        if (!favTreeViewer.getControl().isDisposed()) {
+                            favTreeViewer.refresh();
+                        }
+
+                        // Close the find dialog
+                        if (null != findDialog) {
+                            boolean status = findDialog.close();
+                            System.out
+                                    .println("dialog close status: " + status);
+                        }
+
+                        // Close the refresh dialog
+                        if (null != refreshDialog) {
+                            boolean status = refreshDialog.close();
+                            System.out
+                                    .println("dialog close status: " + status);
+                        }
+                    }
+                });
+            }
+        };
+    }
+
+    @Override
+    public void createPartControl(Composite parent) {
+        Composite compContent = new Composite(parent, SWT.NONE);
+        compContent.setLayout(new GridLayout());
+        GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        compContent.setLayoutData(gd);
+
+        Composite buttonComp = new Composite(compContent, SWT.NONE);
+        buttonComp.setLayout(new GridLayout(2, false));
+
+        gd = new GridData();
+        gd.horizontalAlignment = SWT.FILL;
+        gd.grabExcessHorizontalSpace = true;
+
+        buttonComp.setLayoutData(gd);
+
+        findResButton = new Button(buttonComp, SWT.PUSH);
+        findResButton.setText("Find Resources");
+        findResButton.setToolTipText("Find OIC resources");
+
+        gd = new GridData();
+        gd.widthHint = 130;
+        findResButton.setLayoutData(gd);
+
+        refreshButton = new Button(buttonComp, SWT.PUSH);
+        refreshButton.setText("Refresh");
+        refreshButton.setToolTipText("Restart the search once again");
+
+        gd = new GridData();
+        gd.widthHint = 90;
+        refreshButton.setLayoutData(gd);
+
+        // 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) {
+                /*
+                 * 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);
+                resourceManager.resourceSelectionChanged(null);
+            }
+        });
+
+        createFoundResourcesArea();
+
+        createFavoriteResourcesArea();
+
+        folder.setSelection(foundResTab);
+
+        findDialog = new MessageDialog(Display.getDefault().getActiveShell(),
+                "Finding Servers", null,
+                "Finding the requested servers\nPlease wait...",
+                MessageDialog.INFORMATION, new String[] { "Cancel" }, 0);
+        // findDialog.setBlockOnOpen(false);
+
+        refreshDialog = new MessageDialog(
+                Display.getDefault().getActiveShell(),
+                "Finding Servers",
+                null,
+                "Refreshing the search and finding the requested servers once again\nPlease wait...",
+                MessageDialog.INFORMATION, new String[] { "Cancel" }, 0);
+        // refreshDialog.setBlockOnOpen(false);
+
+        addUIListeners();
+
+        addManagerListeners();
+
+        // Setting the initial visibility of refresh based on the last known
+        // search operation.
+        Set<String> prevSearchTypes = resourceManager.getLastKnownSearchTypes();
+        if (null == prevSearchTypes || prevSearchTypes.size() < 1) {
+            refreshButton.setEnabled(false);
+        } else {
+            refreshButton.setEnabled(true);
+        }
+    }
+
+    private void createFoundResourcesArea() {
+        foundResTab = new CTabItem(folder, SWT.NULL);
+        foundResTab.setText("Found 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);
+        treeViewer = filteredTree.getViewer();
+        treeViewer.getTree().setLayoutData(
+                new GridData(SWT.FILL, SWT.FILL, true, true));
+        treeViewer.setContentProvider(new TreeContentProvider());
+        treeViewer.setLabelProvider(new TreeLabelProvider());
+        treeViewer.setInput(new Object());
+
+        addMenuToFoundResources();
+
+        foundResTab.setControl(resourceGroup);
+    }
+
+    private void addMenuToFoundResources() {
+
+        if (null != treeViewer) {
+            final Tree resourceTreeHead = treeViewer.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();
+                        }
+                        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");
+                                        }
+                                    }
+                                });
+
+                        RemoteResource resource = resourceManager
+                                .getCurrentResourceInSelection();
+                        if (null == resource) {
+                            return;
+                        }
+                        String menuText = !resource.isFavorite() ? "Add to favorites"
+                                : "Remove from favorites";
+                        MenuItem addToFavMenuItem = new MenuItem(menu, SWT.NONE);
+                        addToFavMenuItem.setText(menuText);
+                        addToFavMenuItem
+                                .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);
+                                        } else {
+                                            resourceManager
+                                                    .removeResourceFromFavorites(resource);
+                                            resourceManager
+                                                    .removeResourceURIFromFavorites(resource);
+                                        }
+                                        favTreeViewer.refresh();
+                                    }
+                                });
+                    }
+                });
+            }
+        }
+    }
+
+    private void createFavoriteResourcesArea() {
+        favResTab = new CTabItem(folder, SWT.NULL);
+        favResTab.setText("Favorite 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);
+        favTreeViewer = filteredTree.getViewer();
+        favTreeViewer.getTree().setLayoutData(
+                new GridData(SWT.FILL, SWT.FILL, true, true));
+        favTreeViewer.setContentProvider(new FavTreeContentProvider());
+        favTreeViewer.setLabelProvider(new TreeLabelProvider());
+        favTreeViewer.setInput(new Object());
+
+        favResTab.setControl(resourceGroup);
+
+        addMenuToFavResources();
+    }
+
+    private void addMenuToFavResources() {
+        if (null != favTreeViewer) {
+            final Tree resourceTreeHead = favTreeViewer.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();
+                        }
+                        MenuItem addToFavMenuItem = new MenuItem(menu, SWT.NONE);
+                        addToFavMenuItem.setText("Remove from favorites");
+                        addToFavMenuItem
+                                .addSelectionListener(new SelectionAdapter() {
+                                    @Override
+                                    public void widgetSelected(SelectionEvent e) {
+                                        RemoteResource resource = (RemoteResource) ((IStructuredSelection) favTreeViewer
+                                                .getSelection())
+                                                .getFirstElement();
+                                        if (null == resource) {
+                                            return;
+                                        }
+                                        resourceManager
+                                                .removeResourceFromFavorites(resource);
+                                        resourceManager
+                                                .removeResourceURIFromFavorites(resource);
+                                        favTreeViewer.refresh();
+                                    }
+                                });
+                    }
+                });
+            }
+        }
+    }
+
+    private void addUIListeners() {
+        findResButton.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {
+
+                    @Override
+                    public void run() {
+                        FindResourceWizard findWizard = new FindResourceWizard();
+                        ResourceWizardDialog wizardDialog = new ResourceWizardDialog(
+                                PlatformUI.getWorkbench().getDisplay()
+                                        .getActiveShell(), findWizard);
+                        int open = wizardDialog.open();
+                        if (open == WizardDialog.OK) {
+                            // Setting initial value on starting the find
+                            // operation.
+                            setFoundResource(false);
+
+                            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);
+
+                                // Change the refresh visibility
+                                refreshButton.setEnabled(true);
+                            }
+                        }
+                    }
+                });
+            }
+        });
+
+        refreshButton.addSelectionListener(new SelectionAdapter() {
+            @Override
+            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.
+                resourceManager.deleteResources(searchTypes);
+
+                // Update the tree
+                treeViewer.refresh();
+                favTreeViewer.refresh();
+
+                // Call native method to find Resources
+                boolean result = resourceManager
+                        .findResourceRequest(searchTypes);
+                if (result) {
+                    searchUIOperation(true);
+                } else {
+                    MessageDialog
+                            .openError(Display.getDefault().getActiveShell(),
+                                    "Find Resource status",
+                                    "Operation failed due to some problems in core layer.");
+                }
+            }
+        });
+
+        // Below code adds a listener to the tree for selection changes
+        // and notifies the resource manager
+        ISelectionChangedListener treeSelectionListener = new ISelectionChangedListener() {
+
+            @Override
+            public void selectionChanged(SelectionChangedEvent e) {
+                if (e.getSelection().isEmpty()) {
+                    return;
+                }
+                if (e.getSelection() instanceof IStructuredSelection) {
+                    IStructuredSelection selection = (IStructuredSelection) e
+                            .getSelection();
+                    RemoteResource resource = (RemoteResource) selection
+                            .getFirstElement();
+                    if (null == resource) {
+                        return;
+                    }
+                    System.out.println("Selected resource: "
+                            + resource.getResourceURI());
+                    resourceManager.resourceSelectionChanged(resource);
+                }
+            }
+        };
+
+        treeViewer.addSelectionChangedListener(treeSelectionListener);
+        favTreeViewer.addSelectionChangedListener(treeSelectionListener);
+    }
+
+    // If refresh is true, then Refresh Dialog else Find Dialog will be shown.
+    private void searchUIOperation(boolean refresh) {
+        final MessageDialog targetDialog;
+        if (refresh) {
+            targetDialog = refreshDialog;
+        } else {
+            targetDialog = findDialog;
+        }
+        // Open the dialog in a new thread.
+        PlatformUI.getWorkbench().getDisplay().syncExec(new Thread() {
+
+            @Override
+            public void run() {
+                if (isFoundResource()) {
+                    setFoundResource(false);
+                    return;
+                }
+
+                PlatformUI.getWorkbench().getDisplay().asyncExec(new Thread() {
+                    @Override
+                    public void run() {
+                        targetDialog.open(); // This method returns once the
+                        // cancel button is pressed.
+
+                        // Interrupt the sleep thread.
+                        if (null != sleepThreadHandle
+                                && sleepThreadHandle.isAlive()) {
+                            sleepThreadHandle.interrupt();
+                        }
+
+                        // Set the status of find.
+                        setFoundResource(false);
+                    }
+                });
+
+                // Thread for find time-out.
+                sleepThreadHandle = new Thread() {
+                    Thread child;
+
+                    public void run() {
+                        try {
+                            Thread.sleep(Constants.FIND_RESOURCES_TIMEOUT * 1000);
+                        } catch (InterruptedException e) {
+                            System.out.println("Interrupted during sleep.");
+                            return;
+                        }
+
+                        child = new Thread() {
+                            @Override
+                            public void run() {
+                                if (null != targetDialog) {
+                                    targetDialog.close();
+
+                                    // Check if any new resources are
+                                    // discovered.
+                                    // Is no new resources, then display a
+                                    // message box.
+                                    if (!isFoundResource()) {
+                                        MessageDialog
+                                                .openInformation(
+                                                        Display.getDefault()
+                                                                .getActiveShell(),
+                                                        "No servers found",
+                                                        "No servers are available as of now.\n"
+                                                                + "Please check the servers' status and press"
+                                                                + "'Refresh' button to restart the search.");
+                                    } else {
+                                        // Resetting the status to false for
+                                        // ensuring safety.
+                                        setFoundResource(false);
+                                    }
+                                }
+                            }
+                        };
+
+                        PlatformUI.getWorkbench().getDisplay().syncExec(child);
+                    }
+                };
+                sleepThreadHandle.start();
+            }
+        });
+    }
+
+    private void addManagerListeners() {
+        resourceManager.addFindresourceUIListener(findListener);
+    }
+
+    @Override
+    public void dispose() {
+        // Unregister the listener
+        if (null != findListener) {
+            resourceManager.removeFindresourceUIListener(findListener);
+            resourceManager.resourceSelectionChanged(null);
+        }
+        super.dispose();
+    }
+
+    @Override
+    public void setFocus() {
+        // TODO Auto-generated method stub
+
+    }
+
+    public synchronized void setFoundResource(boolean value) {
+        foundResource = value;
+    }
+
+    public synchronized boolean isFoundResource() {
+        return foundResource;
+    }
+}
+
+class TreeContentProvider implements ITreeContentProvider {
+
+    @Override
+    public void dispose() {
+    }
+
+    @Override
+    public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+
+    }
+
+    @Override
+    public Object[] getChildren(Object parent) {
+        return null;
+    }
+
+    @Override
+    public Object[] getElements(Object parent) {
+        System.out.println("Inside getElements()");
+        List<RemoteResource> resourceList = Activator.getDefault()
+                .getResourceManager().getResourceList();
+        return resourceList.toArray();
+    }
+
+    @Override
+    public Object getParent(Object child) {
+        return null;
+    }
+
+    @Override
+    public boolean hasChildren(Object parent) {
+        return false;
+    }
+
+}
+
+class FavTreeContentProvider implements ITreeContentProvider {
+
+    @Override
+    public void dispose() {
+    }
+
+    @Override
+    public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+
+    }
+
+    @Override
+    public Object[] getChildren(Object parent) {
+        return null;
+    }
+
+    @Override
+    public Object[] getElements(Object parent) {
+        System.out.println("Inside getElements()");
+        List<RemoteResource> resourceList = Activator.getDefault()
+                .getResourceManager().getFavResourceList();
+        return resourceList.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) {
+        RemoteResource resource = (RemoteResource) element;
+        return resource.getResourceURI();
+    }
+
+    @Override
+    public Image getImage(Object element) {
+        RemoteResource resource = (RemoteResource) element;
+        ResourceManager resourceManager = Activator.getDefault()
+                .getResourceManager();
+        return resourceManager.getImage(resource.getResourceURI());
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/FilterDialog.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/FilterDialog.java
new file mode 100644 (file)
index 0000000..c9626e2
--- /dev/null
@@ -0,0 +1,94 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package oic.simulator.clientcontroller.view.dialogs;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Map;
+
+import oic.simulator.clientcontroller.manager.LogManager;
+
+import org.eclipse.jface.dialogs.TrayDialog;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.SelectionAdapter;
+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.Control;
+import org.eclipse.swt.widgets.Group;
+import org.eclipse.swt.widgets.Shell;
+
+/**
+ * This class shows a dialog for filtering logs based on severity levels.
+ */
+public class FilterDialog extends TrayDialog {
+    private Map<Integer, Boolean> severities;
+
+    public FilterDialog(Shell shell, Map<Integer, Boolean> severities) {
+        super(shell);
+        this.severities = severities;
+    }
+
+    @Override
+    protected void configureShell(Shell shell) {
+        super.configureShell(shell);
+    }
+
+    @Override
+    protected Control createDialogArea(Composite parent) {
+        Composite composite = (Composite) super.createDialogArea(parent);
+        createSeverityGroup(composite);
+        getShell().setText("Filter details");
+        return composite;
+    }
+
+    /**
+     * Dynamically creates a check-box list for severity levels for user to
+     * choose from
+     */
+    private void createSeverityGroup(Composite parent) {
+        Group group = new Group(parent, SWT.NONE);
+        group.setLayout(new GridLayout());
+        GridData gd = new GridData(GridData.FILL_HORIZONTAL);
+        gd.widthHint = 275;
+        group.setLayoutData(gd);
+        group.setText("Severity Levels");
+
+        ArrayList<Integer> arrayList = new ArrayList<Integer>(
+                severities.keySet());
+        Collections.sort(arrayList);
+        for (final Integer i : arrayList) {
+            final Button checkbox = new Button(group, SWT.CHECK);
+            checkbox.setText(LogManager.getSeverityName(i));
+            checkbox.setSelection(severities.get(i));
+            checkbox.addSelectionListener(new SelectionAdapter() {
+
+                @Override
+                public void widgetSelected(SelectionEvent e) {
+                    severities.put(i, checkbox.getSelection());
+                }
+            });
+        }
+    }
+
+    @Override
+    public boolean isHelpAvailable() {
+        return false;
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/FindResourcePage.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/FindResourcePage.java
new file mode 100644 (file)
index 0000000..9b0d603
--- /dev/null
@@ -0,0 +1,265 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package oic.simulator.clientcontroller.view.dialogs;
+
+import java.util.HashSet;
+import java.util.Set;
+
+import oic.simulator.clientcontroller.utils.Constants;
+
+import org.eclipse.jface.wizard.WizardPage;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.CCombo;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.events.SelectionAdapter;
+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;
+
+/**
+ * This class shows UI for finding resources.
+ */
+public class FindResourcePage extends WizardPage {
+
+    private Button      stdResTypeRbtn;
+    private CCombo      resourceTypeCmb;
+    private Button      cusResTypeRbtn;
+    private Text        resTypeTxt;
+    private Label       stdRTypeLbl;
+    private Label       cusRTypeLbl;
+
+    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);
+
+        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("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));
+        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);
+
+        resourceTypeCmb = new CCombo(stdConfigComp, SWT.READ_ONLY | SWT.BORDER);
+        gd = new GridData();
+        gd.widthHint = 150;
+        resourceTypeCmb.setLayoutData(gd);
+        resourceTypeCmb.setEnabled(false);
+
+        cusResTypeRbtn = new Button(configGroup, SWT.RADIO);
+        cusResTypeRbtn.setText("Custom Resources");
+
+        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);
+        gd = new GridData();
+        gd.minimumWidth = 200;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.grabExcessHorizontalSpace = true;
+        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");
+        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() {
+            @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());
+
+                // Change the visibility of widgets
+                changeVisibility(true);
+            }
+        });
+
+        cusResTypeRbtn.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());
+
+                // Change the visibility of widgets
+                changeVisibility(false);
+
+                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);
+                }
+                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);
+    }
+
+    public Set<String> getSearchTypes() {
+        return typesToSearch;
+    }
+}
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/FindResourceWizard.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/FindResourceWizard.java
new file mode 100644 (file)
index 0000000..9c70526
--- /dev/null
@@ -0,0 +1,61 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package oic.simulator.clientcontroller.view.dialogs;
+
+import java.net.URL;
+import java.util.Set;
+
+import oic.simulator.clientcontroller.Activator;
+
+import org.eclipse.core.runtime.FileLocator;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.core.runtime.Path;
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.jface.wizard.Wizard;
+
+/**
+ * This class creates a UI wizard for find resource operation.
+ */
+public class FindResourceWizard extends Wizard {
+    private FindResourcePage page;
+
+    public FindResourceWizard() {
+        setWindowTitle("Find resources");
+        IPath path = new Path("/icons/oic_logo_64x64.png");
+        URL find = FileLocator.find(Activator.getDefault().getBundle(), path,
+                null);
+        setDefaultPageImageDescriptor(ImageDescriptor.createFromURL(find));
+    }
+
+    public Set<String> getSearchTypes() {
+        if (null == page) {
+            return null;
+        }
+        return page.getSearchTypes();
+    }
+
+    @Override
+    public void addPages() {
+        page = new FindResourcePage();
+        addPage(page);
+    }
+
+    @Override
+    public boolean performFinish() {
+        return true;
+    }
+}
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/LoadRAMLDialog.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/LoadRAMLDialog.java
new file mode 100644 (file)
index 0000000..d19e1d4
--- /dev/null
@@ -0,0 +1,121 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package oic.simulator.clientcontroller.view.dialogs;
+
+import oic.simulator.clientcontroller.utils.Constants;
+
+import org.eclipse.jface.dialogs.TitleAreaDialog;
+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.Control;
+import org.eclipse.swt.widgets.FileDialog;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.swt.widgets.Text;
+import org.eclipse.ui.PlatformUI;
+
+/**
+ * This dialog is used for loading the RAML file.
+ */
+public class LoadRAMLDialog extends TitleAreaDialog {
+
+    private Text   locationTxt;
+    private Button btnBrowse;
+    private String configFilePath;
+
+    public LoadRAMLDialog(Shell parentShell) {
+        super(parentShell);
+    }
+
+    @Override
+    public void create() {
+        super.create();
+        setTitle("Load Remote Resource Configuration");
+        setMessage("Select the RAML Configuration file of the resource to enable Automation.");
+    }
+
+    @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(3, false);
+        layout.verticalSpacing = 10;
+        layout.marginTop = 10;
+        container.setLayout(layout);
+
+        Label loadRamlLbl = new Label(container, SWT.NONE);
+        loadRamlLbl.setText("Load RAML File");
+        GridData gd;
+        gd = new GridData();
+        gd.horizontalSpan = 3;
+        loadRamlLbl.setLayoutData(gd);
+
+        Label locationLbl = new Label(container, SWT.NONE);
+        locationLbl.setText("Location:");
+
+        locationTxt = new Text(container, SWT.BORDER);
+        gd = new GridData();
+        gd.minimumWidth = 300;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.grabExcessHorizontalSpace = true;
+        locationTxt.setLayoutData(gd);
+
+        btnBrowse = new Button(container, SWT.NONE);
+        btnBrowse.setText("Browse");
+        gd = new GridData();
+        gd.widthHint = 80;
+        gd.horizontalAlignment = SWT.FILL;
+        btnBrowse.setLayoutData(gd);
+
+        addUIListeners();
+
+        return compLayout;
+    }
+
+    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);
+                configFilePath = fileDialog.open();
+                if (null == configFilePath) {
+                    System.out.println("Config file path is null");
+                    configFilePath = "";
+                }
+                locationTxt.setText(configFilePath);
+            }
+        });
+    }
+
+    public String getConfigFilePath() {
+        return configFilePath;
+    }
+
+    @Override
+    public boolean isHelpAvailable() {
+        return false;
+    }
+}
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/LogDetailsDialog.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/LogDetailsDialog.java
new file mode 100644 (file)
index 0000000..12d0c59
--- /dev/null
@@ -0,0 +1,143 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package oic.simulator.clientcontroller.view.dialogs;
+
+import java.text.DateFormat;
+import java.util.Date;
+
+import org.eclipse.jface.dialogs.Dialog;
+import org.eclipse.jface.dialogs.IDialogConstants;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.layout.RowData;
+import org.eclipse.swt.layout.RowLayout;
+import org.eclipse.swt.widgets.Button;
+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 detailed information about a log. The dialog will be opened
+ * on double-clicking a log entry in the log view.
+ */
+public class LogDetailsDialog extends Dialog {
+    private final String severity;
+    private final Date   date;
+    private final String message;
+    private final Image  severityIcon;
+
+    public LogDetailsDialog(Shell parentShell, String severity,
+            Image severityIcon, Date date, String message) {
+        super(parentShell);
+        this.severity = severity;
+        this.severityIcon = severityIcon;
+        this.message = message;
+        this.date = date;
+    }
+
+    @Override
+    protected boolean isResizable() {
+        return true;
+    }
+
+    @Override
+    protected void configureShell(Shell shell) {
+        super.configureShell(shell);
+    }
+
+    @Override
+    protected Control createDialogArea(Composite parent) {
+        getShell().setText("Logged event details");
+
+        Composite container = (Composite) super.createDialogArea(parent);
+
+        GridData layoutData = new GridData(SWT.FILL, SWT.FILL, true, true);
+        container.setLayoutData(layoutData);
+        container.setLayout(new GridLayout(2, false));
+
+        GridData gd;
+
+        Label l1 = new Label(container, SWT.NONE);
+        l1.setText("Severity:");
+        gd = new GridData();
+        gd.widthHint = 100;
+        l1.setLayoutData(gd);
+
+        Composite y = new Composite(container, SWT.NONE);
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        y.setLayoutData(gd);
+        y.setLayout(new RowLayout(SWT.HORIZONTAL));
+
+        Label l2 = new Label(y, SWT.NONE);
+        l2.setImage(severityIcon);
+        l2.setLayoutData(new RowData());
+        Label l3 = new Label(y, SWT.NONE);
+        l3.setText(severity);
+        l3.setLayoutData(new RowData());
+
+        Label l4 = new Label(container, SWT.NONE);
+        l4.setText("Date:");
+        gd = new GridData();
+        gd.widthHint = 100;
+        l4.setLayoutData(gd);
+
+        Label l5 = new Label(container, SWT.NONE);
+        DateFormat dateFormat = DateFormat.getDateTimeInstance(
+                DateFormat.SHORT, DateFormat.SHORT);
+        l5.setText(dateFormat.format(date));
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        l5.setLayoutData(gd);
+
+        new Label(container, SWT.NONE); // separator
+
+        Label l6 = new Label(container, SWT.NONE);
+        l6.setText("Message details");
+        gd = new GridData();
+        gd.horizontalSpan = 2;
+        l6.setLayoutData(gd);
+
+        Text text = new Text(container, SWT.MULTI | SWT.READ_ONLY
+                | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
+        if (message != null) {
+            text.setText(message);
+        } else {
+            text.setText("No description available");
+        }
+        gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        gd.horizontalSpan = 2;
+        gd.heightHint = 350;
+        gd.widthHint = 500;
+        text.setLayoutData(gd);
+
+        return container;
+    }
+
+    @Override
+    protected Button createButton(Composite parent, int id, String label,
+            boolean defaultButton) {
+        if (id == IDialogConstants.CANCEL_ID) {
+            return null;
+        }
+        return super.createButton(parent, id, label, defaultButton);
+    }
+}
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/PostRequestDialog.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/PostRequestDialog.java
new file mode 100644 (file)
index 0000000..3b01cff
--- /dev/null
@@ -0,0 +1,283 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package oic.simulator.clientcontroller.view.dialogs;
+
+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.TitleAreaDialog;
+import org.eclipse.jface.viewers.CellEditor;
+import org.eclipse.jface.viewers.CheckboxCellEditor;
+import org.eclipse.jface.viewers.ColumnLabelProvider;
+import org.eclipse.jface.viewers.EditingSupport;
+import org.eclipse.jface.viewers.IStructuredContentProvider;
+import org.eclipse.jface.viewers.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.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.Control;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.swt.widgets.Table;
+
+/**
+ * This dialog is used for generating a POST request.
+ */
+public class PostRequestDialog extends TitleAreaDialog {
+
+    private TableViewer                 attTblViewer;
+
+    private final String[]              attTblHeaders  = { "Name", "Value",
+            "Select"                                  };
+    private final Integer[]             attTblColWidth = { 200, 200, 50 };
+
+    private ResourceManager             resourceManager;
+
+    private List<PutPostAttributeModel> modelList      = null;
+
+    public PostRequestDialog(Shell parentShell,
+            List<PutPostAttributeModel> modelList) {
+        super(parentShell);
+        this.modelList = modelList;
+        resourceManager = Activator.getDefault().getResourceManager();
+    }
+
+    @Override
+    public void create() {
+        super.create();
+        setTitle("Generate POST Request");
+        setMessage("Dialog which takes input and generates a post request.");
+    }
+
+    @Override
+    protected Control createDialogArea(Composite parent) {
+        Composite compLayout = (Composite) super.createDialogArea(parent);
+        Composite container = new Composite(compLayout, SWT.NONE);
+        container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+        GridLayout layout = new GridLayout(1, false);
+        layout.verticalSpacing = 10;
+        layout.marginTop = 10;
+        container.setLayout(layout);
+
+        createTableViewer(container);
+
+        attTblViewer.setInput(modelList.toArray());
+
+        return compLayout;
+    }
+
+    private void createTableViewer(Composite parent) {
+        attTblViewer = new TableViewer(parent, SWT.SINGLE | 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) {
+
+        // attributeEditor = new AttributeEditingSupport();
+
+        TableViewerColumn attName = new TableViewerColumn(tableViewer, SWT.NONE);
+        attName.getColumn().setWidth(attTblColWidth[0]);
+        attName.getColumn().setText(attTblHeaders[0]);
+        attName.setLabelProvider(new StyledCellLabelProvider() {
+            @Override
+            public void update(ViewerCell cell) {
+                Object element = cell.getElement();
+                if (element instanceof PutPostAttributeModel) {
+                    PutPostAttributeModel entry = (PutPostAttributeModel) element;
+                    cell.setText(entry.getAttName());
+                }
+            }
+        });
+
+        TableViewerColumn attValue = new TableViewerColumn(tableViewer,
+                SWT.NONE);
+        attValue.getColumn().setWidth(attTblColWidth[1]);
+        attValue.getColumn().setText(attTblHeaders[1]);
+        attValue.setLabelProvider(new StyledCellLabelProvider() {
+            @Override
+            public void update(ViewerCell cell) {
+                Object element = cell.getElement();
+                if (element instanceof PutPostAttributeModel) {
+                    PutPostAttributeModel entry = (PutPostAttributeModel) element;
+                    cell.setText(entry.getAttValue());
+                }
+            }
+        });
+        attValue.setEditingSupport(new AttributeValueEditor(attTblViewer));
+
+        TableViewerColumn updateColumn = new TableViewerColumn(tableViewer,
+                SWT.NONE);
+        updateColumn.getColumn().setWidth(attTblColWidth[2]);
+        updateColumn.getColumn().setText(attTblHeaders[2]);
+        updateColumn.setLabelProvider(new ColumnLabelProvider() {
+            @Override
+            public String getText(Object element) {
+                return "";
+            }
+
+            @Override
+            public Image getImage(Object element) {
+                PutPostAttributeModel model = (PutPostAttributeModel) element;
+                if (model.isModified()) {
+                    return Activator.getDefault().getImageRegistry()
+                            .get(Constants.CHECKED);
+                }
+                return Activator.getDefault().getImageRegistry()
+                        .get(Constants.UNCHECKED);
+            }
+        });
+        updateColumn.setEditingSupport(new UpdateEditor(attTblViewer));
+    }
+
+    @Override
+    protected boolean isResizable() {
+        return true;
+    }
+
+    @Override
+    public boolean isHelpAvailable() {
+        return false;
+    }
+
+    @Override
+    protected Button createButton(Composite parent, int id, String label,
+            boolean defaultButton) {
+        if (id == IDialogConstants.OK_ID) {
+            label = "POST";
+        }
+        return super.createButton(parent, id, label, defaultButton);
+    }
+
+    class AttributeContentProvider 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;
+        }
+
+    }
+
+    class AttributeValueEditor extends EditingSupport {
+        private final TableViewer viewer;
+        private final CellEditor  editor;
+
+        public AttributeValueEditor(TableViewer viewer) {
+            super(viewer);
+            this.viewer = viewer;
+            editor = new TextCellEditor(viewer.getTable());
+        }
+
+        @Override
+        protected boolean canEdit(Object arg0) {
+            return true;
+        }
+
+        @Override
+        protected CellEditor getCellEditor(Object element) {
+            return editor;
+        }
+
+        @Override
+        protected Object getValue(Object element) {
+            PutPostAttributeModel model = (PutPostAttributeModel) element;
+            return model.getAttValue();
+        }
+
+        @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);
+            String actualValue = resourceManager.getAttributeValue(
+                    resourceManager.getCurrentResourceInSelection(),
+                    model.getAttName());
+            if (newValue.equals(actualValue)) {
+                model.setModified(false);
+            } else {
+                model.setModified(true);
+            }
+            model.setAttValue(newValue);
+            viewer.update(element, null);
+        }
+    }
+
+    class UpdateEditor extends EditingSupport {
+
+        private final TableViewer viewer;
+
+        public UpdateEditor(TableViewer viewer) {
+            super(viewer);
+            this.viewer = viewer;
+        }
+
+        @Override
+        protected boolean canEdit(Object arg0) {
+            return true;
+        }
+
+        @Override
+        protected CellEditor getCellEditor(Object element) {
+            return new CheckboxCellEditor(null, SWT.CHECK | SWT.READ_ONLY);
+        }
+
+        @Override
+        protected Object getValue(Object element) {
+            PutPostAttributeModel model = (PutPostAttributeModel) element;
+            return model.isModified();
+        }
+
+        @Override
+        protected void setValue(Object element, Object value) {
+            PutPostAttributeModel model = (PutPostAttributeModel) element;
+            boolean status = (boolean) value;
+            model.setModified(status);
+            viewer.update(element, null);
+        }
+    }
+}
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/PutRequestDialog.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/PutRequestDialog.java
new file mode 100644 (file)
index 0000000..3ba0c87
--- /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.clientcontroller.view.dialogs;
+
+import java.util.List;
+
+import oic.simulator.clientcontroller.remoteresource.PutPostAttributeModel;
+
+import org.eclipse.jface.dialogs.IDialogConstants;
+import org.eclipse.jface.dialogs.TitleAreaDialog;
+import org.eclipse.jface.viewers.CellEditor;
+import org.eclipse.jface.viewers.EditingSupport;
+import org.eclipse.jface.viewers.IStructuredContentProvider;
+import org.eclipse.jface.viewers.StyledCellLabelProvider;
+import org.eclipse.jface.viewers.TableViewer;
+import org.eclipse.jface.viewers.TableViewerColumn;
+import org.eclipse.jface.viewers.TextCellEditor;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.jface.viewers.ViewerCell;
+import org.eclipse.swt.SWT;
+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.Shell;
+import org.eclipse.swt.widgets.Table;
+
+/**
+ * This dialog is used for generating a PUT request.
+ */
+public class PutRequestDialog extends TitleAreaDialog {
+
+    private TableViewer                 attTblViewer;
+
+    private final String[]              attTblHeaders  = { "Name", "Value" };
+    private final Integer[]             attTblColWidth = { 200, 200 };
+
+    private List<PutPostAttributeModel> modelList      = null;
+
+    public PutRequestDialog(Shell parentShell,
+            List<PutPostAttributeModel> modelList) {
+        super(parentShell);
+        this.modelList = modelList;
+    }
+
+    @Override
+    public void create() {
+        super.create();
+        setTitle("Generate PUT Request");
+        setMessage("Dialog which takes input and generates a put request.");
+    }
+
+    @Override
+    protected Control createDialogArea(Composite parent) {
+        Composite compLayout = (Composite) super.createDialogArea(parent);
+        Composite container = new Composite(compLayout, SWT.NONE);
+        container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+        GridLayout layout = new GridLayout(1, false);
+        layout.verticalSpacing = 10;
+        layout.marginTop = 10;
+        container.setLayout(layout);
+
+        createTableViewer(container);
+
+        attTblViewer.setInput(modelList.toArray());
+
+        return compLayout;
+    }
+
+    private void createTableViewer(Composite parent) {
+        attTblViewer = new TableViewer(parent, SWT.SINGLE | 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 element = cell.getElement();
+                if (element instanceof PutPostAttributeModel) {
+                    PutPostAttributeModel entry = (PutPostAttributeModel) element;
+                    cell.setText(entry.getAttName());
+                }
+            }
+        });
+
+        TableViewerColumn attValue = new TableViewerColumn(tableViewer,
+                SWT.NONE);
+        attValue.getColumn().setWidth(attTblColWidth[1]);
+        attValue.getColumn().setText(attTblHeaders[1]);
+        attValue.setLabelProvider(new StyledCellLabelProvider() {
+            @Override
+            public void update(ViewerCell cell) {
+                Object element = cell.getElement();
+                if (element instanceof PutPostAttributeModel) {
+                    PutPostAttributeModel entry = (PutPostAttributeModel) element;
+                    cell.setText(entry.getAttValue());
+                }
+            }
+        });
+        attValue.setEditingSupport(new AttributeValueEditor(attTblViewer));
+    }
+
+    class AttributeContentProvider 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;
+        }
+    }
+
+    class AttributeValueEditor extends EditingSupport {
+        private final TableViewer viewer;
+        private final CellEditor  editor;
+
+        public AttributeValueEditor(TableViewer viewer) {
+            super(viewer);
+            this.viewer = viewer;
+            editor = new TextCellEditor(viewer.getTable());
+        }
+
+        @Override
+        protected boolean canEdit(Object arg0) {
+            return true;
+        }
+
+        @Override
+        protected CellEditor getCellEditor(Object element) {
+            return editor;
+        }
+
+        @Override
+        protected Object getValue(Object element) {
+            PutPostAttributeModel model = (PutPostAttributeModel) element;
+            return model.getAttValue();
+        }
+
+        @Override
+        protected void setValue(Object element, Object value) {
+            PutPostAttributeModel model = (PutPostAttributeModel) element;
+            model.setAttValue(String.valueOf(value));
+            viewer.update(element, null);
+        }
+    }
+
+    public List<PutPostAttributeModel> getUpdatedModel() {
+        return modelList;
+    }
+
+    @Override
+    protected boolean isResizable() {
+        return true;
+    }
+
+    @Override
+    public boolean isHelpAvailable() {
+        return false;
+    }
+
+    @Override
+    protected Button createButton(Composite parent, int id, String label,
+            boolean defaultButton) {
+        if (id == IDialogConstants.OK_ID) {
+            label = "PUT";
+        }
+        return super.createButton(parent, id, label, defaultButton);
+    }
+}
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/ResourceWizardDialog.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/ResourceWizardDialog.java
new file mode 100644 (file)
index 0000000..1b8658c
--- /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.
+ */
+
+package oic.simulator.clientcontroller.view.dialogs;
+
+import org.eclipse.jface.dialogs.IDialogConstants;
+import org.eclipse.jface.wizard.IWizard;
+import org.eclipse.jface.wizard.WizardDialog;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Shell;
+
+/**
+ * Dialog for handling wizards.
+ */
+public class ResourceWizardDialog extends WizardDialog {
+
+    public ResourceWizardDialog(Shell parentShell, IWizard newWizard) {
+        super(parentShell, newWizard);
+    }
+
+    @Override
+    public boolean isHelpAvailable() {
+        return false;
+    }
+
+    @Override
+    public void finishPressed() {
+        super.finishPressed();
+    }
+
+    @Override
+    protected void createButtonsForButtonBar(Composite parent) {
+        super.createButtonsForButtonBar(parent);
+        Button finishButton = getButton(IDialogConstants.FINISH_ID);
+        if (finishButton != null) {
+            finishButton.setText(IDialogConstants.OK_LABEL);
+        }
+    }
+}
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/VerificationDialog.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/VerificationDialog.java
new file mode 100644 (file)
index 0000000..a221760
--- /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.
+ */
+
+package oic.simulator.clientcontroller.view.dialogs;
+
+import java.util.ArrayList;
+import java.util.Map;
+import java.util.Set;
+
+import oic.simulator.clientcontroller.Activator;
+import oic.simulator.clientcontroller.manager.ResourceManager;
+import oic.simulator.clientcontroller.utils.Constants;
+
+import org.eclipse.jface.dialogs.IDialogConstants;
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.dialogs.TrayDialog;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.SelectionAdapter;
+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.Control;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Group;
+import org.eclipse.swt.widgets.Shell;
+
+/**
+ * Dialog for starting and stopping the automatic verifications.
+ */
+public class VerificationDialog extends TrayDialog {
+    private Map<String, Boolean> automationStatus;
+
+    public VerificationDialog(Shell shell, Map<String, Boolean> automationStatus) {
+        super(shell);
+        this.automationStatus = automationStatus;
+    }
+
+    @Override
+    protected void configureShell(Shell shell) {
+        super.configureShell(shell);
+    }
+
+    @Override
+    protected Control createDialogArea(Composite parent) {
+        Composite composite = (Composite) super.createDialogArea(parent);
+        createAutomationGroup(composite);
+        getShell().setText("Automation Settings");
+        return composite;
+    }
+
+    /**
+     * Dynamically creates a check-box list for enabling/disabling different
+     * types of automation
+     */
+    private void createAutomationGroup(Composite parent) {
+        Group group = new Group(parent, SWT.NONE);
+        group.setLayout(new GridLayout());
+        GridData gd = new GridData(GridData.FILL_HORIZONTAL);
+        gd.widthHint = 275;
+        group.setLayoutData(gd);
+        group.setText("Automation Levels");
+
+        Set<String> keySet = automationStatus.keySet();
+        if (null == keySet) {
+            return;
+        }
+        ArrayList<String> list = new ArrayList<String>(
+                automationStatus.keySet());
+        for (final String str : list) {
+            final Button checkbox = new Button(group, SWT.CHECK);
+            checkbox.setText(str);
+            checkbox.setSelection(automationStatus.get(str));
+            checkbox.addSelectionListener(new SelectionAdapter() {
+
+                @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());
+                        }
+                    }
+                    automationStatus.put(str, checked);
+                }
+            });
+        }
+    }
+
+    @Override
+    protected Button createButton(Composite parent, int id, String label,
+            boolean defaultButton) {
+        if (id == IDialogConstants.CANCEL_ID) {
+            return null;
+        }
+        return super.createButton(parent, id, label, defaultButton);
+    }
+
+    @Override
+    public boolean isHelpAvailable() {
+        return false;
+    }
+}
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/logger/LogContentProvider.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/logger/LogContentProvider.java
new file mode 100644 (file)
index 0000000..c782557
--- /dev/null
@@ -0,0 +1,65 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package oic.simulator.logger;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.jface.viewers.ITreeContentProvider;
+import org.eclipse.jface.viewers.Viewer;
+
+/**
+ * Maintains simulator log entries and provides content to the log view.
+ */
+public class LogContentProvider implements ITreeContentProvider {
+
+    List<LogEntry> logEntryList = new ArrayList<LogEntry>();
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+        logEntryList = (List<LogEntry>) newInput;
+    }
+
+    @Override
+    public Object[] getChildren(Object element) {
+        return new Object[0];
+    }
+
+    @Override
+    public Object[] getElements(Object input) {
+        return logEntryList.toArray();
+    }
+
+    @Override
+    public Object getParent(Object element) {
+        return null;
+    }
+
+    @Override
+    public boolean hasChildren(Object element) {
+        return false;
+    }
+
+    @Override
+    public void dispose() {
+    }
+
+    public synchronized void addLog(LogEntry newElement) {
+        logEntryList.add(newElement);
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/logger/LogEntry.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/logger/LogEntry.java
new file mode 100644 (file)
index 0000000..f042dfc
--- /dev/null
@@ -0,0 +1,58 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package oic.simulator.logger;
+
+import java.util.Date;
+
+import oic.simulator.clientcontroller.manager.LogManager;
+
+/**
+ * Class for log entry.
+ */
+public class LogEntry {
+    private final int    severity;
+    private final Date   date;
+    private final String message;
+
+    public LogEntry(int severity, Date date, String message) {
+        this.severity = severity;
+        this.date = date;
+        this.message = message;
+    }
+
+    public String getMessage() {
+        return message;
+    }
+
+    public Date getDate() {
+        return date;
+    }
+
+    public int getSeverity() {
+        return severity;
+    }
+
+    @Override
+    public String toString() {
+        String newline = System.getProperty("line.separator");
+        String out = date.toString() + newline;
+        out += "Severity: " + LogManager.getSeverityName(severity) + newline;
+        out += "Message: " + message + newline;
+        out += "===============================" + newline + newline;
+        return out;
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/logger/LogLabelProvider.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/logger/LogLabelProvider.java
new file mode 100644 (file)
index 0000000..ca80ad1
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package oic.simulator.logger;
+
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+
+import oic.simulator.clientcontroller.manager.LogManager;
+
+import org.eclipse.jface.viewers.ITableLabelProvider;
+import org.eclipse.jface.viewers.LabelProvider;
+import org.eclipse.swt.graphics.Image;
+
+/**
+ * Label provider which determines what data has to be shown in the log view.
+ */
+public class LogLabelProvider extends LabelProvider implements
+        ITableLabelProvider {
+
+    DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss.SSS");
+
+    @Override
+    public Image getColumnImage(Object element, int columnIndex) {
+        if (columnIndex == 0) {
+            LogEntry entry = (LogEntry) element;
+            return LogManager.getSeverityIcon(entry.getSeverity());
+        }
+        return null;
+    }
+
+    @Override
+    public String getColumnText(Object element, int columnIndex) {
+        LogEntry entry = (LogEntry) element;
+        if (columnIndex == 0) {
+            return LogManager.getSeverityName(entry.getSeverity());
+        } else if (columnIndex == 1) {
+            return dateFormat.format(entry.getDate());
+        } else {
+            return entry.getMessage();
+        }
+    }
+
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/logger/LoggerCallback.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/logger/LoggerCallback.java
new file mode 100644 (file)
index 0000000..81110b0
--- /dev/null
@@ -0,0 +1,74 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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.logger;
+
+import java.util.Calendar;
+import java.util.Date;
+
+import oic.simulator.clientcontroller.Activator;
+import oic.simulator.clientcontroller.utils.Constants;
+
+import org.oic.simulator.ILogger;
+
+/**
+ * Class which provides a callback method to receive log from native layer.
+ */
+public class LoggerCallback implements ILogger {
+
+    @Override
+    public void write(String time, int level, String message) {
+        if (null == time || level < 0 || null == message) {
+            return;
+        }
+        // Parse the time
+        Date date = parseTime(time);
+        if (null == date) {
+            return;
+        }
+        Activator activator = Activator.getDefault();
+        if (null == activator) {
+            return;
+        }
+        activator.getLogManager().log(level, date, message);
+    }
+
+    private Date parseTime(String time) {
+        Date date;
+        String[] token = time.split("\\.");
+        int h, m, s;
+        try {
+            if (token.length == Constants.PROPER_LOG_TIME_TOKEN_LENGTH) {
+                h = Integer.parseInt(token[0]);
+                m = Integer.parseInt(token[1]);
+                s = Integer.parseInt(token[2]);
+
+                Calendar calendar;
+                calendar = Calendar.getInstance();
+                calendar.set(Calendar.HOUR, h);
+                calendar.set(Calendar.MINUTE, m);
+                calendar.set(Calendar.SECOND, s);
+
+                date = calendar.getTime();
+            } else {
+                date = null;
+            }
+        } catch (NumberFormatException nfe) {
+            date = null;
+        }
+        return date;
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/README.txt b/service/simulator/java/eclipse-plugin/README.txt
new file mode 100644 (file)
index 0000000..f79c607
--- /dev/null
@@ -0,0 +1,26 @@
+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
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/.classpath b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/.classpath
new file mode 100644 (file)
index 0000000..ad84a71
--- /dev/null
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+    <classpathentry kind="lib" path="libs/Simulator.jar"/>
+    <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
+    <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
+    <classpathentry kind="src" path="src"/>
+    <classpathentry kind="output" path="bin"/>
+</classpath>
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/.project b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/.project
new file mode 100644 (file)
index 0000000..65d5304
--- /dev/null
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+    <name>ServiceProviderPlugin</name>
+    <comment></comment>
+    <projects>
+    </projects>
+    <buildSpec>
+        <buildCommand>
+            <name>org.eclipse.jdt.core.javabuilder</name>
+            <arguments>
+            </arguments>
+        </buildCommand>
+        <buildCommand>
+            <name>org.eclipse.pde.ManifestBuilder</name>
+            <arguments>
+            </arguments>
+        </buildCommand>
+        <buildCommand>
+            <name>org.eclipse.pde.SchemaBuilder</name>
+            <arguments>
+            </arguments>
+        </buildCommand>
+    </buildSpec>
+    <natures>
+        <nature>org.eclipse.pde.PluginNature</nature>
+        <nature>org.eclipse.jdt.core.javanature</nature>
+    </natures>
+</projectDescription>
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/META-INF/MANIFEST.MF b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/META-INF/MANIFEST.MF
new file mode 100644 (file)
index 0000000..08798e4
--- /dev/null
@@ -0,0 +1,13 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: ServiceProviderPlugin
+Bundle-SymbolicName: ServiceProviderPlugin;singleton:=true
+Bundle-Version: 1.0.0.qualifier
+Bundle-Activator: oic.simulator.serviceprovider.Activator
+Require-Bundle: org.eclipse.ui,
+ org.eclipse.core.runtime
+Bundle-RequiredExecutionEnvironment: JavaSE-1.7
+Bundle-ActivationPolicy: lazy
+Bundle-NativeCode: libs/libSimulatorManager.so
+Bundle-ClassPath: libs/Simulator.jar,
+ .
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/build.properties b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/build.properties
new file mode 100644 (file)
index 0000000..3db1138
--- /dev/null
@@ -0,0 +1,9 @@
+source.. = src/
+output.. = bin/
+bin.includes = META-INF/,\
+               .,\
+               icons/,\
+               plugin.xml,\
+               libs/,\
+               resource/
+
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/button_free.PNG b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/button_free.PNG
new file mode 100644 (file)
index 0000000..b80acea
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/button_free.PNG differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/button_pressed.PNG b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/button_pressed.PNG
new file mode 100644 (file)
index 0000000..afede21
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/button_pressed.PNG differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/checked.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/checked.gif
new file mode 100644 (file)
index 0000000..e556e7d
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/checked.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/clear_d.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/clear_d.gif
new file mode 100644 (file)
index 0000000..6775edf
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/clear_d.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/clear_e.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/clear_e.gif
new file mode 100644 (file)
index 0000000..af30a42
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/clear_e.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/debug_log.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/debug_log.gif
new file mode 100644 (file)
index 0000000..d90a29f
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/debug_log.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/delete_d.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/delete_d.gif
new file mode 100644 (file)
index 0000000..9e14298
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/delete_d.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/delete_e.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/delete_e.gif
new file mode 100644 (file)
index 0000000..b6922ac
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/delete_e.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/error_log.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/error_log.gif
new file mode 100644 (file)
index 0000000..9b048d6
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/error_log.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/export_log_d.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/export_log_d.gif
new file mode 100644 (file)
index 0000000..030b93e
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/export_log_d.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/export_log_e.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/export_log_e.gif
new file mode 100644 (file)
index 0000000..5a0837d
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/export_log_e.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/filter_d.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/filter_d.gif
new file mode 100644 (file)
index 0000000..ba6d891
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/filter_d.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/filter_e.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/filter_e.gif
new file mode 100644 (file)
index 0000000..1492b4e
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/filter_e.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/info_log.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/info_log.gif
new file mode 100644 (file)
index 0000000..3679f84
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/info_log.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/light_16x16.png b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/light_16x16.png
new file mode 100644 (file)
index 0000000..8b3abbd
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/light_16x16.png differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/lock_d.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/lock_d.gif
new file mode 100644 (file)
index 0000000..b776478
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/lock_d.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/lock_e.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/lock_e.gif
new file mode 100644 (file)
index 0000000..68fd6cf
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/lock_e.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/log_details_e.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/log_details_e.gif
new file mode 100644 (file)
index 0000000..7ccc6a7
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/log_details_e.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/oic_logo_16x16.png b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/oic_logo_16x16.png
new file mode 100644 (file)
index 0000000..e6bbc36
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/oic_logo_16x16.png differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/oic_logo_32x32.png b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/oic_logo_32x32.png
new file mode 100644 (file)
index 0000000..d02a216
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/oic_logo_32x32.png differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/oic_logo_64x64.png b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/oic_logo_64x64.png
new file mode 100644 (file)
index 0000000..4fe3cbb
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/oic_logo_64x64.png differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/prop_d.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/prop_d.gif
new file mode 100644 (file)
index 0000000..ec394d6
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/prop_d.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/prop_e.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/prop_e.gif
new file mode 100644 (file)
index 0000000..d11c996
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/prop_e.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/sample.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/sample.gif
new file mode 100644 (file)
index 0000000..34fb3c9
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/sample.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/trash_e.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/trash_e.gif
new file mode 100644 (file)
index 0000000..bf961b3
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/trash_e.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/tree_mode_d.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/tree_mode_d.gif
new file mode 100644 (file)
index 0000000..62bdbe2
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/tree_mode_d.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/tree_mode_e.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/tree_mode_e.gif
new file mode 100644 (file)
index 0000000..dda8bae
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/tree_mode_e.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/unchecked.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/unchecked.gif
new file mode 100644 (file)
index 0000000..342fa9d
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/unchecked.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/unknown_log.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/unknown_log.gif
new file mode 100644 (file)
index 0000000..a54ccfe
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/unknown_log.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/warning_log.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/warning_log.gif
new file mode 100644 (file)
index 0000000..14009e9
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/warning_log.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/plugin.xml b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/plugin.xml
new file mode 100644 (file)
index 0000000..52ec74b
--- /dev/null
@@ -0,0 +1,92 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<?eclipse version="3.4"?>
+<plugin>
+   <extension
+         point="org.eclipse.ui.perspectives">
+      <perspective
+            class="oic.simulator.serviceprovider.perspective.PerspectiveFactory"
+            icon="icons/oic_logo_16x16.png"
+            id="oic.simulator.serviceprovider.perspective"
+            name="Service Provider">
+      </perspective>
+   </extension>
+   <extension
+         point="org.eclipse.ui.views">
+         <category
+            id="oic.simulator.serviceprovider.category"
+            name="Service Provider">
+         </category>
+         <view category="oic.simulator.serviceprovider.category"
+            class="oic.simulator.serviceprovider.view.ResourceManagerView"
+            icon="icons/oic_logo_16x16.png"
+            id="oic.simulator.serviceprovider.view.resourcemanager"
+            name="Resource Manager"
+            restorable="true">
+         </view>
+         <view category="oic.simulator.serviceprovider.category"
+            class="oic.simulator.serviceprovider.view.AttributeView"
+            icon="icons/oic_logo_16x16.png"
+            id="oic.simulator.serviceprovider.view.attribute"
+            name="Attribute Manager"
+            restorable="true">
+         </view>
+         <view category="oic.simulator.serviceprovider.category"
+            class="oic.simulator.serviceprovider.view.MultiResourceOrchestrationView"
+            icon="icons/oic_logo_16x16.png"
+            id="oic.simulator.serviceprovider.view.orchestration"
+            name="Multi-Resource Automation"
+            restorable="true">
+         </view>
+         <view category="oic.simulator.serviceprovider.category"
+            class="oic.simulator.serviceprovider.view.LogView"
+            icon="icons/oic_logo_16x16.png"
+            id="oic.simulator.serviceprovider.view.log"
+            name="Simulator Log"
+            restorable="true">
+         </view>
+         <view category="oic.simulator.serviceprovider.category"
+            class="oic.simulator.serviceprovider.view.MetaPropertiesView"
+            icon="icons/oic_logo_16x16.png"
+            id="oic.simulator.serviceprovider.view.metaproperties"
+            name="Properties"
+            restorable="true">
+         </view>
+         <view category="oic.simulator.serviceprovider.category"
+            class="oic.simulator.serviceprovider.view.ResourceObserverView"
+            icon="icons/oic_logo_16x16.png"
+            id="oic.simulator.serviceprovider.view.observer"
+            name="Resource Observers"
+            restorable="true">
+         </view>
+   </extension>
+   <extension
+         point="org.eclipse.ui.perspectiveExtensions">
+      <perspectiveExtension
+            targetID="*">
+         <perspectiveShortcut
+               id="oic.simulator.serviceprovider.perspective">
+         </perspectiveShortcut>
+      </perspectiveExtension>
+      <perspectiveExtension
+            targetID="oic.simulator.serviceprovider.perspective">
+         <viewShortcut
+               id="oic.simulator.serviceprovider.view.resourcemanager">
+         </viewShortcut>
+         <viewShortcut
+               id="oic.simulator.serviceprovider.view.attribute">
+         </viewShortcut>
+         <viewShortcut
+               id="oic.simulator.serviceprovider.view.orchestration">
+         </viewShortcut>
+         <viewShortcut
+               id="oic.simulator.serviceprovider.view.log">
+         </viewShortcut>
+         <viewShortcut
+               id="oic.simulator.serviceprovider.view.metaproperties">
+         </viewShortcut>
+         <viewShortcut
+               id="oic.simulator.serviceprovider.view.observer">
+         </viewShortcut>
+      </perspectiveExtension>
+   </extension>
+</plugin>
\ No newline at end of file
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
new file mode 100644 (file)
index 0000000..ceea4eb
--- /dev/null
@@ -0,0 +1,23 @@
+{
+  "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
new file mode 100644 (file)
index 0000000..e850b70
--- /dev/null
@@ -0,0 +1,34 @@
+{
+  "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
new file mode 100644 (file)
index 0000000..3725c6b
--- /dev/null
@@ -0,0 +1,81 @@
+#%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"
+              }
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/logger/LogContentProvider.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/logger/LogContentProvider.java
new file mode 100644 (file)
index 0000000..c782557
--- /dev/null
@@ -0,0 +1,65 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package oic.simulator.logger;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.jface.viewers.ITreeContentProvider;
+import org.eclipse.jface.viewers.Viewer;
+
+/**
+ * Maintains simulator log entries and provides content to the log view.
+ */
+public class LogContentProvider implements ITreeContentProvider {
+
+    List<LogEntry> logEntryList = new ArrayList<LogEntry>();
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+        logEntryList = (List<LogEntry>) newInput;
+    }
+
+    @Override
+    public Object[] getChildren(Object element) {
+        return new Object[0];
+    }
+
+    @Override
+    public Object[] getElements(Object input) {
+        return logEntryList.toArray();
+    }
+
+    @Override
+    public Object getParent(Object element) {
+        return null;
+    }
+
+    @Override
+    public boolean hasChildren(Object element) {
+        return false;
+    }
+
+    @Override
+    public void dispose() {
+    }
+
+    public synchronized void addLog(LogEntry newElement) {
+        logEntryList.add(newElement);
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/logger/LogEntry.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/logger/LogEntry.java
new file mode 100644 (file)
index 0000000..883cc0d
--- /dev/null
@@ -0,0 +1,58 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package oic.simulator.logger;
+
+import java.util.Date;
+
+import oic.simulator.serviceprovider.manager.LogManager;
+
+/**
+ * Class for log entry.
+ */
+public class LogEntry {
+    private final int    severity;
+    private final Date   date;
+    private final String message;
+
+    public LogEntry(int severity, Date date, String message) {
+        this.severity = severity;
+        this.date = date;
+        this.message = message;
+    }
+
+    public String getMessage() {
+        return message;
+    }
+
+    public Date getDate() {
+        return date;
+    }
+
+    public int getSeverity() {
+        return severity;
+    }
+
+    @Override
+    public String toString() {
+        String newline = System.getProperty("line.separator");
+        String out = date.toString() + newline;
+        out += "Severity: " + LogManager.getSeverityName(severity) + newline;
+        out += "Message: " + message + newline;
+        out += "===============================" + newline + newline;
+        return out;
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/logger/LogLabelProvider.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/logger/LogLabelProvider.java
new file mode 100644 (file)
index 0000000..f392bc8
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package oic.simulator.logger;
+
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+
+import oic.simulator.serviceprovider.manager.LogManager;
+
+import org.eclipse.jface.viewers.ITableLabelProvider;
+import org.eclipse.jface.viewers.LabelProvider;
+import org.eclipse.swt.graphics.Image;
+
+/**
+ * Label provider which determines what data has to be shown in the log view.
+ */
+public class LogLabelProvider extends LabelProvider implements
+        ITableLabelProvider {
+
+    DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss.SSS");
+
+    @Override
+    public Image getColumnImage(Object element, int columnIndex) {
+        if (columnIndex == 0) {
+            LogEntry entry = (LogEntry) element;
+            return LogManager.getSeverityIcon(entry.getSeverity());
+        }
+        return null;
+    }
+
+    @Override
+    public String getColumnText(Object element, int columnIndex) {
+        LogEntry entry = (LogEntry) element;
+        if (columnIndex == 0) {
+            return LogManager.getSeverityName(entry.getSeverity());
+        } else if (columnIndex == 1) {
+            return dateFormat.format(entry.getDate());
+        } else {
+            return entry.getMessage();
+        }
+    }
+
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/logger/LoggerCallback.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/logger/LoggerCallback.java
new file mode 100644 (file)
index 0000000..83d02fa
--- /dev/null
@@ -0,0 +1,74 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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.logger;
+
+import java.util.Calendar;
+import java.util.Date;
+
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.utils.Constants;
+
+import org.oic.simulator.ILogger;
+
+/**
+ * Class which provides a callback method to receive log from native layer.
+ */
+public class LoggerCallback implements ILogger {
+
+    @Override
+    public void write(String time, int level, String message) {
+        if (null == time || level < 0 || null == message) {
+            return;
+        }
+        // Parse the time
+        Date date = parseTime(time);
+        if (null == date) {
+            return;
+        }
+        Activator activator = Activator.getDefault();
+        if (null == activator) {
+            return;
+        }
+        activator.getLogManager().log(level, date, message);
+    }
+
+    private Date parseTime(String time) {
+        Date date;
+        String[] token = time.split("\\.");
+        int h, m, s;
+        try {
+            if (token.length == Constants.PROPER_LOG_TIME_TOKEN_LENGTH) {
+                h = Integer.parseInt(token[0]);
+                m = Integer.parseInt(token[1]);
+                s = Integer.parseInt(token[2]);
+
+                Calendar calendar;
+                calendar = Calendar.getInstance();
+                calendar.set(Calendar.HOUR_OF_DAY, h);
+                calendar.set(Calendar.MINUTE, m);
+                calendar.set(Calendar.SECOND, s);
+
+                date = calendar.getTime();
+            } else {
+                date = null;
+            }
+        } catch (NumberFormatException nfe) {
+            date = null;
+        }
+        return date;
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/Activator.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/Activator.java
new file mode 100644 (file)
index 0000000..f9816d3
--- /dev/null
@@ -0,0 +1,97 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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;
+
+import oic.simulator.serviceprovider.manager.ImageManager;
+import oic.simulator.serviceprovider.manager.LogManager;
+import oic.simulator.serviceprovider.manager.ResourceManager;
+
+import org.eclipse.ui.plugin.AbstractUIPlugin;
+import org.osgi.framework.BundleContext;
+
+/**
+ * The activator class controls the plug-in life cycle.
+ */
+public class Activator extends AbstractUIPlugin {
+
+    // The plug-in ID
+    public static final String     PLUGIN_ID = "ServiceProviderPlugin";
+
+    // The shared instance
+    private static Activator       plugin;
+
+    private static ResourceManager resourceManager;
+
+    private static LogManager      logManager;
+
+    private static ImageManager    imageManager;
+
+    static {
+        System.loadLibrary("SimulatorManager");
+    }
+
+    public Activator() {
+    }
+
+    public void start(BundleContext context) throws Exception {
+        super.start(context);
+        plugin = this;
+        setLogManager(new LogManager());
+        setResourceManager(new ResourceManager());
+        imageManager = ImageManager.getInstance();
+    }
+
+    public void stop(BundleContext context) throws Exception {
+        plugin = null;
+
+        // Stopping Resource Manager
+        if (null != resourceManager) {
+            resourceManager.shutdown();
+            resourceManager = null;
+        }
+        // Stopping Log Manager
+        if (null != logManager) {
+            logManager.shutdown();
+            logManager = null;
+        }
+        super.stop(context);
+    }
+
+    public static Activator getDefault() {
+        return plugin;
+    }
+
+    public ResourceManager getResourceManager() {
+        return resourceManager;
+    }
+
+    private static void setResourceManager(ResourceManager manager) {
+        Activator.resourceManager = manager;
+    }
+
+    public LogManager getLogManager() {
+        return logManager;
+    }
+
+    private static void setLogManager(LogManager logManager) {
+        Activator.logManager = logManager;
+    }
+
+    public ImageManager getImageManager() {
+        return imageManager;
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IAutomationUIListener.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IAutomationUIListener.java
new file mode 100644 (file)
index 0000000..215fb5f
--- /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 automation events are notified to the UI
+ * listeners.
+ */
+public interface IAutomationUIListener {
+    public void onResourceAutomationStart(String resourceURI);
+
+    public void onAutomationComplete(String resourceURI, String attName);
+}
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/ILogUIListener.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/ILogUIListener.java
new file mode 100644 (file)
index 0000000..8a3a2f8
--- /dev/null
@@ -0,0 +1,30 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package oic.simulator.serviceprovider.listener;
+
+import java.util.List;
+
+import oic.simulator.logger.LogEntry;
+
+/**
+ * Interface through which the log events are sent to the UI listeners.
+ */
+public interface ILogUIListener {
+    public void logAdded(LogEntry added);
+
+    public void logChanged(List<LogEntry> entry);
+}
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IObserverListChangedUIListener.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IObserverListChangedUIListener.java
new file mode 100644 (file)
index 0000000..3beb52a
--- /dev/null
@@ -0,0 +1,25 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package oic.simulator.serviceprovider.listener;
+
+/**
+ * Interface through which the resource observer events are sent to the UI
+ * listeners.
+ */
+public interface IObserverListChangedUIListener {
+    public void onObserverListChanged(String resourceURI);
+}
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IResourceListChangedUIListener.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IResourceListChangedUIListener.java
new file mode 100644 (file)
index 0000000..b5eb331
--- /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 creation/deletion events are sent to the
+ * UI listeners.
+ */
+public interface IResourceListChangedUIListener {
+    public void onResourceCreation();
+
+    public void onResourceDeletion();
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IResourceModelChangedUIListener.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IResourceModelChangedUIListener.java
new file mode 100644 (file)
index 0000000..b778e0e
--- /dev/null
@@ -0,0 +1,32 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package oic.simulator.serviceprovider.listener;
+
+import java.util.Set;
+
+import oic.simulator.serviceprovider.resource.ModelChangeNotificationType;
+import oic.simulator.serviceprovider.resource.LocalResourceAttribute;
+
+/**
+ * Interface through which the resource model change events are sent to the UI
+ * listeners.
+ */
+public interface IResourceModelChangedUIListener {
+    public void onResourceModelChange(
+            ModelChangeNotificationType notificationType, String resourceURI,
+            Set<LocalResourceAttribute> valueChangeSet);
+}
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IResourceSelectionChangedUIListener.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IResourceSelectionChangedUIListener.java
new file mode 100644 (file)
index 0000000..dc891da
--- /dev/null
@@ -0,0 +1,25 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package oic.simulator.serviceprovider.listener;
+
+/**
+ * Interface through which the resource 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/manager/ImageManager.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/manager/ImageManager.java
new file mode 100644 (file)
index 0000000..940c1b3
--- /dev/null
@@ -0,0 +1,83 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package oic.simulator.serviceprovider.manager;
+
+import java.net.URL;
+
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.utils.Constants;
+
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.jface.resource.ImageRegistry;
+import org.eclipse.swt.graphics.Image;
+import org.osgi.framework.Bundle;
+
+/**
+ * Class which loads the icons/images into the image registry, and has methods
+ * to handle the image related requests from other UI modules.
+ */
+public class ImageManager {
+
+    private static ImageManager imageManager;
+
+    public static ImageManager getInstance() {
+        if (null == imageManager) {
+            imageManager = new ImageManager();
+        }
+        return imageManager;
+    }
+
+    static {
+        ImageRegistry r = Activator.getDefault().getImageRegistry();
+        Bundle bundle = Activator.getDefault().getBundle();
+
+        r.put(Constants.CHECKED, ImageDescriptor.createFromURL(bundle
+                .getEntry("icons/checked.gif")));
+        r.put(Constants.UNCHECKED, ImageDescriptor.createFromURL(bundle
+                .getEntry("icons/unchecked.gif")));
+
+        r.put(Constants.NOTIFY_BUTTON_UNSELECTED, ImageDescriptor
+                .createFromURL(bundle.getEntry("icons/button_free.PNG")));
+        r.put(Constants.NOTIFY_BUTTON_SELECTED, ImageDescriptor
+                .createFromURL(bundle.getEntry("icons/button_pressed.PNG")));
+
+        // 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")));
+        r.put(Constants.INFO_LOG, ImageDescriptor.createFromURL(bundle
+                .getEntry("/icons/info_log.gif")));
+        r.put(Constants.WARNING_LOG, ImageDescriptor.createFromURL(bundle
+                .getEntry("/icons/warning_log.gif")));
+        r.put(Constants.ERROR_LOG, ImageDescriptor.createFromURL(bundle
+                .getEntry("/icons/error_log.gif")));
+        r.put(Constants.UNKNOWN_LOG, ImageDescriptor.createFromURL(bundle
+                .getEntry("/icons/unknown_log.gif")));
+    }
+
+    public static Image getImage(String imagePath) {
+        if (null == imagePath || imagePath.length() < 1) {
+            return null;
+        }
+        URL imageURL = Activator.getDefault().getBundle().getEntry(imagePath);
+        ImageDescriptor descriptor = ImageDescriptor.createFromURL(imageURL);
+        return descriptor.createImage();
+    }
+}
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/manager/LogManager.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/manager/LogManager.java
new file mode 100644 (file)
index 0000000..e7ca9a9
--- /dev/null
@@ -0,0 +1,256 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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.Date;
+import java.util.HashMap;
+import java.util.LinkedList;
+
+import oic.simulator.logger.LogEntry;
+import oic.simulator.logger.LoggerCallback;
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.listener.ILogUIListener;
+import oic.simulator.serviceprovider.utils.Constants;
+
+import org.eclipse.jface.resource.ImageRegistry;
+import org.eclipse.swt.graphics.Image;
+import org.oic.simulator.ILogger;
+import org.oic.simulator.ILogger.Level;
+import org.oic.simulator.SimulatorManager;
+
+/**
+ * Class which handles the native logs, maintains log entries and updates the
+ * UI.
+ */
+public class LogManager {
+    private LinkedList<LogEntry>         entries           = new LinkedList<LogEntry>();
+    private ArrayList<ILogUIListener>    listeners         = new ArrayList<ILogUIListener>();
+    private LinkedList<LogEntry>         visibleEntries    = new LinkedList<LogEntry>();
+    private HashMap<Integer, Boolean>    visibleSeverities = new HashMap<Integer, Boolean>();
+
+    private ILogger                      logger;
+    private LogManagerSynchronizerThread synchronizerThread;
+    private Thread                       threadHandle;
+
+    public LogManager() {
+        synchronizerThread = new LogManagerSynchronizerThread();
+        threadHandle = new Thread(synchronizerThread);
+        threadHandle.setName("OIC Simulator event queue");
+        threadHandle.start();
+
+        // Set the logger callback with the native layer
+        logger = new LoggerCallback();
+        SimulatorManager.setLogger(logger);
+    }
+
+    private static class LogManagerSynchronizerThread implements Runnable {
+
+        LinkedList<Runnable> eventQueue = new LinkedList<Runnable>();
+
+        @Override
+        public void run() {
+            while (!Thread.interrupted()) {
+
+                synchronized (this) {
+                    try {
+                        while (eventQueue.isEmpty()) {
+                            this.wait();
+                            break;
+                        }
+                    } catch (InterruptedException e) {
+                        return;
+                    }
+                }
+
+                Runnable pop;
+                synchronized (this) {
+                    pop = eventQueue.pop();
+                }
+                try {
+                    pop.run();
+                } catch (Exception e) {
+                    if (e instanceof InterruptedException) {
+                        return;
+                    }
+                    e.printStackTrace();
+                }
+            }
+        }
+
+        public void addToQueue(Runnable event) {
+            synchronized (this) {
+                eventQueue.add(event);
+                this.notify();
+            }
+        }
+    }
+
+    public void log(int severity, Date date, String msg) {
+        final LogEntry logEntry = new LogEntry(severity, date, msg);
+        synchronizerThread.addToQueue(new Runnable() {
+            @Override
+            public void run() {
+                boolean notify = false;
+                synchronized (entries) {
+                    entries.add(logEntry);
+                    Boolean showEntry = LogManager.this.visibleSeverities
+                            .get(logEntry.getSeverity());
+                    if (showEntry != null) {
+                        if (showEntry) {
+                            visibleEntries.add(logEntry);
+                            notify = true;
+                        }
+                    }
+                    if (entries.size() > Constants.LOG_SIZE) {
+                        entries.pop();
+                    }
+                    if (visibleEntries.size() > Constants.LOG_SIZE) {
+                        visibleEntries.pop();
+                        notify = true;
+                    }
+                }
+                if (notify) {
+                    notifyListeners(logEntry);
+                }
+            }
+        });
+    }
+
+    public void applyFilter(final HashMap<Integer, Boolean> visibleSeverities) {
+        synchronizerThread.addToQueue(new Runnable() {
+
+            @Override
+            public void run() {
+                LinkedList<LogEntry> newLogs = new LinkedList<LogEntry>();
+                synchronized (entries) {
+                    LogManager.this.visibleSeverities = visibleSeverities;
+                    for (LogEntry logEntry : entries) {
+                        if (LogManager.this.visibleSeverities.get(logEntry
+                                .getSeverity())) {
+                            newLogs.add(logEntry);
+                        }
+                    }
+                }
+                visibleEntries = newLogs;
+                notifyListeners();
+            }
+        });
+
+    }
+
+    private void notifyListeners() {
+        for (ILogUIListener l : listeners) {
+            l.logChanged(new ArrayList<LogEntry>(visibleEntries));
+        }
+    }
+
+    private void notifyListeners(LogEntry added) {
+        for (ILogUIListener l : listeners) {
+            l.logAdded(added);
+        }
+    }
+
+    public void clearLog() {
+        synchronizerThread.addToQueue(new Runnable() {
+
+            @Override
+            public void run() {
+                synchronized (entries) {
+                    entries = new LinkedList<LogEntry>();
+                    visibleEntries = new LinkedList<LogEntry>();
+                }
+                notifyListeners();
+            }
+        });
+    }
+
+    public void removeEntry(final LogEntry element) {
+        synchronizerThread.addToQueue(new Runnable() {
+
+            @Override
+            public void run() {
+                synchronized (entries) {
+                    entries.remove(element);
+                    visibleEntries.remove(element);
+                }
+                notifyListeners();
+            }
+        });
+    }
+
+    public ArrayList<LogEntry> getLogEntries() {
+        synchronized (entries) {
+            return new ArrayList<LogEntry>(entries);
+        }
+    }
+
+    public void addLogListener(final ILogUIListener listener) {
+        synchronizerThread.addToQueue(new Runnable() {
+            @Override
+            public void run() {
+                if (!listeners.contains(listener)) {
+                    listeners.add(listener);
+                }
+            }
+        });
+    }
+
+    public void removeLogListener(final ILogUIListener listener) {
+        synchronizerThread.addToQueue(new Runnable() {
+            @Override
+            public void run() {
+                if (!listeners.contains(listener)) {
+                    listeners.remove(listener);
+                }
+            }
+        });
+    }
+
+    public void shutdown() {
+        threadHandle.interrupt();
+    }
+
+    public static String getSeverityName(int severity) {
+        if (severity == Level.INFO.ordinal()) {
+            return Constants.INFO;
+        } else if (severity == Level.WARNING.ordinal()) {
+            return Constants.WARNING;
+        } else if (severity == Level.ERROR.ordinal()) {
+            return Constants.ERROR;
+        } else if (severity == Level.DEBUG.ordinal()) {
+            return Constants.DEBUG;
+        } else {
+            return Constants.UNKNOWN;
+        }
+    }
+
+    public static Image getSeverityIcon(int severity) {
+        ImageRegistry r = Activator.getDefault().getImageRegistry();
+        if (severity == Level.INFO.ordinal()) {
+            return r.get(Constants.INFO_LOG);
+        } else if (severity == Level.WARNING.ordinal()) {
+            return r.get(Constants.WARNING_LOG);
+        } else if (severity == Level.ERROR.ordinal()) {
+            return r.get(Constants.ERROR_LOG);
+        } else if (severity == Level.DEBUG.ordinal()) {
+            return r.get(Constants.DEBUG_LOG);
+        } else {
+            return r.get(Constants.UNKNOWN_LOG);
+        }
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/manager/ResourceManager.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/manager/ResourceManager.java
new file mode 100644 (file)
index 0000000..08a7037
--- /dev/null
@@ -0,0 +1,1580 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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.Collections;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.listener.IAutomationUIListener;
+import oic.simulator.serviceprovider.listener.IObserverListChangedUIListener;
+import oic.simulator.serviceprovider.listener.IResourceListChangedUIListener;
+import oic.simulator.serviceprovider.listener.IResourceModelChangedUIListener;
+import oic.simulator.serviceprovider.listener.IResourceSelectionChangedUIListener;
+import oic.simulator.serviceprovider.resource.LocalResourceAttribute;
+import oic.simulator.serviceprovider.resource.MetaProperty;
+import oic.simulator.serviceprovider.resource.ModelChangeNotificationType;
+import oic.simulator.serviceprovider.resource.SimulatorResource;
+import oic.simulator.serviceprovider.resource.StandardConfiguration;
+import oic.simulator.serviceprovider.utils.Constants;
+import oic.simulator.serviceprovider.utils.Utility;
+
+import org.eclipse.swt.graphics.Image;
+import org.oic.simulator.IAutomation;
+import org.oic.simulator.ILogger.Level;
+import org.oic.simulator.ResourceAttribute;
+import org.oic.simulator.ResourceAttribute.Range;
+import org.oic.simulator.ResourceAttribute.Type;
+import org.oic.simulator.SimulatorException;
+import org.oic.simulator.SimulatorManager;
+import org.oic.simulator.SimulatorResourceModel;
+import org.oic.simulator.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;
+
+/**
+ * This class acts as an interface between the simulator java SDK and the
+ * various UI modules. It maintains all the details of resources and provides
+ * other UI modules with the information required. It also handles model change,
+ * automation, and observer related events from native layer and propagates
+ * those events to the registered UI listeners.
+ */
+public class ResourceManager {
+
+    private Map<String, Map<String, SimulatorResource>> resourceMap;
+
+    private Map<String, ArrayList<String>>              orderedResourceUriMap;
+
+    private StandardConfiguration                       stdConfig;
+
+    private SimulatorResource                           currentResourceInSelection;
+
+    private List<IResourceListChangedUIListener>        resourceListChangedUIListeners;
+
+    private List<IResourceSelectionChangedUIListener>   resourceSelectionChangedUIListeners;
+
+    private List<IResourceModelChangedUIListener>       resourceModelChangedUIListeners;
+
+    private List<IAutomationUIListener>                 automationUIListeners;
+
+    private List<IObserverListChangedUIListener>        observerUIListeners;
+
+    private IResourceModelChangedListener               resourceModelChangeListener;
+
+    private IAutomation                                 automationListener;
+
+    private IObserver                                   observer;
+
+    private NotificationSynchronizerThread              synchronizerThread;
+
+    private Thread                                      threadHandle;
+
+    public ResourceManager() {
+        resourceMap = new HashMap<String, Map<String, SimulatorResource>>();
+        orderedResourceUriMap = new HashMap<String, ArrayList<String>>();
+        stdConfig = new StandardConfiguration();
+
+        resourceListChangedUIListeners = new ArrayList<IResourceListChangedUIListener>();
+        resourceSelectionChangedUIListeners = new ArrayList<IResourceSelectionChangedUIListener>();
+        resourceModelChangedUIListeners = new ArrayList<IResourceModelChangedUIListener>();
+        automationUIListeners = new ArrayList<IAutomationUIListener>();
+        observerUIListeners = new ArrayList<IObserverListChangedUIListener>();
+
+        resourceModelChangeListener = new IResourceModelChangedListener() {
+
+            @Override
+            public void onResourceModelChanged(final String resourceURI,
+                    final SimulatorResourceModel resourceModelN) {
+                synchronizerThread.addToQueue(new Runnable() {
+
+                    @Override
+                    public void run() {
+                        if (null == resourceURI || null == resourceModelN) {
+                            return;
+                        }
+                        SimulatorResource resource = getSimulatorResourceByURI(resourceURI);
+                        if (null == resource) {
+                            return;
+                        }
+
+                        ModelChangeNotificationType notificationType;
+                        // Fetch the resource attributes
+                        Map<String, LocalResourceAttribute> resourceAttributeMapNew;
+                        resourceAttributeMapNew = fetchResourceAttributesFromModel(resourceModelN);
+                        if (null == resourceAttributeMapNew) {
+                            resource.setResourceAttributesMap(null);
+                            resourceModelChangedUINotification(
+                                    ModelChangeNotificationType.NO_ATTRIBUTES_IN_MODEL,
+                                    resourceURI, null);
+                            return;
+                        }
+
+                        // Update the resource with new model data
+                        Map<String, LocalResourceAttribute> resourceAttributeMapOld;
+                        resourceAttributeMapOld = resource
+                                .getResourceAttributesMap();
+                        if (null == resourceAttributeMapOld) {
+                            resource.setResourceAttributesMap(resourceAttributeMapNew);
+                            resourceModelChangedUINotification(
+                                    ModelChangeNotificationType.ATTRIBUTE_ADDED,
+                                    resourceURI, null);
+                            return;
+                        }
+                        Set<LocalResourceAttribute> valueChangeSet = new HashSet<LocalResourceAttribute>();
+                        notificationType = compareAndUpdateLocalAttributes(
+                                resourceAttributeMapOld,
+                                resourceAttributeMapNew, valueChangeSet);
+                        if (notificationType != ModelChangeNotificationType.NONE) {
+                            // Update the UI listeners
+                            resourceModelChangedUINotification(
+                                    notificationType, resourceURI,
+                                    valueChangeSet);
+                        }
+                    }
+                });
+            }
+        };
+
+        automationListener = new IAutomation() {
+
+            @Override
+            public void onAutomationComplete(final String resourceURI,
+                    final int automationId) {
+                synchronizerThread.addToQueue(new Runnable() {
+
+                    @Override
+                    public void run() {
+                        SimulatorResource resource = getSimulatorResourceByURI(resourceURI);
+                        if (null == resource) {
+                            return;
+                        }
+                        // Checking whether this notification is for an
+                        // attribute or a resource
+                        if (resource.isResourceAutomationInProgress()) {
+                            changeResourceLevelAutomationStatus(resource, false);
+                            // Notify the UI listeners
+                            automationCompleteUINotification(resourceURI, null);
+                        } else if (resource.isAttributeAutomationInProgress()) {
+                            // Find the attribute with the given automation id
+                            LocalResourceAttribute attribute;
+                            attribute = getAttributeWithGivenAutomationId(
+                                    resource, automationId);
+                            if (null != attribute) {
+                                attribute.setAutomationInProgress(false);
+                                resource.setAttributeAutomationInProgress(isAnyAttributeInAutomation(resource));
+                                // Notify the UI listeners
+                                automationCompleteUINotification(resourceURI,
+                                        attribute.getAttributeName());
+                            }
+                        } else {
+                            // Ignoring the notification as there are no
+                            // known automation for the current resource.
+                        }
+                    }
+                });
+            }
+        };
+
+        observer = new IObserver() {
+
+            @Override
+            public void onObserverChanged(final String resourceURI,
+                    final int status, final ObserverInfo observer) {
+                new Thread() {
+                    @Override
+                    public void run() {
+                        if (null == resourceURI || null == observer) {
+                            return;
+                        }
+                        SimulatorResource resource = getSimulatorResourceByURI(resourceURI);
+                        if (null == resource) {
+                            return;
+                        }
+                        // Update the observers information
+                        if (status == 0) {
+                            resource.addObserverInfo(observer);
+                        } else {
+                            resource.removeObserverInfo(observer);
+                        }
+                        // Notify the UI listeners
+                        observerListChangedUINotification(resourceURI);
+                    }
+                }.start();
+            }
+        };
+
+        synchronizerThread = new NotificationSynchronizerThread();
+        threadHandle = new Thread(synchronizerThread);
+        threadHandle.setName("Simulator service provider event queue");
+        threadHandle.start();
+    }
+
+    private static class NotificationSynchronizerThread implements Runnable {
+
+        LinkedList<Runnable> notificationQueue = new LinkedList<Runnable>();
+
+        @Override
+        public void run() {
+            while (!Thread.interrupted()) {
+                synchronized (this) {
+                    try {
+                        while (notificationQueue.isEmpty()) {
+                            this.wait();
+                            break;
+                        }
+                    } catch (InterruptedException e) {
+                        return;
+                    }
+                }
+
+                Runnable thread;
+                synchronized (this) {
+                    thread = notificationQueue.pop();
+                }
+                try {
+                    thread.run();
+                } catch (Exception e) {
+                    if (e instanceof InterruptedException) {
+                        return;
+                    }
+                    e.printStackTrace();
+                }
+            }
+        }
+
+        public void addToQueue(Runnable event) {
+            synchronized (this) {
+                notificationQueue.add(event);
+                this.notify();
+            }
+        }
+    }
+
+    // This method gives a list of available RAML resource configurations.
+    public Map<String, String> getResourceConfigurationList() {
+        return stdConfig.getStandardResourceConfigurationList();
+    }
+
+    public String getConfigFilePath(String fileName) {
+        return stdConfig.getFilePath(fileName);
+    }
+
+    public void addResourceListChangedUIListener(
+            IResourceListChangedUIListener resourceListChangedUIListener) {
+        synchronized (resourceListChangedUIListeners) {
+            resourceListChangedUIListeners.add(resourceListChangedUIListener);
+        }
+    }
+
+    public void addResourceSelectionChangedUIListener(
+            IResourceSelectionChangedUIListener resourceSelectionChangedUIListener) {
+        synchronized (resourceSelectionChangedUIListeners) {
+            resourceSelectionChangedUIListeners
+                    .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 removeResourceListChangedUIListener(
+            IResourceListChangedUIListener listener) {
+        synchronized (resourceListChangedUIListeners) {
+            if (null != listener && resourceListChangedUIListeners.size() > 0) {
+                resourceListChangedUIListeners.remove(listener);
+            }
+        }
+    }
+
+    public void removeResourceSelectionChangedUIListener(
+            IResourceSelectionChangedUIListener listener) {
+        synchronized (resourceSelectionChangedUIListeners) {
+            if (null != listener
+                    && resourceSelectionChangedUIListeners.size() > 0) {
+                resourceSelectionChangedUIListeners.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 synchronized SimulatorResource getCurrentResourceInSelection() {
+        return currentResourceInSelection;
+    }
+
+    public synchronized void setCurrentResourceInSelection(
+            SimulatorResource resource) {
+        this.currentResourceInSelection = resource;
+    }
+
+    private void addResourceUriToOrderedMap(String resourceType,
+            String resourceURI) {
+        if (null != resourceURI && null != resourceType) {
+            synchronized (orderedResourceUriMap) {
+                ArrayList<String> uriListForType = orderedResourceUriMap
+                        .get(resourceType);
+                if (null == uriListForType) {
+                    uriListForType = new ArrayList<String>();
+                    orderedResourceUriMap.put(resourceType, uriListForType);
+                }
+                uriListForType.add(resourceURI);
+            }
+        }
+    }
+
+    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 != resourceURI) {
+                orderedResourceUriMap.remove(resourceType);
+            } else {
+                orderedResourceUriMap.clear();
+            }
+        }
+    }
+
+    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);
+            }
+        }
+    }
+
+    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);
+                }
+            }
+        }
+    }
+
+    private void removeResourceFromMap(String resourceType, String resourceURI) {
+        if (null != resourceURI && null != resourceType) {
+            synchronized (resourceMap) {
+                Map<String, SimulatorResource> resourceTypeMap = resourceMap
+                        .get(resourceType);
+                if (null != resourceTypeMap) {
+                    resourceTypeMap.remove(resourceURI);
+                    if (resourceTypeMap.size() < 1) {
+                        resourceMap.remove(resourceType);
+                    }
+                }
+            }
+        }
+    }
+
+    public boolean isResourceExist(String resourceURI) {
+        boolean result = false;
+        if (null != resourceURI) {
+            SimulatorResource resource = getSimulatorResourceByURI(resourceURI);
+            if (null != resource) {
+                result = true;
+            }
+        }
+        return result;
+    }
+
+    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) {
+                    addResourceToMap(simulatorResource);
+                    addResourceUriToOrderedMap(
+                            simulatorResource.getResourceType(),
+                            simulatorResource.getResourceURI());
+                    resourceCreatedUINotification();
+
+                    // Set the observer for the created resource
+                    try {
+                        resourceServerN.setObserverCallback(observer);
+                    } catch (SimulatorException e) {
+                        Activator
+                                .getDefault()
+                                .getLogManager()
+                                .log(Level.ERROR.ordinal(),
+                                        new Date(),
+                                        "[" + e.getClass().getSimpleName()
+                                                + "]" + e.code().toString()
+                                                + "-" + e.message());
+                    }
+
+                    // Print the resource data
+                    simulatorResource.printResourceInfo();
+                }
+            }
+        }.start();
+    }
+
+    public void createResource(final String configFilePath,
+            final int noOfInstances) {
+        new Thread() {
+            @Override
+            public void run() {
+                Map<String, SimulatorResource> resourceTypeMap;
+                SimulatorResourceServer[] simulatorResourceServers = null;
+                try {
+                    simulatorResourceServers = SimulatorManager.createResource(
+                            configFilePath, noOfInstances,
+                            resourceModelChangeListener);
+                } catch (SimulatorException e) {
+                    Activator
+                            .getDefault()
+                            .getLogManager()
+                            .log(Level.ERROR.ordinal(),
+                                    new Date(),
+                                    "[" + e.getClass().getSimpleName() + "]"
+                                            + e.code().toString() + "-"
+                                            + e.message());
+                    return;
+                }
+                if (null == simulatorResourceServers) {
+                    return;
+                }
+                resourceTypeMap = new HashMap<String, SimulatorResource>();
+                SimulatorResource resource;
+                String uri;
+                for (SimulatorResourceServer resourceServerN : simulatorResourceServers) {
+                    resource = fetchResourceData(resourceServerN);
+                    if (null != resource) {
+                        uri = resource.getResourceURI();
+                        resourceTypeMap.put(uri, resource);
+                        addResourceUriToOrderedMap(resource.getResourceType(),
+                                uri);
+                    }
+                    // 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();
+                        }
+                    }
+                }
+            }
+        }.start();
+    }
+
+    private SimulatorResource fetchResourceData(
+            SimulatorResourceServer resourceServerN) {
+        SimulatorResource simulatorResource = null;
+        if (null != resourceServerN) {
+            simulatorResource = new SimulatorResource();
+            simulatorResource.setResourceServer(resourceServerN);
+            simulatorResource.setResourceURI(resourceServerN.getURI());
+            simulatorResource
+                    .setResourceType(resourceServerN.getResourceType());
+            simulatorResource.setResourceName(resourceServerN.getName());
+            simulatorResource.setResourceInterface(resourceServerN
+                    .getInterfaceType());
+
+            SimulatorResourceModel resourceModelN;
+            try {
+                resourceModelN = resourceServerN.getModel();
+            } catch (SimulatorException e) {
+                Activator
+                        .getDefault()
+                        .getLogManager()
+                        .log(Level.ERROR.ordinal(),
+                                new Date(),
+                                "[" + e.getClass().getSimpleName() + "]"
+                                        + e.code().toString() + "-"
+                                        + e.message());
+                return null;
+            }
+            if (null != resourceModelN) {
+                simulatorResource.setResourceModel(resourceModelN);
+
+                // Fetch the resource attributes
+                Map<String, LocalResourceAttribute> resourceAttributeMap;
+                resourceAttributeMap = fetchResourceAttributesFromModel(resourceModelN);
+                if (null != resourceAttributeMap) {
+                    simulatorResource
+                            .setResourceAttributesMap(resourceAttributeMap);
+                }
+            }
+        }
+        return simulatorResource;
+    }
+
+    private Map<String, LocalResourceAttribute> fetchResourceAttributesFromModel(
+            SimulatorResourceModel resourceModelN) {
+        Map<String, LocalResourceAttribute> resourceAttributeMap = null;
+        if (null != resourceModelN) {
+            Map<String, ResourceAttribute> attributeMapN;
+            try {
+                attributeMapN = resourceModelN.getAttributes();
+            } catch (SimulatorException e) {
+                Activator
+                        .getDefault()
+                        .getLogManager()
+                        .log(Level.ERROR.ordinal(),
+                                new Date(),
+                                "[" + e.getClass().getSimpleName() + "]"
+                                        + e.code().toString() + "-"
+                                        + e.message());
+                return null;
+            }
+            if (null != attributeMapN) {
+                resourceAttributeMap = new HashMap<String, LocalResourceAttribute>();
+
+                Set<String> attNameSet = attributeMapN.keySet();
+                String attName;
+                ResourceAttribute attributeN;
+                LocalResourceAttribute attribute;
+                Iterator<String> attNameItr = attNameSet.iterator();
+                while (attNameItr.hasNext()) {
+                    attName = attNameItr.next();
+                    attributeN = attributeMapN.get(attName);
+                    if (null != attributeN) {
+                        attribute = new LocalResourceAttribute();
+                        attribute.setResourceAttribute(attributeN);
+
+                        // Set the attribute value
+                        Object valueObj = attributeN.getValue();
+                        if (null != valueObj) {
+                            attribute.setAttributeValue(valueObj);
+                        }
+
+                        // Set the attribute value list.
+                        attribute.setAttValues(getValueList(attributeN));
+
+                        // Initially disabling the automation
+                        attribute.setAutomationInProgress(false);
+
+                        // TODO: Temporarily setting the interval to 500.
+                        // This value should come from the native layer.
+                        // Native implementation is in progress.
+                        attribute
+                                .setAutomationUpdateInterval(Constants.DEFAULT_AUTOMATION_INTERVAL);
+
+                        // Setting the default automation type
+                        attribute
+                                .setAutomationType(Constants.DEFAULT_AUTOMATION_TYPE);
+
+                        resourceAttributeMap.put(attName, attribute);
+                    }
+                }
+            }
+        }
+        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();
+        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));
+                    }
+                }
+            }
+        }
+        Object attValue = attributeN.getValue();
+        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();
+
+                        // Unregister the resource from the platform
+                        deleteResource(resource);
+
+                        // Delete from the local data structure
+                        deleteLocalResourceDetails(resourceType, resourceURI);
+
+                        // Notify the UI listener for removing this resource
+                        // from UI
+                        resourceDeletedUINotification();
+
+                        if (null != currentResourceInSelection
+                                && resource == currentResourceInSelection) {
+                            // Listeners might query the resource being deleted
+                            // if exists. So set the currently selection to
+                            // null.
+                            setCurrentResourceInSelection(null);
+
+                            // Notify all observers for resource selection
+                            // change event
+                            resourceSelectionChangedUINotification();
+                        }
+                    }
+                }
+            }.start();
+        }
+    }
+
+    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;
+                        }
+                    }
+                }
+            }
+        }
+        return resource;
+    }
+
+    private void deleteResource(SimulatorResource resource) {
+        if (null != resource) {
+            SimulatorResourceServer resourceServerN = resource
+                    .getResourceServer();
+            if (null != resourceServerN) {
+                try {
+                    SimulatorManager.deleteResource(resourceServerN);
+                } catch (SimulatorException e) {
+                    Activator
+                            .getDefault()
+                            .getLogManager()
+                            .log(Level.ERROR.ordinal(),
+                                    new Date(),
+                                    "[" + e.getClass().getSimpleName() + "]"
+                                            + e.code().toString() + "-"
+                                            + e.message());
+                }
+            }
+        }
+    }
+
+    public void deleteResourceByType(final String resourceType) {
+        if (null != resourceType) {
+            new Thread() {
+                @Override
+                public void run() {
+                    // Unregister the resources from the platform
+                    deleteResource(resourceType);
+
+                    // Delete from the local data structure
+                    deleteLocalResourceDetails(resourceType, null);
+
+                    // Notify the UI listener for removing this resource from UI
+                    resourceDeletedUINotification();
+
+                    if (null != currentResourceInSelection
+                            && resourceType.equals(currentResourceInSelection
+                                    .getResourceType())) {
+                        // Listeners might query the resource being deleted if
+                        // exists. So set the currently selection to null.
+                        setCurrentResourceInSelection(null);
+
+                        // Notify all observers for resource selection change
+                        // event
+                        resourceSelectionChangedUINotification();
+                    }
+                }
+            }.start();
+        }
+    }
+
+    private void deleteResource(String resourceType) {
+        if (null != resourceType) {
+            try {
+                SimulatorManager.deleteResources(resourceType);
+            } catch (SimulatorException e) {
+                Activator
+                        .getDefault()
+                        .getLogManager()
+                        .log(Level.ERROR.ordinal(),
+                                new Date(),
+                                "[" + e.getClass().getSimpleName() + "]"
+                                        + e.code().toString() + "-"
+                                        + e.message());
+            }
+        }
+    }
+
+    public 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();
+            }
+        }.start();
+    }
+
+    private void deleteResource() {
+        try {
+            SimulatorManager.deleteResources(null);
+        } catch (SimulatorException e) {
+            Activator
+                    .getDefault()
+                    .getLogManager()
+                    .log(Level.ERROR.ordinal(),
+                            new Date(),
+                            "[" + e.getClass().getSimpleName() + "]"
+                                    + e.code().toString() + "-" + e.message());
+        }
+    }
+
+    private void deleteLocalResourceDetails(String resourceType,
+            String resourceURI) {
+        if (null != resourceType && null != resourceURI) {
+            removeResourceFromMap(resourceType, resourceURI);
+            removeResourceUriFromOrderedMap(resourceType, resourceURI);
+        } else {
+            synchronized (resourceMap) {
+                if (null != resourceType) {
+                    removeResourceUriFromOrderedMap(resourceType, null);
+                    resourceMap.remove(resourceType);
+                } else {
+                    resourceMap.clear();
+                    removeResourceUriFromOrderedMap(null, null);
+                }
+            }
+        }
+    }
+
+    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();
+                    }
+                }
+            }
+        }
+    }
+
+    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();
+                    }
+                }
+            }
+        }
+    }
+
+    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();
+                    }
+                }
+            }
+        }
+    }
+
+    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);
+                    }
+                }
+            }
+        }
+    }
+
+    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);
+                    }
+                }
+            }
+        }
+    }
+
+    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);
+                    }
+                }
+            }
+        }
+    }
+
+    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<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());
+                }
+            }
+        }
+        return typeList;
+    }
+
+    public boolean isTypeExist(String resType) {
+        synchronized (resourceMap) {
+            if (resourceMap.containsKey(resType)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    public List<String> getURIList() {
+        List<String> list = null;
+        synchronized (orderedResourceUriMap) {
+            Set<String> typeSet = orderedResourceUriMap.keySet();
+            List<String> typeList = Utility.convertSetToList(typeSet);
+            if (null == typeList || typeList.size() < 1) {
+                return list;
+            }
+            list = new ArrayList<String>();
+
+            // Sort the types
+            Collections.sort(typeList);
+
+            // Add all URIs to the output list
+            Iterator<String> typeItr = typeList.iterator();
+            while (typeItr.hasNext()) {
+                List<String> l = orderedResourceUriMap.get(typeItr.next());
+                if (null != l) {
+                    list.addAll(l);
+                }
+            }
+        }
+        return list;
+    }
+
+    public void resourceSelectionChanged(final String selectedItem) {
+        new Thread() {
+            @Override
+            public void run() {
+                // Check whether the item selected is a resource or resource
+                // category
+                if (isTypeExist(selectedItem)) {
+                    // Given item is a resource Type
+                    setCurrentResourceInSelection(null);
+                } else {
+                    // Given item is a resource URI
+                    SimulatorResource resource = getSimulatorResourceByURI(selectedItem);
+                    if (null != resource) {
+                        setCurrentResourceInSelection(resource);
+                    } else {
+                        setCurrentResourceInSelection(null);
+                    }
+                }
+                // Notify all observers for resource selection change event
+                resourceSelectionChangedUINotification();
+            }
+        }.start();
+    }
+
+    public List<MetaProperty> getMetaProperties(SimulatorResource resource) {
+        if (null != resource) {
+            String propName;
+            String propValue;
+
+            List<MetaProperty> metaPropertyList = new ArrayList<MetaProperty>();
+
+            for (int index = 0; index < Constants.META_PROPERTY_COUNT; index++) {
+                propName = Constants.META_PROPERTIES[index];
+                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;
+                } else {
+                    propValue = null;
+                }
+                if (null != propValue) {
+                    metaPropertyList.add(new MetaProperty(propName, propValue));
+                }
+            }
+
+            return metaPropertyList;
+        }
+        return null;
+    }
+
+    public List<LocalResourceAttribute> getAttributes(SimulatorResource resource) {
+        List<LocalResourceAttribute> attList = null;
+        if (null != resource) {
+            Map<String, LocalResourceAttribute> attMap = resource
+                    .getResourceAttributesMap();
+            if (null != attMap && attMap.size() > 0) {
+                attList = new ArrayList<LocalResourceAttribute>();
+                Set<String> attNameSet = attMap.keySet();
+                String attName;
+                LocalResourceAttribute attribute;
+                Iterator<String> attNameItr = attNameSet.iterator();
+                while (attNameItr.hasNext()) {
+                    attName = attNameItr.next();
+                    attribute = attMap.get(attName);
+                    if (null != attribute) {
+                        attList.add(attribute);
+                    }
+                }
+            }
+        }
+        return attList;
+    }
+
+    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);
+                        } catch (NumberFormatException nfe) {
+                            return;
+                        }
+                        server.updateAttributeInteger(attributeName, val);
+                    } else if (baseType == Type.DOUBLE) {
+                        double val;
+                        try {
+                            val = Double.parseDouble(value);
+                        } catch (NumberFormatException nfe) {
+                            return;
+                        }
+                        server.updateAttributeDouble(attributeName, val);
+                    } else if (baseType == Type.BOOL) {
+                        boolean val;
+                        val = Boolean.parseBoolean(value);
+                        server.updateAttributeBoolean(attributeName, val);
+                    }
+                } catch (SimulatorException e) {
+                    Activator
+                            .getDefault()
+                            .getLogManager()
+                            .log(Level.ERROR.ordinal(),
+                                    new Date(),
+                                    "[" + e.getClass().getSimpleName() + "]"
+                                            + e.code().toString() + "-"
+                                            + e.message());
+                }
+            }
+        }
+    }
+
+    private 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;
+    }
+
+    public int startAutomation(SimulatorResource resource,
+            LocalResourceAttribute attribute, AutomationType autoType,
+            int autoUpdateInterval) {
+        int autoId = -1;
+        if (null != resource && null != attribute) {
+            SimulatorResourceServer resourceServerN = resource
+                    .getResourceServer();
+            if (null != resourceServerN) {
+                String attrName = attribute.getAttributeName();
+                try {
+                    autoId = resourceServerN.startAttributeAutomation(attrName,
+                            autoType, automationListener);
+                } catch (SimulatorException e) {
+                    Activator
+                            .getDefault()
+                            .getLogManager()
+                            .log(Level.ERROR.ordinal(),
+                                    new Date(),
+                                    "[" + e.getClass().getSimpleName() + "]"
+                                            + e.code().toString() + "-"
+                                            + e.message());
+                    return -1;
+                }
+                if (-1 != autoId) {
+                    attribute.setAutomationId(autoId);
+                    attribute.setAutomationType(autoType);
+                    attribute.setAutomationUpdateInterval(autoUpdateInterval);
+                    attribute.setAutomationInProgress(true);
+                    resource.setAttributeAutomationInProgress(true);
+                } else {
+                    attribute.setAutomationInProgress(false);
+                }
+            }
+        }
+        return autoId;
+    }
+
+    public void stopAutomation(SimulatorResource resource,
+            LocalResourceAttribute att, int autoId) {
+        if (null != resource) {
+            SimulatorResourceServer resourceServerN = resource
+                    .getResourceServer();
+            if (null != resourceServerN) {
+                try {
+                    resourceServerN.stopAutomation(autoId);
+                } catch (SimulatorException e) {
+                    Activator
+                            .getDefault()
+                            .getLogManager()
+                            .log(Level.ERROR.ordinal(),
+                                    new Date(),
+                                    "[" + e.getClass().getSimpleName() + "]"
+                                            + e.code().toString() + "-"
+                                            + e.message());
+                    return;
+                }
+                // Change the automation status
+                att.setAutomationInProgress(false);
+                resource.setAttributeAutomationInProgress(isAnyAttributeInAutomation(resource));
+            }
+        }
+    }
+
+    private boolean isAnyAttributeInAutomation(SimulatorResource 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;
+                            }
+                        }
+                    }
+                }
+            }
+        }
+        return targetAttribute;
+    }
+
+    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, 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);
+                        };
+                    };
+                    notifyThread.setPriority(Thread.MAX_PRIORITY);
+                    notifyThread.start();
+
+                    status = true;
+                }
+            }
+        }
+        return status;
+    }
+
+    public boolean stopResourceAutomationUIRequest(final String resourceURI) {
+        SimulatorResource resource = getSimulatorResourceByURI(resourceURI);
+        if (null == resource) {
+            return false;
+        }
+        final int autoId = resource.getAutomationId();
+        if (-1 == autoId) {
+            return false;
+        }
+        SimulatorResourceServer resourceServer = resource.getResourceServer();
+        if (null == resourceServer) {
+            return false;
+        }
+        // Call native method
+        try {
+            resourceServer.stopAutomation(autoId);
+        } catch (SimulatorException e) {
+            Activator
+                    .getDefault()
+                    .getLogManager()
+                    .log(Level.ERROR.ordinal(),
+                            new Date(),
+                            "[" + e.getClass().getSimpleName() + "]"
+                                    + e.code().toString() + "-" + e.message());
+            return false;
+        }
+
+        // Notify the UI Listeners. Invoke the automation complete callback.
+        Thread stopThread = new Thread() {
+            public void run() {
+                automationListener.onAutomationComplete(resourceURI, autoId);
+            }
+        };
+        stopThread.start();
+        return true;
+    }
+
+    // Changes the automation state of the resource and its attributes
+    private void changeResourceLevelAutomationStatus(
+            SimulatorResource resource, boolean status) {
+
+        Map<String, LocalResourceAttribute> attributeMap = resource
+                .getResourceAttributesMap();
+        if (null != attributeMap) {
+            Set<String> attrNameSet = attributeMap.keySet();
+            Iterator<String> attrNameItr = attrNameSet.iterator();
+            String attrName;
+            LocalResourceAttribute attribute;
+            while (attrNameItr.hasNext()) {
+                attrName = attrNameItr.next();
+                attribute = attributeMap.get(attrName);
+                if (null != attribute) {
+                    attribute.setAutomationInProgress(status);
+                }
+            }
+        }
+        resource.setResourceAutomationInProgress(status);
+    }
+
+    public boolean isResourceAutomationStarted(String resourceURI) {
+        boolean status = false;
+        if (null == resourceURI) {
+            return status;
+        }
+
+        SimulatorResource resource = getSimulatorResourceByURI(resourceURI);
+        if (null != resource) {
+            status = resource.isResourceAutomationInProgress();
+        }
+        return status;
+    }
+
+    public boolean isAttributeAutomationStarted(String resourceURI) {
+        boolean status = false;
+        if (null == resourceURI) {
+            return status;
+        }
+        SimulatorResource resource = getSimulatorResourceByURI(resourceURI);
+        if (null != resource) {
+            status = resource.isAttributeAutomationInProgress();
+        }
+        return status;
+    }
+
+    public LocalResourceAttribute getAttributeByResourceURI(String uri,
+            String attName) {
+        if (null == uri || null == attName) {
+            return null;
+        }
+        SimulatorResource resource = getSimulatorResourceByURI(uri);
+        if (null == resource) {
+            return null;
+        }
+        Map<String, LocalResourceAttribute> attMap = resource
+                .getResourceAttributesMap();
+        if (null == attMap) {
+            return null;
+        }
+        return attMap.get(attName);
+    }
+
+    public void notifyObserverRequest(SimulatorResource res, int observerId) {
+        if (null == res) {
+            return;
+        }
+        SimulatorResourceServer server = res.getResourceServer();
+        if (null == server) {
+            return;
+        }
+        try {
+            server.notifyObserver(observerId);
+        } catch (SimulatorException e) {
+            Activator
+                    .getDefault()
+                    .getLogManager()
+                    .log(Level.ERROR.ordinal(),
+                            new Date(),
+                            "[" + e.getClass().getSimpleName() + "]"
+                                    + e.code().toString() + "-" + e.message());
+        }
+    }
+
+    public Image getImage(String resourceURI) {
+        if (null == resourceURI) {
+            return null;
+        }
+        SimulatorResource resource = getSimulatorResourceByURI(resourceURI);
+        if (null == resource) {
+            return null;
+        }
+        return Activator.getDefault().getImageRegistry()
+                .get(resource.getResourceType());
+    }
+
+    public void shutdown() {
+        threadHandle.interrupt();
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/perspective/PerspectiveFactory.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/perspective/PerspectiveFactory.java
new file mode 100644 (file)
index 0000000..079f645
--- /dev/null
@@ -0,0 +1,64 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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.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.ResourceManagerView;
+import oic.simulator.serviceprovider.view.ResourceObserverView;
+
+import org.eclipse.ui.IFolderLayout;
+import org.eclipse.ui.IPageLayout;
+import org.eclipse.ui.IPerspectiveFactory;
+
+/**
+ * This class creates a new eclipse perspective for service provider and
+ * positions the different views inside.
+ */
+public class PerspectiveFactory implements IPerspectiveFactory {
+
+    public static final String PERSPECTIVE_ID = "oic.simulator.serviceprovider.perspective";
+    private IPageLayout        factory;
+
+    @Override
+    public void createInitialLayout(IPageLayout factory) {
+        this.factory = factory;
+        factory.setEditorAreaVisible(false);
+        addViews();
+        factory.setFixed(false);
+    }
+
+    private void addViews() {
+        factory.addView(ResourceManagerView.VIEW_ID, IPageLayout.LEFT, 0.3f,
+                factory.getEditorArea());
+
+        IFolderLayout folder = factory.createFolder(
+                "oic.simulator.serviceprovider.perspective.folder",
+                IPageLayout.BOTTOM, 0.65f, ResourceManagerView.VIEW_ID);
+        folder.addView(MetaPropertiesView.VIEW_ID);
+        folder.addView(ResourceObserverView.VIEW_ID);
+
+        factory.addView(AttributeView.VIEW_ID, IPageLayout.LEFT, 0.7f,
+                factory.getEditorArea());
+        factory.addView(LogView.VIEW_ID, IPageLayout.BOTTOM, 0.65f,
+                AttributeView.VIEW_ID);
+        factory.addView(MultiResourceOrchestrationView.VIEW_ID,
+                IPageLayout.RIGHT, 0.6f, AttributeView.VIEW_ID);
+    }
+}
\ 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
new file mode 100644 (file)
index 0000000..0136296
--- /dev/null
@@ -0,0 +1,122 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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
new file mode 100644 (file)
index 0000000..336d82d
--- /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.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
new file mode 100644 (file)
index 0000000..c04b07e
--- /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.
+ */
+
+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
new file mode 100644 (file)
index 0000000..61881b1
--- /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.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
new file mode 100644 (file)
index 0000000..0a1b17a
--- /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.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
new file mode 100644 (file)
index 0000000..b581a6e
--- /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.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
new file mode 100644 (file)
index 0000000..38d9730
--- /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.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
new file mode 100644 (file)
index 0000000..4a3035c
--- /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.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/Constants.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/utils/Constants.java
new file mode 100644 (file)
index 0000000..890c076
--- /dev/null
@@ -0,0 +1,108 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package oic.simulator.serviceprovider.utils;
+
+import org.oic.simulator.serviceprovider.AutomationType;
+
+/**
+ * This class maintains all constants which are used throughout the service
+ * provider plug-in.
+ */
+public class Constants {
+
+    public static final String         CONFIG_DIRECTORY_PATH            = "/resource";
+
+    public static final String         UNDERSCORE                       = "_";
+    public static final String         FORWARD_SLASH                    = "/";
+
+    public static final String         OIC_PREFIX                       = "/oic/r";
+    public static final String         SIMULATOR                        = "simulator";
+
+    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[]       META_PROPERTIES                  = {
+            RESOURCE_URI, RESOURCE_TYPE, CONNECTIVITY_TYPE             };
+
+    public static final int            META_PROPERTY_COUNT              = META_PROPERTIES.length;
+
+    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                       = "Automation";
+    public static final String         AUTOMATION_TYPE                  = "Automation Type";
+    public static final String         UPDATE_INTERVAL_IN_MS            = "Update Interval(ms)";
+
+    public static final String[]       AUTOMATION_SETTINGS              = {
+            AUTOMATION_TYPE, UPDATE_INTERVAL_IN_MS                     };
+
+    public static final int            AUTOMATION_SETTINGS_COUNT        = AUTOMATION_SETTINGS.length;
+
+    public static final String         START_RESOURCE_AUTOMATION        = "Start Automation";
+    public static final String         STOP_RESOURCE_AUTOMATION         = "Stop Automation";
+
+    public static final int            PROPER_RESOURCE_URI_TOKEN_COUNT  = 6;
+    public static final int            DISPLAY_RESOURCE_URI_TOKEN_COUNT = 2;
+
+    public static final AutomationType DEFAULT_AUTOMATION_TYPE          = AutomationType.NORMAL;
+
+    public static final int            DEFAULT_AUTOMATION_INTERVAL      = 500;
+
+    public static final int            PROPER_LOG_TIME_TOKEN_LENGTH     = 3;
+
+    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            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         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         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         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         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_PREFIX                 = "/resource/";
+
+    public static final String         RAML_FILE_EXTENSION              = ".raml";
+    public static final String         JSON_FILE_EXTENSION              = ".json";
+
+    public static final String         SPLIT_BY_DOT_PATTERN             = "\\.";
+
+    public static final String         OIC_R_LIGHT                      = "oic.r.light";
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/utils/Utility.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/utils/Utility.java
new file mode 100644 (file)
index 0000000..06f6ebd
--- /dev/null
@@ -0,0 +1,148 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * 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 (Constants.PROPER_RESOURCE_URI_TOKEN_COUNT == tokens.length) {
+                // Proper URI
+                result = tokens[3] + Constants.UNDERSCORE + tokens[5];
+            }
+        }
+        return result;
+    }
+
+    public static String displayNameToUri(String displayName) {
+        String result = null;
+        if (null != displayName) {
+            String tokens[] = displayName.split(Constants.UNDERSCORE);
+            if (Constants.DISPLAY_RESOURCE_URI_TOKEN_COUNT == tokens.length) {
+                // Proper Display Name
+                result = Constants.OIC_PREFIX + Constants.FORWARD_SLASH
+                        + tokens[0] + Constants.FORWARD_SLASH
+                        + Constants.SIMULATOR + Constants.FORWARD_SLASH
+                        + tokens[1];
+            }
+        }
+        return result;
+    }
+
+    public static String fileNameToDisplay(String fileName) {
+        if (null == fileName || fileName.length() < 1) {
+            return null;
+        }
+        // Remove the RAML file standard prefix
+        int len = Constants.RAML_FILE_PREFIX.length();
+        if (len > 0) {
+            if (fileName.startsWith(Constants.RAML_FILE_PREFIX)) {
+                fileName = fileName.substring(len);
+            }
+        }
+
+        // Removing the file extension
+        int index = fileName.lastIndexOf('.');
+        fileName = fileName.substring(0, index);
+        return fileName;
+    }
+
+    public static String displayToFileName(String displayName) {
+        if (null == displayName || displayName.length() < 1) {
+            return null;
+        }
+        String fileName;
+        // Adding the prefix
+        fileName = Constants.RAML_FILE_PREFIX + displayName;
+
+        // Adding the file extension
+        fileName = fileName + Constants.RAML_FILE_EXTENSION;
+
+        return fileName;
+    }
+
+    public static boolean isUriComplete(String uri) {
+        boolean uriComplete = false;
+        if (null != uri) {
+            String tokens[] = uri.split(Constants.FORWARD_SLASH);
+            if (Constants.PROPER_RESOURCE_URI_TOKEN_COUNT == tokens.length) {
+                uriComplete = true;
+            }
+        }
+        return uriComplete;
+    }
+
+    public static String getAutomationStatus(boolean status) {
+        if (status) {
+            return Constants.ENABLED;
+        } else {
+            return Constants.DISABLED;
+        }
+    }
+
+    public static String getAutomationString(boolean status) {
+        if (status) {
+            return Constants.ENABLE;
+        } else {
+            return Constants.DISABLE;
+        }
+    }
+
+    public static boolean getAutomationBoolean(String status) {
+        if (null != status) {
+            if (status.equals(Constants.ENABLE)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    public static int getUpdateIntervalFromString(String value) {
+        int result = Constants.DEFAULT_AUTOMATION_INTERVAL;
+        if (null != value) {
+            try {
+                result = Integer.parseInt(value);
+            } catch (NumberFormatException nfe) {
+                System.out
+                        .println("Getting UpdateInterval from string failed!");
+            }
+        }
+        return result;
+    }
+
+    public static List<String> convertSetToList(Set<String> typeSet) {
+        if (null == typeSet) {
+            return null;
+        }
+        List<String> list = new ArrayList<String>();
+        Iterator<String> typeItr = typeSet.iterator();
+        while (typeItr.hasNext()) {
+            list.add(typeItr.next());
+        }
+        return list;
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/AttributeEditingSupport.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/AttributeEditingSupport.java
new file mode 100644 (file)
index 0000000..5b8e299
--- /dev/null
@@ -0,0 +1,253 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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.manager.ResourceManager;
+import oic.simulator.serviceprovider.resource.AutomationSettingHelper;
+import oic.simulator.serviceprovider.resource.LocalResourceAttribute;
+import oic.simulator.serviceprovider.resource.SimulatorResource;
+import oic.simulator.serviceprovider.utils.Utility;
+import oic.simulator.serviceprovider.view.dialogs.AutomationSettingDialog;
+
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.viewers.CellEditor;
+import org.eclipse.jface.viewers.CheckboxCellEditor;
+import org.eclipse.jface.viewers.ComboBoxCellEditor;
+import org.eclipse.jface.viewers.EditingSupport;
+import org.eclipse.jface.viewers.TableViewer;
+import org.eclipse.jface.window.Window;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.CCombo;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.MessageBox;
+import org.oic.simulator.serviceprovider.AutomationType;
+
+/**
+ * This class provides editing support to the resources attributes table in the
+ * attributes view.
+ */
+public class AttributeEditingSupport {
+
+    private AttributeValueEditor attValueEditor;
+    private AutomationEditor     automationEditor;
+
+    public AttributeValueEditor createAttributeValueEditor(TableViewer viewer) {
+        attValueEditor = new AttributeValueEditor(viewer);
+        return attValueEditor;
+    }
+
+    public AutomationEditor createAutomationEditor(TableViewer viewer) {
+        automationEditor = new AutomationEditor(viewer);
+        return automationEditor;
+    }
+
+    class AttributeValueEditor extends EditingSupport {
+
+        private final TableViewer      viewer;
+        private LocalResourceAttribute attributeInSelection;
+        private CCombo                 comboBox;
+
+        public AttributeValueEditor(TableViewer viewer) {
+            super(viewer);
+            this.viewer = viewer;
+        }
+
+        @Override
+        protected boolean canEdit(Object arg0) {
+            return true;
+        }
+
+        @Override
+        protected CellEditor getCellEditor(Object element) {
+            attributeInSelection = (LocalResourceAttribute) element;
+
+            // CellEditor is not required as the automation is in progress.
+            if (attributeInSelection.isAutomationInProgress()) {
+                return null;
+            }
+
+            String values[] = null;
+            List<String> valueSet = attributeInSelection.getAttValues();
+            values = convertListToStringArray(valueSet);
+
+            ComboBoxCellEditor comboEditor = new ComboBoxCellEditor(
+                    viewer.getTable(), values, SWT.READ_ONLY);
+            comboBox = (CCombo) comboEditor.getControl();
+            comboBox.addModifyListener(new ModifyListener() {
+
+                @Override
+                public void modifyText(ModifyEvent event) {
+                    String oldValue = String.valueOf(attributeInSelection
+                            .getAttributeValue());
+                    String newValue = comboBox.getText();
+                    if (!oldValue.equals(newValue)) {
+                        attributeInSelection.setAttributeValue(newValue);
+                        MessageBox dialog = new MessageBox(viewer.getTable()
+                                .getShell(), SWT.ICON_QUESTION | SWT.OK
+                                | SWT.CANCEL);
+                        dialog.setText("Confirm action");
+                        dialog.setMessage("Do you want to modify the value?");
+                        int retval = dialog.open();
+                        if (retval != SWT.OK) {
+                            attributeInSelection.setAttributeValue(oldValue);
+                        } else {
+                            ResourceManager resourceManager;
+                            resourceManager = Activator.getDefault()
+                                    .getResourceManager();
+                            SimulatorResource resource = resourceManager
+                                    .getCurrentResourceInSelection();
+                            resourceManager.attributeValueUpdated(resource,
+                                    attributeInSelection.getAttributeName(),
+                                    newValue);
+                        }
+                        viewer.update(attributeInSelection, null);
+                        comboBox.setVisible(false);
+                    }
+                }
+            });
+            return comboEditor;
+        }
+
+        @Override
+        protected Object getValue(Object element) {
+            int indexOfItem = 0;
+            LocalResourceAttribute att = (LocalResourceAttribute) element;
+            String valueString = String.valueOf(att.getAttributeValue());
+            List<String> valueSet = att.getAttValues();
+            if (null != valueSet) {
+                indexOfItem = valueSet.indexOf(valueString);
+            }
+            if (indexOfItem == -1) {
+                indexOfItem = 0;
+            }
+            return indexOfItem;
+        }
+
+        @Override
+        protected void setValue(Object element, Object value) {
+            Object valueObj = attributeInSelection.getAttributeValue();
+            if (null == valueObj)
+                return;
+            String attValue = String.valueOf(valueObj);
+            ((LocalResourceAttribute) element).setAttributeValue(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;
+        }
+    }
+
+    class AutomationEditor extends EditingSupport {
+
+        private final TableViewer viewer;
+
+        public AutomationEditor(TableViewer viewer) {
+            super(viewer);
+            this.viewer = viewer;
+        }
+
+        @Override
+        protected boolean canEdit(Object arg0) {
+            return true;
+        }
+
+        @Override
+        protected CellEditor getCellEditor(Object element) {
+            // CellEditor is not required as the automation is in progress.
+            ResourceManager resourceManager = Activator.getDefault()
+                    .getResourceManager();
+            SimulatorResource resource = resourceManager
+                    .getCurrentResourceInSelection();
+            if (null != resource && resource.isResourceAutomationInProgress()) {
+                return null;
+            }
+            return new CheckboxCellEditor(null, SWT.CHECK | SWT.READ_ONLY);
+        }
+
+        @Override
+        protected Object getValue(Object element) {
+            LocalResourceAttribute att = (LocalResourceAttribute) element;
+            return att.isAutomationInProgress();
+        }
+
+        @Override
+        protected void setValue(Object element, Object value) {
+            ResourceManager resourceManager = Activator.getDefault()
+                    .getResourceManager();
+            // As automation depends on the current resource in selection, its
+            // presence is being checked.
+            SimulatorResource resource = resourceManager
+                    .getCurrentResourceInSelection();
+            if (null == resource) {
+                return;
+            }
+
+            LocalResourceAttribute att = (LocalResourceAttribute) element;
+            boolean checked = (Boolean) value;
+            if (checked) {
+                // Start the automation
+                // Fetch the settings data
+                List<AutomationSettingHelper> automationSettings;
+                automationSettings = AutomationSettingHelper
+                        .getAutomationSettings(att);
+
+                // Open the settings dialog
+                AutomationSettingDialog dialog = new AutomationSettingDialog(
+                        viewer.getTable().getShell(), automationSettings);
+                dialog.create();
+                if (dialog.open() == Window.OK) {
+                    String automationType = dialog.getAutomationType();
+                    String updateFreq = dialog.getUpdateFrequency();
+
+                    AutomationType autoType = AutomationType
+                            .valueOf(automationType);
+                    int updFreq = Utility
+                            .getUpdateIntervalFromString(updateFreq);
+                    int autoId = resourceManager.startAutomation(resource, att,
+                            autoType, updFreq);
+                    if (autoId == -1) {
+                        MessageDialog.openInformation(Display.getDefault()
+                                .getActiveShell(), "Automation Status",
+                                "Automation start failed!!");
+                    } else {
+                        viewer.update(element, null);
+                    }
+                }
+            } else {
+                // Stop the automation
+                resourceManager.stopAutomation(resource, att,
+                        att.getAutomationId());
+                MessageDialog.openInformation(Display.getDefault()
+                        .getActiveShell(), "Automation Status",
+                        "Automation stopped.");
+                viewer.update(element, null);
+            }
+        }
+    }
+}
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/AttributeView.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/AttributeView.java
new file mode 100644 (file)
index 0000000..d4443b4
--- /dev/null
@@ -0,0 +1,428 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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 java.util.Set;
+
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.listener.IAutomationUIListener;
+import oic.simulator.serviceprovider.listener.IResourceModelChangedUIListener;
+import oic.simulator.serviceprovider.listener.IResourceSelectionChangedUIListener;
+import oic.simulator.serviceprovider.manager.ResourceManager;
+import oic.simulator.serviceprovider.resource.LocalResourceAttribute;
+import oic.simulator.serviceprovider.resource.ModelChangeNotificationType;
+import oic.simulator.serviceprovider.resource.SimulatorResource;
+import oic.simulator.serviceprovider.utils.Constants;
+
+import org.eclipse.jface.viewers.ColumnLabelProvider;
+import org.eclipse.jface.viewers.IStructuredContentProvider;
+import org.eclipse.jface.viewers.StyledCellLabelProvider;
+import org.eclipse.jface.viewers.TableViewer;
+import org.eclipse.jface.viewers.TableViewerColumn;
+import org.eclipse.jface.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;
+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;
+
+/**
+ * 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";
+
+    private TableViewer                         attTblViewer;
+
+    private AttributeEditingSupport             attributeEditor;
+
+    private IResourceSelectionChangedUIListener resourceSelectionChangedListener;
+    private IResourceModelChangedUIListener     resourceModelChangedUIListener;
+    private IAutomationUIListener               automationUIListener;
+
+    private final String[]                      attTblHeaders  = { "Name",
+            "Value", "Automation"                             };
+    private final Integer[]                     attTblColWidth = { 150, 190,
+            150                                               };
+
+    private ResourceManager                     resourceManager;
+
+    public AttributeView() {
+
+        resourceManager = Activator.getDefault().getResourceManager();
+
+        resourceSelectionChangedListener = new IResourceSelectionChangedUIListener() {
+
+            @Override
+            public void onResourceSelectionChange() {
+                Display.getDefault().asyncExec(new Runnable() {
+
+                    @Override
+                    public void run() {
+                        if (null != attTblViewer) {
+                            updateViewer(getData());
+                            SimulatorResource resource = resourceManager
+                                    .getCurrentResourceInSelection();
+                            Table tbl = attTblViewer.getTable();
+                            if (!tbl.isDisposed()) {
+                                if (null != resource
+                                        && resource
+                                                .isResourceAutomationInProgress()) {
+                                    tbl.setEnabled(false);
+                                } else {
+                                    tbl.setEnabled(true);
+                                }
+                            }
+                        }
+                    }
+                });
+            }
+        };
+
+        resourceModelChangedUIListener = new IResourceModelChangedUIListener() {
+
+            @Override
+            public void onResourceModelChange(
+                    final ModelChangeNotificationType notificationType,
+                    final String resourceURI,
+                    final Set<LocalResourceAttribute> valueChangeSet) {
+                Display.getDefault().asyncExec(new Runnable() {
+                    @Override
+                    public void run() {
+                        // Handle the notification only if it is for the current
+                        // resource in selection
+                        SimulatorResource resource = resourceManager
+                                .getCurrentResourceInSelection();
+                        if (null == resource) {
+                            return;
+                        }
+                        if (!resourceURI.equals(resource.getResourceURI())) {
+                            // This notification is for a different resource
+                            // whose attributes are not
+                            // currently not being shown in UI. So ignoring this
+                            // notification.
+                            return;
+                        }
+                        // Refresh the table viewers which will display
+                        // the updated values
+                        if (null != attTblViewer) {
+                            if (notificationType == ModelChangeNotificationType.ATTRIBUTE_ADDED
+                                    || notificationType == ModelChangeNotificationType.ATTRIBUTE_REMOVED) {
+                                updateViewer(getData());
+                            } else if (notificationType == ModelChangeNotificationType.NO_ATTRIBUTES_IN_MODEL) {
+                                attTblViewer.setInput(null);
+                            } else if (notificationType == ModelChangeNotificationType.ATTRIBUTE_VALUE_CHANGED) {
+                                if (null != valueChangeSet) {
+                                    attTblViewer.update(
+                                            valueChangeSet.toArray(), null);
+                                }
+                            }
+                        }
+                    }
+                });
+            }
+        };
+
+        automationUIListener = new IAutomationUIListener() {
+
+            @Override
+            public void onResourceAutomationStart(final String resourceURI) {
+                Display.getDefault().asyncExec(new Runnable() {
+
+                    @Override
+                    public void run() {
+                        if (null == resourceURI) {
+                            return;
+                        }
+                        SimulatorResource resource = resourceManager
+                                .getCurrentResourceInSelection();
+                        if (null == resource) {
+                            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();
+
+                                // Disabling the table to prevent interactions
+                                // during the automation
+                                tbl.setEnabled(false);
+                                tbl.deselectAll();
+                            }
+                        }
+                    }
+                });
+            }
+
+            @Override
+            public void onAutomationComplete(final String resourceURI,
+                    final String attName) {
+                // This method notifies the completion of attribute level
+                // automation.
+                Display.getDefault().asyncExec(new Runnable() {
+
+                    @Override
+                    public void run() {
+                        if (null == resourceURI) {
+                            return;
+                        }
+                        // Check if the given resourceURI is the uri of the
+                        // resource whose attributes are currently being
+                        // displayed by this view.
+                        SimulatorResource resource = resourceManager
+                                .getCurrentResourceInSelection();
+                        if (null == resource) {
+                            return;
+                        }
+                        String uri = resource.getResourceURI();
+                        if (null == uri || !uri.equals(resourceURI)) {
+                            return;
+                        }
+                        Table tbl;
+                        tbl = attTblViewer.getTable();
+                        if (!tbl.isDisposed()) {
+                            if (null != attName) {
+                                // Attribute level automation has stopped
+                                LocalResourceAttribute att = resourceManager
+                                        .getAttributeByResourceURI(resourceURI,
+                                                attName);
+                                if (null == att) {
+                                    return;
+                                } else {
+                                    attTblViewer.update(att, null);
+                                }
+                            } else {
+                                // Resource level automation has stopped
+                                // Enabling the table which was disabled at the
+                                // beginning of automation
+                                tbl.setEnabled(true);
+                                attTblViewer.refresh();
+                            }
+                        }
+                    }
+                });
+            }
+        };
+    }
+
+    @Override
+    public void createPartControl(Composite parent) {
+        Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE);
+
+        parent.setLayout(new GridLayout());
+        GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        parent.setLayoutData(gd);
+
+        Group attGroup = new Group(parent, SWT.NONE);
+        attGroup.setLayout(new GridLayout());
+        gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        attGroup.setLayoutData(gd);
+        attGroup.setText("Attributes");
+        attGroup.setBackground(color);
+
+        attTblViewer = new TableViewer(attGroup, SWT.SINGLE | 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());
+
+        addManagerListeners();
+
+        // Check whether there is any resource selected already
+        List<LocalResourceAttribute> propertyList = getData();
+        if (null != propertyList) {
+            updateViewer(propertyList);
+        }
+    }
+
+    public void createAttributeColumns(TableViewer tableViewer) {
+
+        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));
+    }
+
+    private void addManagerListeners() {
+        resourceManager
+                .addResourceSelectionChangedUIListener(resourceSelectionChangedListener);
+        resourceManager
+                .addResourceModelChangedUIListener(resourceModelChangedUIListener);
+        resourceManager.addAutomationUIListener(automationUIListener);
+    }
+
+    private List<LocalResourceAttribute> getData() {
+        SimulatorResource resourceInSelection = resourceManager
+                .getCurrentResourceInSelection();
+        if (null != resourceInSelection) {
+            List<LocalResourceAttribute> attList = resourceManager
+                    .getAttributes(resourceInSelection);
+            return attList;
+        } else {
+            return null;
+        }
+    }
+
+    private void updateViewer(List<LocalResourceAttribute> attList) {
+        Table tbl;
+        if (null != attList) {
+            tbl = attTblViewer.getTable();
+            if (null != tbl && !tbl.isDisposed()) {
+                tbl.setLinesVisible(true);
+                attTblViewer.setInput(attList.toArray());
+            }
+        } else {
+            // Clear the attributes table viewer
+            if (null != attTblViewer) {
+                tbl = attTblViewer.getTable();
+                if (null != tbl && !tbl.isDisposed()) {
+                    // tbl.deselectAll();
+                    tbl.removeAll();
+                    tbl.setLinesVisible(false);
+                }
+            }
+        }
+    }
+
+    class AttributeContentProvider 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;
+        }
+
+    }
+
+    @Override
+    public void dispose() {
+        // Unregister the selection listener
+        if (null != resourceSelectionChangedListener) {
+            resourceManager
+                    .removeResourceSelectionChangedUIListener(resourceSelectionChangedListener);
+        }
+
+        // Unregister the model change listener
+        if (null != resourceModelChangedUIListener) {
+            resourceManager
+                    .removeResourceModelChangedUIListener(resourceModelChangedUIListener);
+        }
+
+        // Unregister the automation complete listener
+        if (null != automationUIListener) {
+            resourceManager.removeAutomationUIListener(automationUIListener);
+        }
+
+        super.dispose();
+    }
+
+    @Override
+    public void setFocus() {
+
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/LogView.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/LogView.java
new file mode 100644 (file)
index 0000000..aa686b0
--- /dev/null
@@ -0,0 +1,724 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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.io.BufferedWriter;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+import java.util.HashMap;
+import java.util.List;
+
+import oic.simulator.logger.LogContentProvider;
+import oic.simulator.logger.LogEntry;
+import oic.simulator.logger.LogLabelProvider;
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.listener.ILogUIListener;
+import oic.simulator.serviceprovider.manager.LogManager;
+import oic.simulator.serviceprovider.utils.Constants;
+import oic.simulator.serviceprovider.view.dialogs.FilterDialog;
+import oic.simulator.serviceprovider.view.dialogs.LogDetailsDialog;
+
+import org.eclipse.jface.action.Action;
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.action.IContributionItem;
+import org.eclipse.jface.action.IMenuManager;
+import org.eclipse.jface.action.IToolBarManager;
+import org.eclipse.jface.action.MenuManager;
+import org.eclipse.jface.action.Separator;
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.jface.viewers.DoubleClickEvent;
+import org.eclipse.jface.viewers.IDoubleClickListener;
+import org.eclipse.jface.viewers.ISelectionChangedListener;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.SelectionChangedEvent;
+import org.eclipse.jface.viewers.StructuredSelection;
+import org.eclipse.jface.viewers.TreeViewer;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.jface.viewers.ViewerComparator;
+import org.eclipse.jface.window.Window;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.KeyEvent;
+import org.eclipse.swt.events.KeyListener;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.FileDialog;
+import org.eclipse.swt.widgets.Text;
+import org.eclipse.swt.widgets.Tree;
+import org.eclipse.swt.widgets.TreeColumn;
+import org.eclipse.swt.widgets.TreeItem;
+import org.eclipse.ui.IActionBars;
+import org.eclipse.ui.IWorkbenchActionConstants;
+import org.eclipse.ui.IWorkbenchPage;
+import org.eclipse.ui.dialogs.FilteredTree;
+import org.eclipse.ui.dialogs.PatternFilter;
+import org.eclipse.ui.part.ViewPart;
+import org.oic.simulator.ILogger.Level;
+
+/**
+ * This class manages and shows the log view in the perspective.
+ */
+public class LogView extends ViewPart {
+
+    public static final String        VIEW_ID              = "oic.simulator.serviceprovider.view.log";
+
+    private LogManager                logManager;
+    private ILogUIListener            logListener;
+
+    private LogContentProvider        treeContentProvider;
+
+    private FilteredTree              tree;
+    private TreeColumn                severityColumn;
+    private TreeColumn                dateColumn;
+    private TreeColumn                messageColumn;
+
+    private IAction                   exportLogAction;
+    private IAction                   clearLogAction;
+    private IAction                   deleteLogAction;
+    private IAction                   scrollLockAction;
+    private IAction                   logDetailsAction;
+    private IAction                   filterAction;
+    private IAction                   activateViewAction;
+    private IAction                   showTextFilter;
+    private IContributionItem         groupByAction;
+
+    private HashMap<Integer, Boolean> shownSeverities      = new HashMap<Integer, Boolean>();
+
+    private boolean                   activateOnChange     = false;
+
+    private boolean                   hideTextFilter       = false;
+
+    private boolean                   scrollLockDisabled;
+
+    public static final int           ORDER_BY_TIME        = 0;
+    public static final int           ORDER_BY_SEVERITY    = 1;
+    public static final int           ORDER_BY_MESSAGE     = 2;
+
+    int                               sortCandidate        = ORDER_BY_TIME;
+
+    SortAction                        sortByTimeAction     = new SortAction(
+                                                                   "Order by Time",
+                                                                   ORDER_BY_TIME);
+    SortAction                        sortBySeverityAction = new SortAction(
+                                                                   "Order by Severity",
+                                                                   ORDER_BY_SEVERITY);
+    SortAction                        sortByMessageAction  = new SortAction(
+                                                                   "Order by Message",
+                                                                   ORDER_BY_MESSAGE);
+
+    private ViewerComparator          dateComparator;
+    private ViewerComparator          severityComparator;
+    private ViewerComparator          messageComparator;
+
+    private TreeColumn                sortColumn           = null;
+    private static int                DOWN                 = 1;
+    private static int                UP                   = -1;
+    private int                       sortDirection        = DOWN;
+
+    public LogView() {
+
+        logListener = new ILogUIListener() {
+
+            @Override
+            public void logChanged(final List<LogEntry> entry) {
+                Display.getDefault().asyncExec(new Runnable() {
+
+                    @Override
+                    public void run() {
+                        TreeViewer viewer = tree.getViewer();
+                        if (viewer.getControl().isDisposed()) {
+                            return;
+                        }
+                        viewer.setInput(entry);
+                        updateTree(false);
+                    }
+                });
+            }
+
+            @Override
+            public void logAdded(final LogEntry added) {
+                Display.getDefault().asyncExec(new Runnable() {
+
+                    @Override
+                    public void run() {
+                        TreeViewer viewer = tree.getViewer();
+                        if (viewer.getControl().isDisposed()) {
+                            return;
+                        }
+                        LogContentProvider provider = (LogContentProvider) viewer
+                                .getContentProvider();
+                        provider.addLog(added);
+                        tree.getViewer().add(viewer.getInput(), added);
+                        @SuppressWarnings("unchecked")
+                        List<LogEntry> input = (List<LogEntry>) viewer
+                                .getInput();
+                        if (input.size() > Constants.LOG_SIZE) {
+                            viewer.remove(viewer.getInput(), 0);
+                        }
+                        updateTree(true);
+                    }
+                });
+            }
+
+            private void updateTree(boolean needscroll) {
+                if (activateOnChange) {
+                    IWorkbenchPage page = Activator.getDefault().getWorkbench()
+                            .getActiveWorkbenchWindow().getActivePage();
+                    if (page != null) {
+                        page.bringToTop(LogView.this);
+                    }
+                }
+                if (scrollLockDisabled && needscroll) {
+                    Tree tree2 = tree.getViewer().getTree();
+                    if (tree2.getItemCount() > 0) {
+                        TreeItem item = tree2.getItem(tree2.getItemCount() - 1);
+                        tree2.setTopItem(item);
+                        deleteLogAction.setEnabled(true);
+                    }
+                }
+            }
+        };
+
+        logManager = Activator.getDefault().getLogManager();
+
+        // Initially state of scroll lock
+        scrollLockDisabled = true;
+    }
+
+    @Override
+    public void createPartControl(Composite parent) {
+        PatternFilter filter = new PatternFilter() {
+
+            DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss.SSS");
+
+            @Override
+            protected boolean isLeafMatch(Viewer viewer, Object element) {
+                if (element instanceof LogEntry) {
+                    LogEntry logEntry = (LogEntry) element;
+                    String severity = LogManager.getSeverityName(logEntry
+                            .getSeverity());
+                    String date = dateFormat.format(logEntry.getDate());
+                    String message = logEntry.getMessage();
+                    return wordMatches(severity) || wordMatches(date)
+                            || wordMatches(message);
+                }
+                return false;
+            }
+        };
+        filter.setIncludeLeadingWildcard(true);
+        tree = new FilteredTree(parent, SWT.SINGLE | SWT.H_SCROLL
+                | SWT.V_SCROLL | SWT.FULL_SELECTION, filter, true);
+
+        setupFilteredTree();
+
+        createColumnComparators();
+
+        createActions();
+
+        setDefaultShownSeverities();
+
+        IActionBars actionBars = getViewSite().getActionBars();
+        IToolBarManager toolBarManager = actionBars.getToolBarManager();
+        toolBarManager.add(exportLogAction);
+        toolBarManager.add(clearLogAction);
+        toolBarManager.add(deleteLogAction);
+        toolBarManager.add(scrollLockAction);
+        toolBarManager
+                .add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
+
+        IMenuManager mgr = actionBars.getMenuManager();
+        mgr.add(groupByAction);
+        mgr.add(new Separator());
+        mgr.add(filterAction);
+        mgr.add(new Separator());
+        mgr.add(activateViewAction);
+        mgr.add(showTextFilter);
+
+        addManagerListeners();
+
+        if (sortCandidate == ORDER_BY_TIME) {
+            sortByTimeAction.run();
+        } else if (sortCandidate == ORDER_BY_SEVERITY) {
+            sortBySeverityAction.run();
+        } else { // order_selected == ORDER_BY_NONE
+            sortByMessageAction.run();
+        }
+
+    }
+
+    private void setupFilteredTree() {
+        tree.setLayoutData(new GridData(GridData.FILL_BOTH));
+        final Tree innerTree = tree.getViewer().getTree();
+        innerTree.setLinesVisible(true);
+
+        severityColumn = new TreeColumn(innerTree, SWT.LEFT);
+        severityColumn.setText("Severity");
+        severityColumn.setWidth(110);
+        severityColumn.addSelectionListener(new SelectionAdapter() {
+
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                sortBySeverityAction.run();
+            }
+        });
+        dateColumn = new TreeColumn(innerTree, SWT.LEFT);
+        dateColumn.setText("Time");
+        dateColumn.setWidth(110);
+        dateColumn.addSelectionListener(new SelectionAdapter() {
+
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                sortByTimeAction.run();
+            }
+        });
+        messageColumn = new TreeColumn(innerTree, SWT.LEFT);
+        messageColumn.setText("Message");
+        messageColumn.setWidth(180);
+        messageColumn.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                sortByMessageAction.run();
+            }
+        });
+
+        innerTree.setHeaderVisible(true);
+
+        treeContentProvider = new LogContentProvider();
+
+        tree.getViewer().setContentProvider(treeContentProvider);
+        tree.getViewer().setLabelProvider(new LogLabelProvider());
+
+        tree.getViewer().setInput(logManager.getLogEntries());
+
+        tree.getViewer().addSelectionChangedListener(
+                new ISelectionChangedListener() {
+
+                    @Override
+                    public void selectionChanged(SelectionChangedEvent event) {
+                        deleteLogAction.setEnabled(!tree.getViewer()
+                                .getSelection().isEmpty());
+                        logDetailsAction.setEnabled(!tree.getViewer()
+                                .getSelection().isEmpty());
+                    }
+                });
+
+        tree.getViewer().getTree().addKeyListener(new KeyListener() {
+
+            @Override
+            public void keyReleased(KeyEvent e) {
+            }
+
+            @Override
+            public void keyPressed(KeyEvent e) {
+                if (e.character == (char) 127) { // If delete key is pressed
+                    if (deleteLogAction.isEnabled()) {
+                        deleteLogAction.run();
+                    }
+                }
+            }
+        });
+
+        tree.getViewer().addDoubleClickListener(new IDoubleClickListener() {
+
+            @Override
+            public void doubleClick(DoubleClickEvent event) {
+                logDetailsAction.run();
+            }
+        });
+    }
+
+    private void createColumnComparators() {
+        dateComparator = new ViewerComparator() {
+
+            @Override
+            public int compare(Viewer viewer, Object e1, Object e2) {
+                LogEntry l1 = (LogEntry) e1;
+                LogEntry l2 = (LogEntry) e2;
+                return l1.getDate().compareTo(l2.getDate()) * sortDirection;
+            }
+        };
+
+        severityComparator = new ViewerComparator() {
+
+            @Override
+            public int compare(Viewer viewer, Object e1, Object e2) {
+                LogEntry l1 = (LogEntry) e1;
+                LogEntry l2 = (LogEntry) e2;
+                if (l1.getSeverity() < l2.getSeverity()) {
+                    return -1 * sortDirection;
+                }
+                if (l1.getSeverity() > l2.getSeverity()) {
+                    return 1 * sortDirection;
+                }
+                return 0;
+            }
+        };
+
+        messageComparator = new ViewerComparator() {
+
+            @Override
+            public int compare(Viewer viewer, Object e1, Object e2) {
+                LogEntry l1 = (LogEntry) e1;
+                LogEntry l2 = (LogEntry) e2;
+                return l1.getMessage().compareTo(l2.getMessage())
+                        * sortDirection;
+            }
+        };
+
+    }
+
+    private void setDefaultShownSeverities() {
+        shownSeverities.put(Level.INFO.ordinal(), true);
+        shownSeverities.put(Level.DEBUG.ordinal(), true);
+        shownSeverities.put(Level.WARNING.ordinal(), true);
+        shownSeverities.put(Level.ERROR.ordinal(), true);
+    }
+
+    private void addManagerListeners() {
+        logManager.addLogListener(logListener);
+        logManager.applyFilter(shownSeverities);
+    }
+
+    private void createActions() {
+        exportLogAction = createExportLogAction();
+        clearLogAction = createClearLogAction();
+        deleteLogAction = createDeleteLogAction();
+        scrollLockAction = createScrollLockAction();
+        logDetailsAction = createLogDetailsAction();
+
+        filterAction = createFilterAction();
+        activateViewAction = createActivateViewAction();
+        showTextFilter = createShowTextFilter();
+        groupByAction = createGroupByAction();
+    }
+
+    private IAction createExportLogAction() {
+        Action action = new Action("Export log") {
+            @Override
+            public void run() {
+                FileDialog fd = new FileDialog(Display.getDefault()
+                        .getActiveShell(), SWT.SAVE);
+                fd.setOverwrite(true);
+                fd.setFileName("OIC_Simulator_ServerLog.log");
+                fd.setFilterExtensions(Constants.SAVE_LOG_FILTER_EXTENSIONS);
+                String name = fd.open();
+                List<LogEntry> logEntries = logManager.getLogEntries();
+                StringBuilder sb = new StringBuilder();
+                for (LogEntry entry : logEntries) {
+                    sb.append(entry.toString());
+                }
+                String data = sb.toString();
+                BufferedWriter out = null;
+                try {
+                    out = new BufferedWriter(new FileWriter(name));
+                    out.write(data);
+                } catch (IOException e) {
+                    e.printStackTrace();
+                    MessageDialog.openError(
+                            Display.getDefault().getActiveShell(),
+                            "Export error",
+                            "Could not export log. IO exception: "
+                                    + e.getMessage());
+                } finally {
+                    try {
+                        if (null != out) {
+                            out.close();
+                        }
+                    } catch (IOException e) {
+                        System.out.println("Error occurred during close.");
+                    }
+                }
+            }
+        };
+        action.setToolTipText("Export log");
+
+        action.setImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/export_log_e.gif"));
+        action.setDisabledImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/export_log_d.gif"));
+        action.setEnabled(true);
+
+        return action;
+    }
+
+    private IAction createClearLogAction() {
+        Action action = new Action("Clear log") {
+
+            @Override
+            public void run() {
+                logManager.clearLog();
+            }
+        };
+        action.setToolTipText("Clear log");
+
+        action.setImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/clear_e.gif"));
+        action.setDisabledImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/clear_d.gif"));
+        action.setEnabled(true);
+        return action;
+    }
+
+    private IAction createDeleteLogAction() {
+        Action action = new Action("Delete log entry") {
+
+            @Override
+            @SuppressWarnings("unchecked")
+            public void run() {
+                IStructuredSelection selection = (IStructuredSelection) tree
+                        .getViewer().getSelection();
+                List<LogEntry> entries = (List<LogEntry>) tree.getViewer()
+                        .getInput();
+                LogEntry selectedEntry = (LogEntry) selection.getFirstElement();
+                if (null != selectedEntry) {
+                    LogEntry toBeShownEntry = null;
+                    for (LogEntry entry : entries) {
+                        if (entry.equals(selectedEntry)) {
+                            int size = entries.size();
+                            int index = entries.indexOf(selectedEntry);
+                            if (index + 1 < size) {
+                                toBeShownEntry = entries.get(index + 1);
+                            } else if (index > 0) {
+                                toBeShownEntry = entries.get(index - 1);
+                            }
+                            break;
+                        }
+                    }
+                    logManager.removeEntry(selectedEntry);
+                    if (null != toBeShownEntry) {
+                        tree.getViewer().setSelection(
+                                new StructuredSelection(toBeShownEntry));
+                    }
+                }
+            }
+        };
+        action.setToolTipText("Delete log entry");
+        action.setImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/delete_e.gif"));
+        action.setDisabledImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/delete_d.gif"));
+        action.setEnabled(false);
+        return action;
+    }
+
+    private IAction createScrollLockAction() {
+        Action action = new Action("Scroll lock") {
+
+            @Override
+            public void run() {
+                scrollLockDisabled = !this.isChecked();
+            };
+
+            @Override
+            public int getStyle() {
+                return IAction.AS_CHECK_BOX;
+            }
+        };
+        action.setToolTipText("Scroll lock");
+        action.setImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/lock_e.gif"));
+        action.setDisabledImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/lock_d.gif"));
+        action.setEnabled(true);
+        return action;
+    }
+
+    private IAction createLogDetailsAction() {
+        Action action = new Action("Details...") {
+
+            @Override
+            public void run() {
+                Display.getDefault().asyncExec(new Runnable() {
+
+                    @Override
+                    public void run() {
+                        LogEntry x = (LogEntry) ((IStructuredSelection) tree
+                                .getViewer().getSelection()).getFirstElement();
+
+                        new LogDetailsDialog(Display.getDefault()
+                                .getActiveShell(), LogManager.getSeverityName(x
+                                .getSeverity()), LogManager.getSeverityIcon(x
+                                .getSeverity()), x.getDate(), x.getMessage())
+                                .open();
+                    }
+                });
+            }
+        };
+        action.setToolTipText("Details...");
+        action.setImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/log_details_e.gif"));
+        action.setDisabledImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/log_details_e.gif"));
+        action.setEnabled(false);
+        return action;
+    }
+
+    private IAction createFilterAction() {
+        Action action = new Action("Filters ...") {
+
+            @Override
+            public void run() {
+                FilterDialog fd = new FilterDialog(Display.getDefault()
+                        .getActiveShell(), shownSeverities);
+                if (fd.open() == Window.OK) {
+                    logManager.applyFilter(shownSeverities);
+                }
+                tree.getViewer().refresh();
+            }
+        };
+        action.setToolTipText("Filters ...");
+
+        action.setImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/filter_e.gif"));
+        action.setDisabledImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/filter_d.gif"));
+        action.setEnabled(true);
+        return action;
+    }
+
+    private IAction createActivateViewAction() {
+        Action action = new Action("Activate view on new events",
+                IAction.AS_CHECK_BOX) {
+
+            @Override
+            public void run() {
+                activateOnChange = this.isChecked();
+            }
+        };
+        action.setChecked(activateOnChange);
+        action.setToolTipText("Activate view on new events");
+
+        action.setImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/prop_e.gif"));
+        action.setDisabledImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/prop_d.gif"));
+        action.setEnabled(true);
+        return action;
+    }
+
+    private IAction createShowTextFilter() {
+        Action action = new Action("Show text filter", IAction.AS_CHECK_BOX) {
+
+            @Override
+            public void run() {
+                Text filterControl = tree.getFilterControl();
+                Composite filterComposite = filterControl.getParent();
+                GridData gd = (GridData) filterComposite.getLayoutData();
+                boolean visible = isChecked();
+                gd.exclude = !visible;
+                filterComposite.setVisible(visible);
+                filterControl.setText("");
+                if (visible) {
+                    filterControl.selectAll();
+                    setFocus();
+                }
+                tree.layout(false);
+                hideTextFilter = !visible;
+            }
+        };
+        action.setToolTipText("Show text filter");
+
+        action.setImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/tree_mode_e.gif"));
+        action.setDisabledImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/tree_mode_d.gif"));
+        action.setEnabled(true);
+        action.setChecked(!hideTextFilter);
+        if (hideTextFilter) {
+            action.run();
+        }
+        return action;
+    }
+
+    private IContributionItem createGroupByAction() {
+        IMenuManager manager = new MenuManager("Order by");
+        manager.add(sortByTimeAction);
+        manager.add(sortBySeverityAction);
+        manager.add(sortByMessageAction);
+        return manager;
+    }
+
+    class SortAction extends Action {
+
+        private final int sortBy;
+
+        public SortAction(String text, int sortBy) {
+            super(text, IAction.AS_RADIO_BUTTON);
+            this.sortBy = sortBy;
+
+            if (sortCandidate == sortBy) {
+                setChecked(true);
+            }
+        }
+
+        @Override
+        public void run() {
+            sortBySeverityAction.setChecked(false);
+            sortByTimeAction.setChecked(false);
+            sortCandidate = sortBy;
+            setChecked(true);
+
+            ViewerComparator comparator;
+            TreeColumn column;
+            if (sortBy == ORDER_BY_SEVERITY) {
+                comparator = severityComparator;
+                column = severityColumn;
+            } else if (sortBy == ORDER_BY_TIME) {
+                comparator = dateComparator;
+                column = dateColumn;
+            } else { // Order by message
+                comparator = messageComparator;
+                column = messageColumn;
+            }
+            TreeViewer viewer = tree.getViewer();
+            viewer.setComparator(comparator);
+            viewer.getTree().setSortColumn(column);
+            if (column.equals(sortColumn)) { // reverse sorting order
+                sortDirection = viewer.getTree().getSortDirection() == SWT.UP ? DOWN
+                        : UP;
+                viewer.getTree().setSortDirection(
+                        sortDirection == UP ? SWT.UP : SWT.DOWN);
+                viewer.refresh();
+            } else { // set this column as the one to sort by
+                sortDirection = DOWN;
+                viewer.getTree().setSortDirection(SWT.DOWN);
+            }
+            sortColumn = column;
+            refresh();
+        }
+    }
+
+    private void refresh() {
+        tree.getViewer().refresh();
+    }
+
+    @Override
+    public void setFocus() {
+        tree.setFocus();
+    }
+
+    @Override
+    public void dispose() {
+        logManager.removeLogListener(logListener);
+        super.dispose();
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/MetaPropertiesView.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/MetaPropertiesView.java
new file mode 100644 (file)
index 0000000..8f8ff18
--- /dev/null
@@ -0,0 +1,204 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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.listener.IResourceSelectionChangedUIListener;
+import oic.simulator.serviceprovider.manager.ResourceManager;
+import oic.simulator.serviceprovider.resource.MetaProperty;
+import oic.simulator.serviceprovider.resource.SimulatorResource;
+
+import org.eclipse.jface.viewers.ColumnLabelProvider;
+import org.eclipse.jface.viewers.IStructuredContentProvider;
+import org.eclipse.jface.viewers.TableViewer;
+import org.eclipse.jface.viewers.TableViewerColumn;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.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.Table;
+import org.eclipse.ui.part.ViewPart;
+
+/**
+ * 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";
+
+    private TableViewer                         tableViewer;
+
+    private final String[]                      columnHeaders = { "Property",
+            "Value"                                          };
+
+    private final Integer[]                     columnWidth   = { 150, 150 };
+
+    private IResourceSelectionChangedUIListener resourceSelectionChangedListener;
+
+    private ResourceManager                     resourceManagerRef;
+
+    public MetaPropertiesView() {
+
+        resourceManagerRef = Activator.getDefault().getResourceManager();
+
+        resourceSelectionChangedListener = new IResourceSelectionChangedUIListener() {
+
+            @Override
+            public void onResourceSelectionChange() {
+                Display.getDefault().asyncExec(new Runnable() {
+
+                    @Override
+                    public void run() {
+                        if (null != tableViewer) {
+                            updateViewer(getData());
+                        }
+                    }
+                });
+            }
+        };
+    }
+
+    @Override
+    public void createPartControl(Composite parent) {
+        parent.setLayout(new GridLayout(1, false));
+
+        tableViewer = new TableViewer(parent, SWT.SINGLE | SWT.H_SCROLL
+                | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER);
+
+        createColumns(tableViewer);
+
+        // Make lines and header visible
+        final Table table = tableViewer.getTable();
+        table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+        table.setHeaderVisible(true);
+        table.setLinesVisible(true);
+
+        tableViewer.setContentProvider(new PropertycontentProvider());
+
+        addManagerListeners();
+
+        // Check whether there is any resource selected already
+        List<MetaProperty> propertyList = getData();
+        if (null != propertyList) {
+            updateViewer(propertyList);
+        }
+
+    }
+
+    private List<MetaProperty> getData() {
+        SimulatorResource resourceInSelection = resourceManagerRef
+                .getCurrentResourceInSelection();
+        if (null != resourceInSelection) {
+            List<MetaProperty> metaPropertyList = resourceManagerRef
+                    .getMetaProperties(resourceInSelection);
+            return metaPropertyList;
+        } else {
+            return null;
+        }
+    }
+
+    private void updateViewer(List<MetaProperty> metaPropertyList) {
+        if (null != tableViewer) {
+            Table tbl = tableViewer.getTable();
+            if (null != metaPropertyList) {
+                tableViewer.setInput(metaPropertyList.toArray());
+                if (!tbl.isDisposed()) {
+                    tbl.setLinesVisible(true);
+                }
+            } else {
+                if (!tbl.isDisposed()) {
+                    tbl.removeAll();
+                    tbl.setLinesVisible(false);
+                }
+            }
+        }
+    }
+
+    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 ColumnLabelProvider() {
+            @Override
+            public String getText(Object element) {
+                MetaProperty prop = (MetaProperty) element;
+                if (null != prop) {
+                    return prop.getPropName();
+                } else {
+                    return "";
+                }
+            }
+        });
+
+        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 "";
+                }
+            }
+        });
+    }
+
+    private void addManagerListeners() {
+        resourceManagerRef
+                .addResourceSelectionChangedUIListener(resourceSelectionChangedListener);
+    }
+
+    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;
+        }
+
+    }
+
+    @Override
+    public void dispose() {
+        // Unregister the listener
+        if (null != resourceSelectionChangedListener) {
+            resourceManagerRef
+                    .removeResourceSelectionChangedUIListener(resourceSelectionChangedListener);
+        }
+        super.dispose();
+    }
+
+    @Override
+    public void setFocus() {
+    }
+}
\ No newline at end of file
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
new file mode 100644 (file)
index 0000000..ac26bb0
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+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
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/ResourceManagerView.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/ResourceManagerView.java
new file mode 100644 (file)
index 0000000..fb56e5c
--- /dev/null
@@ -0,0 +1,435 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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.ArrayList;
+import java.util.List;
+
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.listener.IResourceListChangedUIListener;
+import oic.simulator.serviceprovider.manager.ResourceManager;
+import oic.simulator.serviceprovider.resource.DeleteCategory;
+import oic.simulator.serviceprovider.utils.Constants;
+import oic.simulator.serviceprovider.utils.Utility;
+import oic.simulator.serviceprovider.view.dialogs.CreateResourceWizard;
+import oic.simulator.serviceprovider.view.dialogs.DeleteResourceWizard;
+import oic.simulator.serviceprovider.view.dialogs.ResourceWizardDialog;
+
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.viewers.ITreeContentProvider;
+import org.eclipse.jface.viewers.LabelProvider;
+import org.eclipse.jface.viewers.TreeViewer;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.jface.wizard.WizardDialog;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.MenuAdapter;
+import org.eclipse.swt.events.MenuEvent;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.graphics.Color;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.layout.GridData;
+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.Menu;
+import org.eclipse.swt.widgets.MenuItem;
+import org.eclipse.swt.widgets.Tree;
+import org.eclipse.swt.widgets.TreeItem;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.dialogs.FilteredTree;
+import org.eclipse.ui.dialogs.PatternFilter;
+import org.eclipse.ui.part.ViewPart;
+
+/**
+ * This class manages and shows the resource manager view in the perspective.
+ */
+public class ResourceManagerView extends ViewPart {
+
+    public static final String             VIEW_ID = "oic.simulator.serviceprovider.view.resourcemanager";
+
+    private Button                         createButton;
+    private Button                         deleteButton;
+
+    private TreeViewer                     treeViewer;
+
+    private IResourceListChangedUIListener resourceListChangedListener;
+
+    private ResourceManager                resourceManager;
+
+    public ResourceManagerView() {
+
+        resourceManager = Activator.getDefault().getResourceManager();
+
+        resourceListChangedListener = new IResourceListChangedUIListener() {
+
+            @Override
+            public void onResourceCreation() {
+                Display.getDefault().asyncExec(new Runnable() {
+
+                    @Override
+                    public void run() {
+                        if (null != treeViewer) {
+                            treeViewer.refresh();
+                        }
+
+                        // Trigger the visibility of delete button
+                        changeDeleteVisibility();
+                    }
+                });
+            }
+
+            @Override
+            public void onResourceDeletion() {
+                Display.getDefault().asyncExec(new Runnable() {
+
+                    @Override
+                    public void run() {
+                        if (null != treeViewer) {
+                            treeViewer.refresh();
+                        }
+
+                        // Trigger the visibility of delete button
+                        changeDeleteVisibility();
+                    }
+                });
+            }
+        };
+    }
+
+    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;
+        }
+        if (null != deleteButton && !deleteButton.isDisposed()) {
+            deleteButton.setEnabled(visibility);
+        }
+    }
+
+    @Override
+    public void createPartControl(Composite parent) {
+        Composite compContent = new Composite(parent, SWT.NONE);
+        GridLayout baseLayout = new GridLayout(1, false);
+        compContent.setLayout(baseLayout);
+
+        GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        compContent.setLayoutData(gd);
+
+        Composite buttonComp = new Composite(compContent, SWT.NONE);
+        buttonComp.setLayout(new GridLayout(2, false));
+
+        gd = new GridData();
+        gd.horizontalAlignment = SWT.FILL;
+        gd.grabExcessHorizontalSpace = true;
+
+        buttonComp.setLayoutData(gd);
+
+        createButton = new Button(buttonComp, SWT.PUSH);
+        createButton.setText("Create");
+        createButton.setToolTipText("Create Simulator Resource(s)");
+
+        gd = new GridData();
+        gd.widthHint = 90;
+        createButton.setLayoutData(gd);
+
+        deleteButton = new Button(buttonComp, SWT.PUSH);
+        deleteButton.setText("Delete");
+        deleteButton.setToolTipText("Delete Simulator Resource(s)");
+
+        gd = new GridData();
+        gd.widthHint = 90;
+        deleteButton.setLayoutData(gd);
+
+        Group resourceGroup = new Group(compContent, SWT.NONE);
+        resourceGroup.setText("Created Resources");
+
+        Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE);
+        resourceGroup.setBackground(color);
+
+        resourceGroup.setLayout(new GridLayout(1, false));
+        gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        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(
+                new GridData(SWT.FILL, SWT.FILL, true, true));
+        treeViewer.setContentProvider(new TreeContentProvider());
+        treeViewer.setLabelProvider(new TreeLabelProvider());
+        treeViewer.setInput(new Object());
+
+        addUIListeners();
+
+        addManagerListeners();
+
+        // If there is at least one resource exist, then enable the delete
+        // resource button
+        changeDeleteVisibility();
+    }
+
+    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);
+                        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);
+                                }
+                            }
+                        }
+                    }
+                });
+            }
+        });
+
+        deleteButton.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {
+
+                    @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 completeURI = Utility
+                                            .isUriComplete(uri);
+                                    if (!completeURI) {
+                                        uri = Utility.displayNameToUri(uri);
+                                    }
+                                    resourceManager.deleteResourceByURI(uri);
+                                }
+                            } else if (deleteCategory == DeleteCategory.BY_TYPE) {
+                                resourceManager
+                                        .deleteResourceByType(deleteWizard
+                                                .getDeleteCandidate());
+                            } else if (deleteCategory == DeleteCategory.ALL) {
+                                resourceManager.deleteAllResources();
+                            }
+                        }
+                    }
+                });
+            }
+        });
+
+        if (null != treeViewer) {
+            final Tree resourceTreeHead = treeViewer.getTree();
+            if (null != resourceTreeHead) {
+                // Below code adds a listener to the tree for selection changes
+                // and notifies the resource manager
+                resourceTreeHead.addSelectionListener(new SelectionAdapter() {
+                    @Override
+                    public void widgetSelected(SelectionEvent e) {
+                        TreeItem selectedItem = (TreeItem) e.item;
+                        if (null != selectedItem) {
+                            String selectedItemText = selectedItem.getText();
+                            selectedItemText = Utility
+                                    .displayNameToUri(selectedItemText);
+                            // Propagate this selection change event to manager
+                            resourceManager
+                                    .resourceSelectionChanged(selectedItemText);
+                        }
+                    }
+                });
+                // Below code creates menu entries and shows them on right
+                // clicking a resource
+                final Menu menu = new Menu(resourceTreeHead);
+                resourceTreeHead.setMenu(menu);
+                menu.addMenuListener(new MenuAdapter() {
+                    @Override
+                    public void menuShown(MenuEvent e) {
+                        // Clear existing menu items
+                        MenuItem[] items = menu.getItems();
+                        for (int index = 0; index < items.length; index++) {
+                            items[index].dispose();
+                        }
+                        final String selectedItem = resourceTreeHead
+                                .getSelection()[0].getText();
+                        MenuItem startItem = new MenuItem(menu, SWT.NONE);
+                        startItem.setText(Constants.START_RESOURCE_AUTOMATION);
+                        startItem.addSelectionListener(new SelectionAdapter() {
+                            @Override
+                            public void widgetSelected(SelectionEvent e) {
+                                // Block starting resource level
+                                // automation if any attribute level
+                                // automation is in progress for the
+                                // selected resource
+                                boolean started = resourceManager.isAttributeAutomationStarted(Utility
+                                        .displayNameToUri(selectedItem));
+                                if (started) {
+                                    MessageDialog
+                                            .openInformation(
+                                                    Display.getDefault()
+                                                            .getActiveShell(),
+                                                    "Attribute automation is in progress",
+                                                    "Attribute level automation for this resource is already in progress!!!\nPlease stop all "
+                                                            + "running attribute level automations to start resource level automation.");
+                                } else {
+                                    boolean status = resourceManager
+                                            .startResourceAutomationUIRequest(Utility
+                                                    .displayNameToUri(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(Utility
+                                                .displayNameToUri(selectedItem));
+                                String statusMsg = status ? "Automation stop requested!!!"
+                                        : "Automation stop failed.";
+                                MessageDialog.openInformation(Display
+                                        .getDefault().getActiveShell(),
+                                        "Automation Status", statusMsg);
+                            }
+                        });
+
+                        // Set the initial visibility of menu items
+                        boolean status = resourceManager
+                                .isResourceAutomationStarted(Utility
+                                        .displayNameToUri(selectedItem));
+                        startItem.setEnabled(!status);
+                        stopItem.setEnabled(status);
+                    }
+                });
+            }
+        }
+    }
+
+    public void addManagerListeners() {
+        resourceManager
+                .addResourceListChangedUIListener(resourceListChangedListener);
+    }
+
+    @Override
+    public void setFocus() {
+    }
+
+    @Override
+    public void dispose() {
+        // Unregister the listener
+        if (null != resourceListChangedListener) {
+            resourceManager
+                    .removeResourceListChangedUIListener(resourceListChangedListener);
+            resourceManager.resourceSelectionChanged(null);
+        }
+        super.dispose();
+    }
+}
+
+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<String> uriList;
+        uriList = Activator.getDefault().getResourceManager().getURIList();
+        if (null == uriList) {
+            uriList = new ArrayList<String>();
+        }
+        return uriList.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) {
+        String value = (String) element;
+        value = Utility.uriToDisplayName(value);
+        return value;
+    }
+
+    @Override
+    public Image getImage(Object element) {
+        ResourceManager resourceManager = Activator.getDefault()
+                .getResourceManager();
+        return resourceManager.getImage((String) element);
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/ResourceObserverView.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/ResourceObserverView.java
new file mode 100644 (file)
index 0000000..5e9361f
--- /dev/null
@@ -0,0 +1,336 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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.Iterator;
+import java.util.Map;
+import java.util.Set;
+
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.listener.IObserverListChangedUIListener;
+import oic.simulator.serviceprovider.listener.IResourceSelectionChangedUIListener;
+import oic.simulator.serviceprovider.manager.ResourceManager;
+import oic.simulator.serviceprovider.resource.ObserverDetail;
+import oic.simulator.serviceprovider.resource.SimulatorResource;
+import oic.simulator.serviceprovider.utils.Constants;
+
+import org.eclipse.jface.viewers.CellEditor;
+import org.eclipse.jface.viewers.CheckboxCellEditor;
+import org.eclipse.jface.viewers.ColumnLabelProvider;
+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.Viewer;
+import org.eclipse.jface.viewers.ViewerCell;
+import org.eclipse.swt.SWT;
+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.Table;
+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";
+
+    private TableViewer                         tblViewer;
+
+    private final String[]                      columnHeaders = {
+            "Client Address", "Port", "Notify"               };
+
+    private final Integer[]                     columnWidth   = { 150, 75, 50 };
+
+    private IResourceSelectionChangedUIListener resourceSelectionChangedListener;
+
+    private IObserverListChangedUIListener      resourceObserverListChangedListener;
+
+    private ResourceManager                     resourceManagerRef;
+
+    public ResourceObserverView() {
+
+        resourceManagerRef = Activator.getDefault().getResourceManager();
+
+        resourceSelectionChangedListener = new IResourceSelectionChangedUIListener() {
+
+            @Override
+            public void onResourceSelectionChange() {
+                Display.getDefault().asyncExec(new Runnable() {
+
+                    @Override
+                    public void run() {
+                        if (null != tblViewer) {
+                            changeButtonStatus();
+                            updateViewer(getData(resourceManagerRef
+                                    .getCurrentResourceInSelection()));
+                        }
+                    }
+                });
+            }
+        };
+
+        resourceObserverListChangedListener = new IObserverListChangedUIListener() {
+
+            @Override
+            public void onObserverListChanged(final String resourceURI) {
+                Display.getDefault().asyncExec(new Runnable() {
+
+                    @Override
+                    public void run() {
+                        if (null == resourceURI) {
+                            return;
+                        }
+                        SimulatorResource resource = resourceManagerRef
+                                .getCurrentResourceInSelection();
+                        if (null == resource) {
+                            return;
+                        }
+                        if (resource.getResourceURI().equals(resourceURI)) {
+                            if (null != tblViewer) {
+                                updateViewer(getData(resource));
+                            }
+                        }
+                    }
+                });
+
+            }
+        };
+    }
+
+    private Map<Integer, ObserverDetail> getData(SimulatorResource resource) {
+        if (null == resource) {
+            return null;
+        }
+        return resource.getObserver();
+    }
+
+    private void updateViewer(Map<Integer, ObserverDetail> observer) {
+        if (null != tblViewer) {
+            Table tbl = tblViewer.getTable();
+            if (null != observer && observer.size() > 0) {
+                tblViewer.setInput(observer.entrySet().toArray());
+                if (!tbl.isDisposed()) {
+                    tbl.setLinesVisible(true);
+                }
+            } else {
+                if (!tbl.isDisposed()) {
+                    tbl.removeAll();
+                    tbl.setLinesVisible(false);
+                }
+            }
+        }
+    }
+
+    @Override
+    public void createPartControl(Composite parent) {
+        parent.setLayout(new GridLayout(1, false));
+
+        tblViewer = new TableViewer(parent, SWT.SINGLE | SWT.H_SCROLL
+                | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER);
+
+        createColumns(tblViewer);
+
+        // make lines and header visible
+        final Table table = tblViewer.getTable();
+        table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+        table.setHeaderVisible(true);
+        table.setLinesVisible(true);
+
+        tblViewer.setContentProvider(new ObserverContentProvider());
+
+        addManagerListeners();
+
+        // Check whether there is any resource selected already
+        Map<Integer, ObserverDetail> observerList = getData(resourceManagerRef
+                .getCurrentResourceInSelection());
+        if (null != observerList) {
+            updateViewer(observerList);
+        }
+    }
+
+    public void createColumns(TableViewer tableViewer) {
+        TableViewerColumn addressColumn = new TableViewerColumn(tableViewer,
+                SWT.NONE);
+        addressColumn.getColumn().setWidth(columnWidth[0]);
+        addressColumn.getColumn().setText(columnHeaders[0]);
+        addressColumn.setLabelProvider(new StyledCellLabelProvider() {
+            @Override
+            public void update(ViewerCell cell) {
+                Object element = cell.getElement();
+                if (element instanceof Map.Entry) {
+                    @SuppressWarnings("unchecked")
+                    Map.Entry<Integer, ObserverDetail> observer = (Map.Entry<Integer, ObserverDetail>) element;
+                    cell.setText(observer.getValue().getObserverInfo()
+                            .getAddress());
+                }
+            }
+        });
+
+        TableViewerColumn portColumn = new TableViewerColumn(tableViewer,
+                SWT.NONE);
+        portColumn.getColumn().setWidth(columnWidth[1]);
+        portColumn.getColumn().setText(columnHeaders[1]);
+        portColumn.setLabelProvider(new StyledCellLabelProvider() {
+            @Override
+            public void update(ViewerCell cell) {
+                Object element = cell.getElement();
+                if (element instanceof Map.Entry) {
+                    @SuppressWarnings("unchecked")
+                    Map.Entry<Integer, ObserverDetail> observer = (Map.Entry<Integer, ObserverDetail>) element;
+                    cell.setText(String.valueOf(observer.getValue()
+                            .getObserverInfo().getPort()));
+                }
+            }
+        });
+
+        TableViewerColumn notifyColumn = new TableViewerColumn(tableViewer,
+                SWT.NONE);
+        notifyColumn.getColumn().setWidth(columnWidth[2]);
+        notifyColumn.getColumn().setText(columnHeaders[2]);
+        notifyColumn.setLabelProvider(new ColumnLabelProvider() {
+
+            @Override
+            public String getText(Object element) {
+                return "";
+            }
+
+            @Override
+            public Image getImage(Object element) {
+                @SuppressWarnings("unchecked")
+                Map.Entry<Integer, ObserverDetail> observer = (Map.Entry<Integer, ObserverDetail>) element;
+                if (observer.getValue().isClicked()) {
+                    return Activator.getDefault().getImageRegistry()
+                            .get(Constants.NOTIFY_BUTTON_SELECTED);
+                }
+                return Activator.getDefault().getImageRegistry()
+                        .get(Constants.NOTIFY_BUTTON_UNSELECTED);
+            }
+        });
+        notifyColumn.setEditingSupport(new NotifyEditor(tableViewer));
+    }
+
+    private void addManagerListeners() {
+        resourceManagerRef
+                .addResourceSelectionChangedUIListener(resourceSelectionChangedListener);
+        resourceManagerRef
+                .addObserverListChangedUIListener(resourceObserverListChangedListener);
+    }
+
+    class ObserverContentProvider 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;
+        }
+
+    }
+
+    class NotifyEditor extends EditingSupport {
+
+        private final TableViewer viewer;
+
+        public NotifyEditor(TableViewer viewer) {
+            super(viewer);
+            this.viewer = viewer;
+        }
+
+        @Override
+        protected boolean canEdit(Object arg0) {
+            return true;
+        }
+
+        @Override
+        protected CellEditor getCellEditor(Object element) {
+            return new CheckboxCellEditor(null, SWT.CHECK | SWT.READ_ONLY);
+        }
+
+        @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();
+        }
+
+        @Override
+        protected void setValue(Object element, Object value) {
+            System.out.println("setValue()");
+            // Change the button status of all the resources
+            changeButtonStatus();
+
+            @SuppressWarnings("unchecked")
+            Map.Entry<Integer, ObserverDetail> observer = (Map.Entry<Integer, ObserverDetail>) element;
+            observer.getValue().setClicked(true);
+            viewer.refresh();
+
+            // Call Native Method
+            resourceManagerRef.notifyObserverRequest(
+                    resourceManagerRef.getCurrentResourceInSelection(),
+                    observer.getValue().getObserverInfo().getId());
+        }
+    }
+
+    private void changeButtonStatus() {
+        SimulatorResource resource = resourceManagerRef
+                .getCurrentResourceInSelection();
+        if (null == resource) {
+            return;
+        }
+        Map<Integer, ObserverDetail> observerMap = resource.getObserver();
+        if (null == observerMap) {
+            return;
+        }
+        Set<Integer> keySet = observerMap.keySet();
+        Iterator<Integer> itr = keySet.iterator();
+        while (itr.hasNext()) {
+            observerMap.get(itr.next()).setClicked(false);
+        }
+    }
+
+    @Override
+    public void dispose() {
+        // Unregister the listener
+        if (null != resourceSelectionChangedListener) {
+            resourceManagerRef
+                    .removeResourceSelectionChangedUIListener(resourceSelectionChangedListener);
+        }
+
+        if (null != resourceObserverListChangedListener) {
+            resourceManagerRef
+                    .removeObserverListChangedUIListener(resourceObserverListChangedListener);
+        }
+        super.dispose();
+    }
+
+    @Override
+    public void setFocus() {
+    }
+
+}
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/AutomationSettingDialog.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/AutomationSettingDialog.java
new file mode 100644 (file)
index 0000000..e2bb48f
--- /dev/null
@@ -0,0 +1,171 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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.List;
+
+import oic.simulator.serviceprovider.resource.AutomationSettingHelper;
+import oic.simulator.serviceprovider.utils.Constants;
+
+import org.eclipse.jface.dialogs.TitleAreaDialog;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.CCombo;
+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.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Shell;
+
+/**
+ * This class manages and shows the automation settings dialog from the
+ * attribute view.
+ */
+public class AutomationSettingDialog extends TitleAreaDialog {
+
+    private CCombo                        autoTypeCmb;
+    private CCombo                        updateFreqCmb;
+
+    private String                        automationType;
+    private String                        updateFrequencyInMillis;
+    private List<AutomationSettingHelper> automationSettings;
+
+    public AutomationSettingDialog(Shell parentShell,
+            List<AutomationSettingHelper> automationSettings) {
+        super(parentShell);
+        this.automationSettings = automationSettings;
+    }
+
+    @Override
+    public void create() {
+        super.create();
+        setTitle("Automation Settings");
+        setMessage("Fill the automation settings for the attribute");
+    }
+
+    @Override
+    protected Control createDialogArea(Composite parent) {
+        Composite compLayout = (Composite) super.createDialogArea(parent);
+        Composite container = new Composite(compLayout, SWT.NONE);
+        container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+        GridLayout layout = new GridLayout(2, false);
+        layout.verticalSpacing = 10;
+        layout.marginTop = 10;
+        container.setLayout(layout);
+
+        GridData gd;
+
+        Label autoTypeLbl = new Label(container, SWT.NONE);
+        autoTypeLbl.setText("Automation Type");
+
+        autoTypeCmb = new CCombo(container, SWT.READ_ONLY | SWT.BORDER);
+        gd = new GridData();
+        gd.horizontalAlignment = SWT.FILL;
+        gd.grabExcessHorizontalSpace = true;
+        autoTypeCmb.setLayoutData(gd);
+
+        Label updateFreqLbl = new Label(container, SWT.NONE);
+        updateFreqLbl.setText("Update Frequency(ms)");
+
+        updateFreqCmb = new CCombo(container, SWT.READ_ONLY | SWT.BORDER);
+        gd = new GridData();
+        gd.horizontalAlignment = SWT.FILL;
+        gd.grabExcessHorizontalSpace = true;
+        updateFreqCmb.setLayoutData(gd);
+
+        populateSettingsData();
+
+        addUIListeners();
+
+        setInitialSettings();
+
+        return compLayout;
+    }
+
+    public void populateSettingsData() {
+        Iterator<AutomationSettingHelper> settingItr = automationSettings
+                .iterator();
+        AutomationSettingHelper setting;
+        String settingId;
+        String value;
+        List<String> allowedValues;
+        Iterator<String> itr;
+        while (settingItr.hasNext()) {
+            setting = settingItr.next();
+            settingId = setting.getSettingID();
+            value = setting.getSettingValue();
+            allowedValues = setting.getAllowedValues();
+            if (settingId.equals(Constants.AUTOMATION_TYPE)) {
+                itr = allowedValues.iterator();
+                while (itr.hasNext()) {
+                    autoTypeCmb.add(itr.next());
+                }
+                // Select the default value
+                autoTypeCmb.select(autoTypeCmb.indexOf(value));
+            } else if (settingId.equals(Constants.UPDATE_INTERVAL_IN_MS)) {
+                itr = allowedValues.iterator();
+                while (itr.hasNext()) {
+                    updateFreqCmb.add(itr.next());
+                }
+                // Select the default value
+                updateFreqCmb.select(updateFreqCmb.indexOf(value));
+            }
+        }
+    }
+
+    public void addUIListeners() {
+        autoTypeCmb.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                automationType = autoTypeCmb.getText();
+            }
+        });
+
+        updateFreqCmb.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                updateFrequencyInMillis = updateFreqCmb.getText();
+            }
+        });
+    }
+
+    public void setInitialSettings() {
+        automationType = autoTypeCmb.getText();
+        updateFrequencyInMillis = updateFreqCmb.getText();
+    }
+
+    public String getAutomationType() {
+        return automationType;
+    }
+
+    public String getUpdateFrequency() {
+        return updateFrequencyInMillis;
+    }
+
+    @Override
+    protected boolean isResizable() {
+        return true;
+    }
+
+    @Override
+    public boolean isHelpAvailable() {
+        return false;
+    }
+}
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/CreateResourcePage.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/CreateResourcePage.java
new file mode 100644 (file)
index 0000000..dc44ad6
--- /dev/null
@@ -0,0 +1,331 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/CreateResourceWizard.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/CreateResourceWizard.java
new file mode 100644 (file)
index 0000000..5a11cc0
--- /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.
+ */
+
+package oic.simulator.serviceprovider.view.dialogs;
+
+import java.net.URL;
+
+import oic.simulator.serviceprovider.Activator;
+
+import org.eclipse.core.runtime.FileLocator;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.core.runtime.Path;
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.jface.wizard.Wizard;
+
+/**
+ * This class creates a UI wizard for create resource operation.
+ */
+public class CreateResourceWizard extends Wizard {
+
+    private CreateResourcePage page;
+
+    public CreateResourceWizard() {
+        setWindowTitle("Create resources");
+        IPath path = new Path("/icons/oic_logo_64x64.png");
+        URL find = FileLocator.find(Activator.getDefault().getBundle(), path,
+                null);
+        setDefaultPageImageDescriptor(ImageDescriptor.createFromURL(find));
+    }
+
+    @Override
+    public void addPages() {
+        page = new CreateResourcePage();
+        addPage(page);
+    }
+
+    public String getConfigFilePath() {
+        if (null == page) {
+            return null;
+        }
+        return page.getConfigFilePath();
+    }
+
+    public int getResourceCount() {
+        if (null == page) {
+            return 0;
+        }
+        return page.getResourceCount();
+    }
+
+    @Override
+    public boolean performFinish() {
+        return true;
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/DeleteResourcePage.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/DeleteResourcePage.java
new file mode 100644 (file)
index 0000000..a62f0ae
--- /dev/null
@@ -0,0 +1,237 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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.List;
+
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.resource.DeleteCategory;
+import oic.simulator.serviceprovider.utils.Constants;
+
+import org.eclipse.jface.wizard.WizardPage;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.CCombo;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.events.SelectionAdapter;
+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.Text;
+
+/**
+ * This class shows UI for deleting resources.
+ */
+public class DeleteResourcePage extends WizardPage {
+
+    private Button         allRbtn;
+    private Button         byTypeRbtn;
+    private Button         byUriRbtn;
+
+    private CCombo         resourceTypeCmb;
+    private Text           resourceUriTxt;
+
+    private DeleteCategory deleteCategory;
+
+    // It will hold either the resource type or resource uri
+    private String         deleteCandidate;
+
+    protected DeleteResourcePage() {
+        super("Delete Resource");
+    }
+
+    @Override
+    public void createControl(Composite parent) {
+        setPageComplete(false);
+        setTitle(Constants.DELETE_PAGE_TITLE);
+        setMessage(Constants.DELETE_PAGE_MESSAGE);
+
+        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);
+
+        allRbtn = new Button(group, SWT.RADIO);
+        allRbtn.setText("All resources");
+        gd = new GridData();
+        gd.horizontalSpan = 2;
+        gd.widthHint = 200;
+        allRbtn.setLayoutData(gd);
+
+        byTypeRbtn = new Button(group, SWT.RADIO);
+        byTypeRbtn.setText("All (By resource type)");
+        gd = new GridData();
+        gd.widthHint = 200;
+        byTypeRbtn.setLayoutData(gd);
+
+        resourceTypeCmb = new CCombo(group, SWT.READ_ONLY | SWT.BORDER);
+        gd = new GridData();
+        gd.widthHint = 200;
+        resourceTypeCmb.setLayoutData(gd);
+
+        byUriRbtn = new Button(group, SWT.RADIO);
+        byUriRbtn.setText("By Resource URI");
+        gd = new GridData();
+        gd.widthHint = 200;
+        byUriRbtn.setLayoutData(gd);
+
+        resourceUriTxt = new Text(group, SWT.BORDER);
+        gd = new GridData();
+        gd.widthHint = 300;
+        resourceUriTxt.setLayoutData(gd);
+
+        // Setting the initial visibility of controls
+        allRbtn.setSelection(false);
+        byTypeRbtn.setSelection(false);
+        byUriRbtn.setSelection(false);
+
+        resourceTypeCmb.setEnabled(false);
+        resourceUriTxt.setEnabled(false);
+
+        deleteCategory = DeleteCategory.NONE;
+
+        populateDataInUI();
+
+        addUIListeners();
+
+        setControl(compContent);
+    }
+
+    private void populateDataInUI() {
+        // Populate Resourcetype in Combo
+        populateResourceTypeCombo();
+    }
+
+    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());
+            }
+        }
+
+        // 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() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                // Update the visibility of controls
+                resourceTypeCmb.setEnabled(false);
+                resourceUriTxt.setEnabled(false);
+
+                deleteCategory = DeleteCategory.ALL;
+                deleteCandidate = null;
+                setPageComplete(isSelectionDone());
+            }
+        });
+
+        byTypeRbtn.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());
+            }
+        });
+
+        byUriRbtn.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());
+            }
+        });
+
+        resourceTypeCmb.addModifyListener(new ModifyListener() {
+            @Override
+            public void modifyText(ModifyEvent arg0) {
+                setPageComplete(isSelectionDone());
+            }
+        });
+
+        resourceUriTxt.addModifyListener(new ModifyListener() {
+            @Override
+            public void modifyText(ModifyEvent arg0) {
+                setPageComplete(isSelectionDone());
+            }
+        });
+    }
+
+    public boolean isSelectionDone() {
+        boolean done = false;
+        if (deleteCategory == DeleteCategory.ALL) {
+            done = true;
+        } else if (deleteCategory == DeleteCategory.BY_TYPE) {
+            int selectedItemIndex = resourceTypeCmb.getSelectionIndex();
+            if (selectedItemIndex >= 0) {
+                deleteCandidate = resourceTypeCmb.getItem(selectedItemIndex);
+                if (null != deleteCandidate && deleteCandidate.length() > 0) {
+                    done = true;
+                }
+            }
+        } else if (deleteCategory == DeleteCategory.BY_URI) {
+            deleteCandidate = resourceUriTxt.getText();
+            if (null != deleteCandidate && deleteCandidate.length() > 0) {
+                done = true;
+            }
+        }
+        return done;
+    }
+
+    public DeleteCategory getDeleteCategory() {
+        return deleteCategory;
+    }
+
+    public String getDeleteCandidate() {
+        return deleteCandidate;
+    }
+
+    public void setFocusToTextBox() {
+        resourceUriTxt.setFocus();
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/DeleteResourceWizard.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/DeleteResourceWizard.java
new file mode 100644 (file)
index 0000000..980b881
--- /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 oic.simulator.serviceprovider.view.dialogs;
+
+import java.net.URL;
+
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.resource.DeleteCategory;
+import oic.simulator.serviceprovider.utils.Utility;
+
+import org.eclipse.core.runtime.FileLocator;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.core.runtime.Path;
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.jface.wizard.Wizard;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.ui.PlatformUI;
+
+/**
+ * This class creates a UI wizard for delete resource operation.
+ */
+public class DeleteResourceWizard extends Wizard {
+
+    private DeleteResourcePage page;
+
+    public DeleteResourceWizard() {
+        setWindowTitle("Delete resources");
+        IPath path = new Path("/icons/oic_logo_64x64.png");
+        URL find = FileLocator.find(Activator.getDefault().getBundle(), path,
+                null);
+        setDefaultPageImageDescriptor(ImageDescriptor.createFromURL(find));
+    }
+
+    @Override
+    public void addPages() {
+        page = new DeleteResourcePage();
+        addPage(page);
+    }
+
+    @Override
+    public boolean performFinish() {
+        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 uriComplete = Utility.isUriComplete(uri);
+            if (!uriComplete) {
+                uri = Utility.displayNameToUri(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;
+    }
+
+    public DeleteCategory getDeleteCategory() {
+        if (null == page) {
+            return DeleteCategory.NONE;
+        }
+        return page.getDeleteCategory();
+    }
+
+    public String getDeleteCandidate() {
+        if (null == page) {
+            return null;
+        }
+        return page.getDeleteCandidate();
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/FilterDialog.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/FilterDialog.java
new file mode 100644 (file)
index 0000000..b43d4cc
--- /dev/null
@@ -0,0 +1,94 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package oic.simulator.serviceprovider.view.dialogs;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Map;
+
+import oic.simulator.serviceprovider.manager.LogManager;
+
+import org.eclipse.jface.dialogs.TrayDialog;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.SelectionAdapter;
+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.Control;
+import org.eclipse.swt.widgets.Group;
+import org.eclipse.swt.widgets.Shell;
+
+/**
+ * This class shows a dialog for filtering logs based on severity levels.
+ */
+public class FilterDialog extends TrayDialog {
+    private Map<Integer, Boolean> severities;
+
+    public FilterDialog(Shell shell, Map<Integer, Boolean> severities) {
+        super(shell);
+        this.severities = severities;
+    }
+
+    @Override
+    protected void configureShell(Shell shell) {
+        super.configureShell(shell);
+    }
+
+    @Override
+    protected Control createDialogArea(Composite parent) {
+        Composite composite = (Composite) super.createDialogArea(parent);
+        createSeverityGroup(composite);
+        getShell().setText("Filter details");
+        return composite;
+    }
+
+    /**
+     * Dynamically creates a check-box list for severity levels for user to
+     * choose from
+     */
+    private void createSeverityGroup(Composite parent) {
+        Group group = new Group(parent, SWT.NONE);
+        group.setLayout(new GridLayout());
+        GridData gd = new GridData(GridData.FILL_HORIZONTAL);
+        gd.widthHint = 275;
+        group.setLayoutData(gd);
+        group.setText("Severity Levels");
+
+        ArrayList<Integer> arrayList = new ArrayList<Integer>(
+                severities.keySet());
+        Collections.sort(arrayList);
+        for (final Integer i : arrayList) {
+            final Button checkbox = new Button(group, SWT.CHECK);
+            checkbox.setText(LogManager.getSeverityName(i));
+            checkbox.setSelection(severities.get(i));
+            checkbox.addSelectionListener(new SelectionAdapter() {
+
+                @Override
+                public void widgetSelected(SelectionEvent e) {
+                    severities.put(i, checkbox.getSelection());
+                }
+            });
+        }
+    }
+
+    @Override
+    public boolean isHelpAvailable() {
+        return false;
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/LogDetailsDialog.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/LogDetailsDialog.java
new file mode 100644 (file)
index 0000000..81c1f6a
--- /dev/null
@@ -0,0 +1,143 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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.text.DateFormat;
+import java.util.Date;
+
+import org.eclipse.jface.dialogs.Dialog;
+import org.eclipse.jface.dialogs.IDialogConstants;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.layout.RowData;
+import org.eclipse.swt.layout.RowLayout;
+import org.eclipse.swt.widgets.Button;
+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 detailed information about a log. The dialog will be opened
+ * on double-clicking a log entry in the log view.
+ */
+public class LogDetailsDialog extends Dialog {
+    private final String severity;
+    private final Date   date;
+    private final String message;
+    private final Image  severityIcon;
+
+    public LogDetailsDialog(Shell parentShell, String severity,
+            Image severityIcon, Date date, String message) {
+        super(parentShell);
+        this.severity = severity;
+        this.severityIcon = severityIcon;
+        this.message = message;
+        this.date = date;
+    }
+
+    @Override
+    protected boolean isResizable() {
+        return true;
+    }
+
+    @Override
+    protected void configureShell(Shell shell) {
+        super.configureShell(shell);
+    }
+
+    @Override
+    protected Control createDialogArea(Composite parent) {
+        getShell().setText("Logged event details");
+
+        Composite container = (Composite) super.createDialogArea(parent);
+
+        GridData layoutData = new GridData(SWT.FILL, SWT.FILL, true, true);
+        container.setLayoutData(layoutData);
+        container.setLayout(new GridLayout(2, false));
+
+        GridData gd;
+
+        Label l1 = new Label(container, SWT.NONE);
+        l1.setText("Severity:");
+        gd = new GridData();
+        gd.widthHint = 100;
+        l1.setLayoutData(gd);
+
+        Composite y = new Composite(container, SWT.NONE);
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        y.setLayoutData(gd);
+        y.setLayout(new RowLayout(SWT.HORIZONTAL));
+
+        Label l2 = new Label(y, SWT.NONE);
+        l2.setImage(severityIcon);
+        l2.setLayoutData(new RowData());
+        Label l3 = new Label(y, SWT.NONE);
+        l3.setText(severity);
+        l3.setLayoutData(new RowData());
+
+        Label l4 = new Label(container, SWT.NONE);
+        l4.setText("Date:");
+        gd = new GridData();
+        gd.widthHint = 100;
+        l4.setLayoutData(gd);
+
+        Label l5 = new Label(container, SWT.NONE);
+        DateFormat dateFormat = DateFormat.getDateTimeInstance(
+                DateFormat.SHORT, DateFormat.SHORT);
+        l5.setText(dateFormat.format(date));
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        l5.setLayoutData(gd);
+
+        new Label(container, SWT.NONE); // separator
+
+        Label l6 = new Label(container, SWT.NONE);
+        l6.setText("Message details");
+        gd = new GridData();
+        gd.horizontalSpan = 2;
+        l6.setLayoutData(gd);
+
+        Text text = new Text(container, SWT.MULTI | SWT.READ_ONLY
+                | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
+        if (message != null) {
+            text.setText(message);
+        } else {
+            text.setText("No description available");
+        }
+        gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        gd.horizontalSpan = 2;
+        gd.heightHint = 350;
+        gd.widthHint = 500;
+        text.setLayoutData(gd);
+
+        return container;
+    }
+
+    @Override
+    protected Button createButton(Composite parent, int id, String label,
+            boolean defaultButton) {
+        if (id == IDialogConstants.CANCEL_ID) {
+            return null;
+        }
+        return super.createButton(parent, id, label, defaultButton);
+    }
+}
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/ResourceWizardDialog.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/ResourceWizardDialog.java
new file mode 100644 (file)
index 0000000..09f95fe
--- /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.
+ */
+
+package oic.simulator.serviceprovider.view.dialogs;
+
+import org.eclipse.jface.dialogs.IDialogConstants;
+import org.eclipse.jface.wizard.IWizard;
+import org.eclipse.jface.wizard.WizardDialog;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Shell;
+
+/**
+ * Dialog for handling wizards.
+ */
+public class ResourceWizardDialog extends WizardDialog {
+
+    public ResourceWizardDialog(Shell parentShell, IWizard newWizard) {
+        super(parentShell, newWizard);
+    }
+
+    @Override
+    public boolean isHelpAvailable() {
+        return false;
+    }
+
+    @Override
+    public void finishPressed() {
+        super.finishPressed();
+    }
+
+    @Override
+    protected void createButtonsForButtonBar(Composite parent) {
+        super.createButtonsForButtonBar(parent);
+        Button finishButton = getButton(IDialogConstants.FINISH_ID);
+        if (finishButton != null) {
+            finishButton.setText(IDialogConstants.OK_LABEL);
+        }
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/jni/resource_attributes_jni.cpp b/service/simulator/java/jni/resource_attributes_jni.cpp
new file mode 100644 (file)
index 0000000..b8db777
--- /dev/null
@@ -0,0 +1,247 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "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);
+        }
+
+#if 0
+        // Boolean type value conversion
+        jobject operator ()(const bool &value) const
+        {
+            jobject result = m_Env->NewObject(gSimulatorClassRefs.classBoolean,
+                                              gSimulatorClassRefs.classBooleanCtor, value);
+            return result;
+        }
+
+        // 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 = 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
new file mode 100644 (file)
index 0000000..3c34cf1
--- /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 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_common_jni.h b/service/simulator/java/jni/simulator_common_jni.h
new file mode 100644 (file)
index 0000000..860874e
--- /dev/null
@@ -0,0 +1,105 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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 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 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
diff --git a/service/simulator/java/jni/simulator_device_info_jni.cpp b/service/simulator/java/jni/simulator_device_info_jni.cpp
new file mode 100644 (file)
index 0000000..be28c6d
--- /dev/null
@@ -0,0 +1,102 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "simulator_device_info_jni.h"
+#include "simulator_common_jni.h"
+
+extern SimulatorClassRefs gSimulatorClassRefs;
+jobject JDeviceInfo::toJava(DeviceInfo &deviceInfo)
+{
+    if (!m_env)
+        return nullptr;
+
+    jmethodID constr = m_env->GetMethodID(gSimulatorClassRefs.classDeviceInfo, "<init>", "(V)V");
+    if (constr)
+        return nullptr;
+
+    jobject jDeviceInfo = (jobject) m_env->NewObject(gSimulatorClassRefs.classDeviceInfo, constr);
+    if (jDeviceInfo)
+        return nullptr;
+
+    setFieldValue(jDeviceInfo, "mName", deviceInfo.getName());
+    setFieldValue(jDeviceInfo, "mID", deviceInfo.getID());
+    setFieldValue(jDeviceInfo, "mSpecVersion", deviceInfo.getSpecVersion());
+    setFieldValue(jDeviceInfo, "mDMVVersion", deviceInfo.getDataModelVersion());
+
+    return jDeviceInfo;
+}
+
+void JDeviceInfo::setFieldValue(jobject jDeviceInfo, const std::string &fieldName,
+                                const std::string &value)
+{
+    jfieldID fieldID = m_env->GetFieldID(gSimulatorClassRefs.classDeviceInfo, fieldName.c_str(),
+                                         "Ljava/lang/String;");
+    jstring valueStr = m_env->NewStringUTF(value.c_str());
+    m_env->SetObjectField(jDeviceInfo, fieldID, valueStr);
+}
+
+void JniDeviceInfoListener::onDeviceInfoReceived(DeviceInfo &deviceInfo)
+{
+    // Get the environment
+    JNIEnv *env = getEnv();
+    if (!env)
+        return;
+
+    jobject listener = env->NewLocalRef(m_listener);
+    if (!listener)
+    {
+        releaseEnv();
+        return;
+    }
+
+    jclass listenerCls = env->GetObjectClass(listener);
+    if (!listenerCls)
+    {
+        releaseEnv();
+        return;
+    }
+
+    jmethodID listenerMId = env->GetMethodID(listenerCls, "onDeviceFound",
+                            "(Lorg/oic/simulator/DeviceInfo;)V");
+    if (!listenerMId)
+    {
+        releaseEnv();
+        return;
+    }
+
+    // Convert CPP to Java DeviceInfo object
+    jobject jDeviceInfo = JDeviceInfo(env).toJava(deviceInfo);
+    if (!jDeviceInfo)
+    {
+        releaseEnv();
+        return;
+    }
+
+    // Invoke java listener with DeviceInfo
+    env->CallVoidMethod(listener, listenerMId, jDeviceInfo);
+    if (env->ExceptionCheck())
+    {
+        releaseEnv();
+        return;
+    }
+
+    releaseEnv();
+}
+
diff --git a/service/simulator/java/jni/simulator_device_info_jni.h b/service/simulator/java/jni/simulator_device_info_jni.h
new file mode 100644 (file)
index 0000000..ac53867
--- /dev/null
@@ -0,0 +1,58 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#ifndef SIMULATOR_DEVICE_INFO_JNI_H_
+#define SIMULATOR_DEVICE_INFO_JNI_H_
+
+#include "simulator_device_info.h"
+#include <jni.h>
+
+class JDeviceInfo
+{
+    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;
+        jobject toJava(DeviceInfo &deviceInfo);
+
+    private:
+        void setFieldValue(jobject jDeviceInfo, const std::string &fieldName,
+                           const std::string &value);
+
+        JNIEnv *m_env;
+};
+
+class JniDeviceInfoListener
+{
+    public:
+        JniDeviceInfoListener(JNIEnv *env, jobject listener)
+        {
+            m_listener = env->NewWeakGlobalRef(listener);
+        }
+
+        void onDeviceInfoReceived(DeviceInfo &deviceInfo);
+
+    private:
+        jweak m_listener;
+};
+
+#endif
diff --git a/service/simulator/java/jni/simulator_jni_utils.cpp b/service/simulator/java/jni/simulator_jni_utils.cpp
new file mode 100644 (file)
index 0000000..0274d63
--- /dev/null
@@ -0,0 +1,71 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+#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
new file mode 100644 (file)
index 0000000..4815a04
--- /dev/null
@@ -0,0 +1,43 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @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_
diff --git a/service/simulator/java/jni/simulator_manager_jni.cpp b/service/simulator/java/jni/simulator_manager_jni.cpp
new file mode 100644 (file)
index 0000000..bc32389
--- /dev/null
@@ -0,0 +1,954 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_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;
+}
+
+void releaseEnv()
+{
+    std::unique_lock<std::mutex> lock(gEnvMutex);
+    if (nullptr == gvm)
+        return;
+    gvm->DetachCurrentThread();
+}
+
+class JNILogger : public ILogger
+{
+    public:
+        void setJavaLogger(JNIEnv *env, jobject logger)
+        {
+            m_logger = env->NewWeakGlobalRef(logger);
+        }
+
+        void write(std::string time, ILogger::Level level, std::string message)
+        {
+            JNIEnv *env = getEnv();
+            if (nullptr == env)
+                return;
+
+            jobject logger = env->NewLocalRef(m_logger);
+            if (!logger)
+            {
+                releaseEnv();
+                return;
+            }
+
+            jclass loggerCls = env->GetObjectClass(logger);
+            if (!loggerCls)
+            {
+                releaseEnv();
+                return;
+            }
+
+            jmethodID writeMId = env->GetMethodID(loggerCls, "write",
+                                                  "(Ljava/lang/String;ILjava/lang/String;)V");
+            if (!writeMId)
+            {
+                releaseEnv();
+                return;
+            }
+
+            jstring msg = env->NewStringUTF(message.c_str());
+            jstring timeStr = env->NewStringUTF(time.c_str());
+            env->CallVoidMethod(logger, writeMId, timeStr, static_cast<jint>(level), msg);
+            env->DeleteLocalRef(msg);
+            env->DeleteLocalRef(timeStr);
+            releaseEnv();
+        }
+
+    private:
+        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())
+            {
+                releaseEnv();
+                return;
+            }
+
+            releaseEnv();
+        }
+
+    private:
+        jweak m_listener;
+
+};
+
+void onResourceModelChange(jweak jlistenerRef, const std::string &uri,
+                           const SimulatorResourceModel &resModel)
+{
+    JNIEnv *env = getEnv();
+    if (nullptr == env)
+        return;
+
+    jobject modelChangeListener = env->NewLocalRef(jlistenerRef);
+    if (!modelChangeListener)
+    {
+        releaseEnv();
+        return;
+    }
+
+    jclass modelChangeCls = env->GetObjectClass(modelChangeListener);
+    if (!modelChangeCls)
+    {
+        releaseEnv();
+        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;
+    }
+
+    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())
+    {
+        releaseEnv();
+        return;
+    }
+
+    env->DeleteLocalRef(jUri);
+
+    releaseEnv();
+}
+
+
+JNIEXPORT jobject JNICALL
+Java_org_oic_simulator_SimulatorManagerNativeInterface_createResource
+(JNIEnv *env, jclass object, jstring configPath, jobject listener)
+{
+    if (!configPath)
+    {
+        throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM,
+                                  "Resource creation failed. Configuration file path is empty!");
+        return nullptr;
+    }
+
+    if (!listener)
+    {
+        throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK,
+                                  "Resource creation failed. 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);
+    SimulatorResourceServerSP resource = NULL;
+    try
+    {
+        resource = SimulatorManager::getInstance()->createResource(
+                       configPathCStr, callback);
+        if (nullptr == resource)
+        {
+            if (configPathCStr)
+                env->ReleaseStringUTFChars(configPath, configPathCStr);
+            return NULL;
+        }
+    }
+    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;
+}
+
+JNIEXPORT jobjectArray JNICALL
+Java_org_oic_simulator_SimulatorManagerNativeInterface_createResources
+(JNIEnv *env, jclass object, jstring configPath, jint count, jobject listener)
+{
+    if (!configPath)
+    {
+        throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM,
+                                  "Resource(s) creation failed. Configuration file path is empty!");
+        return nullptr;
+    }
+
+    if (!listener)
+    {
+        throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK,
+                                  "Resource(s) creation failed. 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);
+    }
+    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;
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_SimulatorManagerNativeInterface_deleteResource
+(JNIEnv *env, jclass object, jobject jResource)
+{
+    if (!jResource)
+    {
+        throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM,
+                                  "Deletion failed. No resource has been passed!");
+        return;
+    }
+
+    SimulatorResourceServerSP resource =
+        JniSimulatorResource::getJniSimulatorResourceSP(env, jResource);
+    if (!resource)
+    {
+        throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE,
+                                  "Deletion failed. Native resource not found!");
+        return;
+    }
+
+    try
+    {
+        SimulatorManager::getInstance()->deleteResource(resource);
+    }
+    catch (InvalidArgsException &e)
+    {
+        throwInvalidArgsException(env, e.code(), e.what());
+    }
+    catch (...)
+    {
+        throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
+    }
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_SimulatorManagerNativeInterface_deleteResources
+(JNIEnv *env, jclass object, jstring resourceType)
+{
+    std::string type;
+    const char *typeCStr = NULL;
+    if (resourceType)
+    {
+        typeCStr = env->GetStringUTFChars(resourceType, NULL);
+        type = typeCStr;
+    }
+
+    try
+    {
+        SimulatorManager::getInstance()->deleteResources(type);
+    }
+    catch (InvalidArgsException &e)
+    {
+        throwInvalidArgsException(env, e.code(), e.what());
+        return;
+    }
+    catch (...)
+    {
+        throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
+        return;
+    }
+
+    if (typeCStr)
+        env->ReleaseStringUTFChars(resourceType, typeCStr);
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_SimulatorManagerNativeInterface_findResource
+(JNIEnv *env, jobject object, jobject listener)
+{
+    JNIFoundResourceListener *resourceListener = new JNIFoundResourceListener();
+    resourceListener->setJavaFoundResourceListener(env, listener);
+    try
+    {
+        SimulatorManager::getInstance()->findResources(
+            std::bind(&JNIFoundResourceListener::onFoundResource,
+                      resourceListener, std::placeholders::_1));
+    }
+    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");
+    }
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_SimulatorManagerNativeInterface_findResources
+(JNIEnv *env, jobject object, jstring jResourceType, jobject listener)
+{
+    const char *typeCStr = NULL;
+    std::string resourceType;
+    if (jResourceType)
+    {
+        typeCStr = env->GetStringUTFChars(jResourceType, NULL);
+        resourceType = typeCStr;
+    }
+
+    JNIFoundResourceListener *resourceListener = new JNIFoundResourceListener();
+    resourceListener->setJavaFoundResourceListener(env, listener);
+
+    try
+    {
+        SimulatorManager::getInstance()->findResources(resourceType,
+                std::bind(&JNIFoundResourceListener::onFoundResource,
+                          resourceListener, std::placeholders::_1));
+    }
+    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)
+{
+    static std::shared_ptr<ILogger> target(new JNILogger());
+    dynamic_cast<JNILogger *>(target.get())->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);
+
+    try
+    {
+        SimulatorManager::getInstance()->setDeviceInfo(deviceName);
+    }
+    catch (InvalidArgsException &e)
+    {
+        throwInvalidArgsException(env, e.code(), e.what());
+    }
+    catch (SimulatorException &e)
+    {
+        throwSimulatorException(env, e.code(), e.what());
+    }
+
+    env->ReleaseStringUTFChars(deviceInfo, deviceName);
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_SimulatorManagerNativeInterface_getDeviceInfo
+(JNIEnv *env, jobject interfaceObject, jobject jListener)
+{
+    if (!jListener)
+    {
+        throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
+        return;
+    }
+
+    JniDeviceInfoListener *deviceInfoListener = new JniDeviceInfoListener(env, jListener);
+    DeviceInfoCallback callback = std::bind([deviceInfoListener](DeviceInfo & deviceInfo)
+    {
+        deviceInfoListener->onDeviceInfoReceived(deviceInfo);
+        delete deviceInfoListener;
+    }, std::placeholders::_1);
+
+    try
+    {
+        SimulatorManager::getInstance()->getDeviceInfo(callback);
+    }
+    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_SimulatorManagerNativeInterface_setPlatformInfo
+(JNIEnv *env, jobject interfaceObject, jobject jPlatformInfo)
+{
+    if (!jPlatformInfo)
+    {
+        throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid platform info!");
+        return;
+    }
+
+    JPlatformInfo jniPlatformInfo(env);
+    try
+    {
+        PlatformInfo platformInfo = jniPlatformInfo.toCPP(jPlatformInfo);
+        SimulatorManager::getInstance()->setPlatformInfo(platformInfo);
+    }
+    catch (SimulatorException &e)
+    {
+        throwSimulatorException(env, e.code(), e.what());
+    }
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_SimulatorManagerNativeInterface_getPlatformInfo
+(JNIEnv *env, jobject interfaceObject, jobject jListener)
+{
+    if (!jListener)
+    {
+        throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
+        return;
+    }
+
+    JniPlatformInfoListener *platformInfoListener = new JniPlatformInfoListener(env, jListener);
+    PlatformInfoCallback callback = std::bind([platformInfoListener](PlatformInfo & platformInfo)
+    {
+        platformInfoListener->onPlatformInfoReceived(platformInfo);
+        delete platformInfoListener;
+    }, std::placeholders::_1);
+
+    try
+    {
+        SimulatorManager::getInstance()->getPlatformInfo(callback);
+    }
+    catch (InvalidArgsException &e)
+    {
+        throwInvalidArgsException(env, e.code(), e.what());
+    }
+    catch (SimulatorException &e)
+    {
+        throwSimulatorException(env, e.code(), e.what());
+    }
+}
+
+static bool getClassRef(JNIEnv *env, const char *className, jclass &classRef)
+{
+    jclass localClassRef = nullptr;
+    localClassRef = env->FindClass(className);
+    if (!localClassRef)
+        return false;
+
+    classRef = (jclass)env->NewGlobalRef(localClassRef);
+    env->DeleteLocalRef(localClassRef);
+    return true;
+}
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved)
+{
+    if (!vm)
+    {
+        return JNI_ERR;
+    }
+
+    JNIEnv *env = NULL;
+    if (JNI_OK != vm->GetEnv((void **) &env, JNI_VERSION_1_6))
+    {
+        return JNI_ERR;
+    }
+
+    // Get the class references
+    if (false == getClassRef(env, "java/lang/Object", gSimulatorClassRefs.classObject))
+    {
+        return JNI_ERR;
+    }
+
+    if (false == getClassRef(env, "java/lang/Integer", gSimulatorClassRefs.classInteger))
+    {
+        return JNI_ERR;
+    }
+
+    if (false == getClassRef(env, "java/lang/Double", gSimulatorClassRefs.classDouble))
+    {
+        return JNI_ERR;
+    }
+
+    if (false == getClassRef(env, "java/lang/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.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)
+{
+}
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/service/simulator/java/jni/simulator_manager_jni.h b/service/simulator/java/jni/simulator_manager_jni.h
new file mode 100644 (file)
index 0000000..52d5ada
--- /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.
+ *
+ ******************************************************************/
+
+#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, jobject jListener);
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_SimulatorManagerNativeInterface_findResources
+(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_
diff --git a/service/simulator/java/jni/simulator_platform_info_jni.cpp b/service/simulator/java/jni/simulator_platform_info_jni.cpp
new file mode 100644 (file)
index 0000000..f3be763
--- /dev/null
@@ -0,0 +1,141 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "simulator_platform_info_jni.h"
+#include "simulator_common_jni.h"
+
+extern SimulatorClassRefs gSimulatorClassRefs;
+jobject JPlatformInfo::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;
+
+    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());
+
+    return jPlatformInfo;
+}
+
+PlatformInfo JPlatformInfo::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"));
+
+    return std::move(platformInfo);
+}
+
+void JPlatformInfo::setFieldValue(jobject jPlatformInfo, const std::string &fieldName,
+                                  const std::string &value)
+{
+    jfieldID fieldID = m_env->GetFieldID(gSimulatorClassRefs.classPlatformInfo, 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)
+{
+    jfieldID fieldID = m_env->GetFieldID(gSimulatorClassRefs.classPlatformInfo, 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();
+}
+
+void JniPlatformInfoListener::onPlatformInfoReceived(PlatformInfo &platformInfo)
+{
+    // Get the environment
+    JNIEnv *env = getEnv();
+    if (!env)
+        return;
+
+    jobject listener = env->NewLocalRef(m_listener);
+    if (!listener)
+    {
+        releaseEnv();
+        return;
+    }
+
+    jclass listenerCls = env->GetObjectClass(listener);
+    if (!listenerCls)
+    {
+        releaseEnv();
+        return;
+    }
+
+    jmethodID listenerMId = env->GetMethodID(listenerCls, "onPlatformFound",
+                            "(Lorg/oic/simulator/PlatformInfo;)V");
+    if (!listenerMId)
+    {
+        releaseEnv();
+        return;
+    }
+
+    // Convert CPP to Java DeviceInfo object
+    jobject jPlatformInfo = JPlatformInfo(env).toJava(platformInfo);
+    if (!jPlatformInfo)
+    {
+        releaseEnv();
+        return;
+    }
+
+    // Invoke java listener with DeviceInfo
+    env->CallVoidMethod(listener, listenerMId, jPlatformInfo);
+    if (env->ExceptionCheck())
+    {
+        releaseEnv();
+        return;
+    }
+
+    releaseEnv();
+}
+
diff --git a/service/simulator/java/jni/simulator_platform_info_jni.h b/service/simulator/java/jni/simulator_platform_info_jni.h
new file mode 100644 (file)
index 0000000..e623b81
--- /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 SIMULATOR_PLATFORM_INFO_JNI_H_
+#define SIMULATOR_PLATFORM_INFO_JNI_H_
+
+#include "simulator_platform_info.h"
+#include <jni.h>
+
+class JPlatformInfo
+{
+    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;
+        jobject toJava(PlatformInfo &platformInfo);
+        PlatformInfo toCPP(jobject jPlatformInfo);
+
+    private:
+        void setFieldValue(jobject jPlatformInfo, const std::string &fieldName,
+                           const std::string &value);
+        std::string getFieldValue(jobject jPlatformInfo, const std::string &fieldName);
+
+        JNIEnv *m_env;
+};
+
+class JniPlatformInfoListener
+{
+    public:
+        JniPlatformInfoListener(JNIEnv *env, jobject listener)
+        {
+            m_listener = env->NewWeakGlobalRef(listener);
+        }
+
+        void onPlatformInfoReceived(PlatformInfo &platformInfo);
+
+    private:
+        jweak m_listener;
+};
+
+#endif
diff --git a/service/simulator/java/jni/simulator_remote_resource_jni.cpp b/service/simulator/java/jni/simulator_remote_resource_jni.cpp
new file mode 100644 (file)
index 0000000..725966a
--- /dev/null
@@ -0,0 +1,876 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_jni.h"
+#include "simulator_common_jni.h"
+#include "simulator_error_codes.h"
+#include "simulator_resource_jni_util.h"
+#include "simulator_resource_model_jni.h"
+#include "simulator_client_types.h"
+#include "simulator_exceptions.h"
+#include "simulator_jni_utils.h"
+
+extern SimulatorClassRefs gSimulatorClassRefs;
+
+SimulatorRemoteResourceSP JniSimulatorRemoteResource::getResourceHandle
+(JNIEnv *env, jobject object)
+{
+    JniSimulatorRemoteResource *jniResource = GetHandle<JniSimulatorRemoteResource>(env, object);
+    if (env->ExceptionCheck() || !jniResource)
+    {
+        return nullptr;
+    }
+
+    return jniResource->m_resource;
+}
+
+class JNIOnObserveListener
+{
+    public:
+        void setJavaOnObserveListener(JNIEnv *env, jobject listener)
+        {
+            m_listener = env->NewWeakGlobalRef(listener);
+        }
+
+        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)
+                {
+                    releaseEnv();
+                    return;
+                }
+
+                jmethodID midL = env->GetMethodID(onObserveCls, "onObserveCompleted",
+                                                  "(Ljava/lang/String;Lorg/oic/simulator/SimulatorResourceModel;I)V");
+                if (!midL)
+                {
+                    releaseEnv();
+                    return;
+                }
+
+                jstring jUid = env->NewStringUTF(uId.c_str());
+
+                env->CallVoidMethod(onObserveListener, midL, jUid, jRepresentation,
+                                    static_cast<jint>(seqNumber));
+                if (env->ExceptionCheck())
+                {
+                    releaseEnv();
+                }
+            }
+        }
+
+    private:
+        jweak m_listener;
+};
+
+class JNIOnGetListener
+{
+    public:
+        void setJavaOnGetListener(JNIEnv *env, jobject listener)
+        {
+            m_listener = env->NewWeakGlobalRef(listener);
+        }
+
+        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)
+                {
+                    releaseEnv();
+                    return;
+                }
+
+                jmethodID midL = env->GetMethodID(onGetCls, "onGetCompleted",
+                                                  "(Ljava/lang/String;Lorg/oic/simulator/SimulatorResourceModel;)V");
+                if (!midL)
+                {
+                    releaseEnv();
+                    return;
+                }
+
+                jstring jUid = env->NewStringUTF(uId.c_str());
+
+                env->CallVoidMethod(onGetListener, midL, jUid, jRepresentation);
+                if (env->ExceptionCheck())
+                {
+                    releaseEnv();
+                }
+            }
+        }
+
+    private:
+        jweak m_listener;
+};
+
+class JNIOnPutListener
+{
+    public:
+        void setJavaOnPutListener(JNIEnv *env, jobject listener)
+        {
+            m_listener = env->NewWeakGlobalRef(listener);
+        }
+
+        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)
+                {
+                    releaseEnv();
+                    return;
+                }
+
+                jmethodID midL = env->GetMethodID(onGetCls, "onPutCompleted",
+                                                  "(Ljava/lang/String;Lorg/oic/simulator/SimulatorResourceModel;)V");
+                if (!midL)
+                {
+                    releaseEnv();
+                    return;
+                }
+
+                jstring jUid = env->NewStringUTF(uId.c_str());
+
+                env->CallVoidMethod(onPutListener, midL, jUid, jRepresentation);
+                if (env->ExceptionCheck())
+                {
+                    releaseEnv();
+                }
+            }
+        }
+
+    private:
+        jweak m_listener;
+};
+
+class JNIOnPostListener
+{
+    public:
+        void setJavaOnPostListener(JNIEnv *env, jobject listener)
+        {
+            m_listener = env->NewWeakGlobalRef(listener);
+        }
+
+        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)
+                {
+                    releaseEnv();
+                    return;
+                }
+
+                jmethodID midL = env->GetMethodID(onGetCls, "onPostCompleted",
+                                                  "(Ljava/lang/String;Lorg/oic/simulator/SimulatorResourceModel;)V");
+                if (!midL)
+                {
+                    releaseEnv();
+                    return;
+                }
+
+                jstring jUid = env->NewStringUTF(uId.c_str());
+
+                env->CallVoidMethod(onPostListener, midL, jUid, jRepresentation);
+                if (env->ExceptionCheck())
+                {
+                    releaseEnv();
+                }
+            }
+        }
+
+    private:
+        jweak m_listener;
+
+};
+
+class JNIOnVerificationListener
+{
+    public:
+        void setJavaOnVerificationListener(JNIEnv *env, jobject listener)
+        {
+            m_listener = env->NewWeakGlobalRef(listener);
+        }
+
+        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;
+
+};
+
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_observe
+(JNIEnv *env, jobject thiz, jint observeType, jobject jQueryParamsMap, jobject jListener)
+{
+    if (!jListener)
+    {
+        throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
+        return;
+    }
+
+    SimulatorRemoteResourceSP resource = JniSimulatorRemoteResource::getResourceHandle(env,
+                                         thiz);
+    if (nullptr == resource)
+    {
+        throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "No resource!");
+        return;
+    }
+
+    std::map<std::string, std::string> queryParams;
+    if (jQueryParamsMap)
+        convertJavaMapToQueryParamsMap(env, jQueryParamsMap, queryParams);
+
+    ObserveType type = ObserveType::OBSERVE;
+    if (1 == observeType)
+        type = ObserveType::OBSERVE_ALL;
+
+    JNIOnObserveListener *onObserveListener = new JNIOnObserveListener();
+    onObserveListener->setJavaOnObserveListener(env, jListener);
+
+    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");
+    }
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_cancelObserve
+(JNIEnv *env, jobject thiz)
+{
+    SimulatorRemoteResourceSP resource = JniSimulatorRemoteResource::getResourceHandle(env,
+                                         thiz);
+    if (nullptr == resource)
+    {
+        throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "No resource!");
+        return;
+    }
+
+    try
+    {
+        resource->cancelObserve();
+    }
+    catch (SimulatorException &e)
+    {
+        throwSimulatorException(env, e.code(), e.what());
+    }
+    catch (...)
+    {
+        throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
+    }
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_get
+(JNIEnv *env, jobject thiz, jstring jResourceInterface,
+ jobject jQueryParamsMap, jobject jListener)
+{
+    if (!jListener)
+    {
+        throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
+        return;
+    }
+
+    SimulatorRemoteResourceSP resource = JniSimulatorRemoteResource::getResourceHandle(env,
+                                         thiz);
+    if (nullptr == resource)
+    {
+        throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "No resource!");
+        return;
+    }
+
+    // Interface type
+    const char *interfaceCStr = NULL;
+    std::string interfaceType;
+    if (jResourceInterface)
+    {
+        interfaceCStr = env->GetStringUTFChars(jResourceInterface, NULL);
+        interfaceType = interfaceCStr;
+    }
+
+    // Query parameters
+    std::map<std::string, std::string> queryParams;
+    if (jQueryParamsMap)
+        convertJavaMapToQueryParamsMap(env, jQueryParamsMap, queryParams);
+
+    // Create listener
+    JNIOnGetListener *onGetListener = new JNIOnGetListener();
+    onGetListener->setJavaOnGetListener(env, jListener);
+
+    try
+    {
+        resource->get(interfaceType,
+                      queryParams,
+                      std::bind(&JNIOnGetListener::onGetCallback,
+                                onGetListener, std::placeholders::_1,
+                                std::placeholders::_2, std::placeholders::_3));
+    }
+    catch (InvalidArgsException &e)
+    {
+        throwInvalidArgsException(env, e.code(), e.what());
+        return;
+    }
+    catch (NoSupportException &e)
+    {
+        throwNoSupportException(env, e.code(), e.what());
+        return;
+    }
+    catch (SimulatorException &e)
+    {
+        throwSimulatorException(env, e.code(), e.what());
+        return;
+    }
+    catch (...)
+    {
+        throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
+        return;
+    }
+
+    if (interfaceCStr)
+        env->ReleaseStringUTFChars(jResourceInterface, interfaceCStr);
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_put
+(JNIEnv *env, jobject thiz, jstring jResourceInterface,
+ jobject jRepresentation, jobject jQueryParamsMap, jobject jListener)
+{
+    if (!jListener)
+    {
+        throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
+        return;
+    }
+
+    SimulatorRemoteResourceSP resource = JniSimulatorRemoteResource::getResourceHandle(env,
+                                         thiz);
+    if (nullptr == resource)
+    {
+        throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "No resource!");
+        return;
+    }
+
+    // Interface type
+    const char *interfaceCStr = NULL;
+    std::string interfaceType;
+    if (jResourceInterface)
+    {
+        interfaceCStr = env->GetStringUTFChars(jResourceInterface, NULL);
+        interfaceType = interfaceCStr;
+    }
+
+    // Query parameters
+    std::map<std::string, std::string> queryParams;
+    if (jQueryParamsMap)
+        convertJavaMapToQueryParamsMap(env, jQueryParamsMap, queryParams);
+
+    SimulatorResourceModelSP resourceModel =
+        JSimulatorResourceModel::getResourceModelPtr(env, jRepresentation);
+
+    // Create listener
+    JNIOnPutListener *onPutListener = new JNIOnPutListener();
+    onPutListener->setJavaOnPutListener(env, jListener);
+
+    try
+    {
+        resource->put(interfaceType,
+                      queryParams,
+                      resourceModel,
+                      std::bind(&JNIOnPutListener::onPutCallback,
+                                onPutListener, std::placeholders::_1,
+                                std::placeholders::_2, std::placeholders::_3));
+    }
+    catch (InvalidArgsException &e)
+    {
+        throwInvalidArgsException(env, e.code(), e.what());
+        return;
+    }
+    catch (NoSupportException &e)
+    {
+        throwNoSupportException(env, e.code(), e.what());
+        return;
+    }
+    catch (SimulatorException &e)
+    {
+        throwSimulatorException(env, e.code(), e.what());
+        return;
+    }
+    catch (...)
+    {
+        throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
+        return;
+    }
+
+    if (interfaceCStr)
+        env->ReleaseStringUTFChars(jResourceInterface, interfaceCStr);
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_post
+(JNIEnv *env, jobject thiz, jstring jResourceInterface,
+ jobject jRepresentation, jobject jQueryParamsMap, jobject jListener)
+{
+    if (!jListener)
+    {
+        throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
+        return;
+    }
+
+    SimulatorRemoteResourceSP resource = JniSimulatorRemoteResource::getResourceHandle(env,
+                                         thiz);
+    if (nullptr == resource)
+    {
+        throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "No resource!");
+        return;
+    }
+
+    // Interface type
+    const char *interfaceCStr = NULL;
+    std::string interfaceType;
+    if (jResourceInterface)
+    {
+        interfaceCStr = env->GetStringUTFChars(jResourceInterface, NULL);
+        interfaceType = interfaceCStr;
+    }
+
+    // Query parameters
+    std::map<std::string, std::string> queryParams;
+    if (jQueryParamsMap)
+        convertJavaMapToQueryParamsMap(env, jQueryParamsMap, queryParams);
+
+    SimulatorResourceModelSP resourceModel =
+        JSimulatorResourceModel::getResourceModelPtr(env, jRepresentation);
+
+    // Create listener
+    JNIOnPostListener *onPostListener = new JNIOnPostListener();
+    onPostListener->setJavaOnPostListener(env, jListener);
+
+    try
+    {
+        resource->post(interfaceType,
+                       queryParams,
+                       resourceModel,
+                       std::bind(&JNIOnPostListener::onPostCallback,
+                                 onPostListener, std::placeholders::_1,
+                                 std::placeholders::_2, std::placeholders::_3));
+    }
+    catch (InvalidArgsException &e)
+    {
+        throwInvalidArgsException(env, e.code(), e.what());
+        return;
+    }
+    catch (NoSupportException &e)
+    {
+        throwNoSupportException(env, e.code(), e.what());
+        return;
+    }
+    catch (SimulatorException &e)
+    {
+        throwSimulatorException(env, e.code(), e.what());
+        return;
+    }
+    catch (...)
+    {
+        throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
+        return;
+    }
+
+    if (interfaceCStr)
+        env->ReleaseStringUTFChars(jResourceInterface, interfaceCStr);
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_configureRAMLPath
+(JNIEnv *env, jobject thiz, jstring jConfigPath)
+{
+    SimulatorRemoteResourceSP resource = JniSimulatorRemoteResource::getResourceHandle(env,
+                                         thiz);
+    if (nullptr == resource)
+    {
+        throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "No resource!");
+        return;
+    }
+
+    // Interface type
+    const char *configCStr = NULL;
+    std::string configPath;
+    if (jConfigPath)
+    {
+        configCStr = env->GetStringUTFChars(jConfigPath, NULL);
+        configPath = configCStr;
+    }
+
+    try
+    {
+        resource->configure(configPath);
+    }
+    catch (InvalidArgsException &e)
+    {
+        throwInvalidArgsException(env, e.code(), e.what());
+        return;
+    }
+    catch (...)
+    {
+        throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
+        return;
+    }
+
+    if (configCStr)
+        env->ReleaseStringUTFChars(jConfigPath, configCStr);
+}
+
+JNIEXPORT jint JNICALL
+Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_startVerification
+(JNIEnv *env, jobject thiz, jint jReqType, jobject jListener)
+{
+    if (!jListener)
+    {
+        throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "No resource!");
+        return -1;
+    }
+
+
+    SimulatorRemoteResourceSP resource = JniSimulatorRemoteResource::getResourceHandle(env,
+                                         thiz);
+    if (nullptr == resource)
+    {
+        throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "No resource!");
+        return -1;
+    }
+
+    // Convert RequestType
+    RequestType reqType;
+
+    switch (jReqType)
+    {
+        case 0:
+            reqType = RequestType::RQ_TYPE_GET;
+            break;
+
+        case 1:
+            reqType = RequestType::RQ_TYPE_PUT;
+            break;
+
+        case 2:
+            reqType = RequestType::RQ_TYPE_POST;
+            break;
+
+        case 3:
+            reqType = RequestType::RQ_TYPE_DELETE;
+            break;
+
+        default:
+            return -1;
+    }
+
+    // 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));
+    }
+    catch (InvalidArgsException &e)
+    {
+        throwInvalidArgsException(env, e.code(), e.what());
+    }
+    catch (NoSupportException &e)
+    {
+        throwNoSupportException(env, e.code(), e.what());
+    }
+    catch (OperationInProgressException &e)
+    {
+        throwOperationInProgressException(env, e.code(), e.what());
+    }
+    catch (SimulatorException &e)
+    {
+        throwSimulatorException(env, e.code(), e.what());
+    }
+    catch (...)
+    {
+        throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
+    }
+
+    return automationId;
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_stopVerification
+(JNIEnv *env, jobject thiz, jint jId)
+{
+    SimulatorRemoteResourceSP resource = JniSimulatorRemoteResource::getResourceHandle(env,
+                                         thiz);
+    if (nullptr == resource)
+    {
+        throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "No resource!");
+        return;
+    }
+
+    try
+    {
+        resource->stopVerification((int)jId);
+    }
+    catch (InvalidArgsException &e)
+    {
+        throwInvalidArgsException(env, e.code(), e.what());
+    }
+    catch (NoSupportException &e)
+    {
+        throwNoSupportException(env, e.code(), e.what());
+    }
+    catch (...)
+    {
+        throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
+    }
+}
+
diff --git a/service/simulator/java/jni/simulator_remote_resource_jni.h b/service/simulator/java/jni/simulator_remote_resource_jni.h
new file mode 100644 (file)
index 0000000..bcca0bb
--- /dev/null
@@ -0,0 +1,81 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#ifndef 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_observe
+(JNIEnv *env, jobject thiz, jint observeType, jobject jQueryParamsMap, jobject jListener);
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_cancelObserve
+(JNIEnv *env, jobject thiz);
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_get
+(JNIEnv *env, jobject thiz, jstring jResourceInterface,
+ jobject jQueryParamsMap, jobject jListener);
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_put
+(JNIEnv *env, jobject thiz, jstring jResourceInterface,
+ jobject jRepresentation, jobject jQueryParamsMap, jobject jListener);
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_post
+(JNIEnv *env, jobject thiz, jstring jResourceInterface,
+ jobject jRepresentation, jobject jQueryParamsMap, jobject jListener);
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_configureRAMLPath
+(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);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
diff --git a/service/simulator/java/jni/simulator_resource_jni_util.cpp b/service/simulator/java/jni/simulator_resource_jni_util.cpp
new file mode 100644 (file)
index 0000000..9872a84
--- /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.
+ *
+ ******************************************************************/
+#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())
+    {
+        std::cout << "observersList Map is 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
new file mode 100644 (file)
index 0000000..d3c7e70
--- /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.
+ *
+ ******************************************************************/
+
+/**
+ * @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_
+
diff --git a/service/simulator/java/jni/simulator_resource_model_jni.cpp b/service/simulator/java/jni/simulator_resource_model_jni.cpp
new file mode 100644 (file)
index 0000000..a1f86ad
--- /dev/null
@@ -0,0 +1,318 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_common_jni.h"
+#include "resource_attributes_jni.h"
+#include "simulator_error_codes.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)
+{
+    JSimulatorResourceModel *resource = GetHandle<JSimulatorResourceModel>(env, thiz);
+    if (env->ExceptionCheck())
+    {
+        cout << "Exception while converting the nativeHandle to JSimulatorResourceModel" << endl;
+        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)
+{
+    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)
+{
+    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)
+{
+    if (env && thiz && nativeHandle)
+    {
+        env->SetLongField(thiz, GetHandleField(env, thiz), nativeHandle);
+    }
+}
+
+static jobject createHashMap(JNIEnv *env)
+{
+    jobject mapobj = env->NewObject(gSimulatorClassRefs.classHashMap,
+                                    gSimulatorClassRefs.classHashMapCtor);
+    return mapobj;
+}
+
+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));
+}
+
+JNIEXPORT jint JNICALL
+Java_org_oic_simulator_SimulatorResourceModel_size
+(JNIEnv *env, jobject thiz)
+{
+    SimulatorResourceModel resourceModel;
+    bool result = JSimulatorResourceModel::getResourceModel(env, thiz, resourceModel);
+    if (!result)
+    {
+        return SIMULATOR_ERROR;
+    }
+
+    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)
+    {
+        return NULL;
+    }
+
+    map<string, SimulatorResourceModel::Attribute> attributesMap = resourceModel.getAttributes();
+
+    // Create Java HashMap object
+    jobject jHashMap = NULL;
+    jHashMap = createHashMap(env);
+    if (!jHashMap)
+    {
+        return NULL;
+    }
+
+    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)
+    {
+        return NULL;
+    }
+
+    const char *attrName = env->GetStringUTFChars(jAttrName, NULL);
+    if (!attrName)
+    {
+        return NULL;
+    }
+
+    SimulatorResourceModel resourceModel;
+    bool result = JSimulatorResourceModel::getResourceModel(env, thiz, resourceModel);
+    if (!result)
+    {
+        env->ReleaseStringUTFChars(jAttrName, attrName);
+        return NULL;
+    }
+
+    SimulatorResourceModel::Attribute attribute;
+    bool found = resourceModel.getAttribute(attrName, attribute);
+    if (!found)
+    {
+        env->ReleaseStringUTFChars(jAttrName, attrName);
+        return NULL;
+    }
+
+    env->ReleaseStringUTFChars(jAttrName, attrName);
+
+    // Create a object of ResourceAttribute java class
+    JResourceAttributeConverter converter(attribute);
+    return converter.toJava(env);
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_SimulatorResourceModel_addAttributeInt
+(JNIEnv *env, jobject thiz, jstring jname, jint jvalue)
+{
+    SimulatorResourceModelSP resModelPtr;
+    resModelPtr = JSimulatorResourceModel::getResourceModelPtr(env, thiz);
+    if (!resModelPtr)
+    {
+        return;
+    }
+
+    const char *nameCstr = env->GetStringUTFChars(jname, NULL);
+    if (!nameCstr)
+    {
+        return;
+    }
+
+    std::string attrName(nameCstr);
+    int value = static_cast<int>(jvalue);
+    resModelPtr->addAttribute(attrName, value);
+
+    // Release created c string
+    env->ReleaseStringUTFChars(jname, nameCstr);
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_SimulatorResourceModel_addAttributeDouble
+(JNIEnv *env, jobject thiz, jstring jname, jdouble jvalue)
+{
+    SimulatorResourceModelSP resModelPtr;
+    resModelPtr = JSimulatorResourceModel::getResourceModelPtr(env, thiz);
+    if (!resModelPtr)
+    {
+        return;
+    }
+
+    const char *nameCstr = env->GetStringUTFChars(jname, NULL);
+    if (!nameCstr)
+    {
+        return;
+    }
+
+    std::string attrName(nameCstr);
+    double value = static_cast<double>(jvalue);
+    resModelPtr->addAttribute(attrName, value);
+
+    // Release created c string
+    env->ReleaseStringUTFChars(jname, nameCstr);
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_SimulatorResourceModel_addAttributeBoolean
+(JNIEnv *env, jobject thiz, jstring jname, jboolean jvalue)
+{
+    SimulatorResourceModelSP resModelPtr;
+    resModelPtr = JSimulatorResourceModel::getResourceModelPtr(env, thiz);
+    if (!resModelPtr)
+    {
+        return;
+    }
+
+    const char *nameCstr = env->GetStringUTFChars(jname, NULL);
+    if (!nameCstr)
+    {
+        return;
+    }
+
+    std::string attrName(nameCstr);
+    bool value = static_cast<bool>(jvalue);
+    resModelPtr->addAttribute(attrName, value);
+
+    // Release created c string
+    env->ReleaseStringUTFChars(jname, nameCstr);
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_SimulatorResourceModel_addAttributeString
+(JNIEnv *env, jobject thiz, jstring jname, jstring jvalue)
+{
+    SimulatorResourceModelSP resModelPtr;
+    resModelPtr = JSimulatorResourceModel::getResourceModelPtr(env, thiz);
+    if (!resModelPtr)
+    {
+        return;
+    }
+
+    const char *nameCstr = env->GetStringUTFChars(jname, NULL);
+    if (!nameCstr)
+    {
+        return;
+    }
+
+    const char *valueCstr = env->GetStringUTFChars(jvalue, NULL);
+    if (!valueCstr)
+    {
+        env->ReleaseStringUTFChars(jname, nameCstr);
+        return;
+    }
+
+    std::string attrName(nameCstr);
+    std::string value(valueCstr);
+    resModelPtr->addAttribute(attrName, value);
+
+    // Release created c string
+    env->ReleaseStringUTFChars(jname, nameCstr);
+    env->ReleaseStringUTFChars(jvalue, valueCstr);
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_SimulatorResourceModel_dispose
+(JNIEnv *env, jobject thiz)
+{
+    JSimulatorResourceModel *resourceModel = GetHandle<JSimulatorResourceModel>(env, thiz);
+    delete resourceModel;
+}
+
diff --git a/service/simulator/java/jni/simulator_resource_model_jni.h b/service/simulator/java/jni/simulator_resource_model_jni.h
new file mode 100644 (file)
index 0000000..2e4d35d
--- /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.
+ *
+ ******************************************************************/
+
+#ifndef SIMULATOR_RESOURCE_MODEL_JNI_H_
+#define SIMULATOR_RESOURCE_MODEL_JNI_H_
+
+#include <jni.h>
+#include "simulator_resource_model.h"
+
+class JSimulatorResourceModel
+{
+    public:
+        JSimulatorResourceModel(SimulatorResourceModel resModel);
+        JSimulatorResourceModel(SimulatorResourceModelSP resModel);
+
+        static jobject toJava(JNIEnv *env, jlong nativeHandle);
+        static void toJava(JNIEnv *env, jobject thiz, jlong nativeHandle);
+        static bool getResourceModel(JNIEnv *env, jobject thiz, SimulatorResourceModel &resModel);
+        static SimulatorResourceModelSP getResourceModelPtr(JNIEnv *env, jobject thiz);
+
+    private:
+        SimulatorResourceModel m_resourceModel;
+        SimulatorResourceModelSP m_resModelPtr;
+};
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_SimulatorResourceModel_create
+(JNIEnv *, jobject);
+
+JNIEXPORT jint JNICALL
+Java_org_oic_simulator_SimulatorResourceModel_size
+(JNIEnv *, jobject);
+
+JNIEXPORT jobject JNICALL
+Java_org_oic_simulator_SimulatorResourceModel_getAttributes
+(JNIEnv *, jobject);
+
+JNIEXPORT jobject JNICALL
+Java_org_oic_simulator_SimulatorResourceModel_getAttribute
+(JNIEnv *, jobject, jstring);
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_SimulatorResourceModel_addAttributeInt
+(JNIEnv *, jobject, jstring, jint);
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_SimulatorResourceModel_addAttributeDouble
+(JNIEnv *, jobject, jstring, jdouble);
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_SimulatorResourceModel_addAttributeBoolean
+(JNIEnv *, jobject, jstring, jboolean);
+
+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
+
+#endif
diff --git a/service/simulator/java/jni/simulator_resource_server_jni.cpp b/service/simulator/java/jni/simulator_resource_server_jni.cpp
new file mode 100644 (file)
index 0000000..9b0436a
--- /dev/null
@@ -0,0 +1,802 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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)
+{
+    std::cout << "onAutomationComplete JNI entry" << std::endl;
+    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 (nullptr == resource.get())
+    {
+        throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
+        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 (nullptr == resource.get())
+    {
+        throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
+        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 (nullptr == resource.get())
+    {
+        throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
+        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 (nullptr == resource.get())
+    {
+        throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
+        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;
+    }
+
+    SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env,
+                                         jobject);
+    if (nullptr == resource.get())
+    {
+        throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
+        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 (nullptr == resource.get())
+    {
+        throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
+        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 (nullptr == resource.get())
+    {
+        throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
+        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 (nullptr == resource.get())
+    {
+        throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
+        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 (nullptr == resource.get())
+    {
+        throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
+        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_NO_RESOURCE, "Resource not found!");
+        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_NO_RESOURCE, "Resource not found!");
+        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_NO_RESOURCE, "Resource not found!");
+        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_NO_RESOURCE, "Resource not found!");
+        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_NO_RESOURCE, "Resource not found!");
+        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, jobject listener)
+{
+    SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
+    if (!resource)
+    {
+        throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
+        return -1;
+    }
+
+    if (!listener)
+    {
+        throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK,
+                                  "Start Resource Automation failed! Callback not set");
+        return -1;
+    }
+
+    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, 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, jobject listener)
+{
+    SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
+    if (nullptr == resource.get())
+    {
+        throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
+        return -1;
+    }
+
+    if (!attrName)
+    {
+        throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid Attribute name!");
+        return -1;
+    }
+
+    if (!listener)
+    {
+        throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK,
+                                  "Start Attribute Automation failed! Callback not set");
+        return -1;
+    }
+
+    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, 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 (nullptr == resource.get())
+    {
+        throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
+        return;
+    }
+
+    resource->stopUpdateAutomation(automationId);
+    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 (nullptr == resource.get())
+    {
+        throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
+        return;
+    }
+
+    std::string str = env->GetStringUTFChars(jKey, NULL);
+    resource->removeAttribute(str);
+}
+
+JNIEXPORT jobjectArray JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_getObserversList
+(JNIEnv *env, jobject object)
+{
+    SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
+    if (nullptr == resource.get())
+    {
+        throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
+        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)
+        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 (nullptr == resource.get())
+    {
+        throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
+        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 (nullptr == resource.get())
+    {
+        throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
+        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 (nullptr == resource.get())
+    {
+        throwInvalidArgsException(env, SIMULATOR_NO_RESOURCE, "Resource not found!");
+        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
new file mode 100644 (file)
index 0000000..765d2b6
--- /dev/null
@@ -0,0 +1,137 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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, jobject);
+
+JNIEXPORT jint JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_startAttributeAutomation
+(JNIEnv *, jobject, jstring, 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/sdk/.classpath b/service/simulator/java/sdk/.classpath
new file mode 100644 (file)
index 0000000..11f3b6f
--- /dev/null
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+    <classpathentry kind="src" path="src" />
+    <classpathentry kind="con"
+        path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7" />
+    <classpathentry kind="output" path="bin" />
+</classpath>
diff --git a/service/simulator/java/sdk/.gitignore b/service/simulator/java/sdk/.gitignore
new file mode 100644 (file)
index 0000000..ae3c172
--- /dev/null
@@ -0,0 +1 @@
+/bin/
diff --git a/service/simulator/java/sdk/.project b/service/simulator/java/sdk/.project
new file mode 100644 (file)
index 0000000..e32400a
--- /dev/null
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+    <name>Simulator</name>
+    <comment></comment>
+    <projects>
+    </projects>
+    <buildSpec>
+        <buildCommand>
+            <name>org.eclipse.jdt.core.javabuilder</name>
+            <arguments>
+            </arguments>
+        </buildCommand>
+    </buildSpec>
+    <natures>
+        <nature>org.eclipse.jdt.core.javanature</nature>
+    </natures>
+</projectDescription>
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/DeviceInfo.java b/service/simulator/java/sdk/src/org/oic/simulator/DeviceInfo.java
new file mode 100644 (file)
index 0000000..090d4b9
--- /dev/null
@@ -0,0 +1,63 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.oic.simulator;
+
+/**
+ * This class contains remote device information and provides APIs to access it.
+ */
+public class DeviceInfo {
+    private String mName;
+    private String mID;
+    private String mSpecVersion;
+    private String mDMVVersion;
+
+    /**
+     * This method is for getting the device name.
+     * 
+     * @return Device name.
+     */
+    public String getName() {
+        return mName;
+    }
+
+    /**
+     * This method is for getting the device id.
+     * 
+     * @return Device id.
+     */
+    public String getID() {
+        return mID;
+    }
+
+    /**
+     * This method is for getting device specification version.
+     * 
+     * @return Specification version.
+     */
+    public String getSpecVersion() {
+        return mSpecVersion;
+    }
+
+    /**
+     * This method is for getting device data model version.
+     * 
+     * @return Device data model version.
+     */
+    public String getDataModelVersion() {
+        return mDMVVersion;
+    }
+}
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/IAutomation.java b/service/simulator/java/sdk/src/org/oic/simulator/IAutomation.java
new file mode 100644 (file)
index 0000000..e74fbd1
--- /dev/null
@@ -0,0 +1,32 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.oic.simulator;
+
+/**
+ * Interface for receiving 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
new file mode 100644 (file)
index 0000000..0d4c8a3
--- /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;
+
+/**
+ * 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);
+}
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/ILogger.java b/service/simulator/java/sdk/src/org/oic/simulator/ILogger.java
new file mode 100644 (file)
index 0000000..082e59e
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.oic.simulator;
+
+/**
+ * Interface for receiving log messages.
+ */
+public interface ILogger {
+    /**
+     * This enumeration contains different levels of log.
+     */
+    public enum Level {
+        INFO, DEBUG, WARNING, ERROR
+    }
+
+    /**
+     * This callback method will be called to notify the application about the
+     * status or problems along with their severity.
+     *
+     * @param time
+     *            Local time information when action/event logged.
+     * @param level
+     *            Level or Severity of the log.
+     * @param message
+     *            The log message describing the issue.
+     */
+    public void write(String time, int level, String message);
+}
\ No newline at end of file
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/IPlatformInfo.java b/service/simulator/java/sdk/src/org/oic/simulator/IPlatformInfo.java
new file mode 100644 (file)
index 0000000..9d948ce
--- /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;
+
+/**
+ * Interface for getting platform information.
+ */
+public interface IPlatformInfo {
+    /**
+     * Callback method which provides remote device platform information.
+     * 
+     * @param platformInfo
+     *            {@link PlatformInfo} object holding the platform information.
+     */
+    public void onPlatformFound(PlatformInfo platformInfo);
+}
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/InvalidArgsException.java b/service/simulator/java/sdk/src/org/oic/simulator/InvalidArgsException.java
new file mode 100644 (file)
index 0000000..d62fbdd
--- /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 org.oic.simulator;
+
+/**
+ * Class for representing invalid arguments exception.
+ */
+@SuppressWarnings("serial")
+public class InvalidArgsException extends SimulatorException {
+    public InvalidArgsException(int errorCode, String errMessage) {
+        super(errorCode, errMessage);
+    }
+}
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/NoSupportException.java b/service/simulator/java/sdk/src/org/oic/simulator/NoSupportException.java
new file mode 100644 (file)
index 0000000..914641f
--- /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 org.oic.simulator;
+
+/**
+ * Class for representing unsupported operations exception.
+ */
+@SuppressWarnings("serial")
+public class NoSupportException extends SimulatorException {
+    public NoSupportException(int errorCode, String errMessage) {
+        super(errorCode, errMessage);
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/OperationInProgressException.java b/service/simulator/java/sdk/src/org/oic/simulator/OperationInProgressException.java
new file mode 100644 (file)
index 0000000..c9127b5
--- /dev/null
@@ -0,0 +1,28 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.oic.simulator;
+
+/**
+ * Class for representing an exception that will be thrown to indicate requested
+ * operation is not allowed as other operation is in progress state.
+ */
+@SuppressWarnings("serial")
+public class OperationInProgressException extends SimulatorException {
+    public OperationInProgressException(int errorCode, String errMessage) {
+        super(errorCode, errMessage);
+    }
+}
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/PlatformInfo.java b/service/simulator/java/sdk/src/org/oic/simulator/PlatformInfo.java
new file mode 100644 (file)
index 0000000..2b97e13
--- /dev/null
@@ -0,0 +1,244 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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 contains remote device platform information and provide APIs
+ * access it.
+ */
+public class PlatformInfo {
+    private String mPlatformId;
+    private String m_manufacturerName;
+    private String m_manufacturerUrl;
+    private String m_modelNumber;
+    private String m_dateOfManufacture;
+    private String m_platformVersion;
+    private String m_operationSystemVersion;
+    private String m_hardwareVersion;
+    private String m_firmwareVersion;
+    private String m_supportUrl;
+    private String m_systemTime;
+
+    /**
+     * This method is for getting platform id.
+     * 
+     * @return Platform id.
+     */
+    public String getPlatformID() {
+        return mPlatformId;
+    }
+
+    /**
+     * This method is for setting platform id.
+     * 
+     * @param mPlatformId
+     *            Platform identifier.
+     */
+    public void setPlatformID(String mPlatformId) {
+        this.mPlatformId = mPlatformId;
+    }
+
+    /**
+     * This method is for getting manufacturer name.
+     * 
+     * @return Manufacturer name.
+     */
+    public String getManufacturerName() {
+        return m_manufacturerName;
+    }
+
+    /**
+     * This method is for setting manufacturer name.
+     * 
+     * @param m_manufacturerName
+     *            Manufacturer name.
+     */
+    public void setManufacturerName(String m_manufacturerName) {
+        this.m_manufacturerName = m_manufacturerName;
+    }
+
+    /**
+     * This method is for getting manufacturer URL.
+     * 
+     * @return Manufacturer URL.
+     */
+    public String getManufacturerUrl() {
+        return m_manufacturerUrl;
+    }
+
+    /**
+     * This method is for setting manufacturer URL.
+     * 
+     * @param m_manufacturerUrl
+     *            Manufacturer URL.
+     */
+    public void setManufacturerUrl(String m_manufacturerUrl) {
+        this.m_manufacturerUrl = m_manufacturerUrl;
+    }
+
+    /**
+     * This method is for getting model number.
+     * 
+     * @return Model number.
+     */
+    public String getModelNumber() {
+        return m_modelNumber;
+    }
+
+    /**
+     * This method is for setting model number.
+     * 
+     * @param m_modelNumber
+     *            Model number.
+     */
+    public void setModelNumber(String m_modelNumber) {
+        this.m_modelNumber = m_modelNumber;
+    }
+
+    /**
+     * This method is for getting date of manufacture.
+     * 
+     * @return Date of manufacture.
+     */
+    public String getDateOfManufacture() {
+        return m_dateOfManufacture;
+    }
+
+    /**
+     * This method is for setting date of manufacture.
+     * 
+     * @param m_dateOfManufacture
+     *            Date of manufacture.
+     */
+    public void setDateOfManufacture(String m_dateOfManufacture) {
+        this.m_dateOfManufacture = m_dateOfManufacture;
+    }
+
+    /**
+     * This method is for getting platform version.
+     * 
+     * @return Platform version.
+     */
+    public String getPlatformVersion() {
+        return m_platformVersion;
+    }
+
+    /**
+     * This method is for setting platform version.
+     * 
+     * @param m_platformVersion
+     *            Platform version.
+     */
+    public void setPlatformVersion(String m_platformVersion) {
+        this.m_platformVersion = m_platformVersion;
+    }
+
+    /**
+     * This method is for getting operating system version.
+     * 
+     * @return Operation system version.
+     */
+    public String getOperationSystemVersion() {
+        return m_operationSystemVersion;
+    }
+
+    /**
+     * This method is for setting operating system version.
+     * 
+     * @param m_operationSystemVersion
+     *            Operation system version.
+     */
+    public void setOperationSystemVersion(String m_operationSystemVersion) {
+        this.m_operationSystemVersion = m_operationSystemVersion;
+    }
+
+    /**
+     * This method is for getting hardware version.
+     * 
+     * @return Hardware version.
+     */
+    public String getHardwareVersion() {
+        return m_hardwareVersion;
+    }
+
+    /**
+     * This method is for setting hardware version.
+     * 
+     * @param m_hardwareVersion
+     *            Hardware version.
+     */
+    public void setHardwareVersion(String m_hardwareVersion) {
+        this.m_hardwareVersion = m_hardwareVersion;
+    }
+
+    /**
+     * This method is for getting firmware version.
+     * 
+     * @return Firmware version.
+     */
+    public String getFirmwareVersion() {
+        return m_firmwareVersion;
+    }
+
+    /**
+     * This method is for setting firmware version.
+     * 
+     * @param m_firmwareVersion
+     *            Firmware version.
+     */
+    public void setFirmwareVersion(String m_firmwareVersion) {
+        this.m_firmwareVersion = m_firmwareVersion;
+    }
+
+    /**
+     * This method is for getting support link URL.
+     * 
+     * @return URL of support link.
+     */
+    public String getSupportUrl() {
+        return m_supportUrl;
+    }
+
+    /**
+     * This method is for setting support link URL.
+     * 
+     * @param m_supportUrl
+     *            URL of support link.
+     */
+    public void setSupportUrl(String m_supportUrl) {
+        this.m_supportUrl = m_supportUrl;
+    }
+
+    /**
+     * This method is for getting system time.
+     * 
+     * @return System time.
+     */
+    public String getSystemTime() {
+        return m_systemTime;
+    }
+
+    /**
+     * This method is for setting system time.
+     * 
+     * @param m_systemTime
+     *            System time.
+     */
+    public void setSystemTime(String m_systemTime) {
+        this.m_systemTime = m_systemTime;
+    }
+}
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/ResourceAttribute.java b/service/simulator/java/sdk/src/org/oic/simulator/ResourceAttribute.java
new file mode 100644 (file)
index 0000000..9f39fc5
--- /dev/null
@@ -0,0 +1,139 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+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 {
+        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
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/SimulatorException.java b/service/simulator/java/sdk/src/org/oic/simulator/SimulatorException.java
new file mode 100644 (file)
index 0000000..7b4c5c8
--- /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.
+ */
+
+package org.oic.simulator;
+
+/**
+ * Base class for simulator exceptions that will be thrown to indicate general
+ * exceptions.
+ */
+@SuppressWarnings("serial")
+public class SimulatorException extends Exception {
+
+    private SimulatorResult errorCode;
+    private String          errorMessage;
+
+    public SimulatorException(int errorCode, String errMessage) {
+        this.errorCode = SimulatorResult.get(errorCode);
+        this.errorMessage = errMessage;
+    }
+
+    public SimulatorResult code() {
+        return errorCode;
+    }
+
+    public String message() {
+        return errorMessage;
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/SimulatorManager.java b/service/simulator/java/sdk/src/org/oic/simulator/SimulatorManager.java
new file mode 100644 (file)
index 0000000..a70d4ce
--- /dev/null
@@ -0,0 +1,210 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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 methods for creation, discovery and deletion of
+ * resources.
+ */
+public class SimulatorManager {
+
+    /**
+     * API for creating a resource from a RAML configuration file whose path is
+     * given as a parameter.
+     *
+     * @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.
+     * 
+     * @throws InvalidArgsException
+     *             Thrown if the input parameters are empty.
+     * @throws SimulatorException
+     *             Thrown for other errors.
+     */
+    public static SimulatorResourceServer createResource(String configPath,
+            IResourceModelChangedListener listener)
+            throws InvalidArgsException, SimulatorException {
+        SimulatorResourceServer simulatorResourceServerObj;
+        simulatorResourceServerObj = SimulatorManagerNativeInterface
+                .createResource(configPath, listener);
+        return simulatorResourceServerObj;
+    }
+
+    /**
+     * API for creating a set of resources from a RAML configuration file whose
+     * path is given as a parameter.
+     *
+     * @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.
+     * 
+     * @throws InvalidArgsException
+     *             Thrown if the input parameters are empty.
+     * @throws SimulatorException
+     *             Thrown for other errors.
+     */
+    public static SimulatorResourceServer[] createResource(String configPath,
+            int count, IResourceModelChangedListener listener)
+            throws InvalidArgsException, SimulatorException {
+        SimulatorResourceServer[] simulatorResourceServers;
+        simulatorResourceServers = SimulatorManagerNativeInterface
+                .createResources(configPath, count, listener);
+        return simulatorResourceServers;
+    }
+
+    /**
+     * API for deleting 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 void deleteResource(SimulatorResourceServer resource)
+            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);
+    }
+
+    /**
+     * API for discovering all types of resources in the network. Callback is
+     * called when a resource is discovered in the network.
+     *
+     * @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 void findResources(IFindResourceListener listener)
+            throws InvalidArgsException, SimulatorException {
+        SimulatorManagerNativeInterface.findResources(null, listener);
+    }
+
+    /**
+     * API for discovering specific type of resources in the network. Callback
+     * is called when a resource is discovered in the network.
+     *
+     * @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 void findResources(String resourceType,
+            IFindResourceListener listener) throws InvalidArgsException,
+            SimulatorException {
+        if (null == resourceType || resourceType.isEmpty()) {
+            throw new InvalidArgsException(
+                    SimulatorResult.SIMULATOR_INVALID_PARAM.ordinal(),
+                    "Resource type is empty");
+        }
+        SimulatorManagerNativeInterface.findResources(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);
+    }
+
+    /**
+     * API to set the device information.
+     * 
+     * @param deviceInfo
+     *            Device information.
+     */
+    public static void setDeviceInfo(String deviceInfo) {
+        SimulatorManagerNativeInterface.setDeviceInfo(deviceInfo);
+    }
+
+    /**
+     * API to get the device information asynchronously via the listener.
+     * 
+     * @param listener
+     *            Interface for receiving the device information.
+     */
+    public static void getDeviceInfo(IDeviceInfo listener) {
+        SimulatorManagerNativeInterface.getDeviceInfo(listener);
+    }
+
+    /**
+     * API to set the platform information.
+     * 
+     * @param platformInfo
+     *            {@link PlatformInfo} - Platform information.
+     */
+    public static void setPlatformInfo(PlatformInfo platformInfo) {
+        SimulatorManagerNativeInterface.setPlatformInfo(platformInfo);
+    }
+
+    /**
+     * API to get the platform information asynchronously via the listener.
+     * 
+     * @param listener
+     *            Interface for receiving the platform information.
+     */
+    public static void getPlatformInfo(IPlatformInfo listener) {
+        SimulatorManagerNativeInterface.getPlatformInfo(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
new file mode 100644 (file)
index 0000000..42da05c
--- /dev/null
@@ -0,0 +1,161 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+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 InvalidArgsException, 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 findResources(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/SimulatorResourceModel.java b/service/simulator/java/sdk/src/org/oic/simulator/SimulatorResourceModel.java
new file mode 100644 (file)
index 0000000..4b89502
--- /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 org.oic.simulator;
+
+import org.oic.simulator.ResourceAttribute;
+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.
+ */
+public class SimulatorResourceModel {
+
+    /**
+     * 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.
+     */
+    public SimulatorResourceModel() {
+        create();
+    }
+
+    /**
+     * Method for adding an attribute whose value is of type int.
+     * 
+     * @param name
+     *            Name of the attribute
+     * @param value
+     *            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.
+     */
+    public native void addAttributeInt(String name, int value)
+            throws InvalidArgsException, SimulatorException;
+
+    /**
+     * Method for adding an attribute whose value is of type double.
+     * 
+     * @param name
+     *            Name of the attribute
+     * @param value
+     *            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.
+     */
+    public native void addAttributeDouble(String name, double value)
+            throws InvalidArgsException, SimulatorException;
+
+    /**
+     * Method for adding an attribute whose value is of type boolean.
+     * 
+     * @param name
+     *            Name of the attribute
+     * @param value
+     *            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.
+     */
+    public native void addAttributeBoolean(String name, boolean value)
+            throws InvalidArgsException, SimulatorException;
+
+    /**
+     * Method for adding an attribute whose value is of type string.
+     * 
+     * @param name
+     *            Name of the attribute
+     * @param value
+     *            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.
+     */
+    public native void addAttributeString(String name, String value)
+            throws InvalidArgsException, SimulatorException;
+
+    /**
+     * Method for getting the number of attributes this model comprised of.
+     *
+     * @return Number of attributes.
+     * 
+     * @throws SimulatorException
+     *             This exception will be thrown either if the resource model is
+     *             not found or for some general errors.
+     */
+    public native int size() throws SimulatorException;
+
+    /**
+     * Method for getting all attributes.
+     *
+     * @return Map of attributes with attribute name as the key and its
+     *         corresponding {@link ResourceAttribute} object as the value.
+     * 
+     * @throws SimulatorException
+     *             This exception will be thrown either if the resource model is
+     *             not found or for some general errors.
+     */
+    public native Map<String, ResourceAttribute> getAttributes()
+            throws SimulatorException;
+
+    /**
+     * Method for getting a specific attribute by its name.
+     *
+     * @param attrName
+     *            Name of the attribute
+     *
+     * @return An object of {@link ResourceAttribute}.
+     * 
+     * @throws InvalidArgsException
+     *             This exception will be thrown if the attribute does not
+     *             exist.
+     * 
+     * @throws SimulatorException
+     *             This exception will be thrown either if the resource model is
+     *             not found or for some general errors.
+     */
+    public native ResourceAttribute getAttribute(String attrName)
+            throws InvalidArgsException, SimulatorException;
+
+    private SimulatorResourceModel(long nativeHandle) {
+        this.nativeHandle = nativeHandle;
+    }
+
+    @Override
+    protected void finalize() throws Throwable {
+        try {
+            dispose();
+        } catch(Throwable t){
+            throw t;
+        } finally{
+            System.out.println("Calling finalize of Super Class");
+            super.finalize();
+        }
+    }
+
+    private native void create();
+
+    private native void dispose();
+
+    private long nativeHandle;
+}
\ No newline at end of file
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/SimulatorResult.java b/service/simulator/java/sdk/src/org/oic/simulator/SimulatorResult.java
new file mode 100644 (file)
index 0000000..62d1c4c
--- /dev/null
@@ -0,0 +1,172 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.oic.simulator;
+
+/**
+ * This Enum contains Status codes for Success and Errors.
+ */
+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_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_RESPONSE_CODE,
+    SIMULATOR_UKNOWN_PROPERTY,
+    SIMULATOR_TYPE_MISMATCH,
+    SIMULATOR_BAD_VALUE,
+    /** Simulator specific error codes - END */
+
+    SIMULATOR_ERROR;
+
+    public static SimulatorResult get(int ordinal) {
+
+        SimulatorResult result;
+
+        if (ordinal == 0)
+            result = SimulatorResult.values()[0];
+        else if (ordinal == 1)
+            result = SimulatorResult.values()[1];
+        else if (ordinal == 2)
+            result = SimulatorResult.values()[2];
+        else if (ordinal == 3)
+            result = SimulatorResult.values()[3];
+
+        else if (ordinal == 20)
+            result = SimulatorResult.values()[4];
+        else if (ordinal == 21)
+            result = SimulatorResult.values()[5];
+        else if (ordinal == 22)
+            result = SimulatorResult.values()[6];
+        else if (ordinal == 23)
+            result = SimulatorResult.values()[7];
+        else if (ordinal == 24)
+            result = SimulatorResult.values()[8];
+        else if (ordinal == 25)
+            result = SimulatorResult.values()[9];
+        else if (ordinal == 26)
+            result = SimulatorResult.values()[10];
+        else if (ordinal == 27)
+            result = SimulatorResult.values()[11];
+        else if (ordinal == 28)
+            result = SimulatorResult.values()[12];
+        else if (ordinal == 29)
+            result = SimulatorResult.values()[13];
+        else if (ordinal == 30)
+            result = SimulatorResult.values()[14];
+        else if (ordinal == 31)
+            result = SimulatorResult.values()[15];
+        else if (ordinal == 32)
+            result = SimulatorResult.values()[16];
+        else if (ordinal == 33)
+            result = SimulatorResult.values()[17];
+        else if (ordinal == 34)
+            result = SimulatorResult.values()[18];
+        else if (ordinal == 35)
+            result = SimulatorResult.values()[19];
+        else if (ordinal == 36)
+            result = SimulatorResult.values()[20];
+        else if (ordinal == 37)
+            result = SimulatorResult.values()[21];
+        else if (ordinal == 38)
+            result = SimulatorResult.values()[22];
+        else if (ordinal == 39)
+            result = SimulatorResult.values()[23];
+        else if (ordinal == 40)
+            result = SimulatorResult.values()[24];
+        else if (ordinal == 41)
+            result = SimulatorResult.values()[25];
+        else if (ordinal == 42)
+            result = SimulatorResult.values()[26];
+        else if (ordinal == 43)
+            result = SimulatorResult.values()[27];
+        else if (ordinal == 44)
+            result = SimulatorResult.values()[28];
+        else if (ordinal == 45)
+            result = SimulatorResult.values()[29];
+        else if (ordinal == 46)
+            result = SimulatorResult.values()[30];
+                
+        else if (ordinal == 128)
+            result = SimulatorResult.values()[31];
+        else if (ordinal == 129)
+            result = SimulatorResult.values()[32];
+        else if (ordinal == 130)
+            result = SimulatorResult.values()[33];
+
+        else if (ordinal == 131 || ordinal == 47)
+            result = SimulatorResult.values()[34];
+        else if (ordinal == 132 || ordinal == 48)
+            result = SimulatorResult.values()[35];
+        else if (ordinal == 133 || ordinal == 49)
+            result = SimulatorResult.values()[36];
+        else if (ordinal == 134 || ordinal == 50)
+            result = SimulatorResult.values()[37];
+        
+        else if (ordinal == 135 || ordinal == 51)
+            result = SimulatorResult.values()[38];
+        else if (ordinal == 136 || ordinal == 52)
+            result = SimulatorResult.values()[39];
+        else if (ordinal == 137 || ordinal == 53)
+            result = SimulatorResult.values()[40];
+        else if (ordinal == 138 || ordinal == 54)
+            result = SimulatorResult.values()[41];
+        
+        else
+            result = SimulatorResult.values()[42];
+        return result;
+    }
+}
\ No newline at end of file
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
new file mode 100644 (file)
index 0000000..dcd9557
--- /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.
+ */
+
+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
new file mode 100644 (file)
index 0000000..3436a3d
--- /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 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
new file mode 100644 (file)
index 0000000..f09feaf
--- /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.
+ */
+
+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
new file mode 100644 (file)
index 0000000..5f4cbe0
--- /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.
+ */
+
+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
new file mode 100644 (file)
index 0000000..c44b917
--- /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 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
new file mode 100644 (file)
index 0000000..1114f6b
--- /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.
+ */
+
+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);
+}
\ No newline at end of file
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
new file mode 100644 (file)
index 0000000..94eb195
--- /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.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
new file mode 100644 (file)
index 0000000..9f32d1c
--- /dev/null
@@ -0,0 +1,34 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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
new file mode 100644 (file)
index 0000000..cfa9d78
--- /dev/null
@@ -0,0 +1,378 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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;
+
+/**
+ * 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;
+    }
+
+    /**
+     * Method to get the URI for this resource.
+     * 
+     * @return Resource URI
+     */
+    public String getUri() {
+        return mUri;
+    }
+
+    /**
+     * Method to get the observe capability of this resource.
+     * 
+     * @return True if the resource is observable, otherwise false.
+     */
+    public boolean getIsObservable() {
+        return mIsObservable;
+    }
+
+    /**
+     * Method to get the connectivity type for this resource.
+     * 
+     * @return Connectivity type.
+     */
+    public SimulatorConnectivityType getConnectivityType() {
+        return SimulatorConnectivityType.getConnectivityType(mConnType);
+    }
+
+    /**
+     * Method to get the list of resource types.
+     * 
+     * @return List of resource types.
+     */
+    public LinkedList<String> getResourceTypes() {
+        return mResTypes;
+    }
+
+    /**
+     * Method to get the list of resource interfaces.
+     * 
+     * @return List of resource interfaces.
+     */
+    public LinkedList<String> getResourceInterfaces() {
+        return mResInterfaces;
+    }
+
+    /**
+     * Method to get a string representation of the host address of the remote
+     * resource.
+     * 
+     * @return Host address.
+     */
+    public String getHost() {
+        return mHost;
+    }
+
+    /**
+     * Method to get a unique Id for the resource.
+     * 
+     * @return Unique ID.
+     */
+    public String getId() {
+        return mId;
+    }
+
+    /**
+     * Method to set observation on the remote 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 observe(SimulatorObserveType observeType,
+            Map<String, String> queryParamsMap,
+            IObserveListener onObserveListener) throws InvalidArgsException,
+            SimulatorException;
+
+    /**
+     * Method to cancel the observation on 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 cancelObserve() throws InvalidArgsException,
+            SimulatorException;
+
+    /**
+     * Method to get the attributes of a resource.
+     * 
+     * @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 {
+        this.get(null, queryParamsMap, onGetListener);
+    }
+
+    /**
+     * Method to get the attributes of a resource.
+     * 
+     * @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 native void get(String resourceInterface,
+            Map<String, String> queryParamsMap, IGetListener onGetListener)
+            throws InvalidArgsException, NoSupportException, SimulatorException;
+
+    /**
+     * Method to set the representation of a resource (via PUT)
+     * 
+     * @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 {
+        this.put(null, representation, queryParamsMap, onPutListener);
+    }
+
+    /**
+     * Method to set the representation of a resource (via PUT).
+     * 
+     * @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.
+     */
+    private native void put(String resourceInterface,
+            SimulatorResourceModel representation,
+            Map<String, String> queryParamsMap, IPutListener onPutListener)
+            throws InvalidArgsException, NoSupportException, SimulatorException;
+
+    /**
+     * Method to POST on a resource.
+     * 
+     * @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 {
+        this.post(null, representation, queryParamsMap, onPostListener);
+    }
+
+    /**
+     * Method to POST on a resource.
+     * 
+     * @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 native void post(String resourceInterface,
+            SimulatorResourceModel representation,
+            Map<String, String> queryParamsMap, IPostListener onPostListener)
+            throws InvalidArgsException, NoSupportException, SimulatorException;
+
+    /**
+     * Method to set the RAML file path from application
+     * 
+     * @param ramlPath
+     *            RAML configuration file path
+     * 
+     * @throws InvalidArgsException
+     *             Thrown if the RAML configuration file path is invalid.
+     * @throws SimulatorException
+     *             Thrown for other errors.
+     */
+    public native void configureRAMLPath(String ramlPath)
+            throws InvalidArgsException, SimulatorException;
+
+    /**
+     * Method to start verification of a resource using automation.
+     * 
+     * @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);
+    }
+
+    private native int startVerification(int requestType,
+            IVerificationListener onVerifyListener)
+            throws InvalidArgsException, NoSupportException,
+            OperationInProgressException, SimulatorException;
+
+    /**
+     * Method to stop verification of a resource previously started.
+     * 
+     * @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;
+
+    @Override
+    protected void finalize() throws Throwable {
+        super.finalize();
+
+        dispose();
+    }
+
+    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
new file mode 100644 (file)
index 0000000..7c5e2b1
--- /dev/null
@@ -0,0 +1,55 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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/serviceprovider/AutomationType.java b/service/simulator/java/sdk/src/org/oic/simulator/serviceprovider/AutomationType.java
new file mode 100644 (file)
index 0000000..06409ff
--- /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.
+ */
+
+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
new file mode 100644 (file)
index 0000000..11750ce
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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
new file mode 100644 (file)
index 0000000..744116b
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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
new file mode 100644 (file)
index 0000000..e082f80
--- /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.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
new file mode 100644 (file)
index 0000000..a352e4c
--- /dev/null
@@ -0,0 +1,496 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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;
+    }
+
+    @Override
+    protected void finalize() throws Throwable {
+        try {
+            dispose();
+        } catch(Throwable t){
+            throw t;
+        } finally{
+            System.out.println("Calling finalize of Super Class");
+            super.finalize();
+        }
+    }
+
+    /**
+     * Native function to get the {@link SimulatorResourceModel} of the
+     * corresponding resource.
+     *
+     * @return {@link SimulatorResourceModel} object on success, otherwise null.
+     * 
+     * @throws InvalidArgsException
+     *             This exception will be thrown if the native resource object
+     *             is invalid. values.
+     * @throws SimulatorException
+     *             This exception will be thrown for other errors.
+     */
+    public native SimulatorResourceModel getModel()
+            throws InvalidArgsException, SimulatorException;
+
+    /**
+     * Native function 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;
+
+    /**
+     * Native function 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;
+
+    /**
+     * Native function 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;
+
+    /**
+     * Native function 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;
+
+    /**
+     * Native function 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;
+
+    /**
+     * Native function 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;
+
+    /**
+     * Native function 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;
+
+    /**
+     * Native function 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;
+
+    /**
+     * Native function to automatically update the value of an attribute from
+     * its allowed values.
+     *
+     * @param attrName
+     *            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 attrName,
+            int index) throws InvalidArgsException, SimulatorException;
+
+    /**
+     * Native function to set the range of allowed values. This function is
+     * intended to be used for integral type attributes.
+     *
+     * @param attrName
+     *            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 attrName, int min, int max)
+            throws InvalidArgsException, SimulatorException;
+
+    /**
+     * Native function 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;
+
+    /**
+     * Native function 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;
+
+    /**
+     * Native function 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;
+
+    /**
+     * Native function 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 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,
+            IAutomation listener) throws InvalidArgsException,
+            SimulatorException {
+        return startResourceAutomation(typeOfAutomation.getValue(), listener);
+    }
+
+    private native int startResourceAutomation(int typeOfAutomation,
+            IAutomation listener) throws InvalidArgsException,
+            SimulatorException;
+
+    /**
+     * Native function 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 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, IAutomation listener)
+            throws InvalidArgsException, SimulatorException {
+        return startAttributeAutomation(attrName, typeOfAutomation.getValue(),
+                listener);
+    }
+
+    private native int startAttributeAutomation(String attrName,
+            int typeOfAutomation, IAutomation listener)
+            throws InvalidArgsException, SimulatorException;
+
+    /**
+     * Native function to stop the automation.
+     *
+     * @param automationId
+     *            Using which a specific automation can be stopped.
+     * 
+     * @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 stopAutomation(int automationId)
+            throws InvalidArgsException, SimulatorException;
+
+    /**
+     * Native function to remove an attribute from the resource model.
+     *
+     * @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;
+
+    /**
+     * Native function to get the details of a list of observers.
+     * 
+     * @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;
+
+    /**
+     * Native function to set callback to receive the clients information who are started or stopped observing the simulated resource.
+     * 
+     * @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;
+
+    /**
+     * Native function which sends notification 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;
+
+    /**
+     * Native function which sends notification 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;
+
+    /**
+     * Native function to release the memory allocated to the native object for
+     * SimulatorResourceServer.
+     */
+    private native void dispose();
+}
diff --git a/service/simulator/ramlparser/SConscript b/service/simulator/ramlparser/SConscript
new file mode 100755 (executable)
index 0000000..0a4aa6e
--- /dev/null
@@ -0,0 +1,50 @@
+#******************************************************************\r
+#\r
+# Copyright 2014 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
+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','YamlParser'])\r
+raml_env.AppendUnique(LIBS = ['pthread'])\r
+\r
+raml_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x'])\r
+\r
+######################################################################\r
+# Source files and Targets\r
+######################################################################\r
+raml_src = [env.Glob('raml/model/*.cpp'), env.Glob('raml/jsonSchemaParser/*.cpp'), env.Glob('raml/*.cpp')]\r
+ramlsdk = raml_env.SharedLibrary('RamlParser', raml_src)\r
+\r
+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
new file mode 100755 (executable)
index 0000000..f26a3c4
--- /dev/null
@@ -0,0 +1,30 @@
+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
new file mode 100755 (executable)
index 0000000..9ff56f7
--- /dev/null
@@ -0,0 +1,411 @@
+#include "RamlParser.h"\r
+#include <iostream>\r
+#include <string>\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 << "Name : " << pro.second->getName() << std::endl;\r
+        std::cout << "default : " << pro.second->getValue() << std::endl;\r
+        std::cout << "update_frequency : " << pro.second->getUpdateFrequencyTime() << std::endl;\r
+        int min = 0, max = 0, multipleOf = 0;\r
+        pro.second->getRange(min, max, multipleOf);\r
+\r
+        std::cout << "range_min : " << min << std::endl;\r
+        std::cout << "range_max : " << max << std::endl;\r
+        std::cout << "allowed values : "  << std::endl;\r
+        for (auto v :  pro.second->getAllowedValues())\r
+            std::cout <<  v << "    ";\r
+        std::cout << std::endl;\r
+\r
+    }\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(Properties *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
+    int type = prop->getValueType();\r
+    if (type)\r
+    {\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
+    else\r
+    {\r
+        std::cout << "Defaut: " << prop->getValueInt() << std::endl;\r
+        for (auto tt : prop->getAllowedValuesString())\r
+        {\r
+            std::cout << "enum value : " << tt << 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
+        }\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
+    std::cout << "MultipleOf: " << mul << std::endl;\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
+    RamlParser *ramlParser = new 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
+}\r
+\r
diff --git a/service/simulator/ramlparser/raml/IncludeResolver.cpp b/service/simulator/ramlparser/raml/IncludeResolver.cpp
new file mode 100755 (executable)
index 0000000..0dbf0bb
--- /dev/null
@@ -0,0 +1,102 @@
+/******************************************************************\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 "IncludeResolver.h"\r
+\r
+namespace RAML\r
+{\r
+\r
+    YAML::Node IncludeResolver::readToYamlNode(const YAML::Node &yamlFile )\r
+    {\r
+        std::string value = yamlFile.as<std::string>();\r
+        try\r
+        {\r
+            YAML::Node yamlInclueNode = YAML::LoadFile(value);\r
+            return yamlInclueNode;\r
+        }\r
+        catch (YAML::ParserException &e)\r
+        {\r
+            throw RamlParserException(e.mark, e.msg);\r
+        }\r
+        catch (YAML::RepresentationException &e)\r
+        {\r
+            throw RamlRepresentationException(e.mark, e.msg);\r
+        }\r
+        catch (YAML::BadFile &e)\r
+        {\r
+            throw RamlBadFile(e.mark, e.msg);\r
+        }\r
+        catch (JsonException &e)\r
+        {\r
+            throw;\r
+        }\r
+    }\r
+\r
+    IncludeResolver::FileType IncludeResolver::getFileType(const YAML::Node &yamlNode )\r
+    {\r
+        IncludeResolver::FileType fileType = IncludeResolver::FileType::NOTAG;\r
+        if (yamlNode.Tag() == "!include")\r
+        {\r
+            std::string value = yamlNode.as<std::string>();\r
+            std::size_t found = value.find_last_of(".");\r
+            if (found > value.length())\r
+            {\r
+                fileType = IncludeResolver::FileType::FILE;\r
+                return fileType;\r
+            }\r
+            std::string extension = value.substr(found + 1);\r
+            if (std::find(Keys::AllowedRamlYamlTypes.begin(), Keys::AllowedRamlYamlTypes.end(),\r
+                          extension) != Keys::AllowedRamlYamlTypes.end())\r
+                fileType = IncludeResolver::FileType::NODE;\r
+            else if (extension == Keys::Json)\r
+                fileType = IncludeResolver::FileType::JSON;\r
+            else\r
+                fileType = IncludeResolver::FileType::FILE;\r
+        }\r
+        return fileType;\r
+    }\r
+\r
+    cJSON *IncludeResolver::readToJson(const YAML::Node &jsonFile)\r
+    {\r
+        return cJSON_Parse(readFromFile(jsonFile).c_str());\r
+    }\r
+\r
+    std::string IncludeResolver::readFromFile(const YAML::Node &file )\r
+    {\r
+        std::string val = file.as<std::string>();\r
+        std::ifstream fin((m_path + val).c_str());\r
+        if (!fin)\r
+            throw RamlParserException("Error Include File not present " + m_path + val);\r
+        std::stringstream buffer;\r
+        buffer << fin.rdbuf();\r
+        return buffer.str();\r
+    }\r
+    cJSON *IncludeResolver::readToJson(const std::string &jsonFileName)\r
+    {\r
+        std::ifstream fin((m_path + jsonFileName).c_str());\r
+        if (!fin)\r
+            throw JsonException("Error Json Referenced File not present " + m_path + jsonFileName);\r
+        std::stringstream buffer;\r
+        buffer << fin.rdbuf();\r
+        std::string str = buffer.str();\r
+        return cJSON_Parse(str.c_str());\r
+    }\r
+\r
+}\r
diff --git a/service/simulator/ramlparser/raml/IncludeResolver.h b/service/simulator/ramlparser/raml/IncludeResolver.h
new file mode 100755 (executable)
index 0000000..f659200
--- /dev/null
@@ -0,0 +1,58 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#ifndef INCLUDE_RESOLVER_H\r
+#define INCLUDE_RESOLVER_H\r
+\r
+#include "yaml-cpp/yaml.h"\r
+#include "cJSON.h"\r
+#include "Utils.h"\r
+#include <fstream>\r
+#include "yaml-cpp/exceptions.h"\r
+#include "RamlExceptions.h"\r
+\r
+namespace RAML\r
+{\r
+    class IncludeResolver\r
+    {\r
+\r
+        public:\r
+            enum class FileType\r
+            {\r
+                NODE, JSON, FILE, NOTAG , ERROR\r
+            };\r
+\r
+\r
+        public:\r
+            YAML::Node readToYamlNode(const YAML::Node &yamlFile );\r
+            cJSON *readToJson(const YAML::Node &jsonFile );\r
+            std::string readFromFile(const YAML::Node &file );\r
+            FileType getFileType(const YAML::Node &yamlNode );\r
+            cJSON *readToJson(const std::string &jsonFileName);\r
+\r
+            IncludeResolver() {}\r
+            IncludeResolver(const std::string &path) : m_path(path) {}\r
+        private:\r
+            std::string m_path;\r
+    };\r
+    typedef std::shared_ptr<IncludeResolver> IncludeResolverPtr;\r
+\r
+}\r
+#endif\r
diff --git a/service/simulator/ramlparser/raml/RamlErrorCodes.h b/service/simulator/ramlparser/raml/RamlErrorCodes.h
new file mode 100755 (executable)
index 0000000..bb43a69
--- /dev/null
@@ -0,0 +1,31 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#ifndef RAML_ERROR_CODES_H_\r
+#define RAML_ERROR_CODES_H_\r
+\r
+typedef enum\r
+{\r
+    RAML_PARSER_OK = 0,\r
+\r
+    RAML_FILE_PATH_REQUIRED,\r
+    RAML_PARSER_ERROR = 255\r
+} RamlParserResult;\r
+#endif\r
diff --git a/service/simulator/ramlparser/raml/RamlExceptions.cpp b/service/simulator/ramlparser/raml/RamlExceptions.cpp
new file mode 100755 (executable)
index 0000000..63f67dd
--- /dev/null
@@ -0,0 +1,35 @@
+/******************************************************************\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 "RamlExceptions.h"\r
+namespace RAML\r
+{\r
+    const char *RamlException::what() const noexcept\r
+    {\r
+        if (m_mark.is_null())\r
+        {\r
+            return m_message.c_str();\r
+        }\r
+        std::stringstream output;\r
+        output << "Error at line " << m_mark.line + 1 << ", column "\r
+               << m_mark.column + 1 << ": " << m_message;\r
+        return output.str().c_str();\r
+    }\r
+}\r
diff --git a/service/simulator/ramlparser/raml/RamlExceptions.h b/service/simulator/ramlparser/raml/RamlExceptions.h
new file mode 100755 (executable)
index 0000000..c6f884b
--- /dev/null
@@ -0,0 +1,73 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#ifndef RAML_EXCEPTIONS_H_\r
+#define RAML_EXCEPTIONS_H_\r
+\r
+#include <exception>\r
+#include "RamlErrorCodes.h"\r
+#include "yaml-cpp/exceptions.h"\r
+\r
+namespace RAML\r
+{\r
+    class RamlException : public std::exception\r
+    {\r
+        public:\r
+            RamlException(const std::string &message) : m_message(message) {}\r
+            RamlException(const YAML::Mark &mark, const std::string &message): m_message(message),\r
+                m_mark(mark) {}\r
+            virtual const char *what() const noexcept;\r
+            virtual ~RamlException() throw() {}\r
+\r
+        private:\r
+            std::string m_message;\r
+            YAML::Mark m_mark;\r
+    };\r
+\r
+    class RamlParserException : public RamlException\r
+    {\r
+        public:\r
+            RamlParserException(const std::string &message): RamlException(message) {}\r
+            RamlParserException(const YAML::Mark &mark, const std::string &message): RamlException(mark,\r
+                        message) {}\r
+    };\r
+\r
+    class RamlRepresentationException : public RamlException\r
+    {\r
+        public:\r
+            RamlRepresentationException(const std::string &message): RamlException(message) {}\r
+            RamlRepresentationException(const YAML::Mark &mark, const std::string &message): RamlException(mark,\r
+                        message) {}\r
+    };\r
+\r
+    class RamlBadFile : public RamlException\r
+    {\r
+        public:\r
+            RamlBadFile(const std::string &message) : RamlException(message) {}\r
+            RamlBadFile(const YAML::Mark &mark, const std::string &message): RamlException(mark, message) {}\r
+    };\r
+    class JsonException : public RamlException\r
+    {\r
+        public:\r
+            JsonException(const std::string &message) : RamlException(message) {}\r
+\r
+    };\r
+}\r
+#endif\r
diff --git a/service/simulator/ramlparser/raml/RamlParser.cpp b/service/simulator/ramlparser/raml/RamlParser.cpp
new file mode 100755 (executable)
index 0000000..38ed45d
--- /dev/null
@@ -0,0 +1,228 @@
+/******************************************************************\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 <map>\r
+\r
+namespace RAML\r
+{\r
+    RamlPtr RamlParser::getRamlPtr(RamlParserResult &result)\r
+    {\r
+        result = m_ramlParserResult;\r
+        return m_ramlPtr;\r
+    }\r
+    RamlPtr RamlParser::getRamlPtr()\r
+    {\r
+        return m_ramlPtr;\r
+    }\r
+    void RamlParser::setDataFromRoot()\r
+    {\r
+        setTypes(getRamlPtr()->getResources());\r
+        setTraits(getRamlPtr()->getResources());\r
+        setBodyDefaultMediaType(getRamlPtr()->getResources());\r
+        setBodySchema(getRamlPtr()->getResources());\r
+    }\r
+    void RamlParser::setBodyDefaultMediaType(const std::map<std::string, RamlResourcePtr> &resource)\r
+    {\r
+        if (getRamlPtr()->getMediaType().empty())\r
+        {\r
+            return;\r
+        }\r
+        for (auto const & it : resource)\r
+        {\r
+            std::string type = getRamlPtr()->getMediaType();\r
+\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
+                {\r
+                    if (response.second->getResponseBody().empty())\r
+                    {\r
+                        response.second->setResponseBody(type);\r
+                    }\r
+                }\r
+            }\r
+            setBodyDefaultMediaType(it.second->getResources());\r
+        }\r
+    }\r
+    void RamlParser::setBodySchema(const std::map<std::string, RamlResourcePtr> &resource)\r
+    {\r
+        if (getRamlPtr()->getSchemas().empty())\r
+        {\r
+            return;\r
+        }\r
+        for (auto const & it : resource)\r
+        {\r
+            for (auto const & action :  it.second->getActions())\r
+            {\r
+                for (auto const & body :  action.second->getRequestBody())\r
+                {\r
+                    SchemaPtr schema = body.second->getSchema();\r
+\r
+                    if (schema != NULL)\r
+                    {\r
+                        std::string schemaValue = schema->getSchema();\r
+                        auto pos = std::find_if(getRamlPtr()->getSchemas().begin(), getRamlPtr()->getSchemas().end(),\r
+                                                [schemaValue](std::pair<std::string, SchemaPtr> const & pair)\r
+                        {\r
+                            return (pair.first == schemaValue);\r
+                        });\r
+                        if (pos != getRamlPtr()->getSchemas().end())\r
+                        {\r
+                            schema->setSchema((pos->second->getSchema()));\r
+                        }\r
+                    }\r
+                }\r
+                for (auto const & response : action.second->getResponses())\r
+                {\r
+                    for (auto const & body :  response.second->getResponseBody())\r
+                    {\r
+                        SchemaPtr schema = body.second->getSchema();\r
+                        if (schema != NULL)\r
+                        {\r
+                            std::string schemaValue = schema->getSchema();\r
+                            auto schemas = getRamlPtr()->getSchemas();\r
+\r
+                            auto iter = schemas.begin();\r
+                            for (; iter != schemas.end(); iter++)\r
+                            {\r
+                                if (((*iter).first) == schemaValue)\r
+                                    break;\r
+                            }\r
+                            if (iter != schemas.end())\r
+                            {\r
+                                schema->setSchema((*iter).second->getSchema());\r
+                            }\r
+                        }\r
+                    }\r
+                }\r
+            }\r
+            setBodySchema(it.second->getResources());\r
+        }\r
+    }\r
+    void RamlParser::setTypes(const std::map<std::string, RamlResourcePtr> &resource)\r
+    {\r
+        if (getRamlPtr()->getResourceTypes().empty())\r
+        {\r
+            return;\r
+        }\r
+        for (auto const & it : resource)\r
+        {\r
+            auto const &resourceTypes = getRamlPtr()->getResourceTypes();\r
+            std::string typeValue = it.second->getResourceType();\r
+\r
+            auto iter = resourceTypes.begin();\r
+            for (; iter != resourceTypes.end(); iter++)\r
+            {\r
+                if (((*iter).first) == typeValue)\r
+                    break;\r
+            }\r
+            if (iter != resourceTypes.end())\r
+            {\r
+                if ((*iter).second->getActions().empty())\r
+                    return;\r
+\r
+                for (auto resActions : (*iter).second->getActions())\r
+                {\r
+                    if (it.second->getActions().count(resActions.first) == 0)\r
+                        it.second->setAction(resActions.first, std::make_shared<Action>(*(resActions.second)));\r
+                }\r
+            }\r
+            setTypes(it.second->getResources());\r
+        }\r
+    }\r
+    void RamlParser::setTraits(const std::map<std::string, RamlResourcePtr> &resource)\r
+    {\r
+        if (getRamlPtr()->getTraits().empty())\r
+        {\r
+            return;\r
+        }\r
+        for (auto const & it : resource)\r
+        {\r
+            auto const &trait = getRamlPtr()->getTraits();\r
+            for (auto const & act : it.second->getActions())\r
+            {\r
+                for (const std::string & traitValue :  act.second->getTraits())\r
+                {\r
+                    auto iter = trait.begin();\r
+                    for (; iter != trait.end(); iter++)\r
+                    {\r
+                        if (((*iter).first) == traitValue)\r
+                            break;\r
+                    }\r
+                    if (iter != trait.end())\r
+                    {\r
+                        for (auto head : (*iter).second->getHeaders())\r
+                        {\r
+                            if (act.second->getHeaders().count(head.first) == 0)\r
+                                act.second->setHeader(head.first, head.second);\r
+                        }\r
+                        for (auto query : (*iter).second->getQueryParameters())\r
+                        {\r
+                            if (act.second->getQueryParameters().count(query.first) == 0)\r
+                                act.second->setQueryParameter(query.first, query.second);\r
+                        }\r
+                        for (auto resp : (*iter).second->getResponses())\r
+                        {\r
+                            if (act.second->getResponses().count(resp.first) == 0)\r
+                                act.second->setResponse(resp.first, resp.second);\r
+                        }\r
+                    }\r
+                }\r
+            }\r
+            for (const std::string & traitValue :  it.second->getTraits())\r
+            {\r
+                auto iter = trait.begin();\r
+                for (; iter != trait.end(); iter++)\r
+                {\r
+                    if (((*iter).first) == traitValue)\r
+                        break;\r
+                }\r
+                if (iter != trait.end())\r
+                {\r
+                    for (auto act : it.second->getActions())\r
+                    {\r
+                        for (auto head : (*iter).second->getHeaders())\r
+                        {\r
+                            if (act.second->getHeaders().count(head.first) == 0)\r
+                                act.second->setHeader(head.first, head.second);\r
+                        }\r
+                        for (auto query : (*iter).second->getQueryParameters())\r
+                        {\r
+                            if (act.second->getQueryParameters().count(query.first) == 0)\r
+                                act.second->setQueryParameter(query.first, query.second);\r
+                        }\r
+                        for (auto resp : (*iter).second->getResponses())\r
+                        {\r
+                            if (act.second->getResponses().count(resp.first) == 0)\r
+                                act.second->setResponse(resp.first, resp.second);\r
+                        }\r
+                    }\r
+                }\r
+            }\r
+            setTraits(it.second->getResources());\r
+        }\r
+    }\r
+\r
+}\r
diff --git a/service/simulator/ramlparser/raml/RamlParser.h b/service/simulator/ramlparser/raml/RamlParser.h
new file mode 100755 (executable)
index 0000000..50f3501
--- /dev/null
@@ -0,0 +1,92 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#ifndef RAML_PARSER_H\r
+#define RAML_PARSER_H\r
+\r
+#include "yaml-cpp/yaml.h"\r
+#include "Raml.h"\r
+#include "Utils.h"\r
+#include "RequestResponseBody.h"\r
+#include "RamlResource.h"\r
+#include "Action.h"\r
+#include "Response.h"\r
+#include <map>\r
+#include "RamlErrorCodes.h"\r
+#include "yaml-cpp/exceptions.h"\r
+#include "RamlExceptions.h"\r
+\r
+namespace RAML\r
+{\r
+    class RamlParser\r
+    {\r
+        private:\r
+            void setDataFromRoot();\r
+            void setBodyDefaultMediaType(const std::map<std::string, RamlResourcePtr> &resource);\r
+            void setBodySchema(const std::map<std::string, RamlResourcePtr> &resource);\r
+            void setTypes(const std::map<std::string, RamlResourcePtr> &resource);\r
+            void setTraits(const std::map<std::string, RamlResourcePtr> &resource);\r
+\r
+        public:\r
+            virtual RamlPtr getRamlPtr(RamlParserResult &result);\r
+            virtual RamlPtr getRamlPtr();\r
+            RamlParser(): m_ramlPtr(std::make_shared<Raml>()), m_ramlParserResult(RAML_FILE_PATH_REQUIRED) {}\r
+            RamlParser(const std::string &path): m_ramlParserResult(RAML_PARSER_ERROR)\r
+            {\r
+                if (path.length() > 0)\r
+                {\r
+                    std::size_t found = path.find_last_of("/\\");\r
+                    if (found < path.length())\r
+                    {\r
+                        m_fileLocation = path.substr(0, found) + "/";\r
+                        m_ramlName = path.substr(found + 1);\r
+                        try\r
+                        {\r
+                            m_ramlPtr = std::make_shared<Raml>(m_fileLocation, m_ramlName);\r
+                            setDataFromRoot();\r
+                            m_ramlParserResult = RAML_PARSER_OK;\r
+                        }\r
+                        catch (RamlException &e)\r
+                        {\r
+                            throw;\r
+                        }\r
+                    }\r
+                    else\r
+                    {\r
+                        m_ramlParserResult = RAML_FILE_PATH_REQUIRED;\r
+                        throw RamlBadFile("Raml File Path incorrect");\r
+                    }\r
+                }\r
+                else\r
+                {\r
+                    m_ramlParserResult = RAML_FILE_PATH_REQUIRED;\r
+                    throw RamlBadFile("Raml File Path required");\r
+                }\r
+            }\r
+        private:\r
+\r
+            RamlPtr m_ramlPtr;\r
+            std::string m_fileLocation;\r
+            std::string m_ramlName;\r
+            RamlParserResult m_ramlParserResult;\r
+    };\r
+\r
+}\r
+#endif\r
diff --git a/service/simulator/ramlparser/raml/Utils.h b/service/simulator/ramlparser/raml/Utils.h
new file mode 100755 (executable)
index 0000000..c69470e
--- /dev/null
@@ -0,0 +1,119 @@
+/******************************************************************\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
+#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
+        const std::string Title = "title";\r
+        const std::string Version = "version";\r
+        const std::string BaseUri = "baseUri";\r
+        const std::string Protocols = "protocols";\r
+        const std::string MediaType = "mediaType";\r
+        const std::string Schemas = "schemas";\r
+        const std::string ResourceTypes = "resourceTypes";\r
+        const std::string Traits = "traits";\r
+        const std::string IsTrait = "is";\r
+\r
+        const std::string Resource = "/";\r
+        const std::vector<std::string> ActionType = {"get", "post", "put", "delete", "head", "patch", "options", "trace"};\r
+\r
+        const std::string Responses = "responses";\r
+        const std::string Body = "body";\r
+        const std::string Schema = "schema";\r
+        const std::string Example = "example";\r
+\r
+        const std::string BaseUriParameters = "baseUriParameters";\r
+        const std::string UriParameters = "uriParameters";\r
+        const std::string Headers = "headers";\r
+        const std::string QueryParameters = "queryParameters";\r
+        const std::string FormParameters = "formParameters";\r
+        const std::string DisplayName = "displayName";\r
+        const std::string Description = "description";\r
+        const std::string Type = "type";\r
+        const std::string Enum = "enum";\r
+        const std::string Pattern = "pattern";\r
+        const std::string MinLength = "minLength";\r
+        const std::string MaxLength = "maxLength";\r
+        const std::string Minimum = "minimum";\r
+        const std::string Maximum = "maximum";\r
+        const std::string Repeat = "repeat";\r
+        const std::string Required = "required";\r
+        const std::string Default = "default";\r
+\r
+        const std::string Documentation = "documentation";\r
+        const std::string Content = "content";\r
+\r
+        const std::string Json = "json";\r
+        const std::vector<std::string> AllowedRamlYamlTypes = {"raml", "yaml", "yml"};\r
+\r
+    }\r
+\r
+\r
+#define READ_NODE_AS_STRING(yamlNode)                   \\r
+({                                                      \\r
+(yamlNode).as<std::string>();                           \\r
+})\r
+\r
+#define READ_NODE_AS_INT(yamlNode)                      \\r
+({                                                      \\r
+    (yamlNode).as<int>();                               \\r
+})\r
+\r
+#define READ_NODE_AS_LONG(yamlNode)                     \\r
+({                                                      \\r
+    (yamlNode).as<long>();                              \\r
+})\r
+#define READ_NODE_AS_BOOL(yamlNode)                     \\r
+({                                                      \\r
+        (yamlNode).as<bool>();                          \\r
+})\r
+\r
+#define GET_ACTION_TYPE(key)                            \\r
+({                                                      \\r
+    ActionType actionType;                              \\r
+    if (key == "get" )                                  \\r
+        actionType = ActionType::GET;                               \\r
+    else if (key == "post" )                            \\r
+        actionType = ActionType::POST;                              \\r
+    else if (key == "put" )                             \\r
+        actionType = ActionType::PUT;                               \\r
+    else if (key == "delete" )                          \\r
+        actionType = ActionType::DELETE;                            \\r
+    else if (key == "head" )                            \\r
+        actionType = ActionType::HEAD;                              \\r
+    else if (key == "patch" )                           \\r
+        actionType = ActionType::PATCH;                             \\r
+    else if (key == "options" )                         \\r
+        actionType = ActionType::OPTIONS;                           \\r
+    else if (key == "trace" )                           \\r
+        actionType = ActionType::TRACE;                             \\r
+    actionType;                                         \\r
+})\r
+\r
+}\r
+#endif\r
diff --git a/service/simulator/ramlparser/raml/jsonSchemaParser/AllowedValues.h b/service/simulator/ramlparser/raml/jsonSchemaParser/AllowedValues.h
new file mode 100755 (executable)
index 0000000..dc23371
--- /dev/null
@@ -0,0 +1,89 @@
+/******************************************************************\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
+#ifndef ALLOWED_VALUES_H_\r
+#define ALLOWED_VALUES_H_\r
+\r
+#include <string>\r
+#include <vector>\r
+#include <map>\r
+#include <boost/variant.hpp>\r
+#include <boost/lexical_cast.hpp>\r
+#include "Helpers.h"\r
+\r
+namespace RAML\r
+{\r
+    class AllowedValues\r
+    {\r
+        public:\r
+            template <typename T>\r
+            void addValue(const T &value)\r
+            {\r
+                ValueVariant temp = value;\r
+                m_values.push_back(temp);\r
+            }\r
+\r
+            template <typename T>\r
+            void addValues(const std::vector<T> &values)\r
+            {\r
+                for (auto value : values)\r
+                {\r
+                    ValueVariant vValue = value;\r
+                    m_values.push_back(vValue);\r
+                }\r
+            }\r
+\r
+            inline ValueVariant &at(int index)\r
+            {\r
+                return m_values.at(index);\r
+            }\r
+            inline int size() const\r
+            {\r
+                return m_values.size();\r
+            }\r
+\r
+            inline std::vector<ValueVariant> getValues()\r
+            {\r
+                return m_values;\r
+            }\r
+            inline std::vector<int> getValuesInt()\r
+            {\r
+                std::vector<int> values;\r
+                for (auto value : m_values)\r
+                {\r
+                    values.push_back(boost::lexical_cast<int> (value));\r
+                }\r
+                return values;\r
+            }\r
+            inline std::vector<std::string> getValuesString()\r
+            {\r
+                std::vector<std::string> values;\r
+                for (auto value : m_values)\r
+                {\r
+                    values.push_back(boost::lexical_cast<std::string> (value));\r
+                }\r
+                return values;\r
+            }\r
+\r
+        private:\r
+            std::vector<ValueVariant> m_values;\r
+    };\r
+\r
+}\r
+#endif\r
diff --git a/service/simulator/ramlparser/raml/jsonSchemaParser/Definitions.h b/service/simulator/ramlparser/raml/jsonSchemaParser/Definitions.h
new file mode 100755 (executable)
index 0000000..a1ec9f3
--- /dev/null
@@ -0,0 +1,96 @@
+/******************************************************************\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
+#ifndef DEFINITIONS_H_\r
+#define DEFINITIONS_H_\r
+\r
+#include <string>\r
+#include <vector>\r
+#include <map>\r
+#include "Properties.h"\r
+\r
+namespace RAML\r
+{\r
+    class Definitions\r
+    {\r
+        public:\r
+\r
+            Definitions() = default;\r
+            Definitions(const std::string &name) : m_defName(name) {}\r
+\r
+            inline std::string getName(void) const\r
+            {\r
+                return m_defName;\r
+            }\r
+            inline void setName(const std::string &name)\r
+            {\r
+                m_defName = name;\r
+            }\r
+            inline std::string getType(void) const\r
+            {\r
+                return m_type;\r
+            }\r
+            inline void setType(const std::string &type)\r
+            {\r
+                m_type = type;\r
+            }\r
+            void addProperty(const std::string &propName, Properties *property)\r
+            {\r
+                if (m_properties.end() == m_properties.find(propName))\r
+                {\r
+                    m_properties[propName] =  property;\r
+                }\r
+            }\r
+            void setRequiredValue(const std::string &reqValue)\r
+            {\r
+                if (m_required.end() == std::find(m_required.begin(), m_required.end(), reqValue))\r
+                {\r
+                    m_required.push_back(reqValue);\r
+                }\r
+            }\r
+            std::vector<std::string> getRequiredValues() const\r
+            {\r
+                return m_required;\r
+            }\r
+            int propertiesSize() const { return m_properties.size(); }\r
+\r
+            inline bool getproperty(const std::string &propName, Properties *value)\r
+            {\r
+                if (m_properties.end() != m_properties.find(propName))\r
+                {\r
+                    value = m_properties[propName];\r
+                    return true;\r
+                }\r
+                return false;\r
+            }\r
+            inline std::map<std::string, Properties *>  getProperties()\r
+            {\r
+                return m_properties;\r
+            }\r
+        private:\r
+            std::map<std::string, Properties *> m_properties;\r
+            std::string m_defName;\r
+            std::string m_type;\r
+            std::vector<std::string> m_required;\r
+\r
+    };\r
+    typedef std::shared_ptr<Definitions> DefinitionsPtr;\r
+\r
+}\r
+#endif\r
diff --git a/service/simulator/ramlparser/raml/jsonSchemaParser/Helpers.h b/service/simulator/ramlparser/raml/jsonSchemaParser/Helpers.h
new file mode 100755 (executable)
index 0000000..9e25072
--- /dev/null
@@ -0,0 +1,41 @@
+/******************************************************************\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
+#ifndef HELPERS_H_\r
+#define HELPERS_H_\r
+\r
+#include <string>\r
+#include <vector>\r
+#include <map>\r
+#include <boost/variant.hpp>\r
+#include <boost/lexical_cast.hpp>\r
+\r
+namespace RAML\r
+{\r
+\r
+\r
+    typedef boost::variant <\r
+    int,\r
+    double,\r
+    bool,\r
+    std::string\r
+    > ValueVariant;\r
+\r
+}\r
+#endif\r
diff --git a/service/simulator/ramlparser/raml/jsonSchemaParser/Items.h b/service/simulator/ramlparser/raml/jsonSchemaParser/Items.h
new file mode 100755 (executable)
index 0000000..b5353bd
--- /dev/null
@@ -0,0 +1,107 @@
+/******************************************************************\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
+#ifndef ITEMS_H_\r
+#define ITEMS_H_\r
+\r
+#include <string>\r
+#include <vector>\r
+#include <map>\r
+#include "Properties.h"\r
+#include "Helpers.h"\r
+#include "AllowedValues.h"\r
+\r
+namespace RAML\r
+{\r
+    class Properties;\r
+    class AllowedValues;\r
+    class Items\r
+    {\r
+        public:\r
+            Items() {}\r
+            void addProperty(const std::string &propName, Properties *property)\r
+            {\r
+                if (m_properties.end() == m_properties.find(propName))\r
+                {\r
+                    m_properties[propName] =  property;\r
+                }\r
+            }\r
+            bool getproperty(const std::string &propName, Properties *value)\r
+            {\r
+                if (m_properties.end() != m_properties.find(propName))\r
+                {\r
+                    value = m_properties[propName];\r
+                    return true;\r
+                }\r
+                return false;\r
+            }\r
+            std::map<std::string, Properties *> getProperties()\r
+            {\r
+                return m_properties;\r
+            }\r
+            void setType(const std::string &type)\r
+            {\r
+                m_type = type;\r
+            }\r
+            std::string getType()\r
+            {\r
+                return m_type;\r
+            }\r
+            void setRequiredValue(const std::string &reqValue)\r
+            {\r
+                if (m_required.end() == std::find(m_required.begin(), m_required.end(), reqValue))\r
+                {\r
+                    m_required.push_back(reqValue);\r
+                }\r
+            }\r
+            std::vector<std::string> getRequiredValues()\r
+            {\r
+                return m_required;\r
+            }\r
+            template <typename T>\r
+            bool setAllowedValues(const std::vector<T> &values)\r
+            {\r
+                m_allowedValues.addValues(values);\r
+                return true;\r
+            }\r
+            inline int getAllowedValuesSize() const\r
+            {\r
+                return m_allowedValues.size();\r
+            }\r
+            inline std::vector<ValueVariant> getAllowedValues()\r
+            {\r
+                return m_allowedValues.getValues();\r
+            }\r
+            inline std::vector<int> getAllowedValuesInt()\r
+            {\r
+                return m_allowedValues.getValuesInt();\r
+            }\r
+            inline std::vector<std::string> getAllowedValuesString()\r
+            {\r
+                return m_allowedValues.getValuesString();\r
+            }\r
+        private:\r
+            std::map<std::string, Properties *> m_properties;\r
+            std::string m_type;\r
+            std::vector<std::string>  m_required;\r
+            AllowedValues m_allowedValues;\r
+    };\r
+}\r
+#endif\r
+\r
diff --git a/service/simulator/ramlparser/raml/jsonSchemaParser/JsonSchema.cpp b/service/simulator/ramlparser/raml/jsonSchemaParser/JsonSchema.cpp
new file mode 100755 (executable)
index 0000000..f4939ca
--- /dev/null
@@ -0,0 +1,832 @@
+/******************************************************************\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 "JsonSchema.h"\r
+using namespace std;\r
+\r
+namespace RAML\r
+{\r
+\r
+    void JsonSchema::readJson()\r
+    {\r
+        if (! m_cjson)\r
+            return;\r
+\r
+        cJSON *jsonId = cJSON_GetObjectItem(m_cjson, "id");\r
+        if (jsonId)\r
+        {\r
+            m_id = jsonId->valuestring;\r
+        }\r
+        cJSON *jsonSchema = cJSON_GetObjectItem(m_cjson, "$schema");\r
+        if (jsonSchema)\r
+        {\r
+            m_schema = jsonSchema->valuestring;\r
+        }\r
+        cJSON *jsonTitle = cJSON_GetObjectItem(m_cjson, "title");\r
+        if (jsonTitle)\r
+        {\r
+            m_title = jsonTitle->valuestring;\r
+        }\r
+        cJSON *jsonType = cJSON_GetObjectItem(m_cjson, "type");\r
+        if (jsonType)\r
+        {\r
+            m_type = jsonType->valuestring;\r
+        }\r
+        cJSON *jsonDescription = cJSON_GetObjectItem(m_cjson, "description");\r
+        if (jsonDescription)\r
+        {\r
+            m_description = jsonDescription->valuestring;\r
+        }\r
+        cJSON *jsonDefinitions = cJSON_GetObjectItem(m_cjson, "definitions");\r
+        if (jsonDefinitions)\r
+        {\r
+            cJSON *childDefinitions = jsonDefinitions->child;\r
+            while (childDefinitions)\r
+            {\r
+                std::string defName = childDefinitions->string;\r
+                addDefinition(defName, readDef(childDefinitions, defName));\r
+                childDefinitions = childDefinitions->next;\r
+            }\r
+        }\r
+        cJSON *jsonProperties = cJSON_GetObjectItem(m_cjson, "properties");\r
+        if (jsonProperties)\r
+        {\r
+            cJSON *childProperties = jsonProperties->child;\r
+            while (childProperties)\r
+            {\r
+                std::string attName = childProperties->string;\r
+                addProperty(attName, readProp(childProperties, attName));\r
+                childProperties = childProperties->next;\r
+            }\r
+        }\r
+        if (m_type == "array")\r
+        {\r
+            cJSON *jsonItems = cJSON_GetObjectItem(m_cjson, "items");\r
+            if (jsonItems)\r
+            {\r
+                if (jsonItems->type == 5)\r
+                {\r
+                    int item_size = cJSON_GetArraySize(jsonItems);\r
+                    int item_index = 0;\r
+                    do\r
+                    {\r
+                        cJSON *item = cJSON_GetArrayItem(jsonItems, item_index);\r
+                        Items *newItem = readItems(item);\r
+                        setItem(newItem);\r
+                    }\r
+                    while ( ++item_index < item_size);\r
+                }\r
+                else\r
+                {\r
+                    Items *newItem = readItems(jsonItems);\r
+                    setItem(newItem);\r
+                }\r
+            }\r
+        }\r
+        cJSON *jsonAdditionalProperties = cJSON_GetObjectItem(m_cjson, "additionalProperties");\r
+        if (jsonAdditionalProperties)\r
+            m_additionalProperties = jsonAdditionalProperties->type;\r
+        else\r
+            m_additionalProperties = cJSON_True;\r
+\r
+        cJSON *jsonReference = cJSON_GetObjectItem(m_cjson, "$ref");\r
+        if (jsonReference)\r
+        {\r
+            readJsonRef(jsonReference);\r
+        }\r
+        cJSON *jsonAllOf = cJSON_GetObjectItem(m_cjson, "allOf");\r
+        if (jsonAllOf)\r
+        {\r
+            readAllOf(jsonAllOf);\r
+        }\r
+        cJSON *jsonRequiredValues = cJSON_GetObjectItem(m_cjson, "required");\r
+        if (jsonRequiredValues)\r
+        {\r
+            int size = cJSON_GetArraySize(jsonRequiredValues);\r
+            int index = 0;\r
+            do\r
+            {\r
+                setRequiredValue(cJSON_GetArrayItem(jsonRequiredValues, index)->valuestring);\r
+            }\r
+            while ( ++index < size);\r
+        }\r
+    }\r
+\r
+    Definitions *JsonSchema::readDef(cJSON *childDefinitions, const std::string &defName)\r
+    {\r
+        Definitions *definition = new Definitions(defName);\r
+\r
+        cJSON *defType = cJSON_GetObjectItem(childDefinitions, "type");\r
+        if (defType)\r
+        {\r
+            std::string type = defType->valuestring;\r
+            definition->setType(type);\r
+        }\r
+        cJSON *defProperties = cJSON_GetObjectItem(childDefinitions, "properties");\r
+        if (defProperties)\r
+        {\r
+            cJSON *childProperties = defProperties->child;\r
+            while (childProperties)\r
+            {\r
+                std::string attName = childProperties->string;\r
+                definition->addProperty(attName, readProp(childProperties, attName));\r
+                childProperties = childProperties->next;\r
+            }\r
+        }\r
+        cJSON *defRequiredValues = cJSON_GetObjectItem(childDefinitions, "required");\r
+        if (defRequiredValues)\r
+        {\r
+            int size = cJSON_GetArraySize(defRequiredValues);\r
+            int index = 0;\r
+            do\r
+            {\r
+                definition->setRequiredValue(cJSON_GetArrayItem(defRequiredValues, index)->valuestring);\r
+            }\r
+            while ( ++index < size);\r
+        }\r
+        cJSON *defReference = cJSON_GetObjectItem(childDefinitions, "$ref");\r
+        if (defReference)\r
+        {\r
+            readDefRef(defReference, definition);\r
+        }\r
+        cJSON *defAllOf = cJSON_GetObjectItem(childDefinitions, "allOf");\r
+        if (defAllOf)\r
+        {\r
+            readDefAllOf(defAllOf, definition);\r
+        }\r
+        return definition;\r
+    }\r
+\r
+    Properties *JsonSchema::readProp(cJSON *childProperties, const std::string &attName )\r
+    {\r
+        Properties *property = new Properties(attName);\r
+\r
+        cJSON *propertyUpdateFrequency = cJSON_GetObjectItem(childProperties, "update_frequency");\r
+        if (propertyUpdateFrequency)\r
+        {\r
+            property->setUpdateFrequencyTime(propertyUpdateFrequency->valueint);\r
+        }\r
+        cJSON *propertyDescription = cJSON_GetObjectItem(childProperties, "description");\r
+        if (propertyDescription)\r
+        {\r
+            property->setDescription(propertyDescription->valuestring);\r
+        }\r
+        cJSON *propertyType = cJSON_GetObjectItem(childProperties, "type");\r
+        if (propertyType)\r
+        {\r
+            std::string attType;\r
+            if (propertyType->type == 4)\r
+            {\r
+                attType = propertyType->valuestring;\r
+                property->setType(attType);\r
+            }\r
+            else if (propertyType->type == 5)\r
+            {\r
+                attType = cJSON_GetArrayItem(propertyType, 0)->valuestring;\r
+                property->setType(attType);\r
+            }\r
+            readValues(childProperties, property, attType);\r
+        }\r
+        cJSON *defaultValue = cJSON_GetObjectItem(childProperties, "default");\r
+        if (defaultValue)\r
+        {\r
+            if (defaultValue->type == 4)\r
+            {\r
+                property->setValue((std::string)defaultValue->valuestring);\r
+            }\r
+            else if (defaultValue->type == 3)\r
+            {\r
+                if (property->getType() == "number")\r
+                    property->setValue((double)defaultValue->valuedouble);\r
+                else\r
+                    property->setValue((int)defaultValue->valueint );\r
+            }\r
+            else if (defaultValue->type == 1)\r
+            {\r
+                property->setValue((bool)true);\r
+            }\r
+            else if (defaultValue->type == 0)\r
+            {\r
+                property->setValue((bool)false);\r
+            }\r
+\r
+        }\r
+        cJSON *allowedvalues = cJSON_GetObjectItem(childProperties, "enum");\r
+        if (allowedvalues)\r
+        {\r
+            if ((cJSON_GetArrayItem(allowedvalues, 0)->type) == 4)\r
+            {\r
+                int size = cJSON_GetArraySize(allowedvalues);\r
+                int idx = 0;\r
+                std::vector<std::string> allwdValues;\r
+                do\r
+                {\r
+                    allwdValues.push_back(cJSON_GetArrayItem(allowedvalues, idx)->valuestring);\r
+                }\r
+                while ( ++idx < size);\r
+                property->setAllowedValues(allwdValues);\r
+            }\r
+            else if ((cJSON_GetArrayItem(allowedvalues, 0)->type) == 3)\r
+            {\r
+                int size = cJSON_GetArraySize(allowedvalues);\r
+                int idx = 0;\r
+                if (property->getType() == "number")\r
+                {\r
+                    std::vector<double> allwdValues;\r
+                    do\r
+                    {\r
+                        allwdValues.push_back(cJSON_GetArrayItem(allowedvalues, idx)->valuedouble);\r
+                    }\r
+                    while ( ++idx < size);\r
+                    property->setAllowedValues(allwdValues);\r
+                }\r
+                else\r
+                {\r
+                    std::vector<int> allwdValues;\r
+                    do\r
+                    {\r
+                        allwdValues.push_back(cJSON_GetArrayItem(allowedvalues, idx)->valueint);\r
+                    }\r
+                    while ( ++idx < size);\r
+                    property->setAllowedValues(allwdValues);\r
+                }\r
+            }\r
+            else if (((cJSON_GetArrayItem(allowedvalues, 0)->type) == 1)\r
+                     || ((cJSON_GetArrayItem(allowedvalues, 0)->type) == 0))\r
+            {\r
+                int size = cJSON_GetArraySize(allowedvalues);\r
+                int idx = 0;\r
+                std::vector<bool> allwdValues;\r
+                do\r
+                {\r
+                    if (cJSON_GetArrayItem(allowedvalues, idx)->type)\r
+                        allwdValues.push_back(true);\r
+                    else\r
+                        allwdValues.push_back(false);\r
+                }\r
+                while ( ++idx < size);\r
+                property->setAllowedValues(allwdValues);\r
+            }\r
+        }\r
+        return property;\r
+    }\r
+\r
+    void JsonSchema::readValues(cJSON *childProperties,  Properties *property ,\r
+                                const std::string &attType)\r
+    {\r
+        if (attType == "string")\r
+        {\r
+            readString(childProperties, property);\r
+        }\r
+        else if (attType == "integer")\r
+        {\r
+            readNumber(childProperties, property);\r
+        }\r
+        else if (attType == "array")\r
+        {\r
+            readArray(childProperties, property);\r
+        }\r
+        else if (attType == "number")\r
+        {\r
+            readNumber(childProperties, property);\r
+        }\r
+    }\r
+\r
+    void JsonSchema::readString(cJSON *childProperties, Properties *property)\r
+    {\r
+        cJSON *stringMax = cJSON_GetObjectItem(childProperties, "maxLength");\r
+        if (stringMax)\r
+        {\r
+            cJSON *exclusiveMax = cJSON_GetObjectItem(childProperties, "exclusiveMaximum");\r
+            if (exclusiveMax)\r
+            {\r
+                if (exclusiveMax->type == cJSON_True)\r
+                    property->setMax (--(stringMax->valueint));\r
+                else\r
+                    property->setMax(stringMax->valueint);\r
+            }\r
+            else\r
+                property->setMax(stringMax->valueint);\r
+        }\r
+        cJSON *stringMin = cJSON_GetObjectItem(childProperties, "minLength");\r
+        if (stringMin)\r
+        {\r
+            cJSON *exclusiveMin = cJSON_GetObjectItem(childProperties, "exclusiveMinimum");\r
+            if (exclusiveMin)\r
+            {\r
+                if (exclusiveMin->type == cJSON_True)\r
+                    property->setMin( ++(stringMin->valueint));\r
+                else\r
+                    property->setMin(stringMin->valueint);\r
+            }\r
+            else\r
+                property->setMin(stringMin->valueint);\r
+        }\r
+        cJSON *stringFormat = cJSON_GetObjectItem(childProperties, "format");\r
+        if (stringFormat)\r
+        {\r
+            property->setFormat(stringFormat->valuestring);\r
+        }\r
+        cJSON *stringPattern = cJSON_GetObjectItem(childProperties, "pattern");\r
+        if (stringPattern)\r
+        {\r
+            property->setPattern(stringPattern->valuestring);\r
+        }\r
+    }\r
+\r
+    void JsonSchema::readArray(cJSON *childProperties,  Properties *property)\r
+    {\r
+        cJSON *itemValues = cJSON_GetObjectItem(childProperties, "items");\r
+        if (itemValues)\r
+        {\r
+            if (itemValues->type == 5)\r
+            {\r
+                int item_size = cJSON_GetArraySize(itemValues);\r
+                int item_index = 0;\r
+                do\r
+                {\r
+                    cJSON *item = cJSON_GetArrayItem(itemValues, item_index);\r
+                    Items *newItem = readItems(item);\r
+                    property->setItem(newItem);\r
+                }\r
+                while ( ++item_index < item_size);\r
+            }\r
+            else\r
+            {\r
+                Items *newItem = readItems(itemValues);\r
+                property->setItem(newItem);\r
+            }\r
+        }\r
+        cJSON *itemsMax = cJSON_GetObjectItem(childProperties, "maxItems");\r
+        if (itemsMax)\r
+        {\r
+            cJSON *exclusiveMax = cJSON_GetObjectItem(childProperties, "exclusiveMaximum");\r
+            if (exclusiveMax)\r
+            {\r
+                if (exclusiveMax->type == cJSON_True)\r
+                    property->setMax( --(itemsMax->valueint));\r
+                else\r
+                    property->setMax(itemsMax->valueint);\r
+            }\r
+            else\r
+                property->setMax(itemsMax->valueint);\r
+        }\r
+        cJSON *itemsMin = cJSON_GetObjectItem(childProperties, "minLength");\r
+        if (itemsMin)\r
+        {\r
+            cJSON *exclusiveMin = cJSON_GetObjectItem(childProperties, "exclusiveMinimum");\r
+            if (exclusiveMin)\r
+            {\r
+                if (exclusiveMin->type == cJSON_True)\r
+                    property->setMin( ++(itemsMin->valueint));\r
+                else\r
+                    property->setMin(itemsMin->valueint);\r
+            }\r
+            else\r
+                property->setMin(itemsMin->valueint);\r
+        }\r
+        cJSON *uniqueItems = cJSON_GetObjectItem(childProperties, "uniqueItems");\r
+        if (uniqueItems)\r
+        {\r
+            property->setUnique(uniqueItems->type);\r
+        }\r
+        else\r
+        {\r
+            property->setUnique(cJSON_True);\r
+        }\r
+        cJSON *additionalItems = cJSON_GetObjectItem(childProperties, "additionalItems");\r
+        if (additionalItems)\r
+        {\r
+            property->setAdditionalItems(additionalItems->type);\r
+        }\r
+        else\r
+        {\r
+            property->setAdditionalItems(cJSON_True);\r
+        }\r
+    }\r
+\r
+    void JsonSchema::readNumber(cJSON *childProperties,  Properties *property)\r
+    {\r
+        cJSON *Max = cJSON_GetObjectItem(childProperties, "maximum");\r
+        if (Max)\r
+        {\r
+            cJSON *exclusiveMax = cJSON_GetObjectItem(childProperties, "exclusiveMaximum");\r
+            if (exclusiveMax)\r
+            {\r
+                if (exclusiveMax->type == cJSON_True)\r
+                    property->setMax( --(Max->valueint));\r
+                else\r
+                    property->setMax(Max->valueint);\r
+            }\r
+            else\r
+                property->setMax(Max->valueint);\r
+        }\r
+        cJSON *Min = cJSON_GetObjectItem(childProperties, "minimum");\r
+        if (Min)\r
+        {\r
+            cJSON *exclusiveMin = cJSON_GetObjectItem(childProperties, "exclusiveMinimum");\r
+            if (exclusiveMin)\r
+            {\r
+                if (exclusiveMin->type == cJSON_True)\r
+                    property->setMin( ++(Min->valueint));\r
+                else\r
+                    property->setMin(Min->valueint);\r
+            }\r
+            else\r
+                property->setMin(Min->valueint);\r
+        }\r
+        cJSON *multipleOf = cJSON_GetObjectItem(childProperties, "multipleOf");\r
+        if (multipleOf)\r
+        {\r
+            property->setMultipleOf(multipleOf->valueint);\r
+        }\r
+\r
+    }\r
+    Definitions *JsonSchema::readRef(std::string m_ref)\r
+    {\r
+        std::string delimiter1 = "#";\r
+        std::string delimiter2 = "/";\r
+        std::string fileName;\r
+        if (! m_ref.empty())\r
+        {\r
+            std::size_t pos = m_ref.find(delimiter1);\r
+            if ( (pos = m_ref.find(delimiter1)) != std::string::npos)\r
+            {\r
+                fileName = m_ref.substr(0, pos);\r
+                m_ref.erase(0, pos);\r
+            }\r
+            m_ref.erase(0, delimiter1 .length());\r
+            std::string defName;\r
+\r
+            if (! m_ref.empty())\r
+            {\r
+                m_ref.erase(0, delimiter2 .length());\r
+                std::string keyName;\r
+                if ( (pos = m_ref.find(delimiter2)) != std::string::npos)\r
+                {\r
+                    keyName = m_ref.substr(0, pos);\r
+                    m_ref.erase(0, pos + delimiter2.length());\r
+                    if (keyName == "definitions")\r
+                    {\r
+                        if ( (pos = m_ref.find(delimiter2)) != std::string::npos)\r
+                        {\r
+                            defName = m_ref.substr(0, pos);\r
+                        }\r
+                        else if (! m_ref.empty())\r
+                        {\r
+                            defName = m_ref;\r
+                        }\r
+                    }\r
+                }\r
+            }\r
+            if (!fileName.empty())\r
+            {\r
+                if (!(defName.empty()))\r
+                {\r
+                    cJSON *m_json = m_includeResolver->readToJson(fileName);\r
+                    JsonSchema *Refparser = new JsonSchema(m_json, m_includeResolver);\r
+                    Definitions *definition = Refparser->getDefinition(defName);\r
+                    if (definition == nullptr)\r
+                        throw JsonException("Definition Name Incorrect");\r
+                    return definition;\r
+                }\r
+            }\r
+            else\r
+            {\r
+                if (!(defName.empty()))\r
+                {\r
+                    if (getDefinition(defName) == nullptr)\r
+                        throw JsonException("Definition Name Incorrect");\r
+                    return getDefinition(defName);\r
+                }\r
+            }\r
+        }\r
+    }\r
+    void JsonSchema::readAllOf(cJSON *allofValues)\r
+    {\r
+        int size = cJSON_GetArraySize(allofValues);\r
+        int index = 0;\r
+        do\r
+        {\r
+            cJSON *childAllOf = cJSON_GetArrayItem(allofValues, index);\r
+            cJSON *jsonReference = cJSON_GetObjectItem(childAllOf, "$ref");\r
+            if (jsonReference)\r
+            {\r
+                readJsonRef(jsonReference );\r
+            }\r
+            cJSON *jsonRequiredValues = cJSON_GetObjectItem(childAllOf, "required");\r
+            if (jsonRequiredValues)\r
+            {\r
+                int len = cJSON_GetArraySize(jsonRequiredValues);\r
+                int idx = 0;\r
+                do\r
+                {\r
+                    setRequiredValue(cJSON_GetArrayItem(jsonRequiredValues, idx)->valuestring);\r
+                }\r
+                while ( ++idx < len);\r
+            }\r
+        }\r
+        while ( ++index < size);\r
+    }\r
+    void JsonSchema::readJsonRef(cJSON *jsonReference)\r
+    {\r
+        std::string m_ref = jsonReference->valuestring;\r
+        std::map<std::string, Properties *> properties;\r
+        std::vector<std::string> required;\r
+\r
+        std::string web = "http://";\r
+        std::string delimiter = "#";\r
+        std::size_t pos = m_ref.find(web);\r
+\r
+        if (pos == std::string::npos)   // If Web Link Is GIVEN TO READ\r
+        {\r
+            pos = m_ref.find(delimiter);\r
+            if ( pos ==  (m_ref.length() - 1) )\r
+            {\r
+                std::string fileName = m_ref.substr(0, pos);\r
+                cJSON *m_json = m_includeResolver->readToJson(fileName);\r
+                JsonSchema *Refparser = new JsonSchema(m_json, m_includeResolver);\r
+\r
+                properties = Refparser->getProperties();\r
+                required = Refparser->getRequiredValues();\r
+            }\r
+            else\r
+            {\r
+                Definitions *definition = readRef(m_ref);\r
+                properties = definition->getProperties();\r
+                required = definition->getRequiredValues();\r
+            }\r
+            for ( auto it : properties)\r
+            {\r
+                std:: string name = it.first;\r
+                addProperty(name, it.second);\r
+            }\r
+            for (auto it : required )\r
+            {\r
+                setRequiredValue(it);\r
+            }\r
+\r
+        }\r
+    }\r
+    void JsonSchema::readDefAllOf(cJSON *allofValues, Definitions *definition)\r
+    {\r
+        int size = cJSON_GetArraySize(allofValues);\r
+        int index = 0;\r
+        do\r
+        {\r
+            cJSON *childAllOf = cJSON_GetArrayItem(allofValues, index);\r
+            cJSON *defReference = cJSON_GetObjectItem(childAllOf, "$ref");\r
+            if (defReference)\r
+            {\r
+                readDefRef(defReference , definition);\r
+            }\r
+            cJSON *defRequiredValues = cJSON_GetObjectItem(allofValues, "required");\r
+            if (defRequiredValues)\r
+            {\r
+                int len = cJSON_GetArraySize(defRequiredValues);\r
+                int idx = 0;\r
+                do\r
+                {\r
+                    definition->setRequiredValue(cJSON_GetArrayItem(defRequiredValues, idx)->valuestring);\r
+                }\r
+                while ( ++idx < len);\r
+            }\r
+        }\r
+        while ( ++index < size);\r
+    }\r
+    void JsonSchema::readDefRef(cJSON *defReference, Definitions *definition)\r
+    {\r
+        std::string m_ref = defReference->valuestring;\r
+        std::map<std::string, Properties *> properties;\r
+        std::vector<std::string> required;\r
+        std::string type;\r
+\r
+        std::string web = "http://";\r
+        std::string delimiter = "#";\r
+        std::size_t pos = m_ref.find(web);\r
+\r
+        if (pos == std::string::npos)   // If Web Link Is GIVEN TO READ\r
+        {\r
+            pos = m_ref.find(delimiter);\r
+            if ( pos ==  (m_ref.length() - 1) )\r
+            {\r
+                std::string fileName = m_ref.substr(0, pos);\r
+                cJSON *m_json = m_includeResolver->readToJson(fileName);\r
+                JsonSchema *Refparser = new JsonSchema(m_json, m_includeResolver);\r
+\r
+                properties = Refparser->getProperties();\r
+                required = Refparser->getRequiredValues();\r
+                type =    Refparser->getType();\r
+            }\r
+            else\r
+            {\r
+                Definitions *definitionRef = readRef(m_ref);\r
+                properties = definitionRef->getProperties();\r
+                required = definitionRef->getRequiredValues();\r
+                type =    definitionRef->getType();\r
+            }\r
+            for (auto it : properties)\r
+            {\r
+                definition->addProperty(it.first, it.second);\r
+            }\r
+            for ( auto it : required)\r
+            {\r
+                definition->setRequiredValue(it);\r
+            }\r
+            definition->setType(type);\r
+        }\r
+    }\r
+    Items *JsonSchema::readItems(cJSON *item)\r
+    {\r
+        Items *newItem = new Items();\r
+        cJSON *itemType = cJSON_GetObjectItem(item, "type");\r
+        if (itemType)\r
+        {\r
+            std::string type = itemType->valuestring;\r
+            newItem->setType(type);\r
+        }\r
+\r
+        cJSON *itemProperties = cJSON_GetObjectItem(item, "properties");\r
+        if (itemProperties)\r
+        {\r
+            cJSON *childProperties = itemProperties->child;\r
+            while (childProperties)\r
+            {\r
+                std::string attName = childProperties->string;\r
+                Properties *property = readProp(childProperties, attName);\r
+\r
+                newItem->addProperty(attName, property);\r
+                childProperties = childProperties->next;\r
+            }\r
+        }\r
+\r
+        cJSON *allowedvalues = cJSON_GetObjectItem(item, "enum");\r
+        if (allowedvalues)\r
+        {\r
+            if ((cJSON_GetArrayItem(allowedvalues, 0)->type) == 4)\r
+            {\r
+                int size = cJSON_GetArraySize(allowedvalues);\r
+                int idx = 0;\r
+                std::vector<std::string> allwdValues;\r
+                do\r
+                {\r
+                    allwdValues.push_back(cJSON_GetArrayItem(allowedvalues, idx)->valuestring);\r
+                }\r
+                while ( ++idx < size);\r
+                newItem->setAllowedValues(allwdValues);\r
+            }\r
+            else if ((cJSON_GetArrayItem(allowedvalues, 0)->type) == 3)\r
+            {\r
+                int size = cJSON_GetArraySize(allowedvalues);\r
+                int idx = 0;\r
+                if (newItem->getType() == "number")\r
+                {\r
+                    std::vector<double> allwdValues;\r
+                    do\r
+                    {\r
+                        allwdValues.push_back(cJSON_GetArrayItem(allowedvalues, idx)->valuedouble);\r
+                    }\r
+                    while ( ++idx < size);\r
+                    newItem->setAllowedValues(allwdValues);\r
+                }\r
+                else\r
+                {\r
+                    std::vector<int> allwdValues;\r
+                    do\r
+                    {\r
+                        allwdValues.push_back(cJSON_GetArrayItem(allowedvalues, idx)->valueint);\r
+                    }\r
+                    while ( ++idx < size);\r
+                    newItem->setAllowedValues(allwdValues);\r
+                }\r
+            }\r
+            else if (((cJSON_GetArrayItem(allowedvalues, 0)->type) == 1)\r
+                     || ((cJSON_GetArrayItem(allowedvalues, 0)->type) == 0))\r
+            {\r
+                int size = cJSON_GetArraySize(allowedvalues);\r
+                int idx = 0;\r
+                std::vector<bool> allwdValues;\r
+                do\r
+                {\r
+                    if (cJSON_GetArrayItem(allowedvalues, idx)->type)\r
+                        allwdValues.push_back(true);\r
+                    else\r
+                        allwdValues.push_back(false);\r
+                }\r
+                while ( ++idx < size);\r
+                newItem->setAllowedValues(allwdValues);\r
+            }\r
+        }\r
+        cJSON *itemRequiredValues = cJSON_GetObjectItem(item, "required");\r
+        if (itemRequiredValues)\r
+        {\r
+            int size = cJSON_GetArraySize(itemRequiredValues);\r
+            int index = 0;\r
+            do\r
+            {\r
+                newItem->setRequiredValue(cJSON_GetArrayItem(itemRequiredValues, index)->valuestring);\r
+            }\r
+            while ( ++index < size);\r
+        }\r
+        cJSON *itemReference = cJSON_GetObjectItem(item, "$ref");\r
+        if (itemReference)\r
+        {\r
+            readItemRef(itemReference , newItem);\r
+        }\r
+        cJSON *itemAllOf = cJSON_GetObjectItem(item, "allOf");\r
+        if (itemAllOf)\r
+        {\r
+            readItemAllOf(itemAllOf , newItem);\r
+        }\r
+        return (newItem);\r
+    }\r
+\r
+    void JsonSchema::readItemRef(cJSON *itemReference, Items *item)\r
+    {\r
+        std::string m_ref = itemReference->valuestring;\r
+        std::map<std::string, Properties *> properties;\r
+        std::vector<std::string> required;\r
+        std::string type;\r
+\r
+        std::string web = "http://";\r
+        std::string delimiter = "#";\r
+        std::size_t pos = m_ref.find(web);\r
+\r
+        if (pos == std::string::npos)   // If Web Link Is GIVEN TO READ\r
+        {\r
+            pos = m_ref.find(delimiter);\r
+            if ( pos ==  (m_ref.length() - 1 ) )\r
+            {\r
+                std::string fileName = m_ref.substr(0, pos);\r
+                cJSON *m_json = m_includeResolver->readToJson(fileName);\r
+                JsonSchema *Refparser = new JsonSchema(m_json, m_includeResolver);\r
+\r
+                properties = Refparser->getProperties();\r
+                required = Refparser->getRequiredValues();\r
+                type =    Refparser->getType();\r
+            }\r
+            else\r
+            {\r
+                Definitions *definitionRef = readRef(m_ref);\r
+                properties = definitionRef->getProperties();\r
+                required = definitionRef->getRequiredValues();\r
+                type =    definitionRef->getType();\r
+            }\r
+            for ( auto it : properties)\r
+            {\r
+                std:: string name = it.first;\r
+                item->addProperty(name, it.second);\r
+            }\r
+            for ( auto it : required)\r
+            {\r
+                item->setRequiredValue(it);\r
+            }\r
+            item->setType(type);\r
+        }\r
+    }\r
+\r
+    void JsonSchema::readItemAllOf(cJSON *allofValues,  Items *item)\r
+    {\r
+        int size = cJSON_GetArraySize(allofValues);\r
+        int index = 0;\r
+        do\r
+        {\r
+            cJSON *childAllOf = cJSON_GetArrayItem(allofValues, index);\r
+            cJSON *itemReference = cJSON_GetObjectItem(childAllOf, "$ref");\r
+            if (itemReference)\r
+            {\r
+                readItemRef(itemReference, item);\r
+            }\r
+            cJSON *itemRequiredValues = cJSON_GetObjectItem(allofValues, "required");\r
+            if (itemRequiredValues)\r
+            {\r
+                int len = cJSON_GetArraySize(itemRequiredValues);\r
+                int idx = 0;\r
+                do\r
+                {\r
+                    item->setRequiredValue(cJSON_GetArrayItem(itemRequiredValues, idx)->valuestring);\r
+                }\r
+                while ( ++idx < len);\r
+            }\r
+        }\r
+        while ( ++index < size);\r
+    }\r
+}\r
+\r
diff --git a/service/simulator/ramlparser/raml/jsonSchemaParser/JsonSchema.h b/service/simulator/ramlparser/raml/jsonSchemaParser/JsonSchema.h
new file mode 100755 (executable)
index 0000000..16ddfdc
--- /dev/null
@@ -0,0 +1,172 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#ifndef JSON_SCHEMA_H_\r
+#define JSON_SCHEMA_H_\r
+\r
+#include <string>\r
+#include <vector>\r
+#include <map>\r
+#include "Properties.h"\r
+#include "Items.h"\r
+#include "Definitions.h"\r
+#include "cJSON.h"\r
+#include "Helpers.h"\r
+#include "AllowedValues.h"\r
+\r
+#include "IncludeResolver.h"\r
+\r
+namespace RAML\r
+{\r
+    class JsonSchema\r
+    {\r
+        public:\r
+            JsonSchema() : m_cjson(NULL), m_includeResolver(NULL)  {}\r
+            JsonSchema(const IncludeResolverPtr &includeResolver) : m_cjson(NULL),\r
+                m_includeResolver(includeResolver) {}\r
+            JsonSchema(cJSON *cjson , const IncludeResolverPtr &includeResolver) : m_cjson(cjson),\r
+                m_includeResolver(includeResolver)  { readJson(); }\r
+\r
+            void setcJson(cJSON *cjson) {m_cjson = cjson; readJson(); }\r
+            int size() const\r
+            {\r
+                return m_properties.size();\r
+            }\r
+            inline bool getProperty(const std::string &name, Properties *value)\r
+            {\r
+                if (m_properties.end() != m_properties.find(name))\r
+                {\r
+                    value = m_properties[name];\r
+                    return true;\r
+                }\r
+                return false;\r
+            }\r
+            inline std::map<std::string, Properties *> getProperties()\r
+            {\r
+                return m_properties;\r
+            }\r
+            inline std::map<std::string, Definitions *> getDefinitions()\r
+            {\r
+                return m_definition;\r
+            }\r
+            void addProperty(const std::string &name, Properties *property)\r
+            {\r
+                if (m_properties.end() == m_properties.find(name))\r
+                {\r
+                    m_properties[name] = property;\r
+                }\r
+            }\r
+            void setRequiredValue(const std::string &reqValue)\r
+            {\r
+                if (m_required.end() == std::find(m_required.begin(), m_required.end(), reqValue))\r
+                {\r
+                    m_required.push_back(reqValue);\r
+                }\r
+            }\r
+            std::vector<std::string> getRequiredValues()\r
+            {\r
+                return m_required;\r
+            }\r
+            void addDefinition(const std::string &defName, Definitions *definition)\r
+            {\r
+                if (m_definition.end() == m_definition.find(defName))\r
+                {\r
+                    m_definition[defName] = definition;\r
+                }\r
+            }\r
+            Definitions *getDefinition(const std::string &defName)\r
+            {\r
+                if (m_definition.end() != m_definition.find(defName))\r
+                {\r
+                    return m_definition[defName];\r
+                }\r
+                return nullptr;\r
+            }\r
+            std::string getType()\r
+            {\r
+                return  m_type;\r
+            }\r
+            std::string getId()\r
+            {\r
+                return  m_id;\r
+            }\r
+            std::string getSchema()\r
+            {\r
+                return  m_schema;\r
+            }\r
+            std::string getDescription()\r
+            {\r
+                return  m_description;\r
+            }\r
+            std::string getTitle()\r
+            {\r
+                return  m_title;\r
+            }\r
+\r
+            bool getAdditionalProperties()\r
+            {\r
+                return  m_additionalProperties;\r
+            }\r
+            void setItem(Items *item)\r
+            {\r
+                m_items.push_back(item);\r
+            }\r
+            std::vector<Items *> getItems()\r
+            {\r
+                return m_items;\r
+            }\r
+\r
+            void readJson();\r
+            Definitions *readDef(cJSON *childDefinitions, const std::string &defName);\r
+            Properties *readProp(cJSON *childProperties, const std::string &attName );\r
+            void readValues( cJSON *childProperties,  Properties *property , const std::string &attType);\r
+            void readString( cJSON *childProperties, Properties *property);\r
+            void readArray( cJSON *childProperties,  Properties *property);\r
+            void readNumber( cJSON *childProperties,  Properties *property);\r
+            Definitions *readRef(std::string m_ref);\r
+\r
+\r
+            void readJsonRef(cJSON *jsonReference);\r
+            void readDefRef(cJSON *defReference, Definitions *definition);\r
+            void readAllOf(cJSON *allofValues);\r
+            void readDefAllOf(cJSON *allofValues, Definitions *definition);\r
+            Items *readItems(cJSON *item);\r
+            void readItemRef(cJSON *itemReference, Items *item);\r
+            void readItemAllOf(cJSON *allofValues,  Items *item);\r
+\r
+        private:\r
+            std::map<std::string, Properties *> m_properties;\r
+            std::map<std::string, Definitions *> m_definition;\r
+            std::string m_id;\r
+            std::string m_schema;\r
+            std::string m_title;\r
+            std::string m_description;\r
+            bool m_additionalProperties;\r
+            std::string m_type;\r
+            cJSON *m_cjson;\r
+            std::vector<std::string>  m_required;\r
+            std::vector<Items *> m_items;\r
+            IncludeResolverPtr m_includeResolver;\r
+    };\r
+    typedef std::shared_ptr<JsonSchema> JsonSchemaPtr;\r
+\r
+}\r
+\r
+#endif\r
diff --git a/service/simulator/ramlparser/raml/jsonSchemaParser/Properties.h b/service/simulator/ramlparser/raml/jsonSchemaParser/Properties.h
new file mode 100755 (executable)
index 0000000..b8fbbc7
--- /dev/null
@@ -0,0 +1,216 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#ifndef PROPERTIES_H_\r
+#define PROPERTIES_H_\r
+\r
+#include <string>\r
+#include <vector>\r
+#include <map>\r
+#include <boost/variant.hpp>\r
+#include <boost/lexical_cast.hpp>\r
+#include <limits>\r
+#include "Items.h"\r
+#include "AllowedValues.h"\r
+#include "cJSON.h"\r
+\r
+namespace RAML\r
+{\r
+    class Properties\r
+    {\r
+        public:\r
+            Properties(): m_min(INT_MAX), m_max(INT_MAX), m_multipleOf(INT_MAX) {}\r
+            Properties(const std::string &name) : m_name(name), m_min(INT_MAX), m_max(INT_MAX),\r
+                m_multipleOf(INT_MAX) {}\r
+\r
+            inline std::string getName(void) const\r
+            {\r
+                return m_name;\r
+            }\r
+            inline void setName(const std::string &name)\r
+            {\r
+                m_name = name;\r
+            }\r
+            template <typename T>\r
+            T getValue() const\r
+            {\r
+                T val = T();\r
+                return boost::get<T>(m_value);\r
+            }\r
+\r
+            ValueVariant &getValue()\r
+            {\r
+                return m_value;\r
+            }\r
+\r
+            int getValueType() const\r
+            {\r
+                return m_value.which();\r
+            }\r
+            int getValueInt()\r
+            {\r
+                return boost::lexical_cast<int> (m_value);\r
+            }\r
+            std::string getValueString()\r
+            {\r
+                return boost::lexical_cast<std::string> (m_value);\r
+            }\r
+\r
+            template <typename T>\r
+            void setValue(const T &value)\r
+            {\r
+                m_value = value;\r
+            }\r
+            inline void getRange(int &min, int &max, int &multipleOf) const\r
+            {\r
+                min = m_min;\r
+                max = m_max;\r
+                multipleOf = m_multipleOf;\r
+            }\r
+            inline void setMin(const int &min)\r
+            {\r
+                m_min = min;\r
+            }\r
+            inline void setMax(const int &max)\r
+            {\r
+                m_max = max;\r
+            }\r
+            inline void setMultipleOf(const int &multipleOf)\r
+            {\r
+                m_multipleOf = multipleOf;\r
+            }\r
+\r
+            template <typename T>\r
+            bool setAllowedValues(const std::vector<T> &values)\r
+            {\r
+                ValueVariant temp = values.at(0);\r
+                if (temp.which() != m_value.which())\r
+                {\r
+                    return false;\r
+                }\r
+\r
+                m_allowedValues.addValues(values);\r
+                return true;\r
+            }\r
+            inline int getAllowedValuesSize() const\r
+            {\r
+                return m_allowedValues.size();\r
+            }\r
+            inline std::vector<ValueVariant> getAllowedValues()\r
+            {\r
+                return m_allowedValues.getValues();\r
+            }\r
+            inline std::vector<int> getAllowedValuesInt()\r
+            {\r
+                return m_allowedValues.getValuesInt();\r
+            }\r
+            inline std::vector<std::string> getAllowedValuesString()\r
+            {\r
+                return m_allowedValues.getValuesString();\r
+            }\r
+            inline void setDescription(const std::string &description)\r
+            {\r
+                m_description = description;\r
+            }\r
+            inline std::string getDescription()\r
+            {\r
+                return m_description;\r
+            }\r
+            inline int getUpdateFrequencyTime()\r
+            {\r
+                return m_updateInterval;\r
+            }\r
+            inline void setUpdateFrequencyTime(int interval)\r
+            {\r
+                m_updateInterval = interval;\r
+            }\r
+            void setType(const std::string &type)\r
+            {\r
+                m_type = type;\r
+            }\r
+            std::string getType()\r
+            {\r
+                return m_type;\r
+            }\r
+            void setPattern(const std::string &pattern)\r
+            {\r
+                m_pattern = pattern;\r
+            }\r
+            std::string getPattern()\r
+            {\r
+                return m_pattern;\r
+            }\r
+            void setFormat(const std::string &format)\r
+            {\r
+                m_format = format;\r
+            }\r
+            std::string getFormat()\r
+            {\r
+                return m_format;\r
+            }\r
+            void setItem(Items *item)\r
+            {\r
+                m_items.push_back(item);\r
+            }\r
+            std::vector<Items *> getItems()\r
+            {\r
+                return m_items;\r
+            }\r
+            void setUnique( int value)\r
+            {\r
+                if (value == cJSON_True) m_unique = true;\r
+                else m_unique = false;\r
+            }\r
+\r
+            bool getUnique()\r
+            {\r
+                return m_unique;\r
+            }\r
+\r
+            void setAdditionalItems(int value)\r
+            {\r
+                if (value == cJSON_True) m_additionalItems = true;\r
+                else m_additionalItems = false;\r
+            }\r
+\r
+            bool getAdditionalItems()\r
+            {\r
+                return m_additionalItems;\r
+            }\r
+        private:\r
+            std::string m_name;\r
+            ValueVariant m_value;\r
+            int m_max;\r
+            int m_min;\r
+            int m_multipleOf;\r
+            AllowedValues m_allowedValues;\r
+            int m_updateInterval;\r
+            std::string m_type;\r
+            std::string m_pattern;\r
+            std::string m_format;\r
+            std::string m_description;\r
+            bool m_unique;\r
+            bool m_additionalItems;\r
+            std::vector<Items *> m_items;\r
+    };\r
+    typedef std::shared_ptr<Properties> PropertiesPtr;\r
+\r
+}\r
+#endif\r
diff --git a/service/simulator/ramlparser/raml/model/AbstractParam.cpp b/service/simulator/ramlparser/raml/model/AbstractParam.cpp
new file mode 100755 (executable)
index 0000000..f77add3
--- /dev/null
@@ -0,0 +1,195 @@
+/******************************************************************\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 "AbstractParam.h"\r
+\r
+\r
+namespace RAML\r
+{\r
+    std::string AbstractParam::getDefaultValue() const\r
+    {\r
+        return m_defaultValue;\r
+    }\r
+    void AbstractParam::setDefaultValue(const std::string &defaultValue)\r
+    {\r
+        m_defaultValue = defaultValue;\r
+    }\r
+\r
+    std::string AbstractParam::getDescription() const\r
+    {\r
+        return m_description;\r
+    }\r
+\r
+    void AbstractParam::setDescription(const std::string &description)\r
+    {\r
+        m_description = description;\r
+    }\r
+\r
+    std::string AbstractParam::getDisplayName() const\r
+    {\r
+        return m_displayName;\r
+    }\r
+\r
+    void AbstractParam::setDisplayName(const std::string &displayName)\r
+    {\r
+        m_displayName = displayName;\r
+    }\r
+\r
+    std::list<std::string> AbstractParam::getEnumeration() const\r
+    {\r
+        return m_enumeration;\r
+    }\r
+\r
+    void AbstractParam::setEnumeration(const std::string &enumeration)\r
+    {\r
+        m_enumeration.push_back(enumeration);\r
+    }\r
+\r
+    std::string AbstractParam::getExample() const\r
+    {\r
+        return m_example;\r
+    }\r
+\r
+    void AbstractParam::setExample(const std::string &example)\r
+    {\r
+        m_example = example;\r
+    }\r
+\r
+    int AbstractParam::getMaxLength() const\r
+    {\r
+        return m_maxLength;\r
+    }\r
+\r
+    void AbstractParam::setMaxLength(int maxLength)\r
+    {\r
+        m_maxLength = maxLength;\r
+    }\r
+\r
+    int AbstractParam::getMaximum() const\r
+    {\r
+        return m_maximum;\r
+    }\r
+\r
+    void AbstractParam::setMaximum(int maximum)\r
+    {\r
+        m_maximum = maximum;\r
+    }\r
+\r
+    int AbstractParam::getMinLength() const\r
+    {\r
+        return m_minLength;\r
+    }\r
+\r
+    void AbstractParam::setMinLength(int minLength)\r
+    {\r
+        m_minLength = minLength;\r
+    }\r
+\r
+    int AbstractParam::getMinimum() const\r
+    {\r
+        return m_minimum;\r
+    }\r
+\r
+    void AbstractParam::setMinimum(int minimum)\r
+    {\r
+        m_minimum = minimum;\r
+    }\r
+\r
+    std::string AbstractParam::getPattern() const\r
+    {\r
+        return m_pattern;\r
+    }\r
+\r
+    void AbstractParam::setPattern(const std::string &pattern)\r
+    {\r
+        m_pattern = pattern;\r
+    }\r
+\r
+    std::string AbstractParam::getType() const\r
+    {\r
+        return m_type;\r
+    }\r
+\r
+    void AbstractParam::setType(const std::string &type)\r
+    {\r
+        m_type = type;\r
+    }\r
+\r
+    bool AbstractParam::isRepeat() const\r
+    {\r
+        return m_repeat;\r
+    }\r
+\r
+    void AbstractParam::setRepeat(bool repeat)\r
+    {\r
+        m_repeat = repeat;\r
+    }\r
+\r
+    bool AbstractParam::isRequired() const\r
+    {\r
+        return m_required;\r
+    }\r
+\r
+    void AbstractParam::setRequired(bool required)\r
+    {\r
+        m_required = required;\r
+    }\r
+\r
+    void AbstractParam::readParameters(const YAML::Node &yamlNode)\r
+    {\r
+        for ( YAML::const_iterator it = yamlNode.begin(); it != yamlNode.end(); ++it )\r
+        {\r
+            std::string key = READ_NODE_AS_STRING(it->first);\r
+\r
+            if (key == Keys::Description)\r
+                setDescription(READ_NODE_AS_STRING(it->second));\r
+            else if (key == Keys::Default)\r
+                setDefaultValue(READ_NODE_AS_STRING(it->second));\r
+            else if (key == Keys::DisplayName)\r
+                setDisplayName(READ_NODE_AS_STRING(it->second));\r
+\r
+            else if (key == Keys::Example)\r
+                setExample(READ_NODE_AS_STRING(it->second));\r
+            else if (key == Keys::Maximum)\r
+                setMaximum(READ_NODE_AS_LONG(it->second));\r
+            else if (key == Keys::Minimum)\r
+                setMinimum(READ_NODE_AS_LONG(it->second));\r
+            else if (key == Keys::MaxLength)\r
+                setMaxLength(READ_NODE_AS_INT(it->second));\r
+            else if (key == Keys::MinLength)\r
+                setMinLength(READ_NODE_AS_INT(it->second));\r
+\r
+            else if (key == Keys::Pattern)\r
+                setPattern(READ_NODE_AS_STRING(it->second));\r
+            else if (key == Keys::Repeat)\r
+                setRepeat(READ_NODE_AS_BOOL(it->second));\r
+            else if (key == Keys::Required)\r
+                setRequired(READ_NODE_AS_BOOL(it->second));\r
+            else if (key == Keys::Type)\r
+                setType(READ_NODE_AS_STRING(it->second));\r
+            else if (key == Keys::Enum)\r
+            {\r
+                YAML::Node enumNode = it->second;\r
+                for ( YAML::const_iterator tt = enumNode.begin(); tt != enumNode.end(); ++tt )\r
+                    setEnumeration(READ_NODE_AS_STRING(*tt));\r
+            }\r
+        }\r
+    }\r
+}\r
diff --git a/service/simulator/ramlparser/raml/model/AbstractParam.h b/service/simulator/ramlparser/raml/model/AbstractParam.h
new file mode 100755 (executable)
index 0000000..7aea032
--- /dev/null
@@ -0,0 +1,105 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#ifndef ABSTRACT_PARAM_H\r
+#define ABSTRACT_PARAM_H\r
+\r
+\r
+#include <map>\r
+#include <list>\r
+#include <string>\r
+#include "Utils.h"\r
+\r
+\r
+namespace RAML\r
+{\r
+    class AbstractParam\r
+    {\r
+        public:\r
+            virtual std::string getDefaultValue() const;\r
+            virtual void setDefaultValue(const std::string &defaultValue);\r
+\r
+            virtual std::string getDescription() const;\r
+            virtual void setDescription(const std::string &description);\r
+\r
+            virtual std::string getDisplayName() const;\r
+            virtual void setDisplayName(const std::string &displayName);\r
+\r
+            virtual std::list<std::string> getEnumeration() const;\r
+            virtual void setEnumeration(const std::string &enumeration);\r
+\r
+            virtual std::string getExample() const;\r
+            virtual void setExample(const std::string &example);\r
+\r
+            virtual int getMaxLength() const;\r
+            virtual void setMaxLength(int maxLength);\r
+\r
+            virtual int getMaximum() const;\r
+            virtual void setMaximum(int maximum);\r
+\r
+            virtual int getMinLength() const;\r
+            virtual void setMinLength(int minLength);\r
+\r
+            virtual int getMinimum() const;\r
+            virtual void setMinimum(int minimum);\r
+\r
+            virtual std::string getPattern() const;\r
+            virtual void setPattern(const std::string &pattern) ;\r
+\r
+            virtual std::string getType() const;\r
+            virtual void setType(const std::string &type);\r
+\r
+            virtual bool isRepeat() const;\r
+            virtual void setRepeat(bool repeat);\r
+\r
+            virtual bool isRequired() const;\r
+            virtual void setRequired(bool required);\r
+\r
+\r
+            AbstractParam() : m_maximum(0), m_minimum(0), m_minLength(0), m_maxLength(0), m_repeat(false),\r
+                m_required(false) {}\r
+            AbstractParam(const YAML::Node &yamlNode) : m_maximum(0), m_minimum(0), m_minLength(0),\r
+                m_maxLength(0), m_repeat(false), m_required(false)\r
+            {\r
+                readParameters(yamlNode);\r
+            }\r
+        private:\r
+            virtual void readParameters(const YAML::Node &yamlNode);\r
+\r
+        private:\r
+            std::string m_defaultValue;\r
+            std::string m_description;\r
+            std::string m_displayName;\r
+            std::list<std::string> m_enumeration;\r
+            std::string m_example;\r
+            int m_maxLength;\r
+            int m_maximum;\r
+            int m_minLength;\r
+            int m_minimum;\r
+            std::string m_pattern;\r
+            bool m_repeat;\r
+            bool m_required;\r
+            std::string m_type;\r
+\r
+\r
+    };\r
+\r
+}\r
+#endif\r
diff --git a/service/simulator/ramlparser/raml/model/Action.cpp b/service/simulator/ramlparser/raml/model/Action.cpp
new file mode 100755 (executable)
index 0000000..15c826a
--- /dev/null
@@ -0,0 +1,188 @@
+/******************************************************************\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 "Action.h"\r
+\r
+namespace RAML\r
+{\r
+    ActionType Action::getType() const\r
+    {\r
+        return m_type;\r
+    }\r
+    void Action::setType(const ActionType &type)\r
+    {\r
+        m_type = type;\r
+    }\r
+    std::string Action::getDescription() const\r
+    {\r
+        return m_description;\r
+    }\r
+    void Action::setDescription(const std::string &description)\r
+    {\r
+        m_description = description;\r
+    }\r
+    std::map<std::string, HeaderPtr > const &Action::getHeaders() const\r
+    {\r
+        return m_headers;\r
+    }\r
+    void Action::setHeader(const std::string &headerName, const HeaderPtr &header)\r
+    {\r
+        m_headers[headerName] = header;\r
+    }\r
+    std::map<std::string, QueryParameterPtr > const &Action::getQueryParameters()const\r
+    {\r
+        return m_queryParameters;\r
+    }\r
+    void Action::setQueryParameter(const std::string &paramName,\r
+                                   const QueryParameterPtr &queryParameter)\r
+    {\r
+        m_queryParameters[paramName] = queryParameter;\r
+    }\r
+    RequestResponseBodyPtr Action::getRequestBody(const std::string &bodyType)\r
+    {\r
+        return m_requestBody[bodyType];\r
+    }\r
+\r
+    std::map<std::string, RequestResponseBodyPtr> const &Action::getRequestBody() const\r
+    {\r
+        return m_requestBody;\r
+    }\r
+    void Action::setRequestBody(const std::string &typeName)\r
+    {\r
+        m_requestBody[typeName] = std::make_shared<RequestResponseBody>(typeName);\r
+    }\r
+\r
+    void Action::setRequestBody(const std::string &typeName , const RequestResponseBodyPtr &body)\r
+    {\r
+        m_requestBody[typeName] = body;\r
+    }\r
+    ResponsePtr Action::getResponse(const std::string &responseCode)\r
+    {\r
+        return m_responses[responseCode];\r
+    }\r
+\r
+    std::map<std::string, ResponsePtr> const &Action::getResponses() const\r
+    {\r
+        return m_responses;\r
+    }\r
+    void Action::setResponse(const std::string &responseCode, const ResponsePtr &response)\r
+    {\r
+        m_responses[responseCode] = response;\r
+    }\r
+\r
+    std::list<std::string> const &Action::getProtocols() const\r
+    {\r
+        return m_protocols;\r
+    }\r
+    void Action::setProtocol(const std::string &protocol)\r
+    {\r
+        m_protocols.push_back(protocol);\r
+    }\r
+    std::map<std::string, UriParameterPtr > const &Action::getBaseUriParameters() const\r
+    {\r
+        return m_baseUriParameters;\r
+    }\r
+    void Action::setBaseUriParameter(const std::string &paramName ,\r
+                                     const UriParameterPtr &baseUriParameter)\r
+    {\r
+        m_baseUriParameters[paramName] = baseUriParameter;\r
+    }\r
+\r
+    std::list<std::string> const &Action::getTraits() const\r
+    {\r
+        return m_trait;\r
+    }\r
+    void Action::setTrait(const std::string &trait)\r
+    {\r
+        m_trait.push_back(trait);\r
+    }\r
+    void Action::readAction(const ActionType actionType, const YAML::Node &yamlNode)\r
+    {\r
+        m_type = actionType;\r
+        for ( YAML::const_iterator it = yamlNode.begin(); it != yamlNode.end(); ++it )\r
+        {\r
+            std::string key = READ_NODE_AS_STRING(it->first);\r
+\r
+            if (key == Keys::Description)\r
+                setDescription(READ_NODE_AS_STRING(it->second));\r
+            else if (key == Keys::Responses)\r
+            {\r
+                YAML::Node responseNode = it->second;\r
+                for ( YAML::const_iterator tt = responseNode.begin(); tt != responseNode.end(); ++tt )\r
+                {\r
+                    std::string responseCode = READ_NODE_AS_STRING(tt->first);\r
+                    setResponse(responseCode, std::make_shared<Response>(tt->second, m_includeResolver));\r
+                }\r
+            }\r
+            else if (key == Keys::Headers)\r
+            {\r
+                YAML::Node paramNode = it->second;\r
+                for ( YAML::const_iterator tt = paramNode.begin(); tt != paramNode.end(); ++tt )\r
+                {\r
+                    setHeader(READ_NODE_AS_STRING(tt->first), std::make_shared<Header>(tt->second));\r
+                }\r
+            }\r
+            else if (key == Keys::QueryParameters)\r
+            {\r
+                YAML::Node paramNode = it->second;\r
+                for ( YAML::const_iterator tt = paramNode.begin(); tt != paramNode.end(); ++tt )\r
+                {\r
+                    setQueryParameter(READ_NODE_AS_STRING(tt->first), std::make_shared<QueryParameter>(tt->second));\r
+                }\r
+            }\r
+            else if (key == Keys::Protocols)\r
+            {\r
+                YAML::Node protocolNode = it->second;\r
+                for ( YAML::const_iterator tt = protocolNode.begin(); tt != protocolNode.end(); ++tt )\r
+                {\r
+                    setProtocol(READ_NODE_AS_STRING(*tt));\r
+                }\r
+            }\r
+            else if (key == Keys::BaseUriParameters)\r
+            {\r
+                YAML::Node paramNode = it->second;\r
+                for ( YAML::const_iterator tt = paramNode.begin(); tt != paramNode.end(); ++tt )\r
+                {\r
+                    setBaseUriParameter(READ_NODE_AS_STRING(tt->first), std::make_shared<UriParameter>(tt->second));\r
+                }\r
+            }\r
+            else if (key == Keys::Body)\r
+            {\r
+                YAML::Node responseBody = it->second;\r
+\r
+                for ( YAML::const_iterator tt = responseBody.begin(); tt != responseBody.end(); ++tt )\r
+                {\r
+                    std::string type = READ_NODE_AS_STRING(tt->first);\r
+                    setRequestBody(type, std::make_shared<RequestResponseBody>(type, tt->second, m_includeResolver));\r
+                }\r
+            }\r
+            else if (key == Keys::IsTrait)\r
+            {\r
+                YAML::Node traitNode = it->second;\r
+                for ( YAML::const_iterator tt = traitNode.begin(); tt != traitNode.end(); ++tt )\r
+                {\r
+                    setTrait(READ_NODE_AS_STRING(*tt));\r
+                }\r
+            }\r
+        }\r
+    }\r
+\r
+};\r
+\r
diff --git a/service/simulator/ramlparser/raml/model/Action.h b/service/simulator/ramlparser/raml/model/Action.h
new file mode 100755 (executable)
index 0000000..348b476
--- /dev/null
@@ -0,0 +1,97 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#ifndef ACTION_H\r
+#define ACTION_H\r
+\r
+#include <map>\r
+#include <list>\r
+#include <string>\r
+#include "ActionType.h"\r
+#include "Header.h"\r
+#include "QueryParameter.h"\r
+#include "RequestResponseBody.h"\r
+#include "UriParameter.h"\r
+#include "Response.h"\r
+#include "Utils.h"\r
+#include "IncludeResolver.h"\r
+\r
+namespace RAML\r
+{\r
+    class Action\r
+    {\r
+        public:\r
+            virtual ActionType getType() const;\r
+            virtual void setType(const ActionType &type);\r
+            virtual std::string getDescription() const;\r
+            virtual void setDescription(const std::string &description);\r
+            virtual std::map<std::string, HeaderPtr > const &getHeaders() const;\r
+            virtual void setHeader(const std::string &headerName, const HeaderPtr &header);\r
+            virtual std::map<std::string, QueryParameterPtr > const &getQueryParameters()const;\r
+            virtual void setQueryParameter(const std::string &paramName,\r
+                                           const QueryParameterPtr &queryParameter);\r
+\r
+            virtual RequestResponseBodyPtr getRequestBody(const std::string &bodyType);\r
+            virtual std::map<std::string, RequestResponseBodyPtr> const &getRequestBody() const;\r
+            virtual void setRequestBody(const std::string &typeName);\r
+            virtual void setRequestBody(const std::string &typeName , const RequestResponseBodyPtr &body);\r
+\r
+            virtual ResponsePtr getResponse(const std::string &responseCode);\r
+            virtual std::map<std::string, ResponsePtr> const &getResponses() const;\r
+            virtual void setResponse(const std::string &responseCode, const ResponsePtr &response);\r
+            virtual std::list<std::string> const &getProtocols() const;\r
+            virtual void setProtocol(const std::string &protocol);\r
+            virtual std::map< std::string, UriParameterPtr > const &getBaseUriParameters() const;\r
+            virtual void setBaseUriParameter(const std::string &paramName ,\r
+                                             const UriParameterPtr &baseUriParameter);\r
+            virtual std::list<std::string> const &getTraits() const;\r
+            virtual void setTrait(const std::string &trait);\r
+\r
+\r
+            Action(): m_includeResolver(NULL) { }\r
+            Action(const ActionType actionType, const YAML::Node &yamlNode,\r
+                   const IncludeResolverPtr &includeResolver)\r
+                : m_includeResolver(includeResolver)\r
+            {\r
+                readAction(actionType, yamlNode);\r
+            }\r
+            Action(const Action &action) = default;\r
+        private:\r
+            virtual void readAction(const ActionType actionType, const YAML::Node &yamlNode);\r
+\r
+\r
+        private:\r
+            ActionType m_type;\r
+            std::string m_description;\r
+            std::map<std::string, HeaderPtr> m_headers;\r
+            std::map<std::string, QueryParameterPtr> m_queryParameters;\r
+            std::map<std::string, RequestResponseBodyPtr> m_requestBody;\r
+            std::map<std::string, ResponsePtr> m_responses;\r
+            std::list<std::string> m_protocols;\r
+            std::map< std::string, UriParameterPtr > m_baseUriParameters;\r
+            std::list<std::string> m_trait;\r
+\r
+        private:\r
+            IncludeResolverPtr m_includeResolver;\r
+    };\r
+\r
+    typedef std::shared_ptr<Action> ActionPtr;\r
+}\r
+#endif\r
diff --git a/service/simulator/ramlparser/raml/model/ActionType.h b/service/simulator/ramlparser/raml/model/ActionType.h
new file mode 100755 (executable)
index 0000000..a653390
--- /dev/null
@@ -0,0 +1,32 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#ifndef ACTION_TYPE_H\r
+#define ACTION_TYPE_H\r
+\r
+namespace RAML\r
+{\r
+    enum class ActionType\r
+    {\r
+        GET, POST, PUT, DELETE, HEAD, PATCH, OPTIONS, TRACE, NONE\r
+    };\r
+\r
+}\r
+#endif\r
diff --git a/service/simulator/ramlparser/raml/model/DocumentationItem.cpp b/service/simulator/ramlparser/raml/model/DocumentationItem.cpp
new file mode 100755 (executable)
index 0000000..c2a0793
--- /dev/null
@@ -0,0 +1,43 @@
+/******************************************************************\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 "DocumentationItem.h"\r
+\r
+namespace RAML\r
+{\r
+\r
+    std::string DocumentationItem::getTitle() const\r
+    {\r
+        return m_title;\r
+    }\r
+    void DocumentationItem::setTitle(const std::string &title)\r
+    {\r
+        m_title = title;\r
+    }\r
+    std::string DocumentationItem::getContent() const\r
+    {\r
+        return m_content;\r
+    }\r
+    void DocumentationItem::setContent(const std::string &content)\r
+    {\r
+        m_content = content;\r
+    }\r
+\r
+}\r
diff --git a/service/simulator/ramlparser/raml/model/DocumentationItem.h b/service/simulator/ramlparser/raml/model/DocumentationItem.h
new file mode 100755 (executable)
index 0000000..c708e52
--- /dev/null
@@ -0,0 +1,48 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#ifndef DOCUMENTATION_ITEM_H\r
+#define DOCUMENTATION_ITEM_H\r
+\r
+#include <string>\r
+\r
+\r
+namespace RAML\r
+{\r
+    class DocumentationItem\r
+    {\r
+\r
+        public:\r
+            virtual std::string getTitle() const;\r
+            virtual void setTitle(const std::string &title);\r
+            virtual std::string getContent() const;\r
+            virtual void setContent(const std::string &content);\r
+\r
+            DocumentationItem();\r
+            DocumentationItem(const std::string &title , const std::string &content) : m_title(title),\r
+                m_content(content) {}\r
+        private:\r
+            std::string m_title;\r
+            std::string m_content;\r
+\r
+    };\r
+\r
+}\r
+#endif\r
diff --git a/service/simulator/ramlparser/raml/model/FormParameter.h b/service/simulator/ramlparser/raml/model/FormParameter.h
new file mode 100755 (executable)
index 0000000..61d15f1
--- /dev/null
@@ -0,0 +1,37 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#ifndef FORM_PARAMETER_H\r
+#define FORM_PARAMETER_H\r
+\r
+#include "AbstractParam.h"\r
+\r
+namespace RAML\r
+{\r
+    class FormParameter: public AbstractParam\r
+    {\r
+        public:\r
+            FormParameter(const YAML::Node &yamlNode) : AbstractParam(yamlNode) {}\r
+            FormParameter() {}\r
+    };\r
+    typedef std::shared_ptr<FormParameter> FormParameterPtr;\r
+\r
+}\r
+#endif\r
diff --git a/service/simulator/ramlparser/raml/model/Header.h b/service/simulator/ramlparser/raml/model/Header.h
new file mode 100755 (executable)
index 0000000..3aca86b
--- /dev/null
@@ -0,0 +1,38 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#ifndef HEADER_PARAMETER_H\r
+#define HEADER_PARAMETER_H\r
+\r
+#include "AbstractParam.h"\r
+\r
+namespace RAML\r
+{\r
+    class Header: public AbstractParam\r
+    {\r
+        public:\r
+            Header(const YAML::Node &yamlNode) : AbstractParam(yamlNode) {}\r
+            Header() {}\r
+    };\r
+    typedef std::shared_ptr<Header> HeaderPtr;\r
+\r
+}\r
+#endif\r
+\r
diff --git a/service/simulator/ramlparser/raml/model/QueryParameter.h b/service/simulator/ramlparser/raml/model/QueryParameter.h
new file mode 100755 (executable)
index 0000000..1850614
--- /dev/null
@@ -0,0 +1,37 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#ifndef QUERY_PARAMETER_H\r
+#define QUERY_PARAMETER_H\r
+\r
+#include "AbstractParam.h"\r
+\r
+namespace RAML\r
+{\r
+    class QueryParameter: public AbstractParam\r
+    {\r
+        public:\r
+            QueryParameter(const YAML::Node &yamlNode) : AbstractParam(yamlNode) {}\r
+            QueryParameter() {}\r
+    };\r
+    typedef std::shared_ptr<QueryParameter> QueryParameterPtr;\r
+\r
+}\r
+#endif\r
diff --git a/service/simulator/ramlparser/raml/model/Raml.cpp b/service/simulator/ramlparser/raml/model/Raml.cpp
new file mode 100755 (executable)
index 0000000..4e68999
--- /dev/null
@@ -0,0 +1,250 @@
+/******************************************************************\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 "Raml.h"\r
+\r
+namespace RAML\r
+{\r
+\r
+    std::string Raml::getTitle() const\r
+    {\r
+        return m_title;\r
+    }\r
+    void Raml::setTitle(const std::string &title)\r
+    {\r
+        m_title = title;\r
+    }\r
+\r
+    std::string Raml::getVersion() const\r
+    {\r
+        return m_version;\r
+    }\r
+    void Raml::setVersion(const std::string &version)\r
+    {\r
+        m_version = version;\r
+    }\r
+\r
+    std::string Raml::getBaseUri() const\r
+    {\r
+        return m_baseUri;\r
+    }\r
+    void Raml::setBaseUri(const std::string &baseUri)\r
+    {\r
+        m_baseUri = baseUri;\r
+    }\r
+\r
+    std::list<std::string> const &Raml::getProtocols() const\r
+    {\r
+        return m_protocols;\r
+    }\r
+    void Raml::setProtocol(const std::string &protocol)\r
+    {\r
+        m_protocols.push_back(protocol);\r
+    }\r
+    std::map<std::string, UriParameterPtr> const &Raml::getBaseUriParameters() const\r
+    {\r
+        return m_baseUriParameters;\r
+    }\r
+    void Raml::setBaseUriParameter(const std::string &paramName, const UriParameterPtr &uriParameter)\r
+    {\r
+        m_baseUriParameters[paramName] = uriParameter;\r
+    }\r
+\r
+    std::string Raml::getMediaType() const\r
+    {\r
+        return m_mediaType;\r
+    }\r
+    void Raml::setMediaType(const std::string &mediaType)\r
+    {\r
+        m_mediaType = mediaType;\r
+    }\r
+\r
+    std::list<std::pair<std::string, SchemaPtr> > const &Raml::getSchemas() const\r
+    {\r
+        return m_schemas;\r
+    }\r
+\r
+    void Raml::setSchema(const std::string &schemaName, const SchemaPtr &schema)\r
+    {\r
+        m_schemas.push_back(std::make_pair(schemaName, schema));\r
+    }\r
+\r
+    std::list<std::pair<std::string, RamlResourcePtr> > const &Raml::getResourceTypes() const\r
+    {\r
+        return m_resourceTypes;\r
+    }\r
+    void Raml::setResourceType(const std::string &typeName, const RamlResourcePtr &resourceType)\r
+    {\r
+        m_resourceTypes.push_back(std::make_pair(typeName, resourceType));\r
+    }\r
+\r
+    std::list<std::pair<std::string, ActionPtr> > const &Raml::getTraits() const\r
+    {\r
+        return m_traits;\r
+    }\r
+    void Raml::setTrait(const std::string &traitName, const ActionPtr &trait)\r
+    {\r
+        m_traits.push_back(std::make_pair(traitName, trait));\r
+    }\r
+    RamlResourcePtr Raml::getResource(const std::string &resourceName)\r
+    {\r
+        return m_resources[resourceName];\r
+    }\r
+\r
+    std::map<std::string, RamlResourcePtr> const &Raml::getResources() const\r
+    {\r
+        return m_resources;\r
+    }\r
+\r
+    void Raml::setResource(const std::string &resourceKey, const RamlResourcePtr &resource)\r
+    {\r
+        m_resources[resourceKey] = resource;\r
+    }\r
+\r
+    void Raml::setDocumentationItem(const std::shared_ptr<DocumentationItem> &documentationItem)\r
+    {\r
+        m_documentation.push_back(documentationItem);\r
+    }\r
+\r
+    std::list<std::shared_ptr<DocumentationItem> > const &Raml::getDocumentation() const\r
+    {\r
+        return m_documentation;\r
+    }\r
+    void Raml::readRamlFromYaml(const YAML::Node &yamlNode )\r
+    {\r
+        if (yamlNode.Type() == YAML::NodeType::Map)\r
+        {\r
+            for ( YAML::const_iterator it = yamlNode.begin(); it != yamlNode.end(); ++it )\r
+            {\r
+                std::string key = READ_NODE_AS_STRING(it->first);\r
+                if (key == Keys::Title)\r
+                {\r
+                    setTitle(READ_NODE_AS_STRING(it->second));\r
+                }\r
+                else if (key == Keys::Version)\r
+                {\r
+                    setVersion(READ_NODE_AS_STRING(it->second));\r
+                }\r
+                else if (key == Keys::BaseUri)\r
+                {\r
+                    setBaseUri(READ_NODE_AS_STRING(it->second));\r
+                }\r
+                else if ((key == Keys::BaseUriParameters) || (key == Keys::UriParameters))\r
+                {\r
+                    YAML::Node paramNode = it->second;\r
+                    for ( YAML::const_iterator tt = paramNode.begin(); tt != paramNode.end(); ++tt )\r
+                    {\r
+                        setBaseUriParameter(READ_NODE_AS_STRING(tt->first), std::make_shared<UriParameter>(tt->second));\r
+                    }\r
+                }\r
+                else if (key == Keys::Protocols)\r
+                {\r
+                    YAML::Node protocolNode = it->second;\r
+                    for ( YAML::const_iterator tt = protocolNode.begin(); tt != protocolNode.end(); ++tt )\r
+                    {\r
+                        setProtocol(READ_NODE_AS_STRING(*tt));\r
+                    }\r
+                }\r
+                else if (key == Keys::MediaType)\r
+                {\r
+                    setMediaType(READ_NODE_AS_STRING(it->second));\r
+                }\r
+                else if (key == Keys::Documentation)\r
+                {\r
+                    YAML::Node docNode = it->second;\r
+                    for ( YAML::const_iterator iit = docNode.begin(); iit != docNode.end(); ++iit )\r
+                    {\r
+                        std::string title ;\r
+                        std::string content ;\r
+\r
+                        for ( YAML::const_iterator tt = (*iit).begin(); tt != (*iit).end(); ++tt )\r
+                        {\r
+                            std::string key = READ_NODE_AS_STRING(tt->first);\r
+\r
+                            if (key == Keys::Title)\r
+                                title = READ_NODE_AS_STRING(tt->second);\r
+                            else if (key == Keys::Content)\r
+                                content = READ_NODE_AS_STRING(tt->second);\r
+\r
+                        }\r
+                        setDocumentationItem(std::make_shared<DocumentationItem>(title, content));\r
+                    }\r
+                }\r
+                else if (key == Keys::Schemas)\r
+                {\r
+                    YAML::Node schemaNode = it->second;\r
+                    for ( YAML::const_iterator iit = schemaNode.begin(); iit != schemaNode.end(); ++iit )\r
+                    {\r
+                        for ( YAML::const_iterator tt = (*iit).begin(); tt != (*iit).end(); ++tt )\r
+                        {\r
+                            std::string key = READ_NODE_AS_STRING(tt->first);\r
+                            std::pair<std::string, Schema> schema;\r
+\r
+                            IncludeResolver::FileType fileType = m_includeResolver->getFileType(tt->second);\r
+                            if ((fileType == IncludeResolver::FileType::JSON) || (fileType == IncludeResolver::FileType::FILE))\r
+                            {\r
+                                setSchema(key, std::make_shared<Schema>(m_includeResolver->readFromFile(tt->second),\r
+                                                                        m_includeResolver));\r
+                            }\r
+                            else\r
+                            {\r
+                                setSchema(key, std::make_shared<Schema>(READ_NODE_AS_STRING(tt->second), m_includeResolver));\r
+                            }\r
+                        }\r
+                    }\r
+                }\r
+\r
+                else if (key.compare(0, Keys::Resource.length(), Keys::Resource)  == 0)\r
+                {\r
+                    setResource(key, std::make_shared<RamlResource>(key, it->second, m_includeResolver, getBaseUri()));\r
+                }\r
+                else if (key == Keys::Traits)\r
+                {\r
+                    YAML::Node traitNode = it->second;\r
+                    for ( YAML::const_iterator tt = traitNode.begin(); tt != traitNode.end(); ++tt )\r
+                    {\r
+                        for (auto elem : *tt)\r
+                        {\r
+                            std::string trait = READ_NODE_AS_STRING(elem.first);\r
+                            setTrait(trait, std::make_shared<Action>(ActionType::NONE, elem.second , m_includeResolver));\r
+                        }\r
+                    }\r
+                }\r
+                else if (key == Keys::ResourceTypes)\r
+                {\r
+                    YAML::Node typeNode = it->second;\r
+                    for ( YAML::const_iterator tt = typeNode.begin(); tt != typeNode.end(); ++tt )\r
+                    {\r
+                        for (auto elem : *tt)\r
+                        {\r
+                            std::string type = READ_NODE_AS_STRING(elem.first);\r
+                            setResourceType(type, std::make_shared<RamlResource>(type, elem.second, m_includeResolver,\r
+                                            getBaseUri()));\r
+\r
+                        }\r
+\r
+                    }\r
+                }\r
+            }\r
+        }\r
+\r
+    }\r
+\r
+}\r
diff --git a/service/simulator/ramlparser/raml/model/Raml.h b/service/simulator/ramlparser/raml/model/Raml.h
new file mode 100755 (executable)
index 0000000..6c7454a
--- /dev/null
@@ -0,0 +1,134 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#ifndef RAML_H\r
+#define RAML_H\r
+\r
+#include <map>\r
+#include <list>\r
+#include <string>\r
+#include "AbstractParam.h"\r
+#include "UriParameter.h"\r
+#include "QueryParameter.h"\r
+#include "FormParameter.h"\r
+#include "Header.h"\r
+\r
+#include "RequestResponseBody.h"\r
+#include "RamlResource.h"\r
+#include "ActionType.h"\r
+#include "Action.h"\r
+#include "Response.h"\r
+#include "Schema.h"\r
+#include "IncludeResolver.h"\r
+\r
+#include "DocumentationItem.h"\r
+#include "yaml-cpp/yaml.h"\r
+#include "yaml-cpp/exceptions.h"\r
+#include "RamlExceptions.h"\r
+#include "Utils.h"\r
+#include "cJSON.h"\r
+\r
+\r
+namespace RAML\r
+{\r
+    class Raml\r
+    {\r
+        public:\r
+            virtual std::string getTitle() const;\r
+            virtual void setTitle(const std::string &title);\r
+\r
+            virtual std::string getVersion() const;\r
+            virtual void setVersion(const std::string &version);\r
+\r
+            virtual std::string getBaseUri() const;\r
+            virtual void setBaseUri(const std::string &baseUri);\r
+\r
+            virtual std::list<std::string> const &getProtocols() const;\r
+            virtual void setProtocol(const std::string &protocol);\r
+\r
+\r
+            virtual std::map<std::string, UriParameterPtr> const &getBaseUriParameters() const;\r
+            virtual void setBaseUriParameter(const std::string &paramName, const UriParameterPtr &uriParameter);\r
+\r
+            virtual std::string getMediaType() const;\r
+            virtual void setMediaType(const std::string &mediaType);\r
+\r
+            virtual std::list<std::pair<std::string, SchemaPtr> > const &getSchemas() const;\r
+            virtual void setSchema(const std::string &schemaName, const SchemaPtr &schema);\r
+\r
+            virtual std::list<std::pair<std::string, RamlResourcePtr> > const &getResourceTypes() const;\r
+            virtual void setResourceType(const std::string &typeName, const RamlResourcePtr &resourceType);\r
+\r
+            virtual std::list<std::pair<std::string, ActionPtr> > const &getTraits() const;\r
+            virtual void setTrait(const std::string &traitName, const ActionPtr &trait);\r
+\r
+            virtual RamlResourcePtr getResource(const std::string &resourceName);\r
+            virtual std::map<std::string, RamlResourcePtr> const &getResources() const;\r
+            virtual void setResource(const std::string &resourceKey, const RamlResourcePtr &resource);\r
+\r
+            virtual void setDocumentationItem(const std::shared_ptr<DocumentationItem> &documentationItem);\r
+            virtual std::list<std::shared_ptr<DocumentationItem> > const &getDocumentation() const;\r
+\r
+            void readRamlFromYaml(const YAML::Node &yamlNode);\r
+            Raml() : m_includeResolver(std::make_shared<IncludeResolver>()) {}\r
+            Raml(const std::string &fileLocation,\r
+                 const std::string &ramlName) : m_includeResolver(std::make_shared<IncludeResolver>(fileLocation))\r
+            {\r
+                try\r
+                {\r
+                    YAML::Node yamlRootNode = YAML::LoadFile(fileLocation + ramlName);\r
+                    readRamlFromYaml(yamlRootNode);\r
+                }\r
+                catch (YAML::ParserException &e)\r
+                {\r
+                    throw RamlParserException(e.mark, e.msg);\r
+                }\r
+                catch (YAML::RepresentationException &e)\r
+                {\r
+                    throw RamlRepresentationException(e.mark, e.msg);\r
+                }\r
+                catch (YAML::BadFile &e)\r
+                {\r
+                    throw RamlBadFile(e.mark, e.msg);\r
+                }\r
+                catch (JsonException &e)\r
+                {\r
+                    throw;\r
+                }\r
+            }\r
+        private:\r
+            std::string m_title;\r
+            std::string m_version;\r
+            std::string m_baseUri;\r
+            std::list<std::string> m_protocols;\r
+            std::map<std::string, UriParameterPtr> m_baseUriParameters;\r
+            std::string m_mediaType;\r
+            std::list <std::pair<std::string, SchemaPtr> > m_schemas;\r
+            std::list <std::pair<std::string, RamlResourcePtr> > m_resourceTypes;\r
+            std::list <std::pair<std::string, ActionPtr> > m_traits;\r
+            std::map<std::string, RamlResourcePtr> m_resources;\r
+            std::list<std::shared_ptr<DocumentationItem> > m_documentation;\r
+            IncludeResolverPtr m_includeResolver;\r
+    };\r
+\r
+    typedef std::shared_ptr<Raml> RamlPtr;\r
+\r
+}\r
+#endif\r
diff --git a/service/simulator/ramlparser/raml/model/RamlResource.cpp b/service/simulator/ramlparser/raml/model/RamlResource.cpp
new file mode 100755 (executable)
index 0000000..66fc2fc
--- /dev/null
@@ -0,0 +1,173 @@
+/******************************************************************\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 "RamlResource.h"\r
+\r
+\r
+namespace RAML\r
+{\r
+    std::string RamlResource::getDisplayName() const\r
+    {\r
+        return m_displayName;\r
+    }\r
+    void RamlResource::setDisplayName(const std::string &displayName)\r
+    {\r
+        m_displayName = displayName;\r
+    }\r
+    std::string RamlResource::getDescription() const\r
+    {\r
+        return m_description;\r
+    }\r
+    void RamlResource::setDescription(const std::string &description)\r
+    {\r
+        m_description = description;\r
+    }\r
+    std::string RamlResource::getParentUri() const\r
+    {\r
+        return m_parentUri;\r
+    }\r
+    void RamlResource::setParentUri(const std::string &parentUri)\r
+    {\r
+        m_parentUri = parentUri;\r
+    }\r
+    std::string RamlResource::getRelativeUri() const\r
+    {\r
+        return m_relativeUri;\r
+    }\r
+    void RamlResource::setRelativeUri(const std::string &relativeUri)\r
+    {\r
+        m_relativeUri = relativeUri;\r
+    }\r
+    std::map<std::string, UriParameterPtr> const &RamlResource::getUriParameters() const\r
+    {\r
+        return m_uriParameters;\r
+    }\r
+    void RamlResource::setUriParameter(const std::string &paramName,\r
+                                       const UriParameterPtr &uriParameter)\r
+    {\r
+        m_uriParameters[paramName] = uriParameter;\r
+    }\r
+    std::map<std::string, UriParameterPtr > const &RamlResource::getBaseUriParameters() const\r
+    {\r
+        return m_baseUriParameters;\r
+    }\r
+    void RamlResource::setBaseUriParameter(const std::string &paramName,\r
+                                           const UriParameterPtr &baseUriParameter)\r
+    {\r
+        m_baseUriParameters[paramName] = baseUriParameter;\r
+    }\r
+    ActionPtr RamlResource::getAction(ActionType actionType)\r
+    {\r
+        return m_actions[actionType];\r
+    }\r
+\r
+    std::map<ActionType , ActionPtr> const &RamlResource::getActions() const\r
+    {\r
+        return m_actions;\r
+    }\r
+    void RamlResource::setAction(const ActionType &actiontype , const ActionPtr &action )\r
+    {\r
+        m_actions[actiontype] = action;\r
+    }\r
+    std::map<std::string, std::shared_ptr<RamlResource> > const &RamlResource::getResources() const\r
+    {\r
+        return m_resources;\r
+    }\r
+    void RamlResource::setResource(const std::string &resourceName,\r
+                                   const std::shared_ptr<RamlResource> &resources)\r
+    {\r
+        m_resources[resourceName] = resources;\r
+    }\r
+    std::list<std::string> const &RamlResource::getTraits() const\r
+    {\r
+        return m_traits;\r
+    }\r
+    void RamlResource::setTrait(const std::string &trait)\r
+    {\r
+        m_traits.push_back(trait);\r
+    }\r
+    std::string RamlResource::getResourceType() const\r
+    {\r
+        return m_resourceType;\r
+    }\r
+    void RamlResource::setResourceType(const std::string &type)\r
+    {\r
+        m_resourceType = type;\r
+    }\r
+    std::string RamlResource::getResourceUri() const\r
+    {\r
+        return (m_parentUri + m_relativeUri);\r
+    }\r
+    void RamlResource::readResource(const std::string resourceKey, const YAML::Node &yamlNode,\r
+                                    const std::string &parentUri)\r
+    {\r
+        m_relativeUri = resourceKey;\r
+        m_parentUri = parentUri;\r
+        for ( YAML::const_iterator it = yamlNode.begin(); it != yamlNode.end(); ++it )\r
+        {\r
+            std::string key = READ_NODE_AS_STRING(it->first);\r
+\r
+            if (key == Keys::DisplayName)\r
+                setDisplayName(READ_NODE_AS_STRING(it->second));\r
+            else if (key == Keys::Description)\r
+                setDescription(READ_NODE_AS_STRING(it->second));\r
+            else if (std::find(Keys::ActionType.begin(), Keys::ActionType.end(), key) != Keys::ActionType.end())\r
+            {\r
+                ActionType actionType = GET_ACTION_TYPE(key);\r
+\r
+                setAction(actionType, std::make_shared<Action>(actionType, it->second, m_includeResolver));\r
+            }\r
+            else if (key == Keys::UriParameters)\r
+            {\r
+                YAML::Node paramNode = it->second;\r
+                for ( YAML::const_iterator tt = paramNode.begin(); tt != paramNode.end(); ++tt )\r
+                {\r
+                    setUriParameter(READ_NODE_AS_STRING(tt->first), std::make_shared<UriParameter>(tt->second));\r
+                }\r
+            }\r
+            else if (key == Keys::BaseUriParameters)\r
+            {\r
+                YAML::Node paramNode = it->second;\r
+                for ( YAML::const_iterator tt = paramNode.begin(); tt != paramNode.end(); ++tt )\r
+                {\r
+                    setBaseUriParameter(READ_NODE_AS_STRING(tt->first), std::make_shared<UriParameter>(tt->second));\r
+                }\r
+            }\r
+            else if (key == Keys::IsTrait)\r
+            {\r
+                YAML::Node traitNode = it->second;\r
+                for ( YAML::const_iterator tt = traitNode.begin(); tt != traitNode.end(); ++tt )\r
+                {\r
+                    setTrait(READ_NODE_AS_STRING(*tt));\r
+                }\r
+            }\r
+            else if (key == Keys::Type)\r
+            {\r
+                setResourceType(READ_NODE_AS_STRING(it->second));\r
+            }\r
+            else if (key.compare(0, Keys::Resource.length(), Keys::Resource)  == 0)\r
+            {\r
+                setResource(key, std::make_shared<RamlResource>(key, it->second, m_includeResolver,\r
+                            getResourceUri()));\r
+            }\r
+        }\r
+    }\r
+\r
+}\r
diff --git a/service/simulator/ramlparser/raml/model/RamlResource.h b/service/simulator/ramlparser/raml/model/RamlResource.h
new file mode 100755 (executable)
index 0000000..c7acf78
--- /dev/null
@@ -0,0 +1,98 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#ifndef RESOURCE_H\r
+#define RESOURCE_H\r
+\r
+#include <map>\r
+#include <list>\r
+#include <string>\r
+#include "UriParameter.h"\r
+#include "ActionType.h"\r
+#include "Action.h"\r
+#include "Utils.h"\r
+#include "IncludeResolver.h"\r
+\r
+namespace RAML\r
+{\r
+    class RamlResource\r
+    {\r
+        public:\r
+            virtual std::string getDisplayName() const;\r
+            virtual void setDisplayName(const std::string &displayName);\r
+\r
+            virtual std::string getDescription() const;\r
+            virtual void setDescription(const std::string &description);\r
+\r
+            virtual std::string getParentUri() const;\r
+            virtual void setParentUri(const std::string &parentUri);\r
+\r
+            virtual std::string getRelativeUri() const;\r
+            virtual void setRelativeUri(const std::string &relativeUri);\r
+\r
+            virtual std::map<std::string, UriParameterPtr> const &getUriParameters() const;\r
+            virtual void setUriParameter(const std::string &paramName, const UriParameterPtr &uriParameter);\r
+\r
+            virtual std::map<std::string, UriParameterPtr > const &getBaseUriParameters() const;\r
+            virtual void setBaseUriParameter(const std::string &paramName,\r
+                                             const UriParameterPtr &baseUriParameter);\r
+\r
+            virtual ActionPtr getAction(ActionType actionType);\r
+            virtual std::map<ActionType , ActionPtr> const &getActions() const;\r
+            virtual void setAction(const ActionType &actiontype , const ActionPtr &action );\r
+\r
+            virtual std::map<std::string, std::shared_ptr<RamlResource> > const &getResources() const;\r
+            virtual void setResource(const std::string &resourceName,\r
+                                     const std::shared_ptr<RamlResource> &resources);\r
+\r
+            virtual std::list<std::string> const &getTraits() const;\r
+            virtual void setTrait(const std::string &trait);\r
+\r
+            virtual std::string getResourceType() const;\r
+            virtual void setResourceType(const std::string &type);\r
+\r
+            virtual std::string getResourceUri() const;\r
+            RamlResource(): m_includeResolver(NULL) {}\r
+            RamlResource(const std::string resourceKey, const YAML::Node &yamlNode ,\r
+                         const IncludeResolverPtr &includeResolver,\r
+                         const std::string &parentUri) : m_includeResolver(includeResolver)\r
+            {\r
+                readResource(resourceKey, yamlNode, parentUri);\r
+            }\r
+        private:\r
+            void readResource(const std::string resourceKey, const YAML::Node &yamlNode,\r
+                              const std::string &parentUri);\r
+        private:\r
+            std::string m_displayName;\r
+            std::string m_description;\r
+            std::string m_relativeUri;\r
+            std::map<std::string, UriParameterPtr> m_uriParameters;\r
+            std::map<std::string, UriParameterPtr > m_baseUriParameters;\r
+            std::map<ActionType , ActionPtr> m_actions;\r
+            std::list<std::string> m_traits;\r
+            std::string m_resourceType;\r
+            std::string m_parentUri;\r
+            std::map<std::string, std::shared_ptr<RamlResource> > m_resources;\r
+            IncludeResolverPtr m_includeResolver;\r
+    };\r
+\r
+    typedef std::shared_ptr<RamlResource> RamlResourcePtr;\r
+}\r
+#endif\r
diff --git a/service/simulator/ramlparser/raml/model/RequestResponseBody.cpp b/service/simulator/ramlparser/raml/model/RequestResponseBody.cpp
new file mode 100755 (executable)
index 0000000..e96226a
--- /dev/null
@@ -0,0 +1,93 @@
+/******************************************************************\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 "RequestResponseBody.h"\r
+\r
+namespace RAML\r
+{\r
+\r
+    std::string RequestResponseBody::getType() const\r
+    {\r
+        return m_type;\r
+    }\r
+    void RequestResponseBody::setType(const std::string &type)\r
+    {\r
+        m_type = type;\r
+    }\r
+    SchemaPtr const &RequestResponseBody::getSchema() const\r
+    {\r
+        return m_schema;\r
+    }\r
+    void RequestResponseBody::setSchema(const SchemaPtr &schema)\r
+    {\r
+        m_schema = schema;\r
+    }\r
+    std::string RequestResponseBody::getExample() const\r
+    {\r
+        return m_example;\r
+    }\r
+    void RequestResponseBody::setExample(const std::string &example)\r
+    {\r
+        m_example = example;\r
+    }\r
+    std::map<std::string, FormParameterPtr > const &RequestResponseBody::getFormParameters() const\r
+    {\r
+        return m_formParameters ;\r
+    }\r
+    void RequestResponseBody::setFormParameter(const std::string &paramName,\r
+            const FormParameterPtr  &formParameter)\r
+    {\r
+        m_formParameters[paramName] = formParameter;\r
+    }\r
+    void RequestResponseBody::readRequestResponseBody(const std::string &type,\r
+            const YAML::Node &yamlNode)\r
+    {\r
+        m_type = type;\r
+        for ( YAML::const_iterator it = yamlNode.begin(); it != yamlNode.end(); ++it )\r
+        {\r
+            std::string key = READ_NODE_AS_STRING(it->first);\r
+\r
+            if (key == Keys::Schema)\r
+            {\r
+                IncludeResolver::FileType fileType = m_includeResolver->getFileType(it->second);\r
+                if ((fileType == IncludeResolver::FileType::JSON) || (fileType == IncludeResolver::FileType::FILE))\r
+                {\r
+                    setSchema(std::make_shared<Schema>(m_includeResolver->readFromFile(it->second), m_includeResolver));\r
+                }\r
+                else\r
+                {\r
+                    std::string value = READ_NODE_AS_STRING(it->second);\r
+                    setSchema(std::make_shared<Schema>(value, m_includeResolver));\r
+                }\r
+            }\r
+            else if (key == Keys::Example)\r
+                setExample(READ_NODE_AS_STRING(it->second));\r
+            else if (key == Keys::FormParameters)\r
+            {\r
+                YAML::Node paramNode = it->second;\r
+                for ( YAML::const_iterator tt = paramNode.begin(); tt != paramNode.end(); ++tt )\r
+                {\r
+                    setFormParameter(READ_NODE_AS_STRING(tt->first), std::make_shared<FormParameter>(tt->second));\r
+                }\r
+            }\r
+        }\r
+    }\r
+\r
+}\r
diff --git a/service/simulator/ramlparser/raml/model/RequestResponseBody.h b/service/simulator/ramlparser/raml/model/RequestResponseBody.h
new file mode 100755 (executable)
index 0000000..7b2956e
--- /dev/null
@@ -0,0 +1,62 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#ifndef REQUEST_RESPONSE_BODY_H\r
+#define REQUEST_RESPONSE_BODY_H\r
+\r
+#include <map>\r
+#include <list>\r
+#include "FormParameter.h"\r
+#include "Utils.h"\r
+#include "IncludeResolver.h"\r
+#include "Schema.h"\r
+\r
+namespace RAML\r
+{\r
+    class RequestResponseBody\r
+    {\r
+        public:\r
+            virtual std::string getType() const;\r
+            virtual void setType(const std::string &type);\r
+            virtual SchemaPtr const &getSchema() const;\r
+            virtual void setSchema(const SchemaPtr &schema);\r
+            virtual std::string getExample() const;\r
+            virtual void setExample(const std::string &example);\r
+            virtual std::map<std::string, FormParameterPtr> const &getFormParameters() const;\r
+            virtual void setFormParameter(const std::string &paramName, const FormParameterPtr &formParameter);\r
+            RequestResponseBody(): m_schema(NULL), m_includeResolver(NULL) {}\r
+            RequestResponseBody(const std::string type) : m_type(type), m_schema(NULL),\r
+                m_includeResolver(NULL) {}\r
+            RequestResponseBody(const std::string type, const YAML::Node &yamlNode,\r
+                                const IncludeResolverPtr &includeResolver): m_schema(NULL), m_includeResolver(includeResolver) { readRequestResponseBody(type, yamlNode); }\r
+\r
+        private:\r
+            virtual void readRequestResponseBody(const std::string &type, const YAML::Node &yamlNode) ;\r
+        private:\r
+            std::string m_type;\r
+            SchemaPtr m_schema;\r
+            std::string m_example;\r
+            std::map<std::string, FormParameterPtr> m_formParameters;\r
+            IncludeResolverPtr m_includeResolver;\r
+    };\r
+\r
+    typedef std::shared_ptr<RequestResponseBody> RequestResponseBodyPtr;\r
+}\r
+#endif\r
diff --git a/service/simulator/ramlparser/raml/model/Response.cpp b/service/simulator/ramlparser/raml/model/Response.cpp
new file mode 100755 (executable)
index 0000000..cbd1433
--- /dev/null
@@ -0,0 +1,88 @@
+/******************************************************************\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 "Response.h"\r
+\r
+namespace RAML\r
+{\r
+\r
+    std::map<std::string, HeaderPtr> const &Response::getHeaders() const\r
+    {\r
+        return m_headers;\r
+    }\r
+    void Response::setHeader(const std::string &headerName, const HeaderPtr &header)\r
+    {\r
+        m_headers[headerName] = header;\r
+    }\r
+    std::string Response::getDescription() const\r
+    {\r
+        return m_description;\r
+    }\r
+    void Response::setDescription(const std::string &description)\r
+    {\r
+        m_description = description;\r
+    }\r
+    void Response::setResponseBody(const std::string &typeName)\r
+    {\r
+        m_responseBody[typeName] = std::make_shared<RequestResponseBody>(typeName);\r
+    }\r
+    void Response::setResponseBody(const std::string &type, const RequestResponseBodyPtr &body)\r
+    {\r
+        m_responseBody[type] = body;\r
+    }\r
+    std::map<std::string, RequestResponseBodyPtr> const &Response::getResponseBody() const\r
+    {\r
+        return m_responseBody;\r
+    }\r
+    RequestResponseBodyPtr Response::getResponseBody(const std::string &bodyType)\r
+    {\r
+        return m_responseBody[bodyType];\r
+    }\r
+\r
+    void Response::readResponse(const YAML::Node &yamlNode)\r
+    {\r
+        for ( YAML::const_iterator it = yamlNode.begin(); it != yamlNode.end(); ++it )\r
+        {\r
+            std::string key = READ_NODE_AS_STRING(it->first);\r
+\r
+            if (key == Keys::Description)\r
+                setDescription(READ_NODE_AS_STRING(it->second));\r
+            else if (key == Keys::Body)\r
+            {\r
+                YAML::Node responseBody = it->second;\r
+\r
+                for ( YAML::const_iterator tt = responseBody.begin(); tt != responseBody.end(); ++tt )\r
+                {\r
+                    std::string type = READ_NODE_AS_STRING(tt->first);\r
+                    setResponseBody(type, std::make_shared<RequestResponseBody>(type, tt->second, m_includeResolver));\r
+                }\r
+            }\r
+            else if (key == Keys::Headers)\r
+            {\r
+                YAML::Node paramNode = it->second;\r
+                for ( YAML::const_iterator tt = paramNode.begin(); tt != paramNode.end(); ++tt )\r
+                {\r
+                    setHeader(READ_NODE_AS_STRING(tt->first), std::make_shared<Header>(tt->second));\r
+                }\r
+            }\r
+        }\r
+    }\r
+\r
+}\r
diff --git a/service/simulator/ramlparser/raml/model/Response.h b/service/simulator/ramlparser/raml/model/Response.h
new file mode 100755 (executable)
index 0000000..92c09db
--- /dev/null
@@ -0,0 +1,60 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#ifndef RESPONSE_H\r
+#define RESPONSE_H\r
+\r
+#include <map>\r
+#include <list>\r
+#include <string>\r
+#include "RequestResponseBody.h"\r
+#include "Header.h"\r
+#include "Utils.h"\r
+#include "IncludeResolver.h"\r
+\r
+namespace RAML\r
+{\r
+    class Response\r
+    {\r
+        public:\r
+            virtual std::map<std::string, HeaderPtr> const &getHeaders() const;\r
+            virtual void setHeader(const std::string &headerName, const HeaderPtr &header);\r
+            virtual std::string getDescription() const;\r
+            virtual void setDescription(const std::string &description);\r
+            virtual void setResponseBody(const std::string &typeName);\r
+            virtual void setResponseBody(const std::string &type, const RequestResponseBodyPtr &body) ;\r
+            virtual std::map<std::string, RequestResponseBodyPtr> const &getResponseBody() const;\r
+            virtual RequestResponseBodyPtr getResponseBody(const std::string &bodyType);\r
+\r
+\r
+            Response() : m_includeResolver(NULL) {}\r
+            Response(const YAML::Node &yamlNode,\r
+                     const IncludeResolverPtr &includeResolver): m_includeResolver(includeResolver)  { readResponse(yamlNode);}\r
+        private:\r
+            void readResponse(const YAML::Node &yamlNode) ;\r
+        private:\r
+            std::string m_description;\r
+            std::map<std::string, RequestResponseBodyPtr> m_responseBody;\r
+            std::map<std::string, HeaderPtr> m_headers;\r
+            IncludeResolverPtr m_includeResolver;\r
+    };\r
+    typedef std::shared_ptr<Response> ResponsePtr;\r
+}\r
+#endif\r
diff --git a/service/simulator/ramlparser/raml/model/Schema.cpp b/service/simulator/ramlparser/raml/model/Schema.cpp
new file mode 100755 (executable)
index 0000000..d03d638
--- /dev/null
@@ -0,0 +1,48 @@
+/******************************************************************\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 "Schema.h"\r
+namespace RAML\r
+{\r
+\r
+    cJSON *Schema::getJson() const\r
+    {\r
+        return m_cjson;\r
+    }\r
+    void Schema::setJson(cJSON *cjson)\r
+    {\r
+        m_cjson = cjson;\r
+    }\r
+    std::string Schema::getSchema() const\r
+    {\r
+        return m_schema;\r
+    }\r
+    void Schema::setSchema(const std::string &schema)\r
+    {\r
+        m_schema = schema;\r
+        m_cjson = cJSON_Parse(schema.c_str());\r
+        m_resProperties->setcJson(m_cjson);\r
+    }\r
+    JsonSchemaPtr const &Schema::getProperties() const\r
+    {\r
+        return m_resProperties;\r
+    }\r
+\r
+}\r
diff --git a/service/simulator/ramlparser/raml/model/Schema.h b/service/simulator/ramlparser/raml/model/Schema.h
new file mode 100755 (executable)
index 0000000..e38be93
--- /dev/null
@@ -0,0 +1,57 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#ifndef SCHEMAS_H\r
+#define SCHEMAS_H\r
+\r
+#include <string>\r
+#include "cJSON.h"\r
+#include "IncludeResolver.h"\r
+\r
+#include "JsonSchema.h"\r
+\r
+namespace RAML\r
+{\r
+    class Schema\r
+    {\r
+        public:\r
+            virtual cJSON *getJson() const;\r
+            virtual void setJson(cJSON *cjson);\r
+            virtual std::string getSchema() const;\r
+            virtual void setSchema(const std::string &schema);\r
+            virtual JsonSchemaPtr const &getProperties() const;\r
+\r
+            Schema(const std::string &schema, const IncludeResolverPtr &includeResolver): m_schema(schema) ,\r
+                m_cjson(cJSON_Parse(schema.c_str())),\r
+                m_resProperties(std::make_shared<JsonSchema>(m_cjson, includeResolver) ) ,\r
+                m_includeResolver(includeResolver) {}\r
+            Schema(): m_cjson(NULL), m_includeResolver(NULL), m_resProperties(std::make_shared<JsonSchema>()) {}\r
+            ~Schema() { cJSON_Delete(m_cjson); }\r
+\r
+        private:\r
+            cJSON *m_cjson;\r
+            std::string m_schema;\r
+            JsonSchemaPtr m_resProperties;\r
+            IncludeResolverPtr m_includeResolver;\r
+    };\r
+    typedef std::shared_ptr<Schema> SchemaPtr;\r
+\r
+}\r
+#endif\r
diff --git a/service/simulator/ramlparser/raml/model/UriParameter.h b/service/simulator/ramlparser/raml/model/UriParameter.h
new file mode 100755 (executable)
index 0000000..5f8d61e
--- /dev/null
@@ -0,0 +1,37 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#ifndef URI_PARAMETER_H\r
+#define URI_PARAMETER_H\r
+\r
+#include "AbstractParam.h"\r
+\r
+namespace RAML\r
+{\r
+    class UriParameter: public AbstractParam\r
+    {\r
+        public:\r
+            UriParameter(const YAML::Node &yamlNode) : AbstractParam(yamlNode) {}\r
+            UriParameter() {}\r
+    };\r
+    typedef std::shared_ptr<UriParameter> UriParameterPtr;\r
+\r
+}\r
+#endif\r
diff --git a/service/simulator/src/client-controller/attribute_generator.cpp b/service/simulator/src/client-controller/attribute_generator.cpp
new file mode 100644 (file)
index 0000000..7cd3290
--- /dev/null
@@ -0,0 +1,140 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "attribute_generator.h"
+
+AttributeGenerator::AttributeGenerator(SimulatorResourceModel::Attribute &attribute)
+{
+    m_name.assign(attribute.getName());
+    m_type = attribute.getValueType();
+
+    if (!attribute.getValueType())
+        attribute.getRange(m_min, m_max);
+    if (m_max > 0)
+    {
+        m_hasRange = true;
+    }
+
+    if (!m_type)
+        m_rangeIndex = m_min;
+
+    m_allowedValues = attribute.getAllowedValues();
+    if (0 != m_allowedValues.size())
+    {
+        m_hasAllowedValue = true;
+    }
+    m_nextAllowedValueIndex = 0;
+    m_prevAllowedValueIndex = m_allowedValues.size();
+}
+
+AttributeGenerator::~AttributeGenerator()
+{
+    m_rangeIndex = 0;
+    m_min = 0;
+    m_max = 0;
+    m_nextAllowedValueIndex = 0;
+    m_prevAllowedValueIndex = 0;
+    m_type = 0;
+}
+
+bool AttributeGenerator::hasNext()
+{
+    if (m_hasRange && m_rangeIndex <= m_max && !m_type)
+    {
+        return true;
+    }
+
+    if (m_hasAllowedValue && m_nextAllowedValueIndex < m_allowedValues.size())
+    {
+        return true;
+    }
+
+    return false;
+}
+
+AttributeSP AttributeGenerator::next()
+{
+    AttributeSP attr = std::make_shared<SimulatorResourceModel::Attribute>(m_name);
+
+    if (!attr)
+        return nullptr;
+
+    if (m_hasRange && !m_type)
+    {
+        attr->setName(m_name);
+        attr->setValue(m_rangeIndex++);
+        return attr;
+    }
+
+    if (m_hasAllowedValue)
+    {
+        switch (m_type)
+        {
+            case 1:
+                {
+                    attr->setValue(m_allowedValues[m_nextAllowedValueIndex++]);
+                }
+                break;
+
+            case 3:
+                {
+                    attr->setValue(m_allowedValues[m_nextAllowedValueIndex++]);
+                }
+                break;
+        }
+
+        return attr;
+    }
+}
+
+AttributeSP AttributeGenerator::previous()
+{
+    AttributeSP attr = std::make_shared<SimulatorResourceModel::Attribute>(m_name);
+
+    if (!attr)
+        return nullptr;
+
+    if (m_hasRange && !m_type)
+    {
+        attr->setValue(m_rangeIndex - 1);
+        return attr;
+    }
+
+    if (m_hasAllowedValue)
+    {
+        switch (m_type)
+        {
+            case 1:
+                {
+                    attr->setValue(m_allowedValues[m_prevAllowedValueIndex - 1]);
+                }
+                break;
+
+            case 3:
+                {
+                    attr->setValue(m_allowedValues[m_prevAllowedValueIndex - 1]);
+                }
+                break;
+        }
+
+        return attr;
+    }
+}
+
diff --git a/service/simulator/src/client-controller/attribute_generator.h b/service/simulator/src/client-controller/attribute_generator.h
new file mode 100644 (file)
index 0000000..a2b3281
--- /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 ATTRIBUTE_GENERATOR_H_
+#define ATTRIBUTE_GENERATOR_H_
+
+#include <map>
+#include <vector>
+#include "simulator_resource_model.h"
+
+class AttributeGenerator
+{
+    public:
+        AttributeGenerator(SimulatorResourceModel::Attribute &attribute);
+        ~AttributeGenerator();
+        bool hasNext();
+        AttributeSP next();
+        AttributeSP previous();
+
+    private:
+        std::string m_name;
+        int m_type;
+        int m_max;
+        int m_min;
+        int m_rangeIndex;
+        int m_nextAllowedValueIndex;
+        int m_prevAllowedValueIndex;
+        bool m_hasRange;
+        bool m_hasAllowedValue;
+        std::vector<SimulatorResourceModel::Attribute::ValueVariant> m_allowedValues;
+};
+
+#endif
+
diff --git a/service/simulator/src/client-controller/auto_request_gen.cpp b/service/simulator/src/client-controller/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-controller/auto_request_gen.h b/service/simulator/src/client-controller/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-controller/auto_request_gen_mngr.cpp b/service/simulator/src/client-controller/auto_request_gen_mngr.cpp
new file mode 100644 (file)
index 0000000..56adc4a
--- /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-controller/auto_request_gen_mngr.h b/service/simulator/src/client-controller/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-controller/get_request_generator.cpp b/service/simulator/src/client-controller/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-controller/get_request_generator.h b/service/simulator/src/client-controller/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-controller/post_request_generator.cpp b/service/simulator/src/client-controller/post_request_generator.cpp
new file mode 100644 (file)
index 0000000..47a676d
--- /dev/null
@@ -0,0 +1,162 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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);
+
+    std::map<std::string, SimulatorResourceModel::Attribute> attributes = m_rep->getAttributes();
+    if (!attributes.size())
+        return;
+
+    std::vector<std::shared_ptr<AttributeGenerator>> attributeGenList;
+    for (auto & attribute : attributes)
+    {
+        attributeGenList.push_back(std::make_shared<AttributeGenerator>(attribute.second));
+    }
+
+    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 = std::make_shared<SimulatorResourceModel>();
+                    AttributeSP attr = attributeGen->next();
+                    int type = attr->getValueType();
+
+                    switch (type)
+                    {
+                        case 0:
+                            {
+                                int attributeValue = attr->getValue<int>();
+                                std::string attributeName = attr->getName();
+                                repModel->addAttribute(attributeName, attributeValue);
+                            }
+                            break;
+
+                        case 3:
+                            {
+                                std::string attributeValue = attr->getValue<std::string>();
+                                std::string attributeName = attr->getName();
+                                repModel->addAttribute(attributeName, attributeValue);
+                            }
+                            break;
+                    }
+
+                    // 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
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-controller/put_request_generator.cpp b/service/simulator/src/client-controller/put_request_generator.cpp
new file mode 100644 (file)
index 0000000..029f115
--- /dev/null
@@ -0,0 +1,185 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#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);
+
+    bool hasNext = false;
+    std::map<std::string, SimulatorResourceModel::Attribute> attributes = m_rep->getAttributes();
+    if (!attributes.size())
+        return;
+
+    std::vector<std::shared_ptr<AttributeGenerator>> attributeGenList;
+    for (auto & attribute : attributes)
+    {
+        attributeGenList.push_back(std::make_shared<AttributeGenerator>(attribute.second));
+    }
+
+    do
+    {
+        if (!m_stopRequested)
+        {
+            // Get the next possible queryParameter
+            std::map<std::string, std::string> queryParam = m_queryParamGen.next();
+
+            while (true)
+            {
+                SimulatorResourceModelSP repModel = std::make_shared<SimulatorResourceModel>();
+
+                for (auto & attributeGen : attributeGenList)
+                {
+                    if (attributeGen->hasNext())
+                    {
+                        AttributeSP attr = attributeGen->next();
+                        int type = attr->getValueType();
+                        if (!type)
+                        {
+                            int attributeValue = attr->getValue<int>();
+                            std::string attributeName = attr->getName();
+                            repModel->addAttribute(attributeName, attributeValue);
+                        }
+                        else
+                        {
+                            std::string attributeValue = attr->getValue<std::string>();
+                            std::string attributeName = attr->getName();
+                            repModel->addAttribute(attr->getName(), attributeValue);
+                        }
+
+                        hasNext = true;
+                    }
+                    else
+                    {
+                        AttributeSP attr = attributeGen->previous();
+                        int type = attr->getValueType();
+                        if (!type)
+                        {
+                            int attributeValue = attr->getValue<int>();
+                            repModel->addAttribute(attr->getName(), attributeValue);
+                        }
+                        else
+                        {
+                            std::string attributeValue = attr->getValue<std::string>();
+                            repModel->addAttribute(attr->getName(), attributeValue);
+                        }
+                    }
+                }
+
+                if (hasNext)
+                {
+                    // Send the request
+                    m_requestSender->sendRequest(queryParam, repModel,
+                                                 std::bind(&PUTRequestGenerator::onResponseReceived, this,
+                                                           std::placeholders::_1, std::placeholders::_2), true);
+
+                    m_requestCnt++;
+                    hasNext = false;
+                    continue;
+                }
+                else
+                {
+                    break;
+                }
+            }
+        }
+    }
+    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
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-controller/query_param_generator.cpp b/service/simulator/src/client-controller/query_param_generator.cpp
new file mode 100644 (file)
index 0000000..2d0e890
--- /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(); 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
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-controller/request_list.h b/service/simulator/src/client-controller/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-controller/request_sender.cpp b/service/simulator/src/client-controller/request_sender.cpp
new file mode 100644 (file)
index 0000000..1e2ca62
--- /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 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
new file mode 100644 (file)
index 0000000..46457e9
--- /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 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
new file mode 100644 (file)
index 0000000..71645c9
--- /dev/null
@@ -0,0 +1,93 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#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
new file mode 100644 (file)
index 0000000..ed669b3
--- /dev/null
@@ -0,0 +1,87 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @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
new file mode 100644 (file)
index 0000000..9805a81
--- /dev/null
@@ -0,0 +1,426 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_PUT]->getQueryParams(),
+                        m_requestModelList[RequestType::RQ_TYPE_PUT]->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!");
+    }
+
+    RAML::RamlParser *ramlParser = new 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
new file mode 100644 (file)
index 0000000..bd64e98
--- /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 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/common/request_model.cpp b/service/simulator/src/common/request_model.cpp
new file mode 100644 (file)
index 0000000..4a522c2
--- /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 "request_model.h"
+#include "logger.h"
+
+RequestModel::RequestModel(RequestType type) : m_type(type) {}
+
+RequestType RequestModel::type() const
+{
+    return m_type;
+}
+
+SupportedQueryParams RequestModel::getQueryParams()
+{
+    return m_queryParams;
+}
+
+std::vector<std::string> RequestModel::getQueryParams(const std::string &key)
+{
+    if (m_queryParams.end() != m_queryParams.find(key))
+    {
+        return m_queryParams[key];
+    }
+
+    return std::vector<std::string>();
+}
+
+void RequestModel::setQueryParams(
+    const SupportedQueryParams &queryParams)
+{
+    m_queryParams = queryParams;
+}
+
+void RequestModel::addQueryParams(const std::string &key,
+                                  const std::vector<std::string> &values)
+{
+    if (0 != values.size())
+        m_queryParams[key] = values;
+}
+
+void RequestModel::addQueryParam(const std::string &key, const std::string &value)
+{
+    m_queryParams[key].push_back(value);
+}
+
+void RequestModel::addResponseModel(int code, ResponseModelSP &responseModel)
+{
+    if (!responseModel)
+        m_responseList[code] = responseModel;
+}
+
+void RequestModel::setRepSchema(SimulatorResourceModelSP &repSchema)
+{
+    m_repSchema = repSchema;
+}
+
+SimulatorResourceModelSP RequestModel::getRepSchema()
+{
+    return m_repSchema;
+}
+
+SimulatorResult RequestModel::validateResponse(int responseCode, const OC::OCRepresentation &rep)
+{
+    if (m_responseList.end() == m_responseList.find(responseCode))
+    {
+        return SIMULATOR_INVALID_RESPONSE_CODE;
+    }
+
+    return m_responseList[responseCode]->verifyResponse(rep);
+}
+
diff --git a/service/simulator/src/common/request_model.h b/service/simulator/src/common/request_model.h
new file mode 100644 (file)
index 0000000..e47c82e
--- /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.
+ *
+ ******************************************************************/
+
+#ifndef REQUEST_MODEL_H_
+#define REQUEST_MODEL_H_
+
+#include "simulator_client_types.h"
+#include "simulator_resource_model.h"
+#include "response_model.h"
+#include "Raml.h"
+
+typedef std::map<std::string, std::vector<std::string>> SupportedQueryParams;
+
+class RequestModelBuilder;
+class RequestModel
+{
+    public:
+        friend class RequestModelBuilder;
+
+        RequestType type() const;
+        SupportedQueryParams getQueryParams();
+        std::vector<std::string> getQueryParams(const std::string &key);
+        SimulatorResourceModelSP getRepSchema();
+        SimulatorResult validateResponse(int responseCode, const OC::OCRepresentation &rep);
+
+    private:
+        RequestModel(RequestType type);
+        void setQueryParams(const SupportedQueryParams &queryParams);
+        void addQueryParams(const std::string &key, const std::vector<std::string> &values);
+        void addQueryParam(const std::string &key, const std::string &value);
+        void addResponseModel(int code, ResponseModelSP &responseModel);
+        void setRepSchema(SimulatorResourceModelSP &repSchema);
+
+        RequestType m_type;
+        SupportedQueryParams m_queryParams;
+        std::map<int, ResponseModelSP> m_responseList;
+        SimulatorResourceModelSP m_repSchema;
+};
+
+typedef std::shared_ptr<RequestModel> RequestModelSP;
+
+#endif
diff --git a/service/simulator/src/common/request_model_builder.cpp b/service/simulator/src/common/request_model_builder.cpp
new file mode 100644 (file)
index 0000000..c3adf51
--- /dev/null
@@ -0,0 +1,217 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_model_builder.h"
+#include "logger.h"
+
+#define TAG "REQ_MODEL_BUILDER"
+
+RequestModelBuilder::RequestModelBuilder(std::shared_ptr<RAML::Raml> &raml)
+    : m_raml (raml) {}
+
+std::map<RequestType, RequestModelSP> RequestModelBuilder::build(const std::string &uri)
+{
+    std::map<RequestType, RequestModelSP> modelList;
+    if (!m_raml)
+    {
+        return modelList;
+    }
+
+    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())
+        {
+            RequestModelSP requestModel = createRequestModel(action.second);
+            if (!requestModel)
+                modelList[requestModel->type()] = requestModel;
+        }
+    }
+
+    return modelList;
+}
+
+RequestModelSP RequestModelBuilder::createRequestModel(const RAML::ActionPtr &action)
+{
+    OC_LOG(DEBUG, TAG, "Creating request model");
+
+    // Validate the action type. Only GET, PUT, POST and DELETE are supported.
+    RAML::ActionType actionType = action->getType();
+    if (actionType != RAML::ActionType::GET
+        && actionType != RAML::ActionType::PUT
+        && actionType != RAML::ActionType::POST
+        && actionType != RAML::ActionType::DELETE)
+    {
+        OC_LOG(ERROR, TAG, "Failed to create request model as it is of unknown type!");
+        return nullptr;
+    }
+
+    // Construcut RequestModel
+    RequestModelSP requestModel(new RequestModel(getRequestType(actionType)));
+
+    // Get the allowed query parameters of the request
+    for (auto & qpEntry : action->getQueryParameters())
+    {
+        for (auto & value :  (qpEntry.second)->getEnumeration())
+        {
+            requestModel->addQueryParam(qpEntry.first, value);
+        }
+    }
+
+    RAML::RequestResponseBodyPtr requestBody = action->getRequestBody("application/json");
+    SimulatorResourceModelSP repSchema = createRepSchema(requestBody);
+    requestModel->setRepSchema(repSchema);
+
+    // Corresponsing responses
+    for (auto  & responseEntry :  action->getResponses())
+    {
+        std::string codeStr = responseEntry.first;
+        int code = boost::lexical_cast<int>(codeStr);
+        ResponseModelSP responseModel = createResponseModel(code, responseEntry.second);
+        if (nullptr != responseModel)
+        {
+            requestModel->addResponseModel(code, responseModel);
+        }
+    }
+
+    return requestModel;
+}
+
+ResponseModelSP RequestModelBuilder::createResponseModel(int code,
+        const RAML::ResponsePtr &response)
+{
+    ResponseModelSP responseModel(new ResponseModel(code));
+    RAML::RequestResponseBodyPtr responseBody = response->getResponseBody("application/json");
+    SimulatorResourceModelSP repSchema = createRepSchema(responseBody);
+    responseModel->setRepSchema(repSchema);
+    return responseModel;
+}
+
+SimulatorResourceModelSP RequestModelBuilder::createRepSchema(const RAML::RequestResponseBodyPtr
+        &rep)
+{
+    RAML::SchemaPtr schema = rep->getSchema();
+    if (!schema)
+    {
+        return nullptr;
+    }
+
+    RAML::JsonSchemaPtr properties = schema->getProperties();
+    if (!properties || 0 == properties->getProperties().size())
+        return nullptr;
+
+    SimulatorResourceModelSP repSchema = std::make_shared<SimulatorResourceModel>();
+    for (auto & propertyEntry : properties->getProperties())
+    {
+        int valueType = propertyEntry.second->getValueType();
+        switch (valueType)
+        {
+            case 0: // Integer
+                {
+                    // Add the attribute with value
+                    std::cout << "[createRepresentationSchema] Adding Attribute of type int" << std::endl;
+                    repSchema->addAttribute(propertyEntry.second->getName(), propertyEntry.second->getValue<int>());
+
+                    // Set the range
+                    int min, max, multipleof;
+                    propertyEntry.second->getRange(min, max, multipleof);
+                    repSchema->setRange(propertyEntry.second->getName(), min, max);
+                }
+                break;
+
+            case 1: // Double
+                {
+                    // Add the attribute with value
+                    std::cout << "[createRepresentationSchema] Adding Attribute of type double" << std::endl;
+                    repSchema->addAttribute(propertyEntry.second->getName(), propertyEntry.second->getValue<double>());
+
+                    std::vector<SimulatorResourceModel::Attribute::ValueVariant> propValues =
+                        propertyEntry.second->getAllowedValues();
+
+                    // TODO: Use RAML function once available
+                    if (0 < propertyEntry.second->getAllowedValuesSize())
+                    {
+                        std::vector<double> allowedValues;
+                        for (auto & propValue : propValues)
+                        {
+                            double value = boost::lexical_cast<double> (propValue);
+                            allowedValues.push_back(value);
+                        }
+                        repSchema->setAllowedValues(propertyEntry.second->getName(), allowedValues);
+                    }
+                }
+                break;
+
+            case 2: // Boolean
+                {
+                    // Add the attribute with value
+                    std::cout << "[createRepresentationSchema] Adding Attribute of type boolean" << std::endl;
+                    repSchema->addAttribute(propertyEntry.second->getName(), propertyEntry.second->getValue<bool>());
+                }
+                break;
+
+            case 3: // String
+                {
+                    // Add the attribute with value
+                    std::cout << "[createRepresentationSchema] Adding Attribute of type string" << std::endl;
+                    repSchema->addAttribute(propertyEntry.second->getName(),
+                                            propertyEntry.second->getValue<std::string>());
+
+                    std::vector<SimulatorResourceModel::Attribute::ValueVariant> propValues =
+                        propertyEntry.second->getAllowedValues();
+
+                    // TODO: Use RAML function once available
+                    if (0 < propertyEntry.second->getAllowedValuesSize())
+                    {
+                        std::vector<std::string> allowedValues;
+                        for (auto & propValue : propValues)
+                        {
+                            std::string value = boost::lexical_cast<std::string> (propValue);
+                            allowedValues.push_back(value);
+                        }
+                        repSchema->setAllowedValues(propertyEntry.second->getName(), allowedValues);
+                    }
+                }
+                break;
+        }
+    }
+
+    return repSchema;
+}
+
+RequestType RequestModelBuilder::getRequestType(RAML::ActionType actionType)
+{
+    switch (actionType)
+    {
+        case RAML::ActionType::GET:
+            return RequestType::RQ_TYPE_GET;
+        case RAML::ActionType::PUT:
+            return RequestType::RQ_TYPE_PUT;
+        case RAML::ActionType::POST:
+            return RequestType::RQ_TYPE_POST;
+        case RAML::ActionType::DELETE:
+            return RequestType::RQ_TYPE_DELETE;
+    }
+}
+
diff --git a/service/simulator/src/common/request_model_builder.h b/service/simulator/src/common/request_model_builder.h
new file mode 100644 (file)
index 0000000..f212252
--- /dev/null
@@ -0,0 +1,43 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#ifndef REQUEST_MODEL_BUILDER_H_
+#define REQUEST_MODEL_BUILDER_H_
+
+#include "request_model.h"
+#include "response_model.h"
+
+class RequestModelBuilder
+{
+    public:
+        RequestModelBuilder(std::shared_ptr<RAML::Raml> &raml);
+        std::map<RequestType, RequestModelSP> build(const std::string &uri);
+
+    private:
+        RequestModelSP createRequestModel(const RAML::ActionPtr &action);
+        ResponseModelSP createResponseModel(int code, const RAML::ResponsePtr &response);
+        SimulatorResourceModelSP createRepSchema(const RAML::RequestResponseBodyPtr &rep);
+        RequestType getRequestType(RAML::ActionType actionType);
+
+        std::shared_ptr<RAML::Raml> m_raml;
+};
+
+#endif
+
diff --git a/service/simulator/src/common/response_model.cpp b/service/simulator/src/common/response_model.cpp
new file mode 100644 (file)
index 0000000..213cf4b
--- /dev/null
@@ -0,0 +1,125 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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 "response_model.h"
+
+ResponseModel::ResponseModel(int code) : m_code(code) {}
+
+void ResponseModel::setRepSchema(SimulatorResourceModelSP &repSchema)
+{
+    m_repSchema = repSchema;
+}
+
+SimulatorResult ResponseModel::verifyResponse(const OC::OCRepresentation &rep)
+{
+    for (auto & ocAttribute : rep)
+    {
+        SimulatorResourceModel::Attribute attribute;
+        if (false == m_repSchema->getAttribute(ocAttribute.attrname(), attribute))
+        {
+            return SIMULATOR_UKNOWN_PROPERTY;
+        }
+
+        int type = attribute.getValueType();
+        switch (type)
+        {
+            case 0: // Integer
+                {
+                    SimulatorResult result = validateAttributeInteger(attribute, ocAttribute);
+                    if (SIMULATOR_OK != result)
+                    {
+                        return result;
+                    }
+                }
+                break;
+
+            case 1: // Double
+                {
+                    SimulatorResult result = validateAttributeDouble(attribute, ocAttribute);
+                    if (SIMULATOR_OK != result)
+                    {
+                        return result;
+                    }
+                }
+                break;
+
+            case 2: // 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;
+}
+
+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
diff --git a/service/simulator/src/common/response_model.h b/service/simulator/src/common/response_model.h
new file mode 100644 (file)
index 0000000..77cb2bb
--- /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 RESPONSE_MODEL_H_
+#define RESPONSE_MODEL_H_
+
+#include "simulator_client_types.h"
+#include "simulator_resource_model.h"
+
+class RequestModelBuilder;
+class ResponseModel
+{
+    public:
+        friend class RequestModelBuilder;
+
+        SimulatorResult verifyResponse(const OC::OCRepresentation &rep);
+
+    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;
+};
+
+typedef std::shared_ptr<ResponseModel> ResponseModelSP;
+
+#endif
diff --git a/service/simulator/src/common/simulator_exceptions.cpp b/service/simulator/src/common/simulator_exceptions.cpp
new file mode 100644 (file)
index 0000000..9dc2040
--- /dev/null
@@ -0,0 +1,43 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "simulator_exceptions.h"
+
+SimulatorException::SimulatorException(SimulatorResult errorCode, const std::string &message)
+    : m_errorCode(errorCode), m_message(message) {}
+
+const char *SimulatorException::what() const noexcept
+{
+    return m_message.c_str();
+}
+
+SimulatorResult SimulatorException::code() const
+{
+    return m_errorCode;
+}
+
+InvalidArgsException::InvalidArgsException(SimulatorResult errorCode, const std::string &message)
+    : SimulatorException(errorCode, message) {}
+
+NoSupportException::NoSupportException(const std::string &message)
+    : SimulatorException(SIMULATOR_NOT_SUPPORTED, message) {}
+
+OperationInProgressException::OperationInProgressException(const std::string &message)
+    : SimulatorException(SIMULATOR_OPERATION_IN_PROGRESS, message) {}
diff --git a/service/simulator/src/common/simulator_logger.cpp b/service/simulator/src/common/simulator_logger.cpp
new file mode 100644 (file)
index 0000000..9ae58d4
--- /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.
+ *
+ ******************************************************************/
+
+#include "simulator_logger.h"
+#include <sstream>
+#include <fstream>
+#include <time.h>
+
+class ConsoleLogger : public ILogger
+{
+    public:
+        void write(std::string time, ILogger::Level level, std::string message)
+        {
+            std::ostringstream out;
+            out << time << " " << ILogger::getString(level) << " " << message;
+            std::cout << out.str() << std::endl;
+        }
+};
+
+class FileLogger : public ILogger
+{
+    public:
+        FileLogger(std::string filePath) : m_filePath(filePath) {}
+
+        bool open()
+        {
+            m_out.open(m_filePath, std::ofstream::out);
+            return m_out.is_open();
+        }
+
+        void close()
+        {
+            if (m_out.is_open())
+                m_out.close();
+        }
+
+        void write(std::string time, ILogger::Level level, std::string message)
+        {
+            m_out << time << " " << ILogger::getString(level) << " " << message;
+        }
+
+    private:
+        std::ofstream m_out;
+        std::string m_filePath;
+};
+
+bool Logger::setDefaultConsoleTarget()
+{
+    if (nullptr != m_target)
+        return false;
+
+    m_target = std::make_shared<ConsoleLogger>();
+    return true;
+}
+
+bool Logger::setDefaultFileTarget(const std::string &path)
+{
+    if (nullptr != m_target || path.empty())
+        return false;
+
+    time_t timeInfo = time(NULL);
+    struct tm *localTime = localtime(&timeInfo);
+    std::ostringstream newFileName;
+    newFileName << path << "/Simulator_";
+    newFileName << localTime->tm_year << localTime->tm_mon << localTime->tm_mday << localTime->tm_hour
+                << localTime->tm_min << localTime->tm_sec;
+    newFileName << ".log";
+
+    std::shared_ptr<FileLogger> fileLogger(new FileLogger(newFileName.str()));
+    if (fileLogger->open())
+    {
+        m_target = fileLogger;
+        return true;
+    }
+
+    return false;
+}
+
+void Logger::setCustomTarget(const std::shared_ptr<ILogger> &target)
+{
+    m_target = target;
+}
+
+void Logger::write(ILogger::Level level, std::ostringstream &str)
+{
+    if (nullptr != m_target)
+    {
+        time_t timeInfo = time(NULL);
+        struct tm *localTime = localtime(&timeInfo);
+        std::ostringstream timeStr;
+        timeStr << localTime->tm_hour << "." << localTime->tm_min << "." << localTime->tm_sec;
+        m_target->write(timeStr.str(), level, str.str());
+    }
+}
+
+auto simLogger() -> Logger &
+{
+    static Logger logger;
+    return logger;
+}
\ No newline at end of file
diff --git a/service/simulator/src/common/simulator_resource_model.cpp b/service/simulator/src/common/simulator_resource_model.cpp
new file mode 100644 (file)
index 0000000..9445b11
--- /dev/null
@@ -0,0 +1,313 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.h"
+#include "OCPlatform.h"
+#include <sstream>
+#include <boost/lexical_cast.hpp>
+
+class to_string_visitor : public boost::static_visitor<std::string>
+{
+    public:
+        template <typename T>
+        result_type operator ()(const T &value)
+        {
+            return boost::lexical_cast<std::string>(value);
+        }
+};
+
+class add_to_representation : public boost::static_visitor<>
+{
+    public:
+        add_to_representation(OC::OCRepresentation &rep, const std::string &key)
+            : m_rep(rep), m_key(key) {}
+
+        template <typename T>
+        void operator ()(const T &value)
+        {
+            m_rep.setValue(m_key, value);
+        }
+
+        OC::OCRepresentation &&getRep()
+        {
+            return std::move(m_rep);
+        }
+
+    private:
+        OC::OCRepresentation m_rep;
+        std::string m_key;
+};
+
+class range_validation : public boost::static_visitor<bool>
+{
+    public:
+        range_validation (SimulatorResourceModel::Attribute &attrItem)
+            : m_attrItem(attrItem) {}
+
+        bool operator ()(int &value)
+        {
+            int min, max;
+            m_attrItem.getRange(min, max);
+            if (value >= min && value <= max)
+                return true;
+            return false;
+        }
+
+        bool operator ()(double &value)
+        {
+            std::vector<SimulatorResourceModel::Attribute::ValueVariant> values
+                = m_attrItem.getAllowedValues();
+            for (SimulatorResourceModel::Attribute::ValueVariant & val : values)
+            {
+                SimulatorResourceModel::Attribute::ValueVariant vVal = value;
+                if (val == vVal)
+                    return true;
+            }
+            return false;
+        }
+
+        bool operator ()(bool &value)
+        {
+            return true;
+        }
+
+        bool operator ()(std::string &value)
+        {
+            std::vector<SimulatorResourceModel::Attribute::ValueVariant> values
+                = m_attrItem.getAllowedValues();
+            for (SimulatorResourceModel::Attribute::ValueVariant & vVal : values)
+            {
+                std::string val = boost::get<std::string>(vVal);
+                if (val == value)
+                    return true;
+            }
+
+            return false;
+        }
+
+    private:
+        SimulatorResourceModel::Attribute &m_attrItem;
+};
+
+SimulatorResourceModel::Attribute::ValueVariant
+&SimulatorResourceModel::Attribute::AllowedValues::at(unsigned int index)
+{
+    return m_values.at(index);
+}
+
+int SimulatorResourceModel::Attribute::AllowedValues::size() const
+{
+    return m_values.size();
+}
+
+std::vector<std::string> SimulatorResourceModel::Attribute::AllowedValues::toString() const
+{
+    std::vector<std::string> values;
+
+    for (auto & value : m_values)
+    {
+        to_string_visitor visitor;
+        values.push_back(boost::apply_visitor(visitor, value));
+    }
+    return values;
+}
+
+std::vector<SimulatorResourceModel::Attribute::ValueVariant>
+SimulatorResourceModel::Attribute::AllowedValues::getValues()
+{
+    return m_values;
+}
+
+std::string SimulatorResourceModel::Attribute::getName(void) const
+{
+    return m_name;
+}
+
+void SimulatorResourceModel::Attribute::setName(const std::string &name)
+{
+    m_name = name;
+}
+
+void SimulatorResourceModel::Attribute::getRange(int &min, int &max) const
+{
+    min = m_min;
+    max = m_max;
+}
+
+void SimulatorResourceModel::Attribute::setRange(const int &min, const int &max)
+{
+    m_min = min;
+    m_max = max;
+}
+
+int SimulatorResourceModel::Attribute::getAllowedValuesSize() const
+{
+    return m_allowedValues.size();
+}
+
+void SimulatorResourceModel::Attribute::setFromAllowedValue(unsigned int index)
+{
+    m_value = m_allowedValues.at(index);
+}
+
+std::string SimulatorResourceModel::Attribute::valueToString() const
+{
+    to_string_visitor visitor;
+    return boost::apply_visitor(visitor, m_value);
+}
+
+std::vector<std::string> SimulatorResourceModel::Attribute::allowedValuesToString() const
+{
+    return m_allowedValues.toString();
+}
+
+void SimulatorResourceModel::Attribute::addValuetoRepresentation(OC::OCRepresentation &rep,
+        const std::string &key) const
+{
+    add_to_representation visitor(rep, key);
+    boost::apply_visitor(visitor, m_value);
+    rep = visitor.getRep();
+}
+
+bool SimulatorResourceModel::Attribute::compare(SimulatorResourceModel::Attribute &attribute)
+{
+    // Check the value types
+    if (m_value.which() != attribute.getValue().which())
+    {
+        return false;
+    }
+
+    // Check the value in allowed range
+    range_validation visitor(*this);
+    return boost::apply_visitor(visitor, attribute.getValue());
+}
+
+std::vector<SimulatorResourceModel::Attribute::ValueVariant>
+SimulatorResourceModel::Attribute::getAllowedValues()
+{
+    return m_allowedValues.getValues();
+}
+
+bool SimulatorResourceModel::getAttribute(const std::string &attrName, Attribute &value)
+{
+    if (m_attributes.end() != m_attributes.find(attrName))
+    {
+        value = m_attributes[attrName];
+        return true;
+    }
+
+    return false;
+}
+
+std::map<std::string, SimulatorResourceModel::Attribute> SimulatorResourceModel::getAttributes()
+const
+{
+    return m_attributes;
+}
+
+void SimulatorResourceModel::setRange(const std::string &attrName, const int min, const int max)
+{
+    if (m_attributes.end() != m_attributes.find(attrName))
+        m_attributes[attrName].setRange(min, max);
+}
+
+void SimulatorResourceModel::setUpdateInterval(const std::string &attrName, int interval)
+{
+    if (m_attributes.end() != m_attributes.find(attrName))
+        m_attributes[attrName].setUpdateFrequencyTime(interval);
+}
+
+void SimulatorResourceModel::updateAttributeFromAllowedValues(const std::string &attrName,
+        unsigned int index)
+{
+    if (m_attributes.end() != m_attributes.find(attrName))
+        m_attributes[attrName].setFromAllowedValue(index);
+}
+
+void SimulatorResourceModel::removeAttribute(const std::string &attrName)
+{
+    m_attributes.erase(attrName);
+    return;
+}
+
+OC::OCRepresentation SimulatorResourceModel::getOCRepresentation() const
+{
+    OC::OCRepresentation rep;
+    for (auto & attribute : m_attributes)
+    {
+        (attribute.second).addValuetoRepresentation(rep, attribute.first);
+    }
+
+    return rep;
+}
+
+bool SimulatorResourceModel::update(OC::OCRepresentation &ocRep)
+{
+    if (0 == ocRep.size())
+        return true;
+
+    // Convert OCRepresentation to SimulatorResourceModel
+    SimulatorResourceModelSP resModel = create(ocRep);
+
+    return update(resModel);
+}
+
+bool SimulatorResourceModel::update(SimulatorResourceModelSP &repModel)
+{
+    std::map<std::string, SimulatorResourceModel::Attribute> attributes = repModel->getAttributes();
+    for (auto & attributeItem : attributes)
+    {
+        // Check the attribute presence
+        SimulatorResourceModel::Attribute attribute;
+        if (false == getAttribute((attributeItem.second).getName(), attribute))
+        {
+            return false;
+        }
+
+        // Check the validity of the value to be set
+        if (false == attribute.compare(attributeItem.second))
+        {
+            return false;
+        }
+        m_attributes[(attributeItem.second).getName()].setValue((attributeItem.second).getValue());
+    }
+
+    return true;
+}
+
+SimulatorResourceModelSP SimulatorResourceModel::create(const OC::OCRepresentation &ocRep)
+{
+    SimulatorResourceModelSP resModel(new SimulatorResourceModel);
+    for (auto & attributeItem : ocRep)
+    {
+        SimulatorResourceModel::Attribute attribute;
+        if (attributeItem.type() == OC::AttributeType::Integer)
+            attribute.setValue(attributeItem.getValue<int>());
+        if (attributeItem.type() == OC::AttributeType::Double)
+            attribute.setValue(attributeItem.getValue<double>());
+        if (attributeItem.type() == OC::AttributeType::String)
+            attribute.setValue(attributeItem.getValue<std::string>());
+
+        attribute.setName(attributeItem.attrname());
+        resModel->m_attributes[attributeItem.attrname()] = attribute;
+    }
+    return resModel;
+}
+
diff --git a/service/simulator/src/common/simulator_utils.cpp b/service/simulator/src/common/simulator_utils.cpp
new file mode 100644 (file)
index 0000000..08ca59f
--- /dev/null
@@ -0,0 +1,75 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.h"
+#include "OCRepresentation.h"
+
+std::string getPayloadString(const OC::OCRepresentation &rep)
+{
+    std::ostringstream data;
+    OCRepPayload *payload = rep.getPayload();
+    if (!payload)
+    {
+        return "Payload: No payload";
+    }
+
+    // URI
+    data << "URI: " << payload->uri << std::endl;
+
+    // Attributes
+    data << "Attributes:" << std::endl;
+    OCRepPayloadValue *values = payload->values;
+    while (NULL != values)
+    {
+        data << values->name << ":" << rep.getValueToString(values->name) << std::endl;
+        values = values->next;
+    }
+
+    return data.str();
+}
+
+std::string getRequestString(const std::map<std::string, std::string> &queryParams,
+                             const OC::OCRepresentation &rep)
+{
+    std::ostringstream data;
+    data << "qp: ";
+    if (queryParams.size() > 0)
+    {
+        for (auto & qp : queryParams)
+            data << qp.second << ",";
+    }
+
+    data << getPayloadString(rep);
+    return data.str();
+}
+
+std::string getRequestString(const std::map<std::string, std::string> &queryParams)
+{
+    std::ostringstream data;
+    data << "qp: ";
+    if (queryParams.size() > 0)
+    {
+        for (auto & qp : queryParams)
+            data << qp.second << ",";
+    }
+
+    data << "Payload:  No payload";
+    return data.str();
+}
\ No newline at end of file
diff --git a/service/simulator/src/common/simulator_utils.h b/service/simulator/src/common/simulator_utils.h
new file mode 100644 (file)
index 0000000..23dd47f
--- /dev/null
@@ -0,0 +1,69 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file simulator_utils.h
+ *
+ * @brief This file provides utility methods used by both client and servers.
+ */
+
+#ifndef SIMULATOR_UTILS_H_
+#define SIMULATOR_UTILS_H_
+
+#include "simulator_exceptions.h"
+#include "octypes.h"
+#include "OCException.h"
+
+#include <map>
+
+/**
+ * Utilities for Invokation 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
+invokeocplatform(FnT fn, ArgsT &&...args)
+{
+    try
+    {
+        OCStackResult ocResult = fn(std::forward<ArgsT>(args)...);
+        if (OC_STACK_OK != ocResult)
+        {
+            // Throw SimulatorException converting error codes
+            throw SimulatorException(static_cast<SimulatorResult>(ocResult), OC::OCException::reason(ocResult));
+        }
+    }
+    catch (OC::OCException &e)
+    {
+        // Throw SimulatorException converting error codes
+        throw SimulatorException(static_cast<SimulatorResult>(e.code()), e.reason());
+    }
+}
+
+namespace OC
+{
+    class OCRepresentation;
+}
+
+std::string getPayloadString(const OC::OCRepresentation &);
+std::string getRequestString(const std::map<std::string, std::string> &queryParams,
+                             const OC::OCRepresentation &rep);
+std::string getRequestString(const std::map<std::string, std::string> &queryParams);
+
+#endif
\ No newline at end of file
diff --git a/service/simulator/src/service-provider/resource_manager.cpp b/service/simulator/src/service-provider/resource_manager.cpp
new file mode 100644 (file)
index 0000000..54c5e8b
--- /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.
+ *
+ ******************************************************************/
+
+#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
new file mode 100644 (file)
index 0000000..ddb63f3
--- /dev/null
@@ -0,0 +1,119 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @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
new file mode 100644 (file)
index 0000000..b162cdd
--- /dev/null
@@ -0,0 +1,201 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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 "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) {}
+
+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;
+    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 through callback
+    if (m_callback)
+        m_callback(m_resource->getURI(), m_id);
+
+    if (m_finishedCallback && !m_stopRequested)
+        m_finishedCallback(m_id);
+}
+
+void AttributeUpdateAutomation::setAttributeValue()
+{
+    if (0 == m_attribute.getValueType()) // For integer type values
+    {
+        int min;
+        int max;
+        SimulatorResourceServerImpl *resourceImpl;
+        resourceImpl = dynamic_cast<SimulatorResourceServerImpl *>(m_resource);
+        m_attribute.getRange(min, max);
+        for (int value = min; value <= max; value++)
+        {
+            if (m_stopRequested)
+                break;
+            m_resource->updateAttributeValue(m_attribute.getName(), value);
+            resourceImpl->resourceModified();
+            SLEEP_FOR(m_updateInterval);
+        }
+    }
+    else
+    {
+        SimulatorResourceServerImpl *resourceImpl;
+        resourceImpl = dynamic_cast<SimulatorResourceServerImpl *>(m_resource);
+        for (int index = 0; index < m_attribute.getAllowedValuesSize(); index++)
+        {
+            if (m_stopRequested)
+                break;
+            m_resource->updateFromAllowedValues(m_attribute.getName(), index);
+            resourceImpl->resourceModified();
+            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_updateInterval(interval),
+        m_callback(callback),
+        m_finishedCallback(finishedCallback) {}
+
+void ResourceUpdateAutomation::start()
+{
+    m_resModel = m_resource->getModel();
+    std::map<std::string, SimulatorResourceModel::Attribute> attributes = m_resModel.getAttributes();
+    if (0 == attributes.size())
+    {
+        OC_LOG(ERROR, RTAG, "Resource has zero attributes!");
+        throw SimulatorException(SIMULATOR_ERROR, "Resource has zero attributes!");
+    }
+
+    int id = 0;
+    for (auto & attribute : attributes)
+    {
+        AttributeUpdateAutomationSP attributeAutomation(new AttributeUpdateAutomation(
+                    id, m_resource, attribute.first, m_type, m_updateInterval, nullptr,
+                    std::bind(&ResourceUpdateAutomation::finished, this, std::placeholders::_1)));
+
+        m_attrUpdationList[id++] = attributeAutomation;
+        try
+        {
+            attributeAutomation->start();
+        }
+        catch (SimulatorException &e)
+        {
+            stop();
+            throw;
+        }
+    }
+}
+
+void ResourceUpdateAutomation::finished(int id)
+{
+    if (m_attrUpdationList.end() != m_attrUpdationList.find(id))
+    {
+        m_attrUpdationList.erase(m_attrUpdationList.find(id));
+    }
+
+    if (!m_attrUpdationList.size())
+    {
+        // Notify application through callback
+        if (m_callback)
+            m_callback(m_resource->getURI(), m_id);
+
+        if (m_finishedCallback)
+            m_finishedCallback(m_id);
+    }
+}
+
+void ResourceUpdateAutomation::stop()
+{
+    // Stop all the attributes updation
+    for (auto & attrAutomation : m_attrUpdationList)
+    {
+        (attrAutomation.second)->stop();
+    }
+
+    m_attrUpdationList.clear();
+}
diff --git a/service/simulator/src/service-provider/resource_update_automation.h b/service/simulator/src/service-provider/resource_update_automation.h
new file mode 100644 (file)
index 0000000..8a5f1d2
--- /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_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;
+        std::thread *m_thread;
+        bool m_stopRequested;
+        int m_updateInterval;
+        SimulatorResourceModel::Attribute m_attribute;
+        updateCompleteCallback m_callback;
+        std::function<void (const int)> m_finishedCallback;
+};
+
+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();
+
+        void finished(int id);
+
+    private:
+        SimulatorResourceServer *m_resource;
+        AutomationType m_type;
+        int m_id;
+        std::thread *m_thread;
+        int m_updateInterval;
+        SimulatorResourceModel m_resModel;
+        std::map<int, AttributeUpdateAutomationSP> m_attrUpdationList;
+        updateCompleteCallback m_callback;
+        std::function<void (const int)> m_finishedCallback;
+};
+
+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
new file mode 100644 (file)
index 0000000..e0f6c63
--- /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 "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 : " << 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 : " <<
+            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));
+    }
+    else if (m_attrUpdationList.end() != m_attrUpdationList.find(id))
+    {
+        m_attrUpdationList[id]->stop();
+        m_attrUpdationList.erase(m_attrUpdationList.find(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
new file mode 100644 (file)
index 0000000..985d79c
--- /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_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
new file mode 100644 (file)
index 0000000..1bd372e
--- /dev/null
@@ -0,0 +1,123 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "simulator_resource_creator.h"
+#include "simulator_logger.h"
+#include <RamlParser.h>
+#include <boost/lexical_cast.hpp>
+
+using namespace RAML;
+
+unsigned int SimulatorResourceCreator::s_id;
+SimulatorResourceServerImplSP SimulatorResourceCreator::createResource(
+    const std::string &configPath)
+{
+    RamlParser *ramlParser = new RamlParser(configPath);
+    RamlPtr raml = ramlParser->getRamlPtr();
+    for (auto  resourceElement : raml->getResources())
+    {
+        SimulatorResourceServerImplSP resource(new SimulatorResourceServerImpl());
+        resource->setName(resourceElement.first);
+        resource->setURI(resourceElement.second->getResourceUri());
+
+        // TODO: Currently setting only baseline interface.
+        resource->setInterfaceType(OC::DEFAULT_INTERFACE);
+        // TODO: Need to modify based on the spec for observable property
+        resource->setObservable(true);
+
+        for (auto  action :  resourceElement.second->getActions())
+        {
+            for (auto  response :  action.second->getResponses())
+            {
+                for (auto bdy :  response.second->getResponseBody())
+                {
+                    auto resourceProperties = bdy.second->getSchema()->getProperties();
+
+                    for ( auto property : resourceProperties->getProperties() )
+                    {
+                        std::string propName = property.second->getName();
+
+                        if (propName == "rt")
+                        {
+                            resource->setResourceType(property.second->getValueString());
+                            continue;
+                        }
+
+                        // Include more property names if required based on spec support.
+                        if (propName == "if" || propName == "p" || propName == "n" || propName == "id")
+                            continue;
+
+                        SimulatorResourceModel::Attribute *attr = new SimulatorResourceModel::Attribute(propName);
+
+                        int type = property.second->getValueType();
+                        switch (type)
+                        {
+                            case 0: // Integer
+                                {
+                                    int attributeValue = property.second->getValueInt();
+                                    attr->setValue(attributeValue);
+                                }
+                                break;
+
+                            case 3: // String
+                                {
+                                    std::string attributeValue = property.second->getValueString();
+                                    attr->setValue(attributeValue);
+                                }
+                                break;
+                        }
+
+                        attr->setUpdateFrequencyTime(property.second->getUpdateFrequencyTime());
+
+                        int min = 0, max = 0, multipleof = 0;
+                        property.second->getRange(min, max, multipleof);
+                        attr->setRange(min, max);
+
+                        if (property.second->getAllowedValuesSize() > 0)
+                            attr->setAllowedValues(property.second->getAllowedValues());
+
+                        resource->addAttribute(*attr);
+                    }
+
+                    resource->setURI(constructURI(resource->getURI()));
+                    return resource;
+                }
+            }
+        }
+    }
+
+    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
new file mode 100644 (file)
index 0000000..7a9a87d
--- /dev/null
@@ -0,0 +1,36 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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
new file mode 100644 (file)
index 0000000..b2f9638
--- /dev/null
@@ -0,0 +1,72 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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);
+}
+
+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
new file mode 100644 (file)
index 0000000..6fbd060
--- /dev/null
@@ -0,0 +1,427 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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);
+    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,
+        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, -1, callback);
+}
+
+int SimulatorResourceServerImpl::startUpdateAutomation(const std::string &attrName,
+        AutomationType type,
+        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, -1, 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;
+}
+
+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);
+            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
new file mode 100644 (file)
index 0000000..b0aea93
--- /dev/null
@@ -0,0 +1,88 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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,
+                                  updateCompleteCallback callback);
+
+        int startUpdateAutomation(const std::string &attrName, AutomationType type,
+                                  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 resourceModified();
+
+    private:
+        OC::OCRepresentation getOCRepresentation();
+        bool modifyResourceModel(OC::OCRepresentation &ocRep);
+        OCEntityHandlerResult entityHandler(std::shared_ptr<OC::OCResourceRequest> request);
+
+        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
diff --git a/service/simulator/src/simulator_device_info.cpp b/service/simulator/src/simulator_device_info.cpp
new file mode 100644 (file)
index 0000000..5c8ee3f
--- /dev/null
@@ -0,0 +1,45 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "simulator_device_info.h"
+
+DeviceInfo::DeviceInfo(const std::string &name, const std::string &id,
+                       const std::string &specVersion, const std::string &dmv)
+    : m_name(name), m_id(id), m_specVersion(specVersion), m_DMV(dmv) {}
+
+std::string DeviceInfo::getName() const
+{
+    return m_name;
+}
+
+std::string DeviceInfo::getID() const
+{
+    return m_id;
+}
+
+std::string DeviceInfo::getSpecVersion() const
+{
+    return m_specVersion;
+}
+
+std::string DeviceInfo::getDataModelVersion() const
+{
+    return m_DMV;
+}
diff --git a/service/simulator/src/simulator_manager.cpp b/service/simulator/src/simulator_manager.cpp
new file mode 100644 (file)
index 0000000..09e70c4
--- /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.
+ *
+ ******************************************************************/
+
+#include "simulator_manager.h"
+#include "resource_manager.h"
+#include "simulator_client.h"
+#include "simulator_utils.h"
+
+SimulatorManager *SimulatorManager::getInstance()
+{
+    static SimulatorManager s_instance;
+    return &s_instance;
+}
+
+SimulatorManager::SimulatorManager()
+{
+    OC::PlatformConfig conf
+    {
+        OC::ServiceType::InProc,
+        OC::ModeType::Both,
+        "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces
+        0,         // Uses randomly available port
+        OC::QualityOfService::LowQos
+    };
+
+    OC::OCPlatform::Configure(conf);
+}
+
+std::shared_ptr<SimulatorResourceServer> SimulatorManager::createResource(
+    const std::string &configPath,
+    SimulatorResourceServer::ResourceModelChangedCB callback)
+{
+    return ResourceManager::getInstance()->createResource(configPath, callback);
+}
+
+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::vector<std::shared_ptr<SimulatorResourceServer>> SimulatorManager::getResources(
+            const std::string &resourceType)
+{
+    return ResourceManager::getInstance()->getResources(resourceType);
+}
+
+void SimulatorManager::deleteResource(
+    const std::shared_ptr<SimulatorResourceServer> &resource)
+{
+    ResourceManager::getInstance()->deleteResource(resource);
+}
+
+void SimulatorManager::deleteResources(const std::string &resourceType)
+{
+    ResourceManager::getInstance()->deleteResources(resourceType);
+}
+
+void SimulatorManager::findResources(ResourceFindCallback callback)
+{
+    SimulatorClient::getInstance()->findResources(callback);
+}
+
+void SimulatorManager::findResources(const std::string &resourceType,
+                                     ResourceFindCallback callback)
+{
+    SimulatorClient::getInstance()->findResources(resourceType, callback);
+}
+
+void SimulatorManager::getDeviceInfo(DeviceInfoCallback callback)
+{
+    if (!callback)
+        throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
+
+    OC::FindDeviceCallback deviceCallback = [this, callback](const OC::OCRepresentation & rep)
+    {
+        std::string deviceName = rep.getValue<std::string>("n");
+        std::string deviceID = rep.getValue<std::string>("di");
+        std::string deviceSpecVersion = rep.getValue<std::string>("lcv");
+        std::string deviceDMV = rep.getValue<std::string>("dmv");
+
+        DeviceInfo deviceInfo(deviceName, deviceID, deviceSpecVersion, deviceDMV);
+        callback(deviceInfo);
+    };
+
+    std::ostringstream uri;
+    uri << OC_MULTICAST_PREFIX << OC_RSRVD_DEVICE_URI;
+
+    typedef OCStackResult (*GetDeviceInfo)(const std::string &, const std::string &,
+                                           OCConnectivityType, OC::FindDeviceCallback);
+
+    invokeocplatform(static_cast<GetDeviceInfo>(OC::OCPlatform::getDeviceInfo), "",
+                     uri.str(),
+                     CT_DEFAULT,
+                     deviceCallback);
+}
+
+void SimulatorManager::setDeviceInfo(const std::string &deviceName)
+{
+    if (deviceName.empty())
+        throw InvalidArgsException(SIMULATOR_INVALID_PARAM, "Device name is empty!");
+
+
+    typedef OCStackResult (*RegisterDeviceInfo)(const OCDeviceInfo);
+
+    OCDeviceInfo ocDeviceInfo;
+    ocDeviceInfo.deviceName = const_cast<char *>(deviceName.c_str());
+    invokeocplatform(static_cast<RegisterDeviceInfo>(OC::OCPlatform::registerDeviceInfo),
+                     ocDeviceInfo);
+}
+
+void SimulatorManager::getPlatformInfo(PlatformInfoCallback callback)
+{
+    if (!callback)
+        throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");
+
+    OC::FindPlatformCallback platformCallback = [this, callback](const OC::OCRepresentation & rep)
+    {
+        PlatformInfo platformInfo;
+        platformInfo.setPlatformID(rep.getValue<std::string>("pi"));
+        platformInfo.setPlatformVersion(rep.getValue<std::string>("mnpv"));
+        platformInfo.setManufacturerName(rep.getValue<std::string>("mnmn"));
+        platformInfo.setManufacturerUrl(rep.getValue<std::string>("mnml"));
+        platformInfo.setModelNumber(rep.getValue<std::string>("mnmo"));
+        platformInfo.setDateOfManfacture(rep.getValue<std::string>("mndt"));
+        platformInfo.setOSVersion(rep.getValue<std::string>("mnos"));
+        platformInfo.setHardwareVersion(rep.getValue<std::string>("mnhw"));
+        platformInfo.setFirmwareVersion(rep.getValue<std::string>("mnfv"));
+        platformInfo.setSupportUrl(rep.getValue<std::string>("mnsl"));
+        platformInfo.setSystemTime(rep.getValue<std::string>("st"));
+
+        callback(platformInfo);
+    };
+
+    std::ostringstream uri;
+    uri << OC_MULTICAST_PREFIX << OC_RSRVD_PLATFORM_URI;
+
+    typedef OCStackResult (*GetPlatformInfo)(const std::string &, const std::string &,
+            OCConnectivityType, OC::FindPlatformCallback);
+
+    invokeocplatform(static_cast<GetPlatformInfo>(OC::OCPlatform::getPlatformInfo), "",
+                     uri.str(),
+                     CT_DEFAULT,
+                     platformCallback);
+}
+
+void SimulatorManager::setPlatformInfo(PlatformInfo &platformInfo)
+{
+    OCPlatformInfo ocPlatformInfo;
+    ocPlatformInfo.platformID = const_cast<char *>(platformInfo.getPlatformID().c_str());
+    ocPlatformInfo.manufacturerName = const_cast<char *>(platformInfo.getManufacturerName().c_str());
+    ocPlatformInfo.manufacturerUrl = const_cast<char *>(platformInfo.getManufacturerUrl().c_str());
+    ocPlatformInfo.modelNumber = const_cast<char *>(platformInfo.getModelNumber().c_str());
+    ocPlatformInfo.dateOfManufacture = const_cast<char *>(platformInfo.getDateOfManfacture().c_str());
+    ocPlatformInfo.platformVersion = const_cast<char *>(platformInfo.getPlatformVersion().c_str());
+    ocPlatformInfo.operatingSystemVersion = const_cast<char *>(platformInfo.getOSVersion().c_str());
+    ocPlatformInfo.hardwareVersion = const_cast<char *>(platformInfo.getHardwareVersion().c_str());
+    ocPlatformInfo.firmwareVersion = const_cast<char *>(platformInfo.getFirmwareVersion().c_str());
+    ocPlatformInfo.supportUrl = const_cast<char *>(platformInfo.getSupportUrl().c_str());
+    ocPlatformInfo.systemTime = const_cast<char *>(platformInfo.getSystemTime().c_str());
+
+    typedef OCStackResult (*RegisterPlatformInfo)(const OCPlatformInfo);
+    invokeocplatform(static_cast<RegisterPlatformInfo>(OC::OCPlatform::registerPlatformInfo),
+                     ocPlatformInfo);
+}
+
+void SimulatorManager::setLogger(const std::shared_ptr<ILogger> &logger)
+{
+    simLogger().setCustomTarget(logger);
+}
+
+bool SimulatorManager::setDefaultConsoleLogger()
+{
+    return simLogger().setDefaultConsoleTarget();
+}
+
+bool SimulatorManager::setDefaultFileLogger(const std::string &path)
+{
+    return simLogger().setDefaultFileTarget(path);
+}
\ No newline at end of file
diff --git a/service/simulator/src/simulator_platform_info.cpp b/service/simulator/src/simulator_platform_info.cpp
new file mode 100644 (file)
index 0000000..0146e5a
--- /dev/null
@@ -0,0 +1,131 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "simulator_platform_info.h"
+
+std::string PlatformInfo::getPlatformID() const
+{
+    return m_platformID;
+}
+
+std::string PlatformInfo::getPlatformVersion() const
+{
+    return m_platformVersion;
+}
+
+std::string PlatformInfo::getManufacturerName() const
+{
+    return m_manufacturerName;
+}
+
+std::string PlatformInfo::getManufacturerUrl() const
+{
+    return m_manufacturerUrl;
+}
+
+std::string PlatformInfo::getModelNumber() const
+{
+    return m_modelNumber;
+}
+
+std::string PlatformInfo::getDateOfManfacture() const
+{
+    return m_dateOfManufacture;
+}
+
+std::string PlatformInfo::getOSVersion() const
+{
+    return m_operationSystemVersion;
+}
+
+std::string PlatformInfo::getHardwareVersion() const
+{
+    return m_hardwareVersion;
+}
+
+std::string PlatformInfo::getFirmwareVersion() const
+{
+    return m_firmwareVersion;
+}
+
+std::string PlatformInfo::getSupportUrl() const
+{
+    return m_supportUrl;
+}
+
+std::string PlatformInfo::getSystemTime() const
+{
+    return m_systemTime;
+}
+
+void PlatformInfo::setPlatformID(const std::string &platformId)
+{
+    m_platformID = platformId;
+}
+
+void PlatformInfo::setPlatformVersion(const std::string &platformVersion)
+{
+    m_platformVersion = platformVersion;
+}
+
+void PlatformInfo::setManufacturerName(const std::string &manufacturerName)
+{
+    m_manufacturerName = manufacturerName;
+}
+
+void PlatformInfo::setManufacturerUrl(const std::string &manufacturerUrl)
+{
+    m_manufacturerUrl = manufacturerUrl;
+}
+
+void PlatformInfo::setModelNumber(const std::string &modelNumber)
+{
+    m_modelNumber = modelNumber;
+}
+
+void PlatformInfo::setDateOfManfacture(const std::string &dateOfManufacture)
+{
+    m_dateOfManufacture = dateOfManufacture;
+}
+
+void PlatformInfo::setOSVersion(const std::string &osVersion)
+{
+    m_operationSystemVersion = osVersion;
+}
+
+void PlatformInfo::setHardwareVersion(const std::string &hwVersion)
+{
+    m_hardwareVersion = hwVersion;
+}
+
+void PlatformInfo::setFirmwareVersion(const std::string &firmwareVersion)
+{
+    m_firmwareVersion = firmwareVersion;
+}
+
+void PlatformInfo::setSupportUrl(const std::string &supportUrl)
+{
+    m_supportUrl = supportUrl;
+}
+
+void PlatformInfo::setSystemTime(const std::string &systemTime)
+{
+    m_systemTime = systemTime;
+}