From 2234a647e3ac01f7b3cc1ba2cba888d20f906c6b Mon Sep 17 00:00:00 2001 From: Harish Kumara Marappa Date: Sat, 14 Nov 2015 19:19:08 +0530 Subject: [PATCH] Collection resource support in SDK and Plug-in. - Managing life cycle of collection resource. - Supporting all types of attribute value in SimulatorResourceModel as supported in OCRepresentation. - Updated unit test cases. JIRA: https://jira.iotivity.org/browse/IOT-836 Change-Id: Iba01f46477155adad64e69dec9cda192405b09ee Signed-off-by: Harish Kumara Marappa Reviewed-on: https://gerrit.iotivity.org/gerrit/4209 Tested-by: jenkins-iotivity Reviewed-by: Madan Lanka --- service/simulator/SConscript | 4 +- service/simulator/examples/README.txt | 3 - .../{client-controller => client}/SConscript | 6 +- .../simulator_client.cpp} | 119 +- service/simulator/examples/server/SConscript | 6 +- .../simulator/examples/server/service_provider.cpp | 613 ---- .../simulator/examples/server/simulator_server.cpp | 446 +++ .../simulator/inc/simulator_collection_resource.h | 68 + service/simulator/inc/simulator_manager.h | 48 +- service/simulator/inc/simulator_remote_resource.h | 6 +- service/simulator/inc/simulator_resource.h | 215 ++ service/simulator/inc/simulator_resource_model.h | 428 ++- service/simulator/inc/simulator_resource_server.h | 290 -- service/simulator/inc/simulator_server_types.h | 13 + service/simulator/inc/simulator_single_resource.h | 182 ++ .../simulator_uncopyable.h} | 36 +- .../ClientControllerPlugin/icons/light_16x16.png | Bin 732 -> 0 bytes .../listener/IDevicePlatformInfoUIListener.java | 23 + .../clientcontroller/listener/IGetUIListener.java | 2 - .../listener/IObserveUIListener.java | 2 - .../clientcontroller/listener/IPostUIListener.java | 2 - .../clientcontroller/listener/IPutUIListener.java | 2 - .../clientcontroller/manager/ImageManager.java | 4 - .../clientcontroller/manager/LogManager.java | 11 +- .../clientcontroller/manager/ResourceManager.java | 972 ++++--- .../remoteresource/PutPostAttributeModel.java | 8 +- .../remoteresource/RemoteResource.java | 87 +- .../remoteresource/RemoteResourceAttribute.java | 77 +- .../remoteresource/SerializedClientController.java | 77 + .../utils/AttributeValueBuilder.java | 266 ++ .../clientcontroller/utils/Constants.java | 150 +- .../simulator/clientcontroller/utils/Utility.java | 59 +- .../clientcontroller/view/AttributeView.java | 250 +- .../simulator/clientcontroller/view/LogView.java | 9 +- .../clientcontroller/view/MetaPropertiesView.java | 203 +- .../clientcontroller/view/ResourceManagerView.java | 239 +- .../view/dialogs/FindResourcePage.java | 192 +- .../view/dialogs/LoadRAMLDialog.java | 29 +- .../view/dialogs/PostRequestDialog.java | 135 +- .../view/dialogs/PutRequestDialog.java | 81 +- .../view/dialogs/VerificationDialog.java | 50 +- .../src/oic/simulator/logger/LogLabelProvider.java | 7 +- .../src/oic/simulator/logger/LoggerCallback.java | 2 +- service/simulator/java/eclipse-plugin/README.txt | 90 +- .../ServiceProviderPlugin/build.properties | 1 - .../icons/collection_resource.gif | Bin 0 -> 361 bytes .../ServiceProviderPlugin/icons/device.gif | Bin 0 -> 572 bytes .../icons/single_resource.gif | Bin 0 -> 207 bytes .../ServiceProviderPlugin/plugin.xml | 8 +- .../resource/Light/simple-light-error.json | 23 - .../resource/Light/simple-light.json | 34 - .../resource/Light/simple-light.raml | 81 - .../src/oic/simulator/logger/LogLabelProvider.java | 7 +- .../listener/IAutomationUIListener.java | 6 +- .../listener/IObserverListChangedUIListener.java | 4 +- .../listener/IPropertiesChangedUIListener.java | 27 + .../listener/IResourceListChangedUIListener.java | 8 +- .../listener/IResourceModelChangedUIListener.java | 9 +- ...tener.java => ISelectionChangedUIListener.java} | 9 +- .../simulator/serviceprovider/manager/Data.java | 294 ++ .../serviceprovider/manager/ImageManager.java | 9 +- .../serviceprovider/manager/LogManager.java | 11 +- .../serviceprovider/manager/ResourceManager.java | 3064 +++++++++++++------- .../serviceprovider/manager/UiListenerHandler.java | 325 +++ .../serviceprovider/model/AttributeHelper.java | 364 +++ .../AutomationSettingHelper.java | 58 +- .../serviceprovider/model/CollectionResource.java | 221 ++ .../{resource => model}/DeleteCategory.java | 2 +- .../simulator/serviceprovider/model/Device.java | 117 + .../model/LocalResourceAttribute.java | 78 + .../{resource => model}/MetaProperty.java | 2 +- .../ModelChangeNotificationType.java | 2 +- .../{resource => model}/ObserverDetail.java | 12 +- .../simulator/serviceprovider/model/Resource.java | 260 ++ .../serviceprovider/model/ResourceCategory.java | 21 + .../serviceprovider/model/ResourceType.java | 21 + .../simulator/serviceprovider/model/SRMItem.java} | 40 +- .../model/SerializedServiceProvider.java | 167 ++ .../model/SimulatorPluginException.java | 33 + .../serviceprovider/model/SingleResource.java | 173 ++ .../perspective/PerspectiveFactory.java | 6 +- .../resource/LocalResourceAttribute.java | 142 - .../resource/SimulatorResource.java | 205 -- .../resource/StandardConfiguration.java | 100 - .../utils/AttributeValueBuilder.java | 266 ++ .../simulator/serviceprovider/utils/Constants.java | 174 +- .../simulator/serviceprovider/utils/Utility.java | 713 ++++- .../view/AttributeEditingSupport.java | 425 ++- .../serviceprovider/view/AttributeView.java | 570 ++-- .../view/DevicePlatformInfoView.java | 377 +++ .../serviceprovider/view/MetaPropertiesView.java | 334 ++- .../view/MultiResourceOrchestrationView.java | 39 - .../serviceprovider/view/ResourceManagerView.java | 1658 +++++++++-- .../serviceprovider/view/ResourceObserverView.java | 72 +- .../view/dialogs/AddAttributeDialog.java | 731 +++++ .../view/dialogs/AddResourceToCollections.java | 206 ++ .../view/dialogs/AddResourceToDevices.java | 205 ++ .../serviceprovider/view/dialogs/AddResources.java | 207 ++ .../view/dialogs/AddResourcesToCollectionPage.java | 169 ++ .../view/dialogs/AutomationSettingDialog.java | 2 +- .../CollectionResourceBasicDetailsPage.java | 337 +++ .../view/dialogs/CreateResourceWizard.java | 565 +++- .../view/dialogs/DeleteResourcePage.java | 459 ++- .../view/dialogs/DeleteResourceWizard.java | 94 +- .../serviceprovider/view/dialogs/DevicePage.java | 207 ++ .../{CreateResourcePage.java => LoadRamlPage.java} | 289 +- .../serviceprovider/view/dialogs/MainPage.java | 191 ++ .../dialogs/RemoveResourceFromCollections.java | 206 ++ .../view/dialogs/RemoveResourceFromDevices.java | 205 ++ .../view/dialogs/RemoveResources.java | 207 ++ .../view/dialogs/ResourceWizardDialog.java | 52 +- .../dialogs/SimpleResourceAddAttributePage.java | 379 +++ .../dialogs/SimpleResourceBasicDetailsPage.java | 303 ++ .../dialogs/SimpleResourceOtherDetailsPage.java | 119 + .../view/dialogs/SimpleResourcePage.java | 96 + .../view/dialogs/SingleTextInputDialog.java | 100 + .../view/dialogs/StartStopResourcePage.java | 90 + .../view/dialogs/UpdatePropertiesPage.java | 255 ++ service/simulator/java/jni/jni_listener_holder.h | 54 + service/simulator/java/jni/jni_queryparam.cpp | 68 + service/simulator/java/jni/jni_queryparam.h | 38 + .../simulator/java/jni/jni_sharedobject_holder.h | 49 + .../jni/jni_string.cpp} | 48 +- .../jni/jni_string.h} | 18 +- service/simulator/java/jni/jni_vector.cpp | 92 + service/simulator/java/jni/jni_vector.h | 56 + .../simulator/java/jni/resource_attributes_jni.cpp | 246 -- .../simulator/java/jni/resource_attributes_jni.h | 47 - .../java/jni/simulator_collection_resource_jni.cpp | 154 + service/simulator/java/jni/simulator_common_jni.h | 107 - .../java/jni/simulator_device_info_jni.cpp | 53 +- .../simulator/java/jni/simulator_device_info_jni.h | 26 +- .../java/jni/simulator_exceptions_jni.cpp | 89 + ...ator_jni_utils.h => simulator_exceptions_jni.h} | 17 +- service/simulator/java/jni/simulator_init_jni.cpp | 234 ++ service/simulator/java/jni/simulator_jni_utils.cpp | 71 - .../simulator/java/jni/simulator_manager_jni.cpp | 850 +----- service/simulator/java/jni/simulator_manager_jni.h | 74 - .../java/jni/simulator_platform_info_jni.cpp | 107 +- .../java/jni/simulator_platform_info_jni.h | 28 +- .../java/jni/simulator_remote_resource_jni.cpp | 970 ++----- .../java/jni/simulator_remote_resource_jni.h | 85 - .../simulator/java/jni/simulator_resource_jni.cpp | 470 +++ .../java/jni/simulator_resource_jni_util.cpp | 206 -- .../java/jni/simulator_resource_jni_util.h | 77 - .../java/jni/simulator_resource_model_jni.cpp | 1031 +++++-- .../java/jni/simulator_resource_model_jni.h | 68 +- .../java/jni/simulator_resource_server_jni.cpp | 840 ------ .../java/jni/simulator_resource_server_jni.h | 137 - .../java/jni/simulator_resource_utils_jni.cpp | 158 + .../java/jni/simulator_resource_utils_jni.h | 35 + .../java/jni/simulator_single_resource_jni.cpp | 248 ++ service/simulator/java/jni/simulator_utils_jni.cpp | 293 ++ service/simulator/java/jni/simulator_utils_jni.h | 113 + .../src/org/oic/simulator/AttributeProperty.java | 169 ++ .../sdk/src/org/oic/simulator/AttributeValue.java | 512 ++++ .../oic/simulator/AttributeValueValidation.java | 323 +++ .../org/oic/simulator/AttributeValueVisitor.java | 118 + .../java/sdk/src/org/oic/simulator/DeviceInfo.java | 2 +- .../{IDeviceInfo.java => DeviceListener.java} | 6 +- .../sdk/src/org/oic/simulator/IAutomation.java | 32 - .../java/sdk/src/org/oic/simulator/ILogger.java | 3 +- .../org/oic/simulator/InvalidArgsException.java | 13 +- .../src/org/oic/simulator/NoSupportException.java | 9 +- .../simulator/OperationInProgressException.java | 9 +- .../sdk/src/org/oic/simulator/PlatformInfo.java | 60 +- .../{IPlatformInfo.java => PlatformListener.java} | 6 +- .../src/org/oic/simulator/ResourceAttribute.java | 139 - .../src/org/oic/simulator/SimulatorException.java | 19 +- .../src/org/oic/simulator/SimulatorManager.java | 163 +- .../simulator/SimulatorManagerNativeInterface.java | 161 - .../oic/simulator/SimulatorResourceAttribute.java | 99 + .../org/oic/simulator/SimulatorResourceModel.java | 245 +- .../sdk/src/org/oic/simulator/SimulatorResult.java | 46 +- .../FindResourceListener.java} | 14 +- .../SimulatorConnectivityType.java | 2 +- .../SimulatorRemoteResource.java | 432 +-- .../simulator/clientcontroller/IGetListener.java | 45 - .../clientcontroller/IObserveListener.java | 49 - .../simulator/clientcontroller/IPostListener.java | 46 - .../simulator/clientcontroller/IPutListener.java | 46 - .../clientcontroller/IVerificationListener.java | 54 - .../SimulatorVerificationType.java | 55 - .../ObserverInfo.java => server/Observer.java} | 24 +- .../server/SimulatorCollectionResource.java | 86 + .../oic/simulator/server/SimulatorResource.java | 362 +++ .../simulator/server/SimulatorSingleResource.java | 156 + .../oic/simulator/serviceprovider/IObserver.java | 37 - .../IResourceModelChangedListener.java | 37 - .../serviceprovider/SimulatorResourceServer.java | 488 ---- service/simulator/ramlparser/SConscript | 1 - service/simulator/ramlparser/example/SConscript | 49 - .../simulator/ramlparser/example/raml_parser.cpp | 555 ---- .../simulator/ramlparser/raml/IncludeResolver.h | 2 +- service/simulator/ramlparser/raml/RamlParser.cpp | 26 +- service/simulator/ramlparser/raml/RamlParser.h | 2 +- .../ramlparser/raml/{Utils.h => RamlUtils.h} | 396 +-- .../ramlparser/raml/jsonSchemaParser/Definitions.h | 2 +- .../ramlparser/raml/jsonSchemaParser/Items.h | 2 +- .../raml/jsonSchemaParser/JsonSchema.cpp | 12 +- .../ramlparser/raml/jsonSchemaParser/Properties.h | 51 +- .../ramlparser/raml/model/AbstractParam.h | 2 +- service/simulator/ramlparser/raml/model/Action.h | 2 +- service/simulator/ramlparser/raml/model/Raml.h | 2 +- .../simulator/ramlparser/raml/model/RamlResource.h | 2 +- .../ramlparser/raml/model/RequestResponseBody.h | 2 +- service/simulator/ramlparser/raml/model/Response.h | 2 +- .../src/client-controller/attribute_generator.cpp | 187 -- .../src/client-controller/simulator_client.cpp | 93 - .../src/client-controller/simulator_client.h | 87 - .../simulator/src/client/attribute_generator.cpp | 183 ++ .../attribute_generator.h | 14 +- .../auto_request_gen.cpp | 0 .../auto_request_gen.h | 0 .../auto_request_gen_mngr.cpp | 2 +- .../auto_request_gen_mngr.h | 0 .../get_request_generator.cpp | 0 .../get_request_generator.h | 0 .../post_request_generator.cpp | 8 +- .../post_request_generator.h | 0 .../put_request_generator.cpp | 4 +- .../put_request_generator.h | 0 .../query_param_generator.cpp | 0 .../query_param_generator.h | 0 .../{client-controller => client}/request_list.h | 0 .../request_sender.cpp | 44 +- .../{client-controller => client}/request_sender.h | 12 +- .../simulator_remote_resource_impl.cpp | 145 +- .../simulator_remote_resource_impl.h | 14 +- .../simulator/src/common/request_model_builder.cpp | 91 +- service/simulator/src/common/response_model.cpp | 98 +- service/simulator/src/common/response_model.h | 9 +- .../src/common/simulator_resource_model.cpp | 1072 +++++-- service/simulator/src/common/simulator_utils.cpp | 134 +- service/simulator/src/common/simulator_utils.h | 7 +- .../resource_update_automation.cpp | 136 +- .../resource_update_automation.h | 17 +- .../resource_update_automation_mngr.cpp | 21 +- .../resource_update_automation_mngr.h | 6 +- .../server/simulator_collection_resource_impl.cpp | 562 ++++ .../server/simulator_collection_resource_impl.h | 96 + .../src/server/simulator_resource_factory.cpp | 429 +++ .../src/server/simulator_resource_factory.h | 142 + .../src/server/simulator_single_resource_impl.cpp | 598 ++++ .../src/server/simulator_single_resource_impl.h | 110 + .../src/service-provider/resource_manager.cpp | 215 -- .../src/service-provider/resource_manager.h | 119 - .../simulator_resource_creator.cpp | 154 - .../service-provider/simulator_resource_server.cpp | 75 - .../simulator_resource_server_impl.cpp | 438 --- .../simulator_resource_server_impl.h | 89 - service/simulator/src/simulator_manager.cpp | 122 +- .../simulator/unittests/SimulatorTest/.gitignore | 1 + .../client/test/SimulatorRemoteResourceTest.java | 1148 ++++++++ .../clientcontroller/test/GetListener.java | 59 - .../clientcontroller/test/ListenerObject.java | 61 - .../clientcontroller/test/ObserveListener.java | 56 - .../test/ObserveListenerObject.java | 71 - .../clientcontroller/test/PostListener.java | 59 - .../clientcontroller/test/PutListener.java | 58 - .../test/SimulatorRemoteResourceTest.java | 915 ------ .../clientcontroller/test/VerifyListener.java | 68 - .../test/VerifyListenerObject.java | 59 - .../test/SimulatorCollectionResourceTest.java | 301 ++ .../server/test/SimulatorResourceTest.java | 419 +++ .../server/test/SimulatorSingleResourceTest.java | 649 +++++ .../serviceprovider/test/AutomationListener.java | 46 - .../simulator/serviceprovider/test/Observer.java | 48 - .../serviceprovider/test/ObserverObject.java | 60 - .../test/SimlatorResourceServerTest.java | 936 ------ .../org/oic/simulator/test/AttributeValueTest.java | 478 +++ .../test/AttributeValueValidationTest.java | 253 ++ .../src/org/oic/simulator/test/ExceptionType.java | 21 + .../oic/simulator/test/FindResourceListener.java | 47 - .../test/ResourceModelChangeListener.java | 42 - .../oic/simulator/test/SimulatorManagerTest.java | 915 +++--- .../test/SimulatorRemoteResourceObject.java | 38 - .../simulator/test/SimulatorResourceModelTest.java | 399 +-- .../src/org/oic/simulator/utils/ObjectHolder.java} | 19 +- .../oic/simulator/utils/SampleSingleResource.java | 59 + 280 files changed, 30231 insertions(+), 16779 deletions(-) delete mode 100755 service/simulator/examples/README.txt rename service/simulator/examples/{client-controller => client}/SConscript (85%) rename service/simulator/examples/{client-controller/client_controller.cpp => client/simulator_client.cpp} (88%) delete mode 100644 service/simulator/examples/server/service_provider.cpp create mode 100644 service/simulator/examples/server/simulator_server.cpp create mode 100644 service/simulator/inc/simulator_collection_resource.h create mode 100644 service/simulator/inc/simulator_resource.h delete mode 100644 service/simulator/inc/simulator_resource_server.h create mode 100644 service/simulator/inc/simulator_single_resource.h rename service/simulator/{java/sdk/src/org/oic/simulator/serviceprovider/AutomationType.java => inc/simulator_uncopyable.h} (59%) delete mode 100644 service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/light_16x16.png create mode 100644 service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/listener/IDevicePlatformInfoUIListener.java create mode 100644 service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/remoteresource/SerializedClientController.java create mode 100644 service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/utils/AttributeValueBuilder.java create mode 100644 service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/collection_resource.gif create mode 100644 service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/device.gif create mode 100644 service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/single_resource.gif delete mode 100644 service/simulator/java/eclipse-plugin/ServiceProviderPlugin/resource/Light/simple-light-error.json delete mode 100644 service/simulator/java/eclipse-plugin/ServiceProviderPlugin/resource/Light/simple-light.json delete mode 100644 service/simulator/java/eclipse-plugin/ServiceProviderPlugin/resource/Light/simple-light.raml create mode 100644 service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IPropertiesChangedUIListener.java rename service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/{IResourceSelectionChangedUIListener.java => ISelectionChangedUIListener.java} (74%) create mode 100644 service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/manager/Data.java create mode 100644 service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/manager/UiListenerHandler.java create mode 100644 service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/AttributeHelper.java rename service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/{resource => model}/AutomationSettingHelper.java (63%) create mode 100644 service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/CollectionResource.java rename service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/{resource => model}/DeleteCategory.java (93%) create mode 100644 service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/Device.java create mode 100644 service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/LocalResourceAttribute.java rename service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/{resource => model}/MetaProperty.java (96%) rename service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/{resource => model}/ModelChangeNotificationType.java (94%) rename service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/{resource => model}/ObserverDetail.java (77%) create mode 100644 service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/Resource.java create mode 100644 service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/ResourceCategory.java create mode 100644 service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/ResourceType.java rename service/simulator/{unittests/SimulatorTest/src/org/oic/simulator/test/ResourceModelObject.java => java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/SRMItem.java} (53%) create mode 100644 service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/SerializedServiceProvider.java create mode 100644 service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/SimulatorPluginException.java create mode 100644 service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/SingleResource.java delete mode 100644 service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/LocalResourceAttribute.java delete mode 100644 service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/SimulatorResource.java delete mode 100644 service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/StandardConfiguration.java create mode 100644 service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/utils/AttributeValueBuilder.java create mode 100644 service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/DevicePlatformInfoView.java delete mode 100644 service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/MultiResourceOrchestrationView.java create mode 100644 service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/AddAttributeDialog.java create mode 100644 service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/AddResourceToCollections.java create mode 100644 service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/AddResourceToDevices.java create mode 100644 service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/AddResources.java create mode 100644 service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/AddResourcesToCollectionPage.java create mode 100644 service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/CollectionResourceBasicDetailsPage.java create mode 100644 service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/DevicePage.java rename service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/{CreateResourcePage.java => LoadRamlPage.java} (53%) create mode 100644 service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/MainPage.java create mode 100644 service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/RemoveResourceFromCollections.java create mode 100644 service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/RemoveResourceFromDevices.java create mode 100644 service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/RemoveResources.java create mode 100644 service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/SimpleResourceAddAttributePage.java create mode 100644 service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/SimpleResourceBasicDetailsPage.java create mode 100644 service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/SimpleResourceOtherDetailsPage.java create mode 100644 service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/SimpleResourcePage.java create mode 100644 service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/SingleTextInputDialog.java create mode 100644 service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/StartStopResourcePage.java create mode 100644 service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/UpdatePropertiesPage.java create mode 100644 service/simulator/java/jni/jni_listener_holder.h create mode 100644 service/simulator/java/jni/jni_queryparam.cpp create mode 100644 service/simulator/java/jni/jni_queryparam.h create mode 100644 service/simulator/java/jni/jni_sharedobject_holder.h rename service/simulator/{unittests/SimulatorTest/src/org/oic/simulator/serviceprovider/test/AutomationObject.java => java/jni/jni_string.cpp} (53%) rename service/simulator/{src/service-provider/simulator_resource_creator.h => java/jni/jni_string.h} (71%) create mode 100644 service/simulator/java/jni/jni_vector.cpp create mode 100644 service/simulator/java/jni/jni_vector.h delete mode 100644 service/simulator/java/jni/resource_attributes_jni.cpp delete mode 100644 service/simulator/java/jni/resource_attributes_jni.h create mode 100644 service/simulator/java/jni/simulator_collection_resource_jni.cpp delete mode 100644 service/simulator/java/jni/simulator_common_jni.h create mode 100644 service/simulator/java/jni/simulator_exceptions_jni.cpp rename service/simulator/java/jni/{simulator_jni_utils.h => simulator_exceptions_jni.h} (65%) create mode 100644 service/simulator/java/jni/simulator_init_jni.cpp delete mode 100644 service/simulator/java/jni/simulator_jni_utils.cpp delete mode 100644 service/simulator/java/jni/simulator_manager_jni.h delete mode 100644 service/simulator/java/jni/simulator_remote_resource_jni.h create mode 100644 service/simulator/java/jni/simulator_resource_jni.cpp delete mode 100644 service/simulator/java/jni/simulator_resource_jni_util.cpp delete mode 100644 service/simulator/java/jni/simulator_resource_jni_util.h delete mode 100644 service/simulator/java/jni/simulator_resource_server_jni.cpp delete mode 100644 service/simulator/java/jni/simulator_resource_server_jni.h create mode 100644 service/simulator/java/jni/simulator_resource_utils_jni.cpp create mode 100644 service/simulator/java/jni/simulator_resource_utils_jni.h create mode 100644 service/simulator/java/jni/simulator_single_resource_jni.cpp create mode 100644 service/simulator/java/jni/simulator_utils_jni.cpp create mode 100644 service/simulator/java/jni/simulator_utils_jni.h create mode 100644 service/simulator/java/sdk/src/org/oic/simulator/AttributeProperty.java create mode 100644 service/simulator/java/sdk/src/org/oic/simulator/AttributeValue.java create mode 100644 service/simulator/java/sdk/src/org/oic/simulator/AttributeValueValidation.java create mode 100644 service/simulator/java/sdk/src/org/oic/simulator/AttributeValueVisitor.java rename service/simulator/java/sdk/src/org/oic/simulator/{IDeviceInfo.java => DeviceListener.java} (85%) delete mode 100644 service/simulator/java/sdk/src/org/oic/simulator/IAutomation.java rename service/simulator/java/sdk/src/org/oic/simulator/{IPlatformInfo.java => PlatformListener.java} (84%) delete mode 100644 service/simulator/java/sdk/src/org/oic/simulator/ResourceAttribute.java delete mode 100644 service/simulator/java/sdk/src/org/oic/simulator/SimulatorManagerNativeInterface.java create mode 100644 service/simulator/java/sdk/src/org/oic/simulator/SimulatorResourceAttribute.java rename service/simulator/java/sdk/src/org/oic/simulator/{clientcontroller/IFindResourceListener.java => client/FindResourceListener.java} (66%) rename service/simulator/java/sdk/src/org/oic/simulator/{clientcontroller => client}/SimulatorConnectivityType.java (98%) rename service/simulator/java/sdk/src/org/oic/simulator/{clientcontroller => client}/SimulatorRemoteResource.java (57%) delete mode 100644 service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IGetListener.java delete mode 100644 service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IObserveListener.java delete mode 100644 service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IPostListener.java delete mode 100644 service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IPutListener.java delete mode 100644 service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IVerificationListener.java delete mode 100644 service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/SimulatorVerificationType.java rename service/simulator/java/sdk/src/org/oic/simulator/{serviceprovider/ObserverInfo.java => server/Observer.java} (76%) create mode 100644 service/simulator/java/sdk/src/org/oic/simulator/server/SimulatorCollectionResource.java create mode 100644 service/simulator/java/sdk/src/org/oic/simulator/server/SimulatorResource.java create mode 100644 service/simulator/java/sdk/src/org/oic/simulator/server/SimulatorSingleResource.java delete mode 100644 service/simulator/java/sdk/src/org/oic/simulator/serviceprovider/IObserver.java delete mode 100644 service/simulator/java/sdk/src/org/oic/simulator/serviceprovider/IResourceModelChangedListener.java delete mode 100644 service/simulator/java/sdk/src/org/oic/simulator/serviceprovider/SimulatorResourceServer.java delete mode 100755 service/simulator/ramlparser/example/SConscript delete mode 100755 service/simulator/ramlparser/example/raml_parser.cpp rename service/simulator/ramlparser/raml/{Utils.h => RamlUtils.h} (96%) mode change 100755 => 100644 delete mode 100644 service/simulator/src/client-controller/attribute_generator.cpp delete mode 100644 service/simulator/src/client-controller/simulator_client.cpp delete mode 100644 service/simulator/src/client-controller/simulator_client.h create mode 100644 service/simulator/src/client/attribute_generator.cpp rename service/simulator/src/{client-controller => client}/attribute_generator.h (83%) rename service/simulator/src/{client-controller => client}/auto_request_gen.cpp (100%) rename service/simulator/src/{client-controller => client}/auto_request_gen.h (100%) rename service/simulator/src/{client-controller => client}/auto_request_gen_mngr.cpp (99%) rename service/simulator/src/{client-controller => client}/auto_request_gen_mngr.h (100%) rename service/simulator/src/{client-controller => client}/get_request_generator.cpp (100%) rename service/simulator/src/{client-controller => client}/get_request_generator.h (100%) rename service/simulator/src/{client-controller => client}/post_request_generator.cpp (93%) rename service/simulator/src/{client-controller => client}/post_request_generator.h (100%) rename service/simulator/src/{client-controller => client}/put_request_generator.cpp (95%) rename service/simulator/src/{client-controller => client}/put_request_generator.h (100%) rename service/simulator/src/{client-controller => client}/query_param_generator.cpp (100%) rename service/simulator/src/{client-controller => client}/query_param_generator.h (100%) rename service/simulator/src/{client-controller => client}/request_list.h (100%) rename service/simulator/src/{client-controller => client}/request_sender.cpp (80%) rename service/simulator/src/{client-controller => client}/request_sender.h (87%) rename service/simulator/src/{client-controller => client}/simulator_remote_resource_impl.cpp (76%) rename service/simulator/src/{client-controller => client}/simulator_remote_resource_impl.h (90%) rename service/simulator/src/{service-provider => server}/resource_update_automation.cpp (58%) rename service/simulator/src/{service-provider => server}/resource_update_automation.h (81%) rename service/simulator/src/{service-provider => server}/resource_update_automation_mngr.cpp (87%) rename service/simulator/src/{service-provider => server}/resource_update_automation_mngr.h (90%) create mode 100644 service/simulator/src/server/simulator_collection_resource_impl.cpp create mode 100644 service/simulator/src/server/simulator_collection_resource_impl.h create mode 100644 service/simulator/src/server/simulator_resource_factory.cpp create mode 100644 service/simulator/src/server/simulator_resource_factory.h create mode 100644 service/simulator/src/server/simulator_single_resource_impl.cpp create mode 100644 service/simulator/src/server/simulator_single_resource_impl.h delete mode 100644 service/simulator/src/service-provider/resource_manager.cpp delete mode 100644 service/simulator/src/service-provider/resource_manager.h delete mode 100755 service/simulator/src/service-provider/simulator_resource_creator.cpp delete mode 100644 service/simulator/src/service-provider/simulator_resource_server.cpp delete mode 100644 service/simulator/src/service-provider/simulator_resource_server_impl.cpp delete mode 100644 service/simulator/src/service-provider/simulator_resource_server_impl.h create mode 100644 service/simulator/unittests/SimulatorTest/.gitignore create mode 100644 service/simulator/unittests/SimulatorTest/src/org/oic/simulator/client/test/SimulatorRemoteResourceTest.java delete mode 100644 service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/GetListener.java delete mode 100644 service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/ListenerObject.java delete mode 100644 service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/ObserveListener.java delete mode 100644 service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/ObserveListenerObject.java delete mode 100644 service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/PostListener.java delete mode 100644 service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/PutListener.java delete mode 100644 service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/SimulatorRemoteResourceTest.java delete mode 100644 service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/VerifyListener.java delete mode 100644 service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/VerifyListenerObject.java create mode 100644 service/simulator/unittests/SimulatorTest/src/org/oic/simulator/server/test/SimulatorCollectionResourceTest.java create mode 100644 service/simulator/unittests/SimulatorTest/src/org/oic/simulator/server/test/SimulatorResourceTest.java create mode 100644 service/simulator/unittests/SimulatorTest/src/org/oic/simulator/server/test/SimulatorSingleResourceTest.java delete mode 100644 service/simulator/unittests/SimulatorTest/src/org/oic/simulator/serviceprovider/test/AutomationListener.java delete mode 100644 service/simulator/unittests/SimulatorTest/src/org/oic/simulator/serviceprovider/test/Observer.java delete mode 100644 service/simulator/unittests/SimulatorTest/src/org/oic/simulator/serviceprovider/test/ObserverObject.java delete mode 100644 service/simulator/unittests/SimulatorTest/src/org/oic/simulator/serviceprovider/test/SimlatorResourceServerTest.java create mode 100644 service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/AttributeValueTest.java create mode 100644 service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/AttributeValueValidationTest.java create mode 100644 service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/ExceptionType.java delete mode 100644 service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/FindResourceListener.java delete mode 100644 service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/ResourceModelChangeListener.java delete mode 100644 service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/SimulatorRemoteResourceObject.java rename service/simulator/{java/sdk/src/org/oic/simulator/clientcontroller/SimulatorObserveType.java => unittests/SimulatorTest/src/org/oic/simulator/utils/ObjectHolder.java} (68%) create mode 100644 service/simulator/unittests/SimulatorTest/src/org/oic/simulator/utils/SampleSingleResource.java diff --git a/service/simulator/SConscript b/service/simulator/SConscript index 260cb0b..b77e5dc 100755 --- a/service/simulator/SConscript +++ b/service/simulator/SConscript @@ -36,7 +36,7 @@ target_os = env.get('TARGET_OS') ###################################################################### # Build flags ###################################################################### -simulator_env.AppendUnique(CPPPATH = ['inc', 'src/client-controller', 'src/service-provider', 'src/common']) +simulator_env.AppendUnique(CPPPATH = ['inc', 'src/client', 'src/server', 'src/common']) simulator_env.AppendUnique(CPPPATH = [ '../../resource/include/', '../../resource/csdk/stack/include', @@ -86,4 +86,4 @@ simulator_env.InstallTarget(simulatorsdk, 'libSimulator') #Build sample application SConscript('examples/server/SConscript') -SConscript('examples/client-controller/SConscript') +SConscript('examples/client/SConscript') \ No newline at end of file diff --git a/service/simulator/examples/README.txt b/service/simulator/examples/README.txt deleted file mode 100755 index f0ab383..0000000 --- a/service/simulator/examples/README.txt +++ /dev/null @@ -1,3 +0,0 @@ -Command to run Service Provider with Resource definitions provided throught RAML file : -./simulator-server PATH-TO-RAML-FILE - diff --git a/service/simulator/examples/client-controller/SConscript b/service/simulator/examples/client/SConscript similarity index 85% rename from service/simulator/examples/client-controller/SConscript rename to service/simulator/examples/client/SConscript index 7149b6b..bcf4ec0 100644 --- a/service/simulator/examples/client-controller/SConscript +++ b/service/simulator/examples/client/SConscript @@ -22,7 +22,7 @@ if sim_env.get('SECURED') == '1': ###################################################################### # Source files and Targets ###################################################################### -clientcontroller = sim_env.Program('client-controller', 'client_controller.cpp') +client = sim_env.Program('simulator-client', 'simulator_client.cpp') -Alias("clientcontroller", clientcontroller) -env.AppendTarget('clientcontroller') +Alias("simulatorclient", client) +env.AppendTarget('client') diff --git a/service/simulator/examples/client-controller/client_controller.cpp b/service/simulator/examples/client/simulator_client.cpp similarity index 88% rename from service/simulator/examples/client-controller/client_controller.cpp rename to service/simulator/examples/client/simulator_client.cpp index 18df736..f0f3148 100644 --- a/service/simulator/examples/client-controller/client_controller.cpp +++ b/service/simulator/examples/client/simulator_client.cpp @@ -34,6 +34,21 @@ std::string getOperationStateString(OperationState state) return "OP_UNKNOWN"; } +std::string getPropertyTypeString(SimulatorResourceModel::AttributeProperty::Type type) +{ + switch(type) + { + case SimulatorResourceModel::AttributeProperty::Type::RANGE: + return "RANGE"; + case SimulatorResourceModel::AttributeProperty::Type::VALUE_SET: + return "VALUE_SET"; + default: + break; + } + + return "UNKNOWN"; +} + class AppLogger : public ILogger { public: @@ -105,7 +120,7 @@ class ClientController std::lock_guard lock(m_mutex); if (0 == m_resList.size()) { - std::cout << "No resouces!" << std::endl; + std::cout << "No resources!" << std::endl; return nullptr; } @@ -154,7 +169,8 @@ class ClientController try { SimulatorManager::getInstance()->findResource(resourceType, callback); - std::cout << "SimulatorManager::findResource is successfull" << std::endl; + std::cout << "SimulatorManager::findResource is successful" << std::endl; + m_resList.clear(); } catch (InvalidArgsException &e) { @@ -202,21 +218,16 @@ class ClientController [](std::string uid, SimulatorResult errorCode, SimulatorResourceModelSP rep, int seq) { std::cout << "\nObserve notification received ###[errorcode: " << errorCode << - " seq: " << seq << "UID: " << uid << "]" << std::endl; - std::map 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; + " seq: " << seq << "UID: " << uid << "]" << std::endl; + + std::cout << "Representation is: " << std::endl; + std::cout << rep->toString() << std::endl; }; try { resource->observe(ObserveType::OBSERVE, callback); - std::cout << "Observe is successfull!" << std::endl; + std::cout << "Observe is successful!" << std::endl; } catch (InvalidArgsException &e) { @@ -238,7 +249,7 @@ class ClientController try { resource->cancelObserve(); - std::cout << "Cancelling observe is successfull!" << std::endl; + std::cout << "Cancelling observe is successful!" << std::endl; } catch (SimulatorException &e) { @@ -260,22 +271,13 @@ class ClientController << std::endl; std::cout << "UID is: " << uId << std::endl; std::cout << "Representation is: " << std::endl; - std::map 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; + std::cout << rep->toString() << std::endl; }; try { resource->get(std::map (), callback); - std::cout << "GET is successfull!" << std::endl; + std::cout << "GET is successful!" << std::endl; } catch (InvalidArgsException &e) { @@ -307,27 +309,18 @@ class ClientController << std::endl; std::cout << "UID is: " << uId << std::endl; std::cout << "Representation is: " << std::endl; - std::map 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; + std::cout << rep->toString() << std::endl; }; try { SimulatorResourceModelSP rep = std::make_shared(); std::string value = "off"; - rep->addAttribute("power", value); - rep->addAttribute("intensity", 5); + rep->add("power", value); + rep->add("intensity", 5); resource->put(std::map (), rep, callback); - std::cout << "PUT is successfull!" << std::endl; + std::cout << "PUT is successful!" << std::endl; } catch (InvalidArgsException &e) { @@ -359,27 +352,18 @@ class ClientController << std::endl; std::cout << "UID is: " << uId << std::endl; std::cout << "Representation is: " << std::endl; - std::map 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; + std::cout << rep->toString() << std::endl; }; try { SimulatorResourceModelSP rep = std::make_shared(); std::string value = "on"; - rep->addAttribute("power", value); - rep->addAttribute("intensity", 7); + rep->add("power", value); + rep->add("intensity", 7); resource->post(std::map (), rep, callback); - std::cout << "POST is successfull!" << std::endl; + std::cout << "POST is successful!" << std::endl; } catch (InvalidArgsException &e) { @@ -414,7 +398,7 @@ class ClientController try { int id = resource->startVerification(RequestType::RQ_TYPE_GET, callback); - std::cout << "startVerification for GET is successfull!id: " << id << std::endl; + std::cout << "startVerification for GET is successful!id: " << id << std::endl; } catch (InvalidArgsException &e) { @@ -449,7 +433,7 @@ class ClientController try { int id = resource->startVerification(RequestType::RQ_TYPE_PUT, callback); - std::cout << "startVerification for PUT is successfull!id: " << id << std::endl; + std::cout << "startVerification for PUT is successful!id: " << id << std::endl; } catch (InvalidArgsException &e) { @@ -484,7 +468,7 @@ class ClientController try { int id = resource->startVerification(RequestType::RQ_TYPE_POST, callback); - std::cout << "startVerification for POST is successfull!id: " << id << std::endl; + std::cout << "startVerification for POST is successful!id: " << id << std::endl; } catch (InvalidArgsException &e) { @@ -515,8 +499,33 @@ class ClientController std::cout << "Enter the config path: "; std::cin >> configPath; - resource->configure(configPath); - std::cout << "configuration is successfull!" << std::endl; + SimulatorResourceModelSP representation = resource->configure(configPath); + if (representation) + { + std::cout << "configuration is successful!" << std::endl; + std::map attributes = + representation->getAttributes(); + std::cout << "##### Attributes [" << attributes.size() << "]" << std::endl; + for (auto & attribute : attributes) + { + std::cout << (attribute.second).getName() << " : {" << std::endl; + std::cout << "value: " << (attribute.second).toString() << std::endl; + SimulatorResourceModel::AttributeProperty prop = (attribute.second).getProperty(); + std::cout << "Supported values given by : " << getPropertyTypeString(prop.type()) << std::endl; + if (SimulatorResourceModel::AttributeProperty::Type::RANGE == prop.type()) + { + std::cout << "Min: " << prop.min() << std::endl; + std::cout << "Max: " << prop.max() << std::endl; + } + else if (SimulatorResourceModel::AttributeProperty::Type::VALUE_SET == prop.type()) + { + std::cout << "Value set: " << prop.valueSetToString() << std::endl; + } + + std::cout << "}" << std::endl << std::endl; + } + std::cout << "#############################" << std::endl; + } } catch (InvalidArgsException &e) { diff --git a/service/simulator/examples/server/SConscript b/service/simulator/examples/server/SConscript index 9a5b38e..cb028dd 100644 --- a/service/simulator/examples/server/SConscript +++ b/service/simulator/examples/server/SConscript @@ -22,7 +22,7 @@ if sim_env.get('SECURED') == '1': ###################################################################### # Source files and Targets ###################################################################### -simulatorserver = sim_env.Program('simulator-server', 'service_provider.cpp') +server = sim_env.Program('simulator-server', 'simulator_server.cpp') -Alias("simulatorserver", simulatorserver) -env.AppendTarget('simulatorserver') +Alias("server", server) +env.AppendTarget('server') diff --git a/service/simulator/examples/server/service_provider.cpp b/service/simulator/examples/server/service_provider.cpp deleted file mode 100644 index 3cb3c13..0000000 --- a/service/simulator/examples/server/service_provider.cpp +++ /dev/null @@ -1,613 +0,0 @@ -/****************************************************************** - * - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************/ - -#include "simulator_manager.h" - -class AppLogger : public ILogger -{ - public: - void write(std::string time, ILogger::Level level, std::string message) - { - std::cout << "[APPLogger] " << time << " " << ILogger::getString(level) << " " - << message; - } -}; -std::shared_ptr gAppLogger(new AppLogger()); - -class SimLightResource -{ - public: - void startTest() - { - printMenu(); - bool cont = true; - while (cont) - { - int choice = -1; - std::cout << "Enter your choice: "; - std::cin >> choice; - if (choice < 0 || choice > 10) - { - std::cout << "Invaild choice !" << std::endl; continue; - } - - switch (choice) - { - case 1 : simulateResource(); break; - case 2 : displayResource(); break; - case 3 : deleteResource(); break; - case 4 : updateAttributePower(); break; - case 5 : updateAttributeIntensity(); break; - case 6 : automateResourceUpdate(); break; - case 7 : automateAttributeUpdate(); break; - case 8 : stopAutomation(); break; - case 9 : getObservers(); break; - case 10: printMenu(); break; - case 0: cont = false; - } - } - } - - private: - void printMenu() - { - std::cout << "########### LIGHT RESOURCE TESTING ###########" << std::endl; - std::cout << "1. Simulate resource" << std::endl; - std::cout << "2. Display resource information" << std::endl; - std::cout << "3. Delete resource" << std::endl; - std::cout << "4. Update attribute \"power\"" << std::endl; - std::cout << "5. Update attribute \"intensity\"" << std::endl; - std::cout << "6. Automate resource update" << std::endl; - std::cout << "7. Automate attributes update" << std::endl; - std::cout << "8. Stop Automation" << std::endl; - std::cout << "9. Get Observers of a resource" << std::endl; - std::cout << "10: Help" << std::endl; - std::cout << "0. Exit" << std::endl; - std::cout << "#######################################" << std::endl; - } - - int selectResource() - { - if (0 == m_resources.size()) - { - std::cout << "No resouces!" << std::endl; - return -1; - } - - int index = 1; - for (auto & resource : m_resources) - { - std::cout << index++ << ": " << resource->getURI().c_str() << std::endl; - } - - int choice = -1; - std::cout << "Choose the resource: "; - std::cin >> choice; - - if (choice < 1 || choice > index - 1) - { - std::cout << "Invalid choice !" << std::endl; - choice = -1; - } - - return choice; - } - - void onResourceModelChanged(const std::string &uri, - const SimulatorResourceModel &resModel) - { - std::cout << "[callback] Resource model is changed URI: " << uri.c_str() - << " Count : " << resModel.size() << std::endl; - std::cout << "#### Modified attributes are ####" << std::endl; - for (auto & attribute : resModel.getAttributes()) - { - std::cout << attribute.second.getName() << " : " - << attribute.second.valueToString().c_str() << std::endl; - } - std::cout << "########################" << std::endl; - } - - void simulateResource() - { - SimulatorResourceServer::ResourceModelChangedCB callback = std::bind( - &SimLightResource::onResourceModelChanged, this, std::placeholders::_1, - std::placeholders::_2); - - try - { - std::string configPath; - std::cout << "Enter RAML path: "; - std::cin>>configPath; - SimulatorResourceServerSP resource = - SimulatorManager::getInstance()->createResource(configPath, callback); - m_resources.push_back(resource); - std::cout << "Resource created successfully! URI= " << resource->getURI().c_str() - << std::endl; - } - catch (InvalidArgsException &e) - { - std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: " - << e.what() << "]" << std::endl; - } - catch (SimulatorException &e) - { - std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " - << e.what() << "]" << std::endl; - } - } - - void deleteResource() - { - int choice = -1; - std::cout << "1. Delete single resource" << std::endl; - std::cout << "2. Delete resources on resource types" << std::endl; - std::cout << "3. Delete all resources" << std::endl; - - std::cout << "Enter your choice: "; - std::cin >> choice; - if (choice < 1 || choice > 3) - { - std::cout << "Invalid choice !" << std::endl; - return; - } - - switch (choice) - { - case 1: - { - int index = selectResource(); - if (-1 == index) - return; - - SimulatorManager::getInstance()->deleteResource(m_resources[index - 1]); - std::cout << "Resource deleted successfully! " << std::endl; - m_resources.erase(m_resources.begin() + (index - 1)); - - } break; - - case 2: - { - std::string resourceType; - std::cout << "Enter resource type: "; - std::cin >> resourceType; - if (resourceType.empty()) - { - std::cout << "Invalid resource type!" << std::endl; - break; - } - - try - { - SimulatorManager::getInstance()->deleteResource(resourceType); - std::cout << "Resources of type \"" << resourceType << "\"" << - " deleted successfully! " << std::endl; - std::vector::iterator ite = m_resources.begin(); - while (ite != m_resources.end()) - { - if (!resourceType.compare((*ite)->getResourceType())) - { - ite = m_resources.erase(ite); - continue; - } - ite++; - } - } - catch (InvalidArgsException &e) - { - std::cout << "InvalidArgsException occured [code : " << e.code() - << " Detail: " << e.what() << "]" << std::endl; - } - catch (SimulatorException &e) - { - std::cout << "SimulatorException occured [code : " << e.code() - << " Detail: " << e.what() << "]" << std::endl; - } - } break; - - case 3: - { - SimulatorManager::getInstance()->deleteResource(); - std::cout << "All resources deleted successfully! " << std::endl; - m_resources.clear(); - } break; - } - - } - - void updateAttributePower() - { - int index = selectResource(); - if (-1 == index) - return; - - SimulatorResourceServerSP resource = m_resources[index - 1]; - SimulatorResourceModel resModel = resource->getModel(); - SimulatorResourceModel::Attribute powerAttribute; - resModel.getAttribute("power", powerAttribute); - - int allowedValuesSize = powerAttribute.getAllowedValuesSize(); - if (0 == allowedValuesSize) - { - std::cout << "This attribute does not have allowed values!" << std::endl; - return; - } - - std::cout << "Setting the new values from allowed values list to power attribute" << - std::endl; - // Update all possible values from allowed values - for (int index = 0; index < allowedValuesSize; index++) - { - // Update the new value and display the resource model after modifying - resource->updateFromAllowedValues("power", index); - std::cout << "Attribute value is modified ####" << std::endl; - - // Display the resource to user to verify the changed attribute value - displayResource(resource); - std::cout << std::endl << std::endl; - - // Get user input for continuing this operation - if ((index + 1) < allowedValuesSize) - { - int choice; - std::cout << "Would you like to change attribute value again ? (1/0): "; - std::cin >> choice; - if (0 == choice) - break; - } - } - - std::cout << "All the allowed values are tried!" << std::endl; - } - - void updateAttributeIntensity() - { - int index = selectResource(); - if (-1 == index) - return; - - SimulatorResourceServerSP resource = m_resources[index - 1]; - SimulatorResourceModel resModel = resource->getModel(); - SimulatorResourceModel::Attribute intensityAttribute; - resModel.getAttribute("intensity", intensityAttribute); - - int min, max; - intensityAttribute.getRange(min, max); - if (!min && !max) - { - std::cout << "This attribute does not have range!" << std::endl; - return; - } - - std::cout << "Setting the new values from allowed values list to intensity attribute" - << std::endl; - // Update all possible values from allowed values - for (int index = min; index <= max; index++) - { - // Update the new value and display the resource model after modifying - resource->updateAttributeValue("intensity", index); - std::cout << "Attribute value is modified ####" << std::endl; - - // Display the resource to user to verify the changed attribute value - displayResource(resource); - std::cout << std::endl << std::endl; - - // Get user input for continuing this operation - if ((index + 1) <= max) - { - int choice; - std::cout << "Would you like to change attribute value again ? (1/0): "; - std::cin >> choice; - if (0 == choice) - break; - } - } - - std::cout << "All the allowed values are tried!" << std::endl; - } - - void displayResource() - { - int index = selectResource(); - if (-1 == index) - return; - - SimulatorResourceServerSP resource = m_resources[index - 1]; - displayResource(resource); - } - - void displayResource(SimulatorResourceServerSP resource) - { - std::cout << "#############################" << std::endl; - std::cout << "Name: " << resource->getName().c_str() << std::endl; - std::cout << "URI: " << resource->getURI().c_str() << std::endl; - std::cout << "R. Type: " << resource->getResourceType().c_str() << std::endl; - std::cout << "I. Type: " << resource->getInterfaceType().c_str() << std::endl; - - // Attributes - SimulatorResourceModel resModel = resource->getModel(); - std::map attributes = - resModel.getAttributes(); - std::cout << "##### Attributes [" << attributes.size() << "]" << std::endl; - for (auto & attribute : attributes) - { - std::cout << (attribute.second).getName() << " : {" << std::endl; - std::cout << "value: " << (attribute.second).valueToString().c_str() << std::endl; - int min, max; - (attribute.second).getRange(min, max); - std::cout << "min: " << min << std::endl; - std::cout << "max: " << max << std::endl; - std::cout << "allowed values : "; - std::cout << "[ "; - for (auto & value : (attribute.second).allowedValuesToString()) - std::cout << value << " "; - std::cout << "]" << std::endl; - std::cout << "}" << std::endl << std::endl; - } - std::cout << "#############################" << std::endl; - } - - void onUpdateAutomationCompleted(const std::string &uri, - const int id) - { - std::cout << "Update automation is completed [URI: " << uri.c_str() - << " AutomationID: " << id << "] ###" << std::endl; - } - - void automateResourceUpdate() - { - int index = selectResource(); - if (-1 == index) - return; - - AutomationType type = AutomationType::NORMAL; - int choice = 0; - std::cout << "Press 1 if you want recurrent automation: "; - std::cin >> choice; - if (1 == choice) - type = AutomationType::RECURRENT; - - try - { - int id = m_resources[index - 1]->startUpdateAutomation(type, 500, - std::bind(&SimLightResource::onUpdateAutomationCompleted, this, - std::placeholders::_1, std::placeholders::_2)); - - std::cout << "startUpdateAutomation() returned succces : " << id << std::endl; - } - catch (SimulatorException &e) - { - std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " << - e.what() << "]" << std::endl; - } - } - - void automateAttributeUpdate() - { - int index = selectResource(); - if (-1 == index) - return; - - SimulatorResourceServerSP resource = m_resources[index - 1]; - SimulatorResourceModel resModel = resource->getModel(); - std::map attributes = - resModel.getAttributes(); - int size = 0; - for (auto & attribute : attributes) - { - std::cout << ++size << ": " << attribute.first.c_str() << std::endl; - } - - if (0 == size) - { - std::cout << "This resource doest not contain any attributes!" << std::endl; - return; - } - - int choice = -1; - std::cout << "Select the attribute which you want to automate for updation: " << - std::endl; - std::cin >> choice; - if (choice < 0 || choice > size) - { - std::cout << "Invalid selection!" << std::endl; - return; - } - - int count = 0; - std::string attributeName; - for (auto & attribute : attributes) - { - if (count == choice - 1) - { - attributeName = attribute.first; - break; - } - - count++; - } - - AutomationType type = AutomationType::NORMAL; - std::cout << "Press 1 if you want recurrent automation: "; - std::cin >> choice; - if (1 == choice) - type = AutomationType::RECURRENT; - - std::cout << "Requesting attribute automation for " << attributeName.c_str() << - std::endl; - - try - { - - int id = resource->startUpdateAutomation(attributeName, type, 500, - std::bind(&SimLightResource::onUpdateAutomationCompleted, this, - std::placeholders::_1, std::placeholders::_2)); - std::cout << "startUpdateAutomation() returned succces : " << id << std::endl; - } - catch (SimulatorException &e) - { - std::cout << "SimulatorException occured [Error: " << e.code() << " Details: " << - e.what() << "]" << std::endl; - } - } - - void stopAutomation() - { - int index = selectResource(); - if (-1 == index) - return; - - SimulatorResourceServerSP resource = m_resources[index - 1]; - - // Select the automation to stop - std::vector ids; - { - std::vector rids = resource->getResourceAutomationIds(); - std::vector 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 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 m_resources; -}; - -void printMainMenu() -{ - std::cout << "############### MAIN MENU###############" << std::endl; - std::cout << "1. Test simulation of resource" << std::endl; - std::cout << "2. Set Logger" << std::endl; - std::cout << "3. Help" << std::endl; - std::cout << "0. Exit" << std::endl; - std::cout << "######################################" << std::endl; -} - -void setLogger() -{ - std::cout << "1. Default console logger" << std::endl; - std::cout << "2. Default file logger" << std::endl; - std::cout << "3. custom logger" << std::endl; - - int choice = -1; - std::cin >> choice; - if (choice <= 0 || choice > 3) - { - std::cout << "Invalid selection !" << std::endl; - return; - } - - switch (choice) - { - case 1: - { - if (false == SimulatorManager::getInstance()->setConsoleLogger()) - std::cout << "Failed to set the default console logger" << std::endl; - } break; - case 2: - { - std::string filePath; - std::cout << "Enter the file path (without file name) : "; - std::cin >> filePath; - if (false == SimulatorManager::getInstance()->setFileLogger(filePath)) - std::cout << "Failed to set default file logger" << std::endl; - } break; - case 3: SimulatorManager::getInstance()->setLogger(gAppLogger); - } -} - -int main(int argc, char *argv[]) -{ - SimLightResource lightResource; - - printMainMenu(); - bool cont = true; - while (cont == true) - { - int choice = -1; - std::cout << "Enter your choice: "; - std::cin >> choice; - if (choice < 0 || choice > 3) - { - std::cout << "Invaild choice !" << std::endl; continue; - } - - switch (choice) - { - case 1: lightResource.startTest(); - std::cout << "Welcome back to main menu !" << std::endl; - break; - case 2: setLogger(); break; - case 3: printMainMenu(); break; - case 0: cont = false; - } - } - - std::cout << "Terminating test !!!" << std::endl; -} diff --git a/service/simulator/examples/server/simulator_server.cpp b/service/simulator/examples/server/simulator_server.cpp new file mode 100644 index 0000000..74f4b15 --- /dev/null +++ b/service/simulator/examples/server/simulator_server.cpp @@ -0,0 +1,446 @@ +/****************************************************************** + * + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +#include "simulator_manager.h" + +std::vector g_singleResources; +std::vector g_collectionResources; + +std::string getPropertyTypeString(SimulatorResourceModel::AttributeProperty::Type type) +{ + switch(type) + { + case SimulatorResourceModel::AttributeProperty::Type::RANGE: + return "RANGE"; + case SimulatorResourceModel::AttributeProperty::Type::VALUE_SET: + return "VALUE_SET"; + default: + break; + } + + return "UNKNOWN"; +} + +class AppLogger : public ILogger +{ + public: + void write(std::string time, ILogger::Level level, std::string message) + { + std::cout << "[APPLogger] " << time << " " << ILogger::getString(level) << " " + << message; + } +}; +std::shared_ptr gAppLogger(new AppLogger()); + +int selectResource() +{ + if (0 == g_singleResources.size()) + { + std::cout << "No resouces!" << std::endl; + return -1; + } + + int index = 1; + for (auto & resource : g_singleResources) + { + std::cout << index++ << ": " << resource->getURI().c_str() << std::endl; + } + + int choice = -1; + std::cout << "Choose the resource: "; + std::cin >> choice; + + if (choice < 1 || choice > index - 1) + { + std::cout << "Invalid choice !" << std::endl; + choice = -1; + } + + return choice; +} + +void simulateResource() +{ + try + { + // Resource model change callback + SimulatorResource::ResourceModelChangedCallback modelChangeCB = + [](const std::string &uri, SimulatorResourceModel &resModel) + { + std::cout << "[callback] Resource model is changed URI: " << uri.c_str() << std::endl; + std::cout << "#### Modified attributes are ####" << std::endl; + std::cout << "#### Updated resource model ####" << std::endl; + std::cout << resModel.toString() << std::endl; + std::cout << "########################" << std::endl; + }; + + // Observer added/removed callback + SimulatorResource::ObserverCallback observerCB = + [] (const std::string &uri, ObservationStatus state, const ObserverInfo &observerInfo) + { + std::cout << "[callback] Observer notification received..." << uri << std::endl; + + std::ostringstream out; + out << "ID: " << (int) observerInfo.id << std::endl; + out << " [address: " << observerInfo.address << " port: " << observerInfo.port + << "]" << std::endl; + std::cout << out.str(); + }; + + // Get the RAML file path from user + std::string configPath; + std::cout << "Enter RAML path: "; + std::cin>>configPath; + + SimulatorResourceSP resource = + SimulatorManager::getInstance()->createResource(configPath); + + // Add resource to appropriate list + if (SimulatorResource::Type::SINGLE_RESOURCE == resource->getType()) + { + std::cout << "Single type resource created [URI: " << resource->getURI() << " ]" << std::endl; + SimulatorSingleResourceSP singleRes = + std::dynamic_pointer_cast(resource); + singleRes->setModelChangeCallback(modelChangeCB); + singleRes->setObserverCallback(observerCB); + g_singleResources.push_back(singleRes); + } + else + { + std::cout << "Collection type resource created [URI: " << resource->getURI() << " ]" << std::endl; + SimulatorCollectionResourceSP collectionRes = + std::dynamic_pointer_cast(resource); + collectionRes->setObserverCallback(observerCB); + g_collectionResources.push_back(collectionRes); + } + } + catch (InvalidArgsException &e) + { + std::cout << "InvalidArgsException occured [code : " << e.code() << " Details: " + << e.what() << "]" << std::endl; + } + catch (SimulatorException &e) + { + std::cout << "SimulatorException occured [code : " << e.code() << " Details: " + << e.what() << "]" << std::endl; + } +} + +void displayResource() +{ + int index = selectResource(); + if (-1 == index) + return; + + SimulatorSingleResourceSP resource = g_singleResources[index - 1]; + + std::cout << "#############################" << std::endl; + std::cout << "Name: " << resource->getName() << std::endl; + std::cout << "URI: " << resource->getURI() << std::endl; + std::cout << "Resource type: " << resource->getResourceType() << std::endl; + std::cout << "Interface type:"; + for (auto &interfaceType : resource->getInterface()) + std::cout << " " << interfaceType << std::endl; + + // Attributes + SimulatorResourceModel resModel = resource->getResourceModel(); + std::map attributes = + resModel.getAttributes(); + std::cout << "##### Attributes [" << attributes.size() << "]" << std::endl; + for (auto & attribute : attributes) + { + std::cout << (attribute.second).getName() << " : {" << std::endl; + std::cout << "value: " << (attribute.second).toString() << std::endl; + SimulatorResourceModel::AttributeProperty prop = (attribute.second).getProperty(); + std::cout << "Supported values given by : " << getPropertyTypeString(prop.type()) << std::endl; + if (SimulatorResourceModel::AttributeProperty::Type::RANGE == prop.type()) + { + std::cout << "Min: " << prop.min() << std::endl; + std::cout << "Max: " << prop.max() << std::endl; + } + else if (SimulatorResourceModel::AttributeProperty::Type::VALUE_SET == prop.type()) + { + std::cout << "Value set: " << prop.valueSetToString() << std::endl; + } + + std::cout << "}" << std::endl << std::endl; + } + std::cout << "#############################" << std::endl; +} + +void startResource() +{ + int index = selectResource(); + if (-1 == index) + return; + + SimulatorSingleResourceSP resource = g_singleResources[index - 1]; + resource->start(); + std::cout << "Resource started!" << std::endl; +} + +void stopResource() +{ + int index = selectResource(); + if (-1 == index) + return; + + SimulatorSingleResourceSP resource = g_singleResources[index - 1]; + resource->stop(); + std::cout << "Resource stopped!" << std::endl; +} + +void automateResourceUpdate() +{ + updateCompleteCallback callback = [](const std::string &uri, const int id) + { + std::cout << "Update automation is completed [URI: " << uri + << " AutomationID: " << id << "] ###" << std::endl; + }; + + int index = selectResource(); + if (-1 == index) + return; + + AutomationType type = AutomationType::NORMAL; + int choice = 0; + std::cout << "Press 1 if you want recurrent automation: "; + std::cin >> choice; + if (1 == choice) + type = AutomationType::RECURRENT; + + try + { + int id = g_singleResources[index - 1]->startResourceUpdation(type, -1, callback); + + std::cout << "startUpdateAutomation() returned succces : " << id << std::endl; + } + catch (SimulatorException &e) + { + std::cout << "SimulatorException occured [code : " << e.code() << " Details: " << + e.what() << "]" << std::endl; + } +} + +void automateAttributeUpdate() +{ + updateCompleteCallback callback = [](const std::string &uri, const int id) + { + std::cout << "Update automation is completed [URI: " << uri + << " AutomationID: " << id << "] ###" << std::endl; + }; + + int index = selectResource(); + if (-1 == index) + return; + + SimulatorSingleResourceSP resource = g_singleResources[index - 1]; + SimulatorResourceModel resModel = resource->getResourceModel(); + std::map attributes = + resModel.getAttributes(); + int size = 0; + for (auto & attribute : attributes) + { + std::cout << ++size << ": " << attribute.first.c_str() << std::endl; + } + + if (0 == size) + { + std::cout << "This resource doest not contain any attributes!" << std::endl; + return; + } + + int choice = -1; + std::cout << "Select the attribute which you want to automate for updation: " << + std::endl; + std::cin >> choice; + if (choice < 0 || choice > size) + { + std::cout << "Invalid selection!" << std::endl; + return; + } + + int count = 0; + std::string attributeName; + for (auto & attribute : attributes) + { + if (count == choice - 1) + { + attributeName = attribute.first; + break; + } + + count++; + } + + AutomationType type = AutomationType::NORMAL; + std::cout << "Press 1 if you want recurrent automation: "; + std::cin >> choice; + if (1 == choice) + type = AutomationType::RECURRENT; + + std::cout << "Requesting attribute automation for " << attributeName << + std::endl; + + try + { + + int id = resource->startAttributeUpdation(attributeName, type, -1, callback); + std::cout << "startUpdateAutomation() returned succces : " << id << std::endl; + } + catch (SimulatorException &e) + { + std::cout << "SimulatorException occured [Error: " << e.code() << " Details: " << + e.what() << "]" << std::endl; + } +} + +void stopAutomation() +{ + int index = selectResource(); + if (-1 == index) + return; + + SimulatorSingleResourceSP resource = g_singleResources[index - 1]; + + // Select the automation to stop + std::vector ids; + { + std::vector rids = resource->getResourceUpdationIds(); + std::vector aids = resource->getAttributeUpdationIds(); + ids.insert(ids.end(), rids.begin(), rids.end()); + ids.insert(ids.end(), aids.begin(), aids.end()); + } + + if (!ids.size()) + { + std::cout << "No automation operation is going on this resource right now!" << + std::endl; + return; + } + + for (auto & id : ids) + { + std::cout << id << " "; + resource->stopUpdation(id); + } +} + +void getObservers() +{ + int index = selectResource(); + if (-1 == index) + return; + + SimulatorSingleResourceSP resource = g_singleResources[index - 1]; + + std::vector observersList = resource->getObserversList(); + + std::cout << "##### Number of Observers [" << observersList.size() << "]" << std::endl; + for (auto & observerInfo : observersList) + { + std::cout << " ID : " << (int) observerInfo.id << " [address: " << + observerInfo.address << " port: " << observerInfo.port << "]" << std::endl; + } + std::cout << "########################" << std::endl; +} + +void printMainMenu() +{ + std::cout << "############### MAIN MENU###############" << std::endl; + std::cout << "1. Simulate resource" << std::endl; + std::cout << "2. Display resource information" << std::endl; + std::cout << "3. Start resource" << std::endl; + std::cout << "4. Stop resource" << std::endl; + std::cout << "5. Automate resource update" << std::endl; + std::cout << "6. Automate attributes update" << std::endl; + std::cout << "7. Stop Automation" << std::endl; + std::cout << "8. Get Observers of a resource" << std::endl; + std::cout << "9. Set Logger" << std::endl; + std::cout << "10. Help" << std::endl; + std::cout << "0. Exit" << std::endl; + std::cout << "######################################" << std::endl; +} + +void setLogger() +{ + std::cout << "1. Default console logger" << std::endl; + std::cout << "2. Default file logger" << std::endl; + std::cout << "3. custom logger" << std::endl; + + int choice = -1; + std::cin >> choice; + if (choice <= 0 || choice > 3) + { + std::cout << "Invalid selection !" << std::endl; + return; + } + + switch (choice) + { + case 1: + { + if (false == SimulatorManager::getInstance()->setConsoleLogger()) + std::cout << "Failed to set the default console logger" << std::endl; + } break; + case 2: + { + std::string filePath; + std::cout << "Enter the file path (without file name) : "; + std::cin >> filePath; + if (false == SimulatorManager::getInstance()->setFileLogger(filePath)) + std::cout << "Failed to set default file logger" << std::endl; + } break; + case 3: SimulatorManager::getInstance()->setLogger(gAppLogger); + } +} + +int main(int argc, char *argv[]) +{ + printMainMenu(); + bool cont = true; + while (cont == true) + { + int choice = -1; + std::cout << "Enter your choice: "; + std::cin >> choice; + if (choice < 0 || choice > 10) + { + std::cout << "Invaild choice !" << std::endl; continue; + } + + switch (choice) + { + case 1 : simulateResource(); break; + case 2 : displayResource(); break; + case 3 : startResource(); break; + case 4 : stopResource(); break; + case 5 : automateResourceUpdate(); break; + case 6 : automateAttributeUpdate(); break; + case 7 : stopAutomation(); break; + case 8 : getObservers(); break; + case 9: setLogger(); break; + case 10: printMainMenu(); break; + case 0: cont = false; + } + } + + std::cout << "Terminating test !!!" << std::endl; +} diff --git a/service/simulator/inc/simulator_collection_resource.h b/service/simulator/inc/simulator_collection_resource.h new file mode 100644 index 0000000..88addd0 --- /dev/null +++ b/service/simulator/inc/simulator_collection_resource.h @@ -0,0 +1,68 @@ +/****************************************************************** + * + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +#ifndef SIMULATOR_COLLECTION_RESOURCE_H_ +#define SIMULATOR_COLLECTION_RESOURCE_H_ + +#include "simulator_resource.h" + +class SimulatorCollectionResource : public SimulatorResource +{ + public: + + /** + * API to get list of resources types which collection supports. + * + * @return List of supported resources types. + */ + virtual std::vector getSupportedResources() = 0; + + /** + * API to add a child resource to collection. + * + * @param resource - SimulatorResource shared object. + */ + virtual void addChildResource(SimulatorResourceSP &resource) = 0; + + /** + * API to remove a child resource from collection. + * + * @param resource - SimulatorResource shared object. + */ + virtual void removeChildResource(SimulatorResourceSP &resource) = 0; + + /** + * API to remove a child resource from collection. + * + * @param uri - URI of child resource to be removed. + */ + virtual void removeChildResource(const std::string &uri) = 0; + + /** + * API to get child resources of collection. + * + * @return List of child resources of collection. + */ + virtual std::vector getChildResources() = 0; +}; + +typedef std::shared_ptr SimulatorCollectionResourceSP; + +#endif diff --git a/service/simulator/inc/simulator_manager.h b/service/simulator/inc/simulator_manager.h index 662ea3e..5b3d76e 100644 --- a/service/simulator/inc/simulator_manager.h +++ b/service/simulator/inc/simulator_manager.h @@ -32,7 +32,8 @@ #include "simulator_client_types.h" #include "simulator_device_info.h" #include "simulator_platform_info.h" -#include "simulator_resource_server.h" +#include "simulator_single_resource.h" +#include "simulator_collection_resource.h" #include "simulator_remote_resource.h" #include "simulator_exceptions.h" #include "simulator_logger.h" @@ -57,15 +58,13 @@ class SimulatorManager * RAML file. * * @param configPath - RAML configuration file path. - * @param callback - Callback method for receiving notifications when resource model changes. * - * @return SimulatorResourceServer shared object representing simulated/created resource. + * @return SimulatorResource shared object representing simulated/created resource. * * NOTE: API would throw @InvalidArgsException when invalid arguments passed, and * @SimulatorException if any other error occured. */ - std::shared_ptr createResource(const std::string &configPath, - SimulatorResourceServer::ResourceModelChangedCB callback); + std::shared_ptr createResource(const std::string &configPath); /** * This method is for creating multiple resources of same type based on the input data @@ -75,45 +74,20 @@ class SimulatorManager * @param count - Number of resource to be created. * @param callback - Callback method for receiving notifications when resource model changes. * - * @return vector of SimulatorResourceServer shared objects representing simulated/created + * @return vector of SimulatorResource shared objects representing simulated/created * resources. * * NOTE: API would throw @InvalidArgsException when invalid arguments passed, and * @SimulatorException if any other error occured. */ - std::vector> 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> getResources( - const std::string &resourceType = ""); + std::vector> createResource( + const std::string &configPath, unsigned int count); - /** - * This method is for deleting/unregistering resource. - * - * @param resource - SimulatorResourceServer shared object. - * - * NOTE: API would throw @InvalidArgsException when invalid arguments passed - */ - void deleteResource(const std::shared_ptr &resource); + std::shared_ptr createSingleResource( + const std::string &name, const std::string &uri, const std::string &resourceType); - /** - * This method is for deleting multiple resources based on resource type. - * - * @param resourceType - Resource type. Empty value will delete all the resources. - * Default value is empty string. - * - * NOTE: API would throw @InvalidArgsException when invalid arguments passed - */ - void deleteResource(const std::string &resourceType = ""); + std::shared_ptr createCollectionResource( + const std::string &name, const std::string &uri, const std::string &resourceType); /** * API for discovering all type of resources. diff --git a/service/simulator/inc/simulator_remote_resource.h b/service/simulator/inc/simulator_remote_resource.h index 5388bcc..917b6ac 100644 --- a/service/simulator/inc/simulator_remote_resource.h +++ b/service/simulator/inc/simulator_remote_resource.h @@ -30,12 +30,14 @@ #include "simulator_client_types.h" #include "simulator_resource_model.h" +#include "simulator_uncopyable.h" +#include "simulator_exceptions.h" /** * @class SimulatorRemoteResource * @brief This class provides a set of functions for the client to hande the resources currently running on the servers. */ -class SimulatorRemoteResource +class SimulatorRemoteResource : public UnCopyable { public: @@ -150,7 +152,7 @@ class SimulatorRemoteResource virtual void stopVerification(int id) = 0; - virtual void configure(const std::string &path) = 0; + virtual SimulatorResourceModelSP configure(const std::string &path) = 0; }; typedef std::shared_ptr SimulatorRemoteResourceSP; diff --git a/service/simulator/inc/simulator_resource.h b/service/simulator/inc/simulator_resource.h new file mode 100644 index 0000000..d5b99ca --- /dev/null +++ b/service/simulator/inc/simulator_resource.h @@ -0,0 +1,215 @@ +/****************************************************************** + * + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +#ifndef SIMULATOR_RESOURCE_H_ +#define SIMULATOR_RESOURCE_H_ + +#include "simulator_server_types.h" +#include "simulator_resource_model.h" +#include "simulator_uncopyable.h" +#include "simulator_exceptions.h" + +class SimulatorResource : public UnCopyable +{ + public: + enum class Type + { + SINGLE_RESOURCE, + COLLECTION_RESOURCE + }; + + /** + * Callback method for receiving notifications when resource representation model changes. + * + * @param uri - URI of resource whose representation model got changed. + * @param resModel - Resource model. + */ + typedef std::function + ResourceModelChangedCallback; + + /** + * Callback method for receiving notifications when observer is registered/unregistered + * with resource. + * + * @param uri - Resource URI + * @param state - OBSERVE_REGISTER if observer is registered, otherwise OBSERVE_UNREGISTER. + * @param observerInfo - Information about observer. + */ + typedef std::function + ObserverCallback; + + /** + * API to get the name of the resource. + * + * @return Resource name. + */ + virtual std::string getName() const = 0; + + /** + * API to get the type which indicates whether resource is single or collection resource. + * + * @return Type of resource. + */ + virtual SimulatorResource::Type getType() const = 0; + + /** + * API to get the resource URI. + * + * @return Resource URI. + */ + virtual std::string getURI() const = 0; + + /** + * API to get the resource type. + * + * @return Resource type. + */ + virtual std::string getResourceType() const = 0; + + /** + * API to get the interfaces resource is bound with. + * + * @return Interface type. + */ + virtual std::vector getInterface() const = 0; + + /** + * API to get the observable state of resource. + * + * @return bool - true if resource is observable, otherwise false. + */ + virtual bool isObservable() = 0; + + /** + * API to get the start state of resource. + * + * @return bool - true if resource is started, otherwise false. + */ + virtual bool isStarted() = 0; + + /** + * API to get SimulatorResourceModel of resource. + * + * @return Resource model of the resource. + */ + virtual SimulatorResourceModel getResourceModel() = 0; + + /** + * API to set the name of the resource. + * + * @param name - Name to be set. + * + * NOTE: API throws @InvalidArgsException, @SimulatorException exceptions. + */ + virtual void setName(const std::string &name) = 0; + + /** + * API to set the resource URI. + * + * @param uri - URI to be set. + * + * NOTE: API throws @InvalidArgsException, @SimulatorException exceptions. + */ + virtual void setURI(const std::string &uri) = 0; + + /** + * API to set the resource type. + * + * @param resourceType - resource type string. + * + * NOTE: API throws @InvalidArgsException, @SimulatorException exceptions. + */ + virtual void setResourceType(const std::string &resourceType) = 0; + + /** + * API to add interface type for resource. + * + * @param interfaceType - interface to be added for resource. + * + * NOTE: API throws @InvalidArgsException, @SimulatorException exceptions. + */ + virtual void addInterface(std::string interfaceType) = 0; + + /** + * API to make the resource observable or not. + * + * @param state - true make the resource observable, otherwise non-observable. + * + * NOTE: API throws @SimulatorException exceptions. + */ + virtual void setObservable(bool state) = 0; + + /** + * API to set the callback for receiving the notifications when + * observer is registered or unregistered with resource. + * + * @param callback - Callback to be set for receiving the notifications. + */ + virtual void setObserverCallback(ObserverCallback callback) = 0; + + /** + * API to set the callback for receiving the notifications when the + * resource model changes. + * + * @param callback - Callback to be set for receiving the notifications. + */ + virtual void setModelChangeCallback(ResourceModelChangedCallback callback) = 0; + + /** + * API to start the resource. + * + * NOTE: API throws @SimulatorException exception. + */ + virtual void start() = 0; + + /** + * API to stop the resource. + * + * NOTE: API throws @SimulatorException exception. + */ + virtual void stop() = 0; + + /** + * API to get observers which are registered with resource. + * + * @return vector of ObserverInfo. + */ + virtual std::vector getObserversList() = 0; + + /** + * API to notify current resource model to specific observer. + * + * @param id - Observer ID to notify. + * + * NOTE: API throws @SimulatorException exception. + */ + virtual void notify(int id) = 0; + + /** + * API to notify all registered observers. + * + * NOTE: API throws @SimulatorException exception. + */ + virtual void notifyAll() = 0; +}; + +typedef std::shared_ptr SimulatorResourceSP; + +#endif diff --git a/service/simulator/inc/simulator_resource_model.h b/service/simulator/inc/simulator_resource_model.h index d596ed9..40a112b 100644 --- a/service/simulator/inc/simulator_resource_model.h +++ b/service/simulator/inc/simulator_resource_model.h @@ -28,10 +28,11 @@ #ifndef SIMULATOR_RESOURCE_MODEL_H_ #define SIMULATOR_RESOURCE_MODEL_H_ -#include -#include #include "OCPlatform.h" -#include +#include + +class OCRepresentationBuilder; +class ToStringConverter; /** * @class SimulatorResourceModel @@ -40,300 +41,215 @@ class SimulatorResourceModel { public: - SimulatorResourceModel() = default; - SimulatorResourceModel(const SimulatorResourceModel &) = default; - SimulatorResourceModel &operator=(const SimulatorResourceModel &) = default; - SimulatorResourceModel(SimulatorResourceModel &&) = default; - SimulatorResourceModel &operator=(SimulatorResourceModel && ) = default; + friend class OCRepresentationBuilder; + friend class ToStringConverter; + + typedef boost::variant < + int, + double, + bool, + std::string, + SimulatorResourceModel, + + std::vector, + std::vector, + std::vector, + std::vector, + std::vector, + + std::vector>, + std::vector>, + std::vector>, + std::vector>, + std::vector>, + + std::vector>>, + std::vector>>, + std::vector>>, + std::vector>>, + std::vector>> + > ValueVariant; + + enum class ValueType + { + UNKNOWN, + INTEGER, + DOUBLE, + BOOLEAN, + STRING, + RESOURCE_MODEL, + VECTOR + }; - /** - * @class Attribute - * @brief This class represents a resource attribute whose values can be generic. - */ - class Attribute + class TypeInfo { public: - typedef boost::variant < - int, - double, - bool, - std::string - > ValueVariant; - - enum class ValueType + TypeInfo(ValueType, ValueType, int); + TypeInfo(const TypeInfo &) = default; + TypeInfo &operator=(const TypeInfo &) = default; + TypeInfo(TypeInfo &&) = default; + TypeInfo &operator=(TypeInfo &&) = default; + + ValueType type() const; + ValueType baseType() const; + int depth() const; + bool operator ==(const TypeInfo &) const; + bool operator !=(const TypeInfo &) const; + + private: + ValueType m_type; + ValueType m_baseType; + int m_depth; + }; + + class AttributeProperty + { + public: + enum class Type { UNKNOWN, - INTEGER, - DOUBLE, - BOOLEAN, - STRING + RANGE, + VALUE_SET }; - Attribute() - { - m_min = INT_MIN; - m_max = INT_MAX; - m_updateInterval = -1; - } + AttributeProperty(); + AttributeProperty(const AttributeProperty &) = default; + AttributeProperty &operator=(const AttributeProperty &) = default; + AttributeProperty(AttributeProperty &&) = default; + AttributeProperty &operator=(AttributeProperty &&) = default; + + explicit AttributeProperty(double min, double max); + explicit AttributeProperty(const std::vector &valueSet); + explicit AttributeProperty(const std::vector &valueSet); + explicit AttributeProperty(const std::vector &valueSet); + explicit AttributeProperty(const std::vector &valueSet); + explicit AttributeProperty(const std::vector &valueSet); + + Type type() const; + double min() const; + double max() const; + int valueSetSize() const; + std::vector valueSet() const; + std::string valueSetToString() const; + void setChildProperty(AttributeProperty &childProperty); + std::shared_ptr getChildProperty(); - Attribute(const std::string &attrName) - { - m_name = attrName; - m_min = INT_MIN; - m_max = INT_MAX; - m_updateInterval = -1; - } + private: + Type m_type; + double m_min; + double m_max; + std::vector m_valueSet; + std::shared_ptr m_childProperty; + }; - /** - * API to get attribute's name. - * - * @return Attribute name. - */ - std::string getName(void) const; - - /** - * API to set the name of attribute. - * - * @param name - Attribute name. - */ - void setName(const std::string &name); - - /** - * API to get attribute's value. - * - * @return value of attribute. - */ - template - T getValue() const - { - T val = T(); - return boost::get(m_value); - } + class Attribute + { + public: + Attribute(const std::string &name) : m_name(name) {} + Attribute() = default; + Attribute(const Attribute &) = default; + Attribute &operator=(const Attribute &) = default; + Attribute(Attribute &&) = default; + Attribute &operator=(Attribute &&) = default; - /** - * API to get attribute's value. - * - * @return value of attribute as ValueVariant. - */ - ValueVariant &getValue() - { - return m_value; - } + std::string getName() const; + TypeInfo getType() const; + const AttributeProperty &getProperty() const; + AttributeProperty &getProperty(); - /** - * API to get attribute's value type. - * - * @return ValueType enum. - */ - ValueType getValueType() const; - - /** - * API to set the attribute's value. - * - * @param value - value to be set. - */ - template - void setValue(const T &value) - { - m_value = value; - } + void setName(const std::string &); + void setProperty(const AttributeProperty &); - /** - * API to set the attribute's value from allowed values container. - * - * @param allowedValueIndex - Index of value to be set from allowed vaules container. - */ - void setFromAllowedValue(unsigned int index); - - /** - * API to get range of attribute's value. - */ - void getRange(int &min, int &max) const; - - /** - * API to set range of attribute's value. - * - * @param min - minimum value could be set as attribute value. - * @param max - maximum value could be set as attribute value. - */ - void setRange(const int &min, const int &max); - - /** - * API to set the values to allowed values set. - * - * @param values - vector of values which will be set as allowed values. - */ template - bool setAllowedValues(const std::vector &values) + void setValue(const T &value) { - ValueVariant temp = values.at(0); - if (temp.which() != m_value.which()) - { - return false; - } - - m_allowedValues.addValues(values); - return true; + m_value = std::make_shared(value); } - /** - * API to get the number of values present in allowed values set. - * - * @return Size of the allowed values. - */ - int getAllowedValuesSize() const; + ValueVariant getValue() const { return *m_value; } - /** - * API to get the string representation of the value. - * - * @return Attribute's value as a string. - */ - std::string valueToString() const; - - /** - * API to get the string representation of all the allowed values. - * - * @return All allowed values as a string. - */ - std::vector allowedValuesToString() const; - - void addValuetoRepresentation(OC::OCRepresentation &rep, - const std::string &key) const; - - bool compare(Attribute &attribute); - - std::vector getAllowedValues() const; - - int getUpdateFrequencyTime() {return m_updateInterval;} - void setUpdateFrequencyTime(int interval) {m_updateInterval = interval;} + std::string toString() const; private: - class AllowedValues - { - public: - template - void addValue(const T &value) - { - ValueVariant temp = value; - m_values.push_back(temp); - } - - template - void addValues(const std::vector &values) - { - for (auto value : values) - { - ValueVariant vValue = value; - m_values.push_back(vValue); - } - } - - ValueVariant &at(unsigned int index); - int size() const; - std::vector toString() const; - std::vector getValues() const; - private: - std::vector m_values; - }; - std::string m_name; - ValueVariant m_value; - int m_max; - int m_min; - AllowedValues m_allowedValues; - int m_updateInterval; + std::shared_ptr m_value; + AttributeProperty m_property; }; - /** - * API to get the number of attributes in the resource model. - * - * @return Number of attributes. - */ - int size() const { return m_attributes.size(); } - - /** - * API to get the value of an attribute. - * - * @param attrName - Attribute name - * @param value - Attribute value - * - * @return true if attribute exists, otherwise false. - */ - bool getAttribute(const std::string &attrName, Attribute &value); - - /** - * API to get the entire list of attributes in the form of key-value pair. - * Attribute name is the key and an instance of Attribute is the value. - * - * @return A map of all the attributes - */ - std::map getAttributes() const; - - /** - * API to add new attribute to resource model. - * - * @param attrName - Attribute name - * @param attrValue - Attribute value - */ + SimulatorResourceModel() = default; + SimulatorResourceModel(const SimulatorResourceModel &) = default; + SimulatorResourceModel &operator=(const SimulatorResourceModel &) = default; + SimulatorResourceModel(SimulatorResourceModel &&) = default; + SimulatorResourceModel &operator=(SimulatorResourceModel && ) = default; + template - void addAttribute(const std::string &attrName, const T &attrValue) + bool add(const std::string &key, T value) { - if (m_attributes.end() == m_attributes.find(attrName)) - { - m_attributes[attrName] = Attribute(attrName); - m_attributes[attrName].setValue(attrValue); - } + ValueVariant newValue = value; + return setAttributeValue(key, newValue, true, false); } - /** - * API to add new attribute to resource model. - * - * @param attr - Attribute pointer - * - */ - void addAttribute(const Attribute &attribute, bool overwrite = false); - - /** - * API to set range of attribute value. - * - * @param attrName - Attribute name. - * @param min - Minimum value could be set as attribute value. - * @param max - Maximum value could be set as attribute value. - */ - void setRange(const std::string &attrName, const int min, const int max); - - OC::OCRepresentation getOCRepresentation() const; - static std::shared_ptr create(const OC::OCRepresentation &ocRep); + bool add(const Attribute &attribute); template - void setAllowedValues(const std::string &attrName, const std::vector &values) + T get(const std::string &key) const { - if (m_attributes.end() != m_attributes.find(attrName)) - m_attributes[attrName].setAllowedValues(values); + T val = T(); + auto x = m_attributes.find(key); + if (x != m_attributes.end()) + { + val = boost::get(x->second); + } + return val; } - bool update(OC::OCRepresentation &ocRep); - - bool update(std::shared_ptr &repModel); - template - void updateAttribute(const std::string &attrName, const T &value) + bool updateValue(const std::string &key, T value, bool forcewrite = false) { - if (m_attributes.end() != m_attributes.find(attrName)) - m_attributes[attrName].setValue(value); + ValueVariant newValue = value; + return setAttributeValue(key, newValue, false, forcewrite); } - void updateAttributeFromAllowedValues(const std::string &attrName, unsigned int index); + bool updateValue(const Attribute &attribute, bool forcewrite = false); + + bool containsAttribute(const std::string &key); + + bool setAttributeProperty(const std::string &key, const AttributeProperty &property); + + bool getAttributeProperty(const std::string &key, AttributeProperty &property); + + int size() const; + + TypeInfo getType(const std::string &key); + + std::map getAttributes(); + + bool getAttribute(const std::string &key, Attribute &attribute); + + bool removeAttribute(const std::string &key); + + bool update(OC::OCRepresentation &ocRep); + + OC::OCRepresentation getOCRepresentation(); + + bool match(const SimulatorResourceModel &resModel, bool strict = false); - void removeAttribute(const std::string &attrName); + std::string toString() const; - void setUpdateInterval(const std::string &attrName, int interval); + static SimulatorResourceModel build(const OC::OCRepresentation &ocRep); private: - std::map m_attributes; + TypeInfo getTypeInfo(const ValueVariant &value) const; + bool setAttributeValue(const std::string &key, const ValueVariant &newValue, + bool create, bool overwrite); + bool match(const std::string &key, const ValueVariant &newValue); + bool update(SimulatorResourceModel &resModel); + std::map getValues() const; + + std::map m_attributes; + std::map m_attrProperties; }; typedef std::shared_ptr SimulatorResourceModelSP; -typedef std::shared_ptr AttributeSP; #endif diff --git a/service/simulator/inc/simulator_resource_server.h b/service/simulator/inc/simulator_resource_server.h deleted file mode 100644 index b6f61a1..0000000 --- a/service/simulator/inc/simulator_resource_server.h +++ /dev/null @@ -1,290 +0,0 @@ -/****************************************************************** - * - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************/ - -/** - * @file simulator_resource_server.h - * - * @brief This file contains a class which represents a simulator resource that provides a set - * of functions for operating a resource and performing automation on attribute values. - */ - -#ifndef SIMULATOR_RESOURCE_SERVER_H_ -#define SIMULATOR_RESOURCE_SERVER_H_ - -#include "simulator_server_types.h" -#include "simulator_resource_model.h" -#include "simulator_exceptions.h" - -enum class ObservationStatus : unsigned char -{ - OBSERVE_REGISTER, - OBSERVE_UNREGISTER -}; - -typedef struct -{ - uint8_t id; - std::string address; - uint16_t port; -} ObserverInfo; - -/** - * @class SimulatorResourceServer - * @brief This class provides a set of functions for operating and automating a resource. - */ -class SimulatorResourceServer -{ - public: - /** - * Callback method for receiving notifications when resource model gets changed. - * - * @param uri - Resource URI - * @param resModel - Resource model - */ - typedef std::function - 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 - 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 - void setAllowedValues(const std::string &attrName, const std::vector &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 - void updateAttributeValue(const std::string &attrName, const T &value) - { - m_resModel.updateAttribute(attrName, value); - - // Notify all the subscribers - notifyAll(); - } - - /** - * API to update the attribute's value by taking the index of the value - * in the allowed values range. - * - * @param attrName - Name of the attribute - * @param allowedValueIndex - Index of the value in the allowed values range - */ - void updateFromAllowedValues(const std::string &attrName, unsigned int index); - - /** - * API to remove an attribute from the resource model. - * - * @param attName - Name of the attribute to be removed - */ - void removeAttribute(const std::string &attName); - - /** - * API to get the object of SimulatorResourceModel. - * Attributes of the resource are accessed using this object. - * - * @return Resource model of the resource. - */ - SimulatorResourceModel getModel() const; - - /** - * API to get the observable state of resource. - * - * @return bool - true if resource is observable, otherwise false. - */ - virtual bool isObservable() const = 0; - - /** - * API to start the attribute value automation for all attributes. - * Once started, values for the attributes will be selected randomly from their allowed range - * and the updated values will be notified to all the observers of the resource. - * - * @param type - Automation type. - * @param callback - Callback to get notifiy when update automation is finished. - * @param id - Identifier for automation. - * - * @return ID representing update automation session. - * NOTE: API throws @InvalidArgsException, @SimulatorException exceptions. - */ - virtual int startUpdateAutomation(AutomationType type, int updateInterval, - updateCompleteCallback callback) = 0; - - /** - * This method is used to start the attribute value automation for a specific attribute. - * Once started, values for the attribute will be selected randomly from its allowed range - * and the updated value will be notified to all the observers of the resource. - * - * @param attrName - Name of the attribute to be automated. - * @param type - Automation type. - * @param updateInterval -Interval time in milliseconds for attribute value update automation. - * @param callback - Callback to get notifiy when update automation is finished. - * @param id - Identifier for automation. - * - * @return ID representing update automation session. - * NOTE: API throws @InvalidArgsException, @SimulatorException exceptions. - */ - virtual int startUpdateAutomation(const std::string &attrName, AutomationType type, - int updateInterval, updateCompleteCallback callback) = 0; - - /** - * API to get the Ids of all ongoing resource update automation . - * - * @return vector of resource automation ids. - */ - virtual std::vector getResourceAutomationIds() = 0; - - /** - * API to get the Ids of all ongoing attribute update automation . - * - * @return vector of attribute automation ids. - */ - virtual std::vector 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 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 SimulatorResourceServerSP; - -#endif diff --git a/service/simulator/inc/simulator_server_types.h b/service/simulator/inc/simulator_server_types.h index 2449d0a..9d92977 100644 --- a/service/simulator/inc/simulator_server_types.h +++ b/service/simulator/inc/simulator_server_types.h @@ -24,6 +24,19 @@ #include #include +enum class ObservationStatus +{ + REGISTER, + UNREGISTER +}; + +typedef struct +{ + uint8_t id; + std::string address; + uint16_t port; +} ObserverInfo; + enum class AutomationType { NORMAL, diff --git a/service/simulator/inc/simulator_single_resource.h b/service/simulator/inc/simulator_single_resource.h new file mode 100644 index 0000000..3fb7935 --- /dev/null +++ b/service/simulator/inc/simulator_single_resource.h @@ -0,0 +1,182 @@ +/****************************************************************** + * + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +/** + * @file simulator_single_resource.h + * + * @brief This file contains a class which represents a simulator resource that provides a set + * of functions for operating a resource and performing automation on attribute values. + */ + +#ifndef SIMULATOR_SINGLE_RESOURCE_H_ +#define SIMULATOR_SINGLE_RESOURCE_H_ + +#include "simulator_resource.h" + +/** + * @class SimulatorSingleResource + * @brief This class provides a set of APIs for handling simulated resource. + */ +class SimulatorSingleResource : public SimulatorResource +{ + public: + + /** + * API to get attribute from resource's resource model. + * + * @param attrName - Attribute's name. + * @param attribute - A attribute of resource's resource model. + * + * @return bool - true on success, otherwise false. + */ + virtual bool getAttribute(const std::string &attrName, + SimulatorResourceModel::Attribute &attribute) = 0; + + /** + * API to add a new attribute to the resource model. + * + * @param attribute - Attribute to be add to model. + * @param notify - If value is true then notification will be send to observers on success. + * This flag is set to true by default. + * + * NOTE: API throws @SimulatorException exceptions on failure. + */ + virtual void addAttribute(const SimulatorResourceModel::Attribute &attribute, + bool notify = true) = 0; + + /** + * API to get property of attribute's value. + * + * @param attrName - Attribute's name. + * @param property - Property which was set to attribute's value. + * + * @return bool - true on success, otherwise false. + */ + virtual bool getAttributeProperty(const std::string &attrName, + SimulatorResourceModel::AttributeProperty &property) = 0; + + /** + * API to set property of attribute's value. + * + * @param attrName - Attribute's name. + * @param property - Property to be set for attribute's value. + * + * @return bool - true on success, otherwise false. + */ + virtual bool setAttributeProperty(const std::string &attrName, + const SimulatorResourceModel::AttributeProperty &property) = 0; + + /** + * API to remove an attribute from the resource model. + * + * @param attrName - Name of the attribute to be removed. + * @param notify - If value is true then notification will be send to observers on success. + * This flag is set to true by default. + * + * @return bool - true on success, otherwise false. + */ + virtual bool removeAttribute(const std::string &attrName, bool notify = true) = 0; + + /** + * API to update the value of an attribute. + * + * @param attrName - Name of the attribute. + * @param value - Value of the attribute. + * @param notify - If value is true then notification will be send to observers on success. + * This flag is set to true by default. + */ + template + bool updateAttributeValue(const std::string &attrName, const T &value, bool notify = true) + { + SimulatorResourceModel::Attribute attribute(attrName); + attribute.setValue(value); + return updateAttributeValue(attribute, notify); + } + + /** + * API to update the value of an attribute. + * + * @param attribute - A resource model attribute. + * @param notify - If value is true then notification will be send to observers on success. + * This flag is set to true by default. + * + * @return bool - true on success, otherwise false. + */ + virtual bool updateAttributeValue(const SimulatorResourceModel::Attribute &attribute, + bool notify = true) = 0; + + /** + * API to start the attribute value update automation for all attributes. + * Values for the attributes will be selected from their allowed range + * and the updated resource model will be notified to all the observers of the resource. + * + * @param type - Automation type. + * @param updateInterval - Time in milliseconds to be set as interval between updating + * attribute values. + * @param callback - Callback to get notifiy when update automation is finished. + * + * @return ID representing update automation session. + * NOTE: API throws @InvalidArgsException, @SimulatorException exceptions. + */ + virtual int startResourceUpdation(AutomationType type, int updateInterval, + updateCompleteCallback callback) = 0; + + /** + * This method is used to start the attribute value update automation for + * specific attribute. Values for the attribute will be selected from its allowed range + * and the updated resource model will be notified to all the observers of the resource. + * + * @param attrName - Name of the attribute to be automated. + * @param type - Automation type. + * @param updateInterval - Time in milliseconds to be set as interval between updating + * attribute values. + * @param callback - Callback to get notifiy when update automation is finished. + * + * @return ID representing update automation session. + * NOTE: API throws @InvalidArgsException, @SimulatorException exceptions. + */ + virtual int startAttributeUpdation(const std::string &attrName, AutomationType type, + int updateInterval, updateCompleteCallback callback) = 0; + + /** + * API to get the Ids of all ongoing resource update automation . + * + * @return vector of resource automation ids. + */ + virtual std::vector getResourceUpdationIds() = 0; + + /** + * API to get the Ids of all ongoing attribute update automation . + * + * @return vector of attribute automation ids. + */ + virtual std::vector getAttributeUpdationIds() = 0; + + /** + * API to stop the resource/attribute automation. + * + * @param id - Identifier for automation. + */ + virtual void stopUpdation(int id) = 0; +}; + +typedef std::shared_ptr SimulatorSingleResourceSP; + +#endif diff --git a/service/simulator/java/sdk/src/org/oic/simulator/serviceprovider/AutomationType.java b/service/simulator/inc/simulator_uncopyable.h similarity index 59% rename from service/simulator/java/sdk/src/org/oic/simulator/serviceprovider/AutomationType.java rename to service/simulator/inc/simulator_uncopyable.h index 06409ff..7d87e38 100644 --- a/service/simulator/java/sdk/src/org/oic/simulator/serviceprovider/AutomationType.java +++ b/service/simulator/inc/simulator_uncopyable.h @@ -1,6 +1,9 @@ -/* +/****************************************************************** + * * Copyright 2015 Samsung Electronics All Rights Reserved. * + * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,24 +15,19 @@ * WITHOUT WARRANTIES 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; +#ifndef SIMULATOR_UNCOPYABLE_H_ +#define SIMULATOR_UNCOPYABLE_H_ - private AutomationType(int value) { - this.value = value; - } +class UnCopyable +{ + public: + UnCopyable() = default; + UnCopyable(const UnCopyable &) = delete; + UnCopyable &operator=(const UnCopyable &) = delete; + virtual ~UnCopyable() {}; +}; - public int getValue() { - return this.value; - } -} +#endif diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/light_16x16.png b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/icons/light_16x16.png deleted file mode 100644 index 8b3abbd5e9b85fdff73b372ef0cd011268de54d7..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 732 zcmV<20wev2P)7-rC1y8yiDmP;aqWRnlMV7i3*OZ zF{E_L!j&f-0ZRAkd%}_0&=qLjIyklkk%{&1{&?5F`YiO)5%$BwcNStLox!Cn8wkz3 ze_-%=*mty>RvH|chof;Yj|P9R9iEm4;nbVQIvw69=`i+RIK<0sfNjUYwvs3`*Mi66 zs)Ff%2E1%AlKv9yZRz2VTc4nFADFs`=fG?ml77PRHX;3CNxi{HNu;R?iWsw25-&Cu zObAoJ$tLLbG#StjcsUCD45%~3A?`$}azj)M62;xrd|cP`rbuIOm&7y&jCM^AvTOT6 zXRj2eQb3a^E7ulbIJvMBVMeR_oo<=BAIWd@z0xh++GFrv1uCMmM{eQx!47nHbs_q5 z5g%vfFu(Z~*UZ=N_mVYKiDSW5n!XG?jdd^$RE??z`MeE(eX~2Ix@1)i*yQA7BjuB7 z5{vmnAP~4TJ~oc2skg}Gc5r@RATu~L)DVlsM(KQ>u&mJ6*Ejb^fB^ua9bkr!Qwgg8 O0000 observeUIListeners; private List verificationUIListeners; private List configUploadUIListeners; + private List devicePlatformInfoUIListeners; // Map with Server ID as key and the complete object as the value private Map resourceMap; @@ -105,6 +115,9 @@ public class ResourceManager { // Maintaining a list of observed resource URIs. private List observedResourceURIList; + private DeviceInfo devInfo; + private PlatformInfo platInfo; + public ResourceManager() { resourceMap = new HashMap(); favoriteResources = new ArrayList(); @@ -118,41 +131,41 @@ public class ResourceManager { observeUIListeners = new ArrayList(); verificationUIListeners = new ArrayList(); configUploadUIListeners = new ArrayList(); + devicePlatformInfoUIListeners = new ArrayList(); - findResourceListener = new IFindResourceListener() { + findResourceListener = new FindResourceListener() { @Override - public void onResourceCallback( - final SimulatorRemoteResource resourceN) { + public void onResourceFound(final SimulatorRemoteResource resourceN) { synchronizerThread.addToQueue(new Runnable() { @Override public void run() { - System.out.println("onResourceCallback() entry"); if (null == resourceN) { return; } - // If resource already exist, then ignore it. + + // If id is not available, then it cannot be added to + // the local map as null value should not be allowed as + // key. String uid = resourceN.getId(); if (null == uid) { return; } + + // If resource already exist, then ignore it. boolean exist = isUidExist(uid); if (exist) { - System.out.println("Duplicate resource found: [" - + uid + "]"); return; } // Fetch the resource data - RemoteResource resource = fetchResourceDetails(resourceN); - if (null == resource) { - return; - } - - resource.setResource(resourceN); + // RemoteResource resource = + // fetchResourceDetails(resourceN); + RemoteResource resource = new RemoteResource(); + resource.setRemoteResourceRef(resourceN); - String uri = resource.getResourceURI(); - if (null != uri) { + String uri = resourceN.getURI(); + if (null != uri && uri.trim().length() > 0) { // Add resource to favorite list if it was in // favorites list during find/refresh operation. if (favoriteURIList.contains(uri)) { @@ -161,8 +174,15 @@ public class ResourceManager { // Add resource to observed resources list if it was // in observe list during find/refresh operation. if (observedResourceURIList.contains(uri)) { - resource.setObserved(true); + sendObserveRequest(resource); } + } else { + Activator + .getDefault() + .getLogManager() + .log(Level.INFO.ordinal(), new Date(), + "Found a resource without URI. Ignoring it."); + return; } // Add the resource in local data structure @@ -171,6 +191,14 @@ public class ResourceManager { // Notify the UI listener newResourceFoundNotification(resource); + Activator + .getDefault() + .getLogManager() + .log(Level.INFO.ordinal(), + new Date(), + "Resource Found [" + resourceN.getURI() + + "]."); + // Send an initial GET request to get the resource // attributes try { @@ -181,50 +209,86 @@ public class ResourceManager { .getLogManager() .log(Level.ERROR.ordinal(), new Date(), - "[" + e.getClass().getSimpleName() - + "]" + e.code().toString() - + "-" + e.message()); + Utility.getSimulatorErrorString(e, + null)); + } + + // Get the device and platform information + try { + SimulatorManager.findDevices(deviceListener); + SimulatorManager + .getPlatformInformation(platformListener); + } catch (SimulatorException e) { + Activator + .getDefault() + .getLogManager() + .log(Level.ERROR.ordinal(), + new Date(), + Utility.getSimulatorErrorString(e, + null)); } } }); } }; - getListener = new IGetListener() { + // TODO: Listeners for device and platform information. + deviceListener = new DeviceListener() { + @Override - public void onGetCompleted(final String uid, - final SimulatorResourceModel resourceModelN) { + public void onDeviceFound(final DeviceInfo deviceInfo) { + if (null == deviceInfo) { + return; + } synchronizerThread.addToQueue(new Runnable() { @Override public void run() { - // Handling the response which includes retrieving the - // attributes and updating the local model. - RemoteResource resource = handleResponse(uid, - resourceModelN); - if (null != resource) { - // Notify the UI listeners - getCompleteNotification(resource); - } + setDeviceInfo(deviceInfo); + + // Notify UI listeners + deviceInfoReceivedNotification(); } }); } + }; + + platformListener = new PlatformListener() { @Override - public void onGetFailed(Throwable th) { + public void onPlatformFound(final PlatformInfo platformInfo) { + if (null == platformInfo) { + return; + } synchronizerThread.addToQueue(new Runnable() { @Override public void run() { + setPlatformInfo(platformInfo); + + // Notify UI listeners + platformInfoReceivedNotification(); } }); } }; - putListener = new IPutListener() { - + getListener = new GetResponseListener() { @Override - public void onPutCompleted(final String uid, + public void onGetResponse(final String uid, + final SimulatorResult result, final SimulatorResourceModel resourceModelN) { - synchronizerThread.addToQueue(new Thread() { + System.out.println(result); + if (result != SimulatorResult.SIMULATOR_OK) { + Activator + .getDefault() + .getLogManager() + .log(Level.ERROR.ordinal(), + new Date(), + "[" + + result.toString() + + "] Received error response for GET request."); + return; + } + synchronizerThread.addToQueue(new Runnable() { @Override public void run() { // Handling the response which includes retrieving the @@ -233,26 +297,62 @@ public class ResourceManager { resourceModelN); if (null != resource) { // Notify the UI listeners - putCompleteNotification(resource); + getCompleteNotification(resource); } } }); } + }; + + putListener = new PutResponseListener() { @Override - public void onPutFailed(Throwable th) { - synchronizerThread.addToQueue(new Runnable() { + public void onPutResponse(final String uid, + final SimulatorResult result, + final SimulatorResourceModel resourceModelN) { + if (result != SimulatorResult.SIMULATOR_OK) { + Activator + .getDefault() + .getLogManager() + .log(Level.ERROR.ordinal(), + new Date(), + "[" + + result.toString() + + "] Received error response for PUT request."); + return; + } + synchronizerThread.addToQueue(new Thread() { @Override public void run() { + // Handling the response which includes retrieving the + // attributes and updating the local model. + RemoteResource resource = handleResponse(uid, + resourceModelN); + if (null != resource) { + // Notify the UI listeners + putCompleteNotification(resource); + } } }); } }; - postListener = new IPostListener() { + postListener = new PostResponseListener() { @Override - public void onPostCompleted(final String uid, + public void onPostResponse(final String uid, + final SimulatorResult result, final SimulatorResourceModel resourceModelN) { + if (result != SimulatorResult.SIMULATOR_OK) { + Activator + .getDefault() + .getLogManager() + .log(Level.ERROR.ordinal(), + new Date(), + "[" + + result.toString() + + "] Received error response for POST request."); + return; + } synchronizerThread.addToQueue(new Runnable() { @Override public void run() { @@ -267,23 +367,13 @@ public class ResourceManager { } }); } - - @Override - public void onPostFailed(Throwable th) { - synchronizerThread.addToQueue(new Runnable() { - @Override - public void run() { - } - }); - } }; - observeListener = new IObserveListener() { + observeListener = new ObserveNotificationListener() { @Override - public void onObserveCompleted(final String uid, + public void onObserveNotification(final String uid, final SimulatorResourceModel resourceModelN, final int seq) { - System.out.println("ResourceManager: onObserveCallback()"); synchronizerThread.addToQueue(new Runnable() { @Override public void run() { @@ -298,18 +388,12 @@ public class ResourceManager { } }); } - - @Override - public void onObserveFailed(Throwable th) { - // TODO Auto-generated method stub - } }; - verifyListener = new IVerificationListener() { + verifyListener = new VerificationListener() { @Override public void onVerificationStarted(final String uid, final int autoId) { - System.out.println("onVefificationStarted: " + autoId); synchronizerThread.addToQueue(new Runnable() { @Override public void run() { @@ -331,7 +415,6 @@ public class ResourceManager { @Override public void onVerificationCompleted(final String uid, final int autoId) { - System.out.println("onVefificationCompleted: " + autoId); synchronizerThread.addToQueue(new Runnable() { @Override public void run() { @@ -352,7 +435,6 @@ public class ResourceManager { @Override public void onVerificationAborted(final String uid, final int autoId) { - System.out.println("onVefificationAborted: " + autoId); synchronizerThread.addToQueue(new Runnable() { @Override public void run() { @@ -391,20 +473,75 @@ public class ResourceManager { return null; } - resource.setResourceModel(resourceModelN); + resource.setResourceModelRef(resourceModelN); Map attributeMap = fetchResourceAttributesFromModel(resourceModelN); - - // TODO: For debugging + if (resource.isConfigUploaded()) { + updateResourceAttributesFromResponse(resource, attributeMap); + } else { + resource.setResourceAttributesMap(attributeMap); + } + // TODO: Printing the values for debugging if (null != attributeMap) { RemoteResourceAttribute.printAttributes(attributeMap); - System.out.println("Attributes found: " + (null != attributeMap)); - System.out.println("No of attributes: " + attributeMap.size()); - - resource.setResourceAttributesMap(attributeMap); } return resource; } + private void updateResourceAttributesFromResponse(RemoteResource res, + Map newAttributeMap) { + if (null == res || null == newAttributeMap) { + return; + } + Map oldAttributeMap = res + .getResourceAttributesMap(); + if (null == oldAttributeMap) { + return; + } + Iterator itr = oldAttributeMap.keySet().iterator(); + String attName; + RemoteResourceAttribute newAtt; + RemoteResourceAttribute oldAtt; + while (itr.hasNext()) { + attName = itr.next(); + newAtt = newAttributeMap.get(attName); + if (null == newAtt) { + // Attribute does not exist in the received model. Hence + // removing it from local model. + itr.remove(); + } else { + oldAtt = oldAttributeMap.get(attName); + if (null != oldAtt) { + oldAtt.setAttributeValue(newAtt.getAttributeValue()); + } else { + itr.remove(); + } + newAttributeMap.remove(attName); + } + } + // Adding new attributes in the received model. + itr = newAttributeMap.keySet().iterator(); + while (itr.hasNext()) { + attName = itr.next(); + oldAttributeMap.put(attName, newAttributeMap.get(attName)); + } + } + + public synchronized DeviceInfo getDeviceInfo() { + return devInfo; + } + + public synchronized void setDeviceInfo(DeviceInfo devInfo) { + this.devInfo = devInfo; + } + + public synchronized PlatformInfo getPlatformInfo() { + return platInfo; + } + + public synchronized void setPlatformInfo(PlatformInfo platInfo) { + this.platInfo = platInfo; + } + private static class ResponseSynchronizerThread implements Runnable { LinkedList responseQueue = new LinkedList(); @@ -491,6 +628,20 @@ public class ResourceManager { } } + public void addDevicePlatformInfoUIListener( + IDevicePlatformInfoUIListener deviceUIListener) { + synchronized (devicePlatformInfoUIListeners) { + devicePlatformInfoUIListeners.add(deviceUIListener); + } + } + + public void removeDevicePlatformInfoUIListener( + IDevicePlatformInfoUIListener platformUIListener) { + synchronized (devicePlatformInfoUIListeners) { + devicePlatformInfoUIListeners.remove(platformUIListener); + } + } + public void removeResourceSelectionChangedUIListener( IResourceSelectionChangedUIListener listener) { synchronized (resourceSelectionChangedUIListeners) { @@ -545,7 +696,6 @@ public class ResourceManager { resource.setFavorite(true); synchronized (favoriteResources) { favoriteResources.add(resource); - favoriteURIList.add(resource.getResourceURI()); } } @@ -559,12 +709,21 @@ public class ResourceManager { } } + public void addResourceURItoFavorites(RemoteResource resource) { + if (null == resource) { + return; + } + synchronized (favoriteURIList) { + favoriteURIList.add(resource.getRemoteResourceRef().getURI()); + } + } + public void removeResourceURIFromFavorites(RemoteResource resource) { if (null == resource) { return; } synchronized (favoriteURIList) { - favoriteURIList.remove(resource.getResourceURI()); + favoriteURIList.remove(resource.getRemoteResourceRef().getURI()); } } @@ -600,7 +759,8 @@ public class ResourceManager { private void addResourceDetails(RemoteResource remoteResource) { if (null != remoteResource) { synchronized (resourceMap) { - resourceMap.put(remoteResource.getuId(), remoteResource); + resourceMap.put(remoteResource.getRemoteResourceRef().getId(), + remoteResource); } } } @@ -623,24 +783,6 @@ public class ResourceManager { } } - private RemoteResource fetchResourceDetails( - SimulatorRemoteResource remoteResourceN) { - if (null == remoteResourceN) { - return null; - } - RemoteResource remoteResource = new RemoteResource(); - remoteResource.setuId(remoteResourceN.getId()); - remoteResource.setResourceURI(remoteResourceN.getUri()); - remoteResource.setHost(remoteResourceN.getHost()); - remoteResource.setResourceTypes(remoteResourceN.getResourceTypes()); - remoteResource.setResourceInterfaces(remoteResourceN - .getResourceInterfaces()); - remoteResource.setConnectivityType(remoteResourceN - .getConnectivityType()); - remoteResource.setObservable(remoteResourceN.getIsObservable()); - return remoteResource; - } - private boolean isUidExist(String uid) { boolean exist; synchronized (resourceMap) { @@ -664,27 +806,19 @@ public class ResourceManager { SimulatorResourceModel resourceModelN) { Map resourceAttributeMap = null; if (null != resourceModelN) { - Map attributeMapN; - try { - attributeMapN = resourceModelN.getAttributes(); - } catch (SimulatorException e) { - Activator - .getDefault() - .getLogManager() - .log(Level.ERROR.ordinal(), - new Date(), - "[" + e.getClass().getSimpleName() + "]" - + e.code().toString() + "-" - + e.message()); - return null; - } + Map attributeMapN; + attributeMapN = resourceModelN.getAttributes(); if (null != attributeMapN) { resourceAttributeMap = new HashMap(); Set attNameSet = attributeMapN.keySet(); String attName; Object attValueObj; - ResourceAttribute attributeN; + AttributeValue attValueN; + AttributeProperty attPropN; + TypeInfo typeInfo; + Type valuesType; + SimulatorResourceAttribute attributeN; RemoteResourceAttribute attribute; Iterator attNameItr = attNameSet.iterator(); while (attNameItr.hasNext()) { @@ -692,53 +826,42 @@ public class ResourceManager { attributeN = attributeMapN.get(attName); if (null != attributeN) { attribute = new RemoteResourceAttribute(); - attribute.setResourceAttribute(attributeN); + attribute.setResourceAttributeRef(attributeN); attribute.setAttributeName(attName); - attValueObj = attributeN.getValue(); - if (null != attValueObj) { - attribute.setAttributeValue(attValueObj); - } + attValueN = attributeN.value(); + if (null != attValueN) { + attValueObj = attValueN.get(); + if (null != attValueObj) { + attribute.setAttributeValue(attValueObj); + } - // Set the attribute type - attribute.setAttValBaseType(attributeN.getBaseType()); - attribute.setAttValType(attributeN.getType()); + // Set the attribute type + typeInfo = attValueN.typeInfo(); + if (null != typeInfo) { + attribute.setAttValBaseType(typeInfo.mBaseType); + attribute.setAttValType(typeInfo.mType); + attribute.setDepth(typeInfo.mDepth); + } + + } // Set the range and allowed values - Range range = attributeN.getRange(); - if (null != range) { - attribute.setMinValue(range.getMin()); - attribute.setMaxValue(range.getMax()); - } else { - Object[] values = attributeN.getAllowedValues(); + attPropN = attributeN.property(); + valuesType = attPropN.type(); + attribute.setValuesType(valuesType); + if (valuesType == Type.RANGE) { + attribute.setMinValue(attPropN.min()); + attribute.setMaxValue(attPropN.max()); + } else if (valuesType == Type.VALUESET) { + Object[] values = attPropN.valueSet(); if (null != values && values.length > 0) { List valueList = new ArrayList(); for (Object obj : values) { - valueList.add(obj); + valueList.add(((AttributeValue) obj).get()); } attribute.setAllowedValues(valueList); } - /* - * Type baseType = attribute.getAttValBaseType(); - * - * if(baseType == Type.INT) { //int[] values = - * attributeN.getAllowedValues(); - * attribute.setAllowedValues - * (attributeN.getAllowedValues()); } else - * if(baseType == Type.DOUBLE) { double[] values = - * attributeN.getAllowedValues(); - * attribute.setAllowedValues - * (Utility.converArrayToList(values)); } else - * if(baseType == Type.BOOL) { //boolean[] values = - * attributeN.getAllowedValues(); List obj = - * new ArrayList(); obj.add(true); - * obj.add(false); attribute.setAllowedValues(obj); - * } else if(baseType == Type.STRING) { String[] - * values = attributeN.getAllowedValues(); - * attribute. - * setAllowedValues(Utility.converArrayToList - * (values)); } - */ } resourceAttributeMap.put(attName, attribute); } @@ -911,31 +1034,36 @@ public class ResourceManager { } } - // TODO: Temporarily used to display the resource in the UI - public List getURIList() { - List list = new ArrayList(); - synchronized (resourceMap) { - /* - * Set idSet = resourceMap.keySet(); Iterator 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 uriSet = resourceMap.keySet(); - Iterator uriItr = uriSet.iterator(); - String uri; - while (uriItr.hasNext()) { - uri = uriItr.next(); - if (null != uri) { - list.add(uri); + private void deviceInfoReceivedNotification() { + synchronized (devicePlatformInfoUIListeners) { + if (devicePlatformInfoUIListeners.size() > 0) { + IDevicePlatformInfoUIListener listener; + Iterator listenerItr = devicePlatformInfoUIListeners + .iterator(); + while (listenerItr.hasNext()) { + listener = listenerItr.next(); + if (null != listener) { + listener.onDeviceInfoFound(); + } } } + } + } - // Sort the types - Collections.sort(list); + private void platformInfoReceivedNotification() { + synchronized (devicePlatformInfoUIListeners) { + if (devicePlatformInfoUIListeners.size() > 0) { + IDevicePlatformInfoUIListener listener; + Iterator listenerItr = devicePlatformInfoUIListeners + .iterator(); + while (listenerItr.hasNext()) { + listener = listenerItr.next(); + if (null != listener) { + listener.onPlatformInfoFound(); + } + } + } } - return list; } public synchronized Set getLastKnownSearchTypes() { @@ -948,45 +1076,71 @@ public class ResourceManager { } public boolean findResourceRequest(Set searchTypes) { - if (null == searchTypes || searchTypes.size() < 1) { - return false; - } boolean result = false; - Iterator searchItr = searchTypes.iterator(); - String rType; - while (searchItr.hasNext()) { - rType = searchItr.next(); + if (null == searchTypes || searchTypes.size() < 1) { try { - SimulatorManager.findResource(rType, findResourceListener); + SimulatorManager.findResource(findResourceListener); result = true; } catch (SimulatorException e) { Activator .getDefault() .getLogManager() - .log(Level.ERROR.ordinal(), - new Date(), - "[" + e.getClass().getSimpleName() + "]" - + e.code().toString() + "-" - + e.message()); + .log(Level.ERROR.ordinal(), new Date(), + Utility.getSimulatorErrorString(e, null)); + } + } else { + Iterator searchItr = searchTypes.iterator(); + String rType; + while (searchItr.hasNext()) { + rType = searchItr.next(); + try { + SimulatorManager.findResource(rType, findResourceListener); + result = true; + } catch (SimulatorException e) { + Activator + .getDefault() + .getLogManager() + .log(Level.ERROR.ordinal(), new Date(), + Utility.getSimulatorErrorString(e, null)); + } } } return result; } public void deleteResources(final Set searchTypes) { - if (null == searchTypes || searchTypes.size() < 1) { - return; + synchronized (resourceMap) { + if (null == resourceMap && resourceMap.isEmpty()) { + return; + } } new Thread() { public void run() { - Iterator typeItr = searchTypes.iterator(); - String resType; - while (typeItr.hasNext()) { - resType = typeItr.next(); - deleteResourcesByType(resType); - + if (null == searchTypes || searchTypes.size() < 1) { + synchronized (resourceMap) { + // Stop observing all the resources + Iterator itr = resourceMap.keySet().iterator(); + while (itr.hasNext()) { + sendCancelObserveRequest( + resourceMap.get(itr.next()), false); + } + // Delete all cached details of resources + resourceMap.clear(); + favoriteResources.clear(); + } // Change the current resource in selection - updateCurrentResourceInSelection(searchTypes); + setCurrentResourceInSelection(null); + resourceSelectionChangedUINotification(null); + } else { + Iterator typeItr = searchTypes.iterator(); + String resType; + while (typeItr.hasNext()) { + resType = typeItr.next(); + deleteResourcesByType(resType); + + // Change the current resource in selection + updateCurrentResourceInSelection(searchTypes); + } } } }.start(); @@ -1000,7 +1154,8 @@ public class ResourceManager { if (null == resourceInSelection) { return; } - List typesOfSelection = resourceInSelection.getResourceTypes(); + List typesOfSelection = resourceInSelection + .getRemoteResourceRef().getResourceTypes(); if (null == typesOfSelection || typesOfSelection.size() < 1) { return; } @@ -1036,14 +1191,16 @@ public class ResourceManager { if (null == resource) { continue; } - types = resource.getResourceTypes(); + types = resource.getRemoteResourceRef().getResourceTypes(); if (null != types) { exist = types.contains(resourceType); if (exist) { - // Remove the resource - keyItr.remove(); + // Cancel observing the resource. + sendCancelObserveRequest(resource, false); // Remove the resource from favorites list. removeResourceFromFavorites(resource); + // Remove the resource + keyItr.remove(); } } } @@ -1061,7 +1218,7 @@ public class ResourceManager { }.start(); } - public List getMetaProperties(RemoteResource resource) { + public List getDefaultProperties(RemoteResource resource) { if (null != resource) { String propName; String propValue; @@ -1071,22 +1228,26 @@ public class ResourceManager { for (int index = 0; index < Constants.META_PROPERTY_COUNT; index++) { propName = Constants.META_PROPERTIES[index]; if (propName.equals(Constants.RESOURCE_URI)) { - propValue = resource.getResourceURI(); + propValue = resource.getRemoteResourceRef().getURI(); } else if (propName.equals(Constants.CONNECTIVITY_TYPE)) { - propValue = resource.getConnectivityType().toString(); + propValue = resource.getRemoteResourceRef() + .getConnectivityType().toString(); + } else if (propName.equals(Constants.ADDRESS)) { + propValue = resource.getRemoteResourceRef().getHost(); } else if (propName.equals(Constants.OBSERVABLE)) { propValue = Utility.getObservableInString(resource - .isObservable()); - // see in UI + .getRemoteResourceRef().isObservable()); } else if (propName.equals(Constants.RESOURCE_TYPES)) { - List types = resource.getResourceTypes(); + Vector types = resource.getRemoteResourceRef() + .getResourceTypes(); if (null != types) { propValue = types.toString(); } else { propValue = Constants.NOT_AVAILABLE; } } else if (propName.equals(Constants.RESOURCE_INTERFACES)) { - List interfaces = resource.getResourceInterfaces(); + Vector interfaces = resource.getRemoteResourceRef() + .getResourceInterfaces(); if (null != interfaces) { propValue = interfaces.toString(); } else { @@ -1105,6 +1266,84 @@ public class ResourceManager { return null; } + public List getDeviceProperties() { + if (null == devInfo) { + return null; + } + + List metaProperties = new ArrayList(); + + metaProperties.add(new MetaProperty(Constants.DEVICE_ID, devInfo + .getID())); + metaProperties.add(new MetaProperty(Constants.DEVICE_NAME, devInfo + .getName())); + metaProperties.add(new MetaProperty(Constants.DEVICE_SPEC_VERSION, + devInfo.getSpecVersion())); + metaProperties.add(new MetaProperty(Constants.DEVICE_DMV_VERSION, + devInfo.getDataModelVersion())); + + /* + * metaProperties.add(new MetaProperty(Constants.DEVICE_ID, "")); + * metaProperties.add(new MetaProperty(Constants.DEVICE_NAME, "")); + * metaProperties.add(new MetaProperty(Constants.DEVICE_SPEC_VERSION, + * "")); metaProperties.add(new + * MetaProperty(Constants.DEVICE_DMV_VERSION, "")); + */ + return metaProperties; + } + + public List getPlatformProperties() { + if (null == platInfo) { + return null; + } + + List metaProperties = new ArrayList(); + + metaProperties.add(new MetaProperty(Constants.PLATFORM_ID, platInfo + .getPlatformID())); + metaProperties.add(new MetaProperty(Constants.PLATFORM_MANUFAC_NAME, + platInfo.getManufacturerName())); + metaProperties.add(new MetaProperty(Constants.PLATFORM_MANUFAC_URL, + platInfo.getManufacturerUrl())); + metaProperties.add(new MetaProperty(Constants.PLATFORM_MODEL_NO, + platInfo.getModelNumber())); + metaProperties.add(new MetaProperty(Constants.PLATFORM_DATE_OF_MANUFAC, + platInfo.getDateOfManufacture())); + metaProperties.add(new MetaProperty(Constants.PLATFORM_VERSION, + platInfo.getPlatformVersion())); + metaProperties.add(new MetaProperty(Constants.PLATFORM_OS_VERSION, + platInfo.getOperationSystemVersion())); + metaProperties.add(new MetaProperty( + Constants.PLATFORM_HARDWARE_VERSION, platInfo + .getHardwareVersion())); + metaProperties.add(new MetaProperty( + Constants.PLATFORM_FIRMWARE_VERSION, platInfo + .getFirmwareVersion())); + metaProperties.add(new MetaProperty(Constants.PLATFORM_SUPPORT_URL, + platInfo.getSupportUrl())); + metaProperties.add(new MetaProperty(Constants.PLATFORM_SYSTEM_TIME, + platInfo.getSystemTime())); + + /* + * metaProperties.add(new MetaProperty(Constants.PLATFORM_ID, "")); + * metaProperties .add(new MetaProperty(Constants.PLATFORM_MANUFAC_NAME, + * "")); metaProperties .add(new + * MetaProperty(Constants.PLATFORM_MANUFAC_URL, "")); + * metaProperties.add(new MetaProperty(Constants.PLATFORM_MODEL_NO, + * "")); metaProperties.add(new + * MetaProperty(Constants.PLATFORM_DATE_OF_MANUFAC, "")); + * metaProperties.add(new MetaProperty(Constants.PLATFORM_VERSION, "")); + * metaProperties.add(new MetaProperty(Constants.PLATFORM_OS_VERSION, + * "")); metaProperties.add(new MetaProperty( + * Constants.PLATFORM_HARDWARE_VERSION, "")); metaProperties.add(new + * MetaProperty( Constants.PLATFORM_FIRMWARE_VERSION, "")); + * metaProperties .add(new MetaProperty(Constants.PLATFORM_SUPPORT_URL, + * "")); metaProperties .add(new + * MetaProperty(Constants.PLATFORM_SYSTEM_TIME, "")); + */ + return metaProperties; + } + public Map getAutomationStatus(RemoteResource resource) { if (null == resource) { return null; @@ -1116,13 +1355,6 @@ public class ResourceManager { return autoStatus; } - public Map getDummyAttributes() { - Map attributes = new HashMap(); - attributes.put("intensity", "1"); - attributes.put("power", "off"); - return attributes; - } - public List getResourceList() { List resourceList = new ArrayList(); synchronized (resourceMap) { @@ -1139,8 +1371,8 @@ public class ResourceManager { // Sort the list Collections.sort(resourceList, new Comparator() { public int compare(RemoteResource res1, RemoteResource res2) { - String s1 = res1.getResourceURI(); - String s2 = res2.getResourceURI(); + String s1 = res1.getRemoteResourceRef().getURI(); + String s2 = res2.getRemoteResourceRef().getURI(); String s1Part = s1.replaceAll("\\d", ""); String s2Part = s2.replaceAll("\\d", ""); @@ -1180,7 +1412,7 @@ public class ResourceManager { if (null == resource) { return; } - SimulatorRemoteResource resourceN = resource.getResource(); + SimulatorRemoteResource resourceN = resource.getRemoteResourceRef(); if (null == resourceN) { return; } @@ -1190,56 +1422,46 @@ public class ResourceManager { Activator .getDefault() .getLogManager() - .log(Level.ERROR.ordinal(), - new Date(), - "[" + e.getClass().getSimpleName() + "]" - + e.code().toString() + "-" + e.message()); + .log(Level.ERROR.ordinal(), new Date(), + Utility.getSimulatorErrorString(e, null)); } } public void sendPutRequest(RemoteResource resource, List putPostModelList) { - System.out.println(putPostModelList); - System.out.println("ResourceManager: sendPutRequest"); if (null == resource) { return; } - System.out.println("ResourceManager: resource not null"); - SimulatorRemoteResource resourceN = resource.getResource(); + SimulatorRemoteResource resourceN = resource.getRemoteResourceRef(); if (null == resourceN) { return; } - System.out.println("ResourceManager: Native resource not null"); Map attMap = resource .getResourceAttributesMap(); if (null == attMap || attMap.size() < 1) { return; } - System.out.println("ResourceManager: attrubutes obtained"); - SimulatorResourceModel resourceModel = getUpdatedResourceModel(attMap, - putPostModelList); - System.out.println("ResourceModel exist?:" + (resourceModel != null)); try { - resourceN.put(resourceModel, null, putListener); - } catch (SimulatorException e) { + SimulatorResourceModel resourceModel = getUpdatedResourceModel( + attMap, putPostModelList); + resourceN.put(null, resourceModel, putListener); + } catch (Exception e) { + String addlInfo; + addlInfo = "Invalid Attribute Value. Cannot send PUT request."; Activator .getDefault() .getLogManager() - .log(Level.ERROR.ordinal(), - new Date(), - "[" + e.getClass().getSimpleName() + "]" - + e.code().toString() + "-" + e.message()); + .log(Level.ERROR.ordinal(), new Date(), + Utility.getSimulatorErrorString(e, addlInfo)); } - System.out.println("ResourceManager: called native put"); } public void sendPostRequest(RemoteResource resource, List putPostModelList) { - System.out.println(putPostModelList); if (null == resource) { return; } - SimulatorRemoteResource resourceN = resource.getResource(); + SimulatorRemoteResource resourceN = resource.getRemoteResourceRef(); if (null == resourceN) { return; } @@ -1257,196 +1479,114 @@ public class ResourceManager { itr.remove(); } } - SimulatorResourceModel resourceModel = getUpdatedResourceModel(attMap, - putPostModelList); try { - resourceN.post(resourceModel, null, postListener); - } catch (SimulatorException e) { + SimulatorResourceModel resourceModel = getUpdatedResourceModel( + attMap, putPostModelList); + resourceN.post(null, resourceModel, postListener); + } catch (Exception e) { + String addlInfo; + addlInfo = "Invalid Attribute Value. Cannot send POST request."; Activator .getDefault() .getLogManager() - .log(Level.ERROR.ordinal(), - new Date(), - "[" + e.getClass().getSimpleName() + "]" - + e.code().toString() + "-" + e.message()); + .log(Level.ERROR.ordinal(), new Date(), + Utility.getSimulatorErrorString(e, addlInfo)); } } private SimulatorResourceModel getUpdatedResourceModel( Map attMap, - List putPostModelList) { - String attName; + List putPostModelList) throws Exception { SimulatorResourceModel resourceModel = new SimulatorResourceModel(); - PutPostAttributeModel model; - RemoteResourceAttribute attribute; - Type attType; - Iterator itr = putPostModelList.iterator(); - while (itr.hasNext()) { - model = itr.next(); - attName = model.getAttName(); - attribute = attMap.get(attName); - if (null == attribute) { - continue; - } - attType = attribute.getAttValBaseType(); - if (attType == Type.INT) { - int attValue; - try { - attValue = Integer.parseInt(model.getAttValue()); - resourceModel.addAttributeInt(attName, attValue); - } catch (NumberFormatException e) { - Activator - .getDefault() - .getLogManager() - .log(Level.ERROR.ordinal(), new Date(), - e.getMessage()); - } catch (SimulatorException e) { - Activator - .getDefault() - .getLogManager() - .log(Level.ERROR.ordinal(), - new Date(), - "[" + e.getClass().getSimpleName() + "]" - + e.code().toString() + "-" - + e.message()); - } - } else if (attType == Type.DOUBLE) { - double attValue; - try { - attValue = Double.parseDouble(model.getAttValue()); - resourceModel.addAttributeDouble(attName, attValue); - } catch (NumberFormatException e) { - Activator - .getDefault() - .getLogManager() - .log(Level.ERROR.ordinal(), new Date(), - e.getMessage()); - } catch (SimulatorException e) { - Activator - .getDefault() - .getLogManager() - .log(Level.ERROR.ordinal(), - new Date(), - "[" + e.getClass().getSimpleName() + "]" - + e.code().toString() + "-" - + e.message()); - } - } else if (attType == Type.BOOL) { - boolean attValue; - attValue = Boolean.parseBoolean(model.getAttValue()); - try { - resourceModel.addAttributeBoolean(attName, attValue); - } catch (SimulatorException e) { - Activator - .getDefault() - .getLogManager() - .log(Level.ERROR.ordinal(), - new Date(), - "[" + e.getClass().getSimpleName() + "]" - + e.code().toString() + "-" - + e.message()); - } - } else if (attType == Type.STRING) { - String attValue; - attValue = model.getAttValue(); - try { - resourceModel.addAttributeString(attName, attValue); - } catch (SimulatorException e) { - Activator - .getDefault() - .getLogManager() - .log(Level.ERROR.ordinal(), - new Date(), - "[" + e.getClass().getSimpleName() + "]" - + e.code().toString() + "-" - + e.message()); - } - } + for (PutPostAttributeModel putPostAttribute : putPostModelList) + { + String attributeName = putPostAttribute.getAttName(); + RemoteResourceAttribute resourceAttribute = attMap.get(attributeName); + AttributeValue attributeValue = AttributeValueBuilder.build( + putPostAttribute.getAttValue(), resourceAttribute.getAttValBaseType()); + resourceModel.addAttribute(attributeName, attributeValue); } + return resourceModel; } - public void sendObserveRequest(RemoteResource resource) { - System.out.println("sendObserverRequest() entry"); + public boolean sendObserveRequest(RemoteResource resource) { if (null == resource) { - return; + return false; } - System.out.println("Resource is null:" + (resource == null)); - resource.setObserved(true); - SimulatorRemoteResource resourceN = resource.getResource(); + SimulatorRemoteResource resourceN = resource.getRemoteResourceRef(); if (null == resourceN) { - return; + return false; } try { - resourceN.startObserve(SimulatorObserveType.OBSERVE, null, - observeListener); + resourceN.startObserve(null, observeListener); + resource.setObserved(true); // Add observed resource URI to show the proper status after every // find/refresh operations. - addObservedResourceURI(resource.getResourceURI()); + addObservedResourceURI(resource.getRemoteResourceRef().getURI()); } catch (SimulatorException e) { Activator .getDefault() .getLogManager() - .log(Level.ERROR.ordinal(), - new Date(), - "[" + e.getClass().getSimpleName() + "]" - + e.code().toString() + "-" + e.message()); + .log(Level.ERROR.ordinal(), new Date(), + Utility.getSimulatorErrorString(e, null)); + return false; } - System.out.println("Observer called."); + return true; } - public void sendCancelObserveRequest(RemoteResource resource) { - if (null == resource) { - return; + public boolean sendCancelObserveRequest(RemoteResource resource, + boolean removeEntry) { + if (null == resource || !resource.isObserved()) { + return false; } - resource.setObserved(false); - SimulatorRemoteResource resourceN = resource.getResource(); + SimulatorRemoteResource resourceN = resource.getRemoteResourceRef(); if (null == resourceN) { - return; + return false; } try { resourceN.stopObserve(); + resource.setObserved(false); // Remove observed resource URI to show the proper status after // every find/refresh operations. - removeObservedResourceURI(resource.getResourceURI()); + if (removeEntry) + removeObservedResourceURI(resource.getRemoteResourceRef() + .getURI()); } catch (SimulatorException e) { Activator .getDefault() .getLogManager() - .log(Level.ERROR.ordinal(), - new Date(), - "[" + e.getClass().getSimpleName() + "]" - + e.code().toString() + "-" + e.message()); + .log(Level.ERROR.ordinal(), new Date(), + Utility.getSimulatorErrorString(e, null)); + return false; } + return true; } - public void startAutomationRequest(int reqType, RemoteResource resource) { + public void startAutomationRequest(VerificationType reqType, + RemoteResource resource) { if (null == resource) { return; } - SimulatorRemoteResource resourceN = resource.getResource(); + SimulatorRemoteResource resourceN = resource.getRemoteResourceRef(); if (null == resourceN) { return; } - SimulatorVerificationType type = SimulatorVerificationType - .getVerificationType(reqType); - if (null == type) { + if (null == reqType) { return; } - System.out.println("Before calling startVerification: " + reqType); int autoId; try { - autoId = resourceN.startVerification(type, verifyListener); - System.out.println("After calling startVerification: " + autoId); + autoId = resourceN.startVerification(reqType, verifyListener); if (autoId != -1) { - if (reqType == Constants.GET_AUTOMATION_INDEX) { + if (reqType == VerificationType.GET) { // resource.setGetAutomtnInProgress(true); resource.setGetAutomtnId(autoId); - } else if (reqType == Constants.PUT_AUTOMATION_INDEX) { + } else if (reqType == VerificationType.PUT) { // resource.setPutAutomtnInProgress(true); resource.setPutAutomtnId(autoId); } else {// if(reqType == Constants.POST_AUTOMATION_INDEX) { - // resource.setPostAutomtnInProgress(true); + // resource.setPostAutomtnInProgress(true); resource.setPostAutomtnId(autoId); } } @@ -1454,26 +1594,25 @@ public class ResourceManager { Activator .getDefault() .getLogManager() - .log(Level.ERROR.ordinal(), - new Date(), - "[" + e.getClass().getSimpleName() + "]" - + e.code().toString() + "-" + e.message()); + .log(Level.ERROR.ordinal(), new Date(), + Utility.getSimulatorErrorString(e, null)); } } - public void stopAutomationRequest(int reqType, RemoteResource resource) { + public void stopAutomationRequest(VerificationType reqType, + RemoteResource resource) { if (null == resource) { return; } - SimulatorRemoteResource resourceN = resource.getResource(); + SimulatorRemoteResource resourceN = resource.getRemoteResourceRef(); if (null == resourceN) { return; } int autoId; - if (reqType == Constants.GET_AUTOMATION_INDEX) { + if (reqType == VerificationType.GET) { resource.setGetAutomtnInProgress(false); autoId = resource.getGetAutomtnId(); - } else if (reqType == Constants.PUT_AUTOMATION_INDEX) { + } else if (reqType == VerificationType.PUT) { resource.setPutAutomtnInProgress(false); autoId = resource.getPutAutomtnId(); } else {// if(reqType == Constants.POST_AUTOMATION_INDEX) { @@ -1486,60 +1625,53 @@ public class ResourceManager { Activator .getDefault() .getLogManager() - .log(Level.ERROR.ordinal(), - new Date(), - "[" + e.getClass().getSimpleName() + "]" - + e.code().toString() + "-" + e.message()); + .log(Level.ERROR.ordinal(), new Date(), + Utility.getSimulatorErrorString(e, null)); } } - public void setConfigFilePath(RemoteResource resource, String configFilePath) { + public boolean setConfigFilePath(RemoteResource resource, + String configFilePath) throws SimulatorException { if (null == resource) { - return; + return false; } - SimulatorRemoteResource resourceN = resource.getResource(); + SimulatorRemoteResource resourceN = resource.getRemoteResourceRef(); if (null == resourceN) { - return; + return false; } try { - resourceN.setConfigInfo(configFilePath); + SimulatorResourceModel resourceModel; + resourceModel = resourceN.setConfigInfo(configFilePath); + if (null == resourceModel) { + return false; + } + // Store the resource model in the local cache + resource.setResourceModelRef(resourceModel); + + // Fetching the allowed values and range for all the attributes + Map attributeMap = fetchResourceAttributesFromModel(resourceModel); + resource.setResourceAttributesMap(attributeMap); + // TODO: Printing the values for debugging + if (null != attributeMap) { + RemoteResourceAttribute.printAttributes(attributeMap); + } } catch (SimulatorException e) { Activator .getDefault() .getLogManager() - .log(Level.ERROR.ordinal(), - new Date(), - "[" + e.getClass().getSimpleName() + "]" - + e.code().toString() + "-" + e.message()); - return; + .log(Level.ERROR.ordinal(), new Date(), + Utility.getSimulatorErrorString(e, null)); + throw e; } // Update the status resource.setConfigUploaded(true); // Notify the UI listeners configUploadedNotification(resource); - } - - public Image getImage(String resourceURI) { - if (null == resourceURI) { - return null; - } - URL url = Activator.getDefault().getBundle() - .getEntry(getImageURL(resourceURI)); - if (null == url) { - return null; - } - return ImageDescriptor.createFromURL(url).createImage(); - } - private String getImageURL(String resourceURI) { - // TODO: Hard-coding the image file name temporarily. - // It will be included in a separate class which manages all image - // resources - return "/icons/light_16x16.png"; + return true; } public void shutdown() { - // TODO: To be implemented for clean-up activities. } } 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 index 0b566a0..de3f384 100644 --- 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 @@ -53,6 +53,13 @@ public class PutPostAttributeModel { this.values = values; } + public void prependNewValue(String customValue) { + if (values.contains(customValue)) { + values.remove(customValue); + } + values.add(0, customValue); + } + public boolean isModified() { return modified; } @@ -79,5 +86,4 @@ public class PutPostAttributeModel { public String toString() { return attName + "," + attValue + "\n"; } - } 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 index 17a052e..04c39d1 100644 --- 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 @@ -18,34 +18,25 @@ package oic.simulator.clientcontroller.remoteresource; import java.util.ArrayList; import java.util.Iterator; -import java.util.LinkedList; import java.util.List; import java.util.Map; import oic.simulator.clientcontroller.utils.Constants; import org.oic.simulator.SimulatorResourceModel; -import org.oic.simulator.clientcontroller.SimulatorConnectivityType; -import org.oic.simulator.clientcontroller.SimulatorRemoteResource; +import org.oic.simulator.client.SimulatorRemoteResource; /** * This class represents a remote resource. It maintains all the necessary * information about the resource. */ public class RemoteResource { - private String uId; - private String resourceURI; - private String host; - private LinkedList resourceTypes; - private LinkedList resourceInterfaces; - private SimulatorConnectivityType connectivityType; - private boolean isObservable; private boolean observed; // Native object references - private SimulatorRemoteResource resourceN; - private SimulatorResourceModel resourceModel; + private SimulatorRemoteResource remoteResourceRef; + private SimulatorResourceModel resourceModelRef; private Map resourceAttributesMap; private boolean configUploaded; @@ -60,12 +51,12 @@ public class RemoteResource { private boolean isFavorite; - public SimulatorResourceModel getResourceModel() { - return resourceModel; + public SimulatorResourceModel getResourceModelRef() { + return resourceModelRef; } - public void setResourceModel(SimulatorResourceModel resourceModel) { - this.resourceModel = resourceModel; + public void setResourceModelRef(SimulatorResourceModel resourceModel) { + this.resourceModelRef = resourceModel; } public Map getResourceAttributesMap() { @@ -101,54 +92,6 @@ public class RemoteResource { this.postAutomtnId = postAutomtnId; } - public String getResourceURI() { - return resourceURI; - } - - public void setResourceURI(String resourceURI) { - this.resourceURI = resourceURI; - } - - public String getHost() { - return host; - } - - public void setHost(String host) { - this.host = host; - } - - public LinkedList getResourceTypes() { - return resourceTypes; - } - - public void setResourceTypes(LinkedList resourceTypes) { - this.resourceTypes = resourceTypes; - } - - public LinkedList getResourceInterfaces() { - return resourceInterfaces; - } - - public void setResourceInterfaces(LinkedList resourceInterfaces) { - this.resourceInterfaces = resourceInterfaces; - } - - public SimulatorConnectivityType getConnectivityType() { - return connectivityType; - } - - public void setConnectivityType(SimulatorConnectivityType connectivityType) { - this.connectivityType = connectivityType; - } - - public boolean isObservable() { - return isObservable; - } - - public void setObservable(boolean isObservable) { - this.isObservable = isObservable; - } - public boolean isGetAutomtnInProgress() { return getAutomtnInProgress; } @@ -181,12 +124,12 @@ public class RemoteResource { this.configUploaded = configUploaded; } - public SimulatorRemoteResource getResource() { - return resourceN; + public SimulatorRemoteResource getRemoteResourceRef() { + return remoteResourceRef; } - public void setResource(SimulatorRemoteResource resource) { - this.resourceN = resource; + public void setRemoteResourceRef(SimulatorRemoteResource resource) { + this.remoteResourceRef = resource; } public boolean isObserved() { @@ -226,14 +169,6 @@ public class RemoteResource { return String.valueOf(attribute.getAttributeValue()); } - public String getuId() { - return uId; - } - - public void setuId(String uId) { - this.uId = uId; - } - public int getAutomationtype(int autoId) { if (getAutomtnId == autoId) { return Constants.GET_AUTOMATION_INDEX; 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 index 27cbdc8..e014bdc 100644 --- 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 @@ -21,8 +21,10 @@ import java.util.Iterator; import java.util.List; import java.util.Map; -import org.oic.simulator.ResourceAttribute; -import org.oic.simulator.ResourceAttribute.Type; +import org.oic.simulator.AttributeProperty.Type; +import org.oic.simulator.AttributeValue; +import org.oic.simulator.AttributeValue.ValueType; +import org.oic.simulator.SimulatorResourceAttribute; /** * This class represents an attribute in the remote resource. @@ -30,23 +32,27 @@ import org.oic.simulator.ResourceAttribute.Type; public class RemoteResourceAttribute { // Native object reference - private ResourceAttribute resourceAttribute; + private SimulatorResourceAttribute resourceAttributeRef; - private String attributeName; - private Object attributeValue; - private Type attValType; - private Type attValBaseType; - private List allowedValues; + private String attributeName; + private Object attributeValue; - private Object minValue; - private Object maxValue; + private ValueType attValType; + private ValueType attValBaseType; + private int depth; - public ResourceAttribute getResourceAttribute() { - return resourceAttribute; + private Type valuesType; + private List allowedValues; + private Object minValue; + private Object maxValue; + + public SimulatorResourceAttribute getResourceAttributeRef() { + return resourceAttributeRef; } - public void setResourceAttribute(ResourceAttribute resourceAttribute) { - this.resourceAttribute = resourceAttribute; + public void setResourceAttributeRef( + SimulatorResourceAttribute resourceAttribute) { + this.resourceAttributeRef = resourceAttribute; } public String getAttributeName() { @@ -112,7 +118,7 @@ public class RemoteResourceAttribute { clone.setAttValType(attribute.getAttValType()); clone.setMinValue(attribute.getMinValue()); clone.setMaxValue(attribute.getMaxValue()); - clone.setResourceAttribute(null); + clone.setResourceAttributeRef(null); } return clone; } @@ -132,18 +138,10 @@ public class RemoteResourceAttribute { } } } else if (null != minValue && null != maxValue) { - if (attributeValue.getClass() == Integer.class) { - int min = (Integer) minValue; - int max = (Integer) maxValue; - for (int value = min; value <= max; value++) { - valueList.add(String.valueOf(value)); - } - } else if (attributeValue.getClass() == Double.class) { - double min = (Double) minValue; - double max = (Double) maxValue; - for (double value = min; value <= max; value++) { - valueList.add(String.valueOf(value)); - } + double min = (Double) minValue; + double max = (Double) maxValue; + for (double value = min; value <= max; value++) { + valueList.add(String.valueOf(value)); } } if (valueList.size() < 1 && null != attributeValue) { @@ -152,6 +150,7 @@ public class RemoteResourceAttribute { return valueList; } + // Method added for debugging purpose public static void printAttributes( Map attributeMap) { Iterator itr = attributeMap.keySet().iterator(); @@ -167,19 +166,35 @@ public class RemoteResourceAttribute { } } - public Type getAttValType() { + public ValueType getAttValType() { return attValType; } - public void setAttValType(Type attValType) { + public void setAttValType(ValueType attValType) { this.attValType = attValType; } - public Type getAttValBaseType() { + public ValueType getAttValBaseType() { return attValBaseType; } - public void setAttValBaseType(Type attValBaseType) { + public void setAttValBaseType(ValueType attValBaseType) { this.attValBaseType = attValBaseType; } + + public Type getValuesType() { + return valuesType; + } + + public void setValuesType(Type valuesType) { + this.valuesType = valuesType; + } + + public int getDepth() { + return depth; + } + + public void setDepth(int depth) { + this.depth = depth; + } } \ No newline at end of file diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/remoteresource/SerializedClientController.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/remoteresource/SerializedClientController.java new file mode 100644 index 0000000..c41a96f --- /dev/null +++ b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/remoteresource/SerializedClientController.java @@ -0,0 +1,77 @@ +/* + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package oic.simulator.clientcontroller.remoteresource; + +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; +import java.util.List; + +public class SerializedClientController implements Serializable { + + public List getResourceTypes() { + return m_resourceTypes; + } + + public void setResourceTypes(List resourceTypes) { + this.m_resourceTypes = resourceTypes; + } + + public List getFavorites() { + return m_favorites; + } + + public void setFavorites(List favorites) { + this.m_favorites = favorites; + } + + public void serialize(String filePath) throws Exception { + try { + FileOutputStream fileOut = new FileOutputStream(filePath); + ObjectOutputStream out = new ObjectOutputStream(fileOut); + out.writeObject(this); + out.close(); + fileOut.close(); + } catch (IOException i) { + throw new Exception("Failed to Serialize data : IOException"); + } + } + + public static SerializedClientController deSerialize(String filePath) + throws Exception { + SerializedClientController r = null; + try { + FileInputStream fileIn = new FileInputStream(filePath); + ObjectInputStream in = new ObjectInputStream(fileIn); + r = (SerializedClientController) in.readObject(); + in.close(); + fileIn.close(); + } catch (IOException i) { + throw new Exception("Failed to DeSerialize data : IOException"); + } catch (ClassNotFoundException c) { + throw new Exception("Failed to DeSerialize data : ClassNotFound"); + } + return r; + } + + private List m_resourceTypes; + private List m_favorites; + +} \ No newline at end of file diff --git a/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/utils/AttributeValueBuilder.java b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/utils/AttributeValueBuilder.java new file mode 100644 index 0000000..1716846 --- /dev/null +++ b/service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/utils/AttributeValueBuilder.java @@ -0,0 +1,266 @@ +/* + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package oic.simulator.clientcontroller.utils; + +import java.util.Vector; + +import org.oic.simulator.AttributeValue; + +public class AttributeValueBuilder { + public static AttributeValue build(String valueString, + AttributeValue.ValueType valueType) { + int depth = findDepth(valueString); + if (0 == depth) { + return handleDepth0(valueString, valueType); + } else if (1 == depth) { + return handleDepth1(valueString, valueType); + } else if (2 == depth) { + return handleDepth2(valueString, valueType); + } else if (3 == depth) { + return handleDepth3(valueString, valueType); + } + + return null; + } + + private static int findDepth(String value) { + int depth = 0; + for (char ch : value.toCharArray()) { + if (ch == '[') + depth++; + else + break; + } + + return depth; + } + + private static boolean isValidSyntax(String value) { + int count = 0; + for (char ch : value.toCharArray()) { + if (ch == '[') + count++; + if (ch == ']') + count--; + } + + if (count == 0) + return true; + return false; + + } + + private static AttributeValue handleDepth0(String valueString, + AttributeValue.ValueType valueType) { + valueString = valueString.trim(); + if (0 != findDepth(valueString)) + return null; + + if (valueType == AttributeValue.ValueType.INTEGER) + return new AttributeValue(Integer.parseInt(valueString)); + else if (valueType == AttributeValue.ValueType.DOUBLE) + return new AttributeValue(Double.parseDouble(valueString)); + else if (valueType == AttributeValue.ValueType.BOOLEAN) + return new AttributeValue(Boolean.parseBoolean(valueString)); + else if (valueType == AttributeValue.ValueType.STRING) + return new AttributeValue(valueString); + return null; + } + + private static String[] splitIntoArrays(String value) { + Vector values = new Vector(); + String valueString = new String(value); + valueString = valueString.substring(valueString.indexOf('[') + 1, + valueString.lastIndexOf(']')); + + int count = 0; + int startPos = 0; + char[] charArray = valueString.toCharArray(); + for (int index = 0; index < charArray.length; index++) { + if (charArray[index] == '[' && 0 == count++) { + startPos = index; + } + + if (charArray[index] == ']' && 0 == --count) { + values.add(valueString.substring(startPos, index + 1)); + } + } + + String[] result = new String[values.size()]; + values.toArray(result); + return result; + } + + private static AttributeValue handleDepth1(String valueString, + AttributeValue.ValueType valueType) { + valueString = valueString.trim(); + if (1 != findDepth(valueString) || false == isValidSyntax(valueString)) + return null; + + valueString = valueString.substring(valueString.indexOf('[') + 1, + valueString.lastIndexOf(']')); + String[] valuesString = valueString.split(","); + if (null == valuesString || 0 == valuesString.length) + return null; + + if (valueType == AttributeValue.ValueType.INTEGER) { + Integer[] result = new Integer[valuesString.length]; + for (int index = 0; index < valuesString.length; index++) { + Integer value = (Integer) handleDepth0(valuesString[index], + valueType).get(); + if (null == value) + return null; + result[index] = value; + } + return new AttributeValue(result); + } else if (valueType == AttributeValue.ValueType.DOUBLE) { + Double[] result = new Double[valuesString.length]; + for (int index = 0; index < valuesString.length; index++) { + Double value = (Double) handleDepth0(valuesString[index], + valueType).get(); + if (null == value) + return null; + result[index] = value; + } + return new AttributeValue(result); + } else if (valueType == AttributeValue.ValueType.BOOLEAN) { + Boolean[] result = new Boolean[valuesString.length]; + for (int index = 0; index < valuesString.length; index++) { + Boolean value = (Boolean) handleDepth0(valuesString[index], + valueType).get(); + if (null == value) + return null; + result[index] = value; + } + return new AttributeValue(result); + } else if (valueType == AttributeValue.ValueType.STRING) { + return new AttributeValue(valuesString); + } + + return null; + } + + private static AttributeValue handleDepth2(String valueString, + AttributeValue.ValueType valueType) { + valueString = valueString.trim(); + if (2 != findDepth(valueString) || false == isValidSyntax(valueString)) + return null; + + String[] valuesString = splitIntoArrays(valueString); + if (null == valuesString || 0 == valuesString.length) + return null; + + if (valueType == AttributeValue.ValueType.INTEGER) { + Integer[][] result = new Integer[valuesString.length][]; + for (int index = 0; index < valuesString.length; index++) { + Integer[] value = (Integer[]) handleDepth1(valuesString[index], + valueType).get(); + if (null == value) + return null; + result[index] = value; + } + return new AttributeValue(result); + } else if (valueType == AttributeValue.ValueType.DOUBLE) { + Double[][] result = new Double[valuesString.length][]; + for (int index = 0; index < valuesString.length; index++) { + Double[] value = (Double[]) handleDepth1(valuesString[index], + valueType).get(); + if (null == value) + return null; + result[index] = value; + } + return new AttributeValue(result); + } else if (valueType == AttributeValue.ValueType.BOOLEAN) { + Boolean[][] result = new Boolean[valuesString.length][]; + for (int index = 0; index < valuesString.length; index++) { + Boolean[] value = (Boolean[]) handleDepth1(valuesString[index], + valueType).get(); + if (null == value) + return null; + result[index] = value; + } + return new AttributeValue(result); + } else if (valueType == AttributeValue.ValueType.STRING) { + String[][] result = new String[valuesString.length][]; + for (int index = 0; index < valuesString.length; index++) { + String[] value = (String[]) handleDepth1(valuesString[index], + valueType).get(); + if (null == value) + return null; + result[index] = value; + } + return new AttributeValue(result); + } + + return null; + } + + public static AttributeValue handleDepth3(String valueString, + AttributeValue.ValueType valueType) { + valueString = valueString.trim(); + if (3 != findDepth(valueString) || false == isValidSyntax(valueString)) + return null; + + String[] valuesString = splitIntoArrays(valueString); + if (null == valuesString || 0 == valuesString.length) + return null; + + if (valueType == AttributeValue.ValueType.INTEGER) { + Integer[][][] result = new Integer[valuesString.length][][]; + for (int index = 0; index < valuesString.length; index++) { + Integer[][] value = (Integer[][]) handleDepth2( + valuesString[index], valueType).get(); + if (null == value) + return null; + result[index] = value; + } + return new AttributeValue(result); + } else if (valueType == AttributeValue.ValueType.DOUBLE) { + Double[][][] result = new Double[valuesString.length][][]; + for (int index = 0; index < valuesString.length; index++) { + Double[][] value = (Double[][]) handleDepth2( + valuesString[index], valueType).get(); + if (null == value) + return null; + result[index] = value; + } + return new AttributeValue(result); + } else if (valueType == AttributeValue.ValueType.BOOLEAN) { + Boolean[][][] result = new Boolean[valuesString.length][][]; + for (int index = 0; index < valuesString.length; index++) { + Boolean[][] value = (Boolean[][]) handleDepth2( + valuesString[index], valueType).get(); + if (null == value) + return null; + result[index] = value; + } + return new AttributeValue(result); + } else if (valueType == AttributeValue.ValueType.STRING) { + String[][][] result = new String[valuesString.length][][]; + for (int index = 0; index < valuesString.length; index++) { + String[][] value = (String[][]) handleDepth2( + valuesString[index], valueType).get(); + if (null == value) + return null; + result[index] = value; + } + return new AttributeValue(result); + } + + return null; + } +} 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 index 3fe81ac..eba2905 100644 --- 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 @@ -16,77 +16,91 @@ package oic.simulator.clientcontroller.utils; -import org.oic.simulator.serviceprovider.AutomationType; - /** * This class maintains all constants which are used throughout the client * controller plug-in. */ public class Constants { - public static final String FIND_PAGE_TITLE = "Find Resources"; - - public static final String FIND_PAGE_MESSAGE = "Select the resource type of the resources to be discovered"; - - public static final int FIND_RESOURCES_TIMEOUT = 10; - - public static final String RESOURCE_URI = "Resource URI"; - public static final String CONNECTIVITY_TYPE = "Connectivity Type"; - public static final String OBSERVABLE = "Observable"; - public static final String RESOURCE_TYPES = "Resource Types"; - public static final String RESOURCE_INTERFACES = "Resource Interfaces"; - - public static final String[] META_PROPERTIES = { - RESOURCE_URI, CONNECTIVITY_TYPE, OBSERVABLE, RESOURCE_TYPES, - RESOURCE_INTERFACES }; - - public static final int META_PROPERTY_COUNT = META_PROPERTIES.length; - - public static final AutomationType DEFAULT_AUTOMATION_TYPE = AutomationType.NORMAL; - - public static final int DEFAULT_AUTOMATION_INTERVAL = 500; - - public static final String YES = "Yes"; - public static final String NO = "No"; - - public static final String GET = "Get"; - public static final String PUT = "Put"; - public static final String POST = "Post"; - - public static final String ENABLE = "Enable"; - public static final String DISABLE = "Disable"; - public static final String ENABLED = "Enabled"; - public static final String DISABLED = "Disabled"; - - public static final String NOT_AVAILABLE = "Not Available"; - - public static final int PROPER_LOG_TIME_TOKEN_LENGTH = 3; - - public static final int LOG_SIZE = 1000; - - public static final String INFO_LOG = "info_log"; - public static final String WARNING_LOG = "warning_log"; - public static final String ERROR_LOG = "error_log"; - public static final String DEBUG_LOG = "debug_log"; - public static final String UNKNOWN_LOG = "unknown_log"; - - public static final String CHECKED = "Checked"; - public static final String UNCHECKED = "Unchecked"; - - public static final String INFO = "Info"; - public static final String WARNING = "Warning"; - public static final String ERROR = "Error"; - public static final String DEBUG = "Debug"; - public static final String UNKNOWN = "Unknown"; - - public static final String[] BROWSE_RAML_FILTER_EXTENSIONS = new String[] { - "*.raml", "*" }; - public static final String[] SAVE_LOG_FILTER_EXTENSIONS = new String[] { - "*.log", "*" }; - - public static final int GET_AUTOMATION_INDEX = 0; - public static final int PUT_AUTOMATION_INDEX = 1; - public static final int POST_AUTOMATION_INDEX = 2; - public static final int DELETE_AUTOMATION_INDEX = 3; - - public static final String OIC_R_LIGHT = "oic.r.light"; + public static final String FIND_PAGE_TITLE = "Find Resources"; + + public static final String FIND_PAGE_MESSAGE = "Select the resource type of the resources to be discovered"; + + public static final int FIND_RESOURCES_TIMEOUT = 10; + + public static final String RESOURCE_URI = "Resource URI"; + public static final String ADDRESS = "Address"; + public static final String CONNECTIVITY_TYPE = "Connectivity Type"; + public static final String OBSERVABLE = "Observable"; + public static final String RESOURCE_TYPES = "Resource Types"; + public static final String RESOURCE_INTERFACES = "Resource Interfaces"; + + public static final String[] META_PROPERTIES = { + RESOURCE_URI, ADDRESS, CONNECTIVITY_TYPE, OBSERVABLE, + RESOURCE_TYPES, RESOURCE_INTERFACES }; + + public static final int META_PROPERTY_COUNT = META_PROPERTIES.length; + + public static final String YES = "Yes"; + public static final String NO = "No"; + + public static final String GET = "Get"; + public static final String PUT = "Put"; + public static final String POST = "Post"; + public static final String OBSERVE = "Observe"; + public static final String STOP_OBSERVE = "Stop Observe"; + + public static final String ENABLE = "Enable"; + public static final String DISABLE = "Disable"; + public static final String ENABLED = "Enabled"; + public static final String DISABLED = "Disabled"; + + public static final String NOT_AVAILABLE = "Not Available"; + + public static final int PROPER_LOG_TIME_TOKEN_LENGTH = 3; + + public static final int LOG_SIZE = 1000; + + public static final String INFO_LOG = "info_log"; + public static final String WARNING_LOG = "warning_log"; + public static final String ERROR_LOG = "error_log"; + public static final String DEBUG_LOG = "debug_log"; + public static final String UNKNOWN_LOG = "unknown_log"; + + public static final String CHECKED = "Checked"; + public static final String UNCHECKED = "Unchecked"; + + public static final String INFO = "Info"; + public static final String WARNING = "Warning"; + public static final String ERROR = "Error"; + public static final String DEBUG = "Debug"; + public static final String UNKNOWN = "Unknown"; + + public static final String[] BROWSE_RAML_FILTER_EXTENSIONS = new String[] { + "*.raml", "*" }; + public static final String[] SAVE_LOG_FILTER_EXTENSIONS = new String[] { + "*.log", "*" }; + + public static final int GET_AUTOMATION_INDEX = 0; + public static final int PUT_AUTOMATION_INDEX = 1; + public static final int POST_AUTOMATION_INDEX = 2; + public static final int DELETE_AUTOMATION_INDEX = 3; + + // Device information + public static final String DEVICE_NAME = "Name"; + public static final String DEVICE_ID = "Id"; + public static final String DEVICE_SPEC_VERSION = "Spec Version"; + public static final String DEVICE_DMV_VERSION = "DMV Version"; + + // Platform information + public static final String PLATFORM_ID = "Id"; + public static final String PLATFORM_MANUFAC_NAME = "Manufacturer Name"; + public static final String PLATFORM_MANUFAC_URL = "Manufacturer URL"; + public static final String PLATFORM_MODEL_NO = "Model Number"; + public static final String PLATFORM_DATE_OF_MANUFAC = "Date of Manufacture"; + public static final String PLATFORM_VERSION = "Version"; + public static final String PLATFORM_OS_VERSION = "OS Version"; + public static final String PLATFORM_HARDWARE_VERSION = "HardWare Version"; + public static final String PLATFORM_FIRMWARE_VERSION = "Firmware Version"; + public static final String PLATFORM_SUPPORT_URL = "Support URL"; + public static final String PLATFORM_SYSTEM_TIME = "System Time"; } 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 index 8baed7c..254f1f8 100644 --- 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 @@ -17,10 +17,13 @@ package oic.simulator.clientcontroller.utils; import java.util.ArrayList; +import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; +import org.oic.simulator.SimulatorException; + /** * This class has common utility methods. */ @@ -55,25 +58,39 @@ public class Utility { return strArr; } - /* - * public static List converArrayToList(int[] arr) { if(null == arr - * || arr.length < 1) { return null; } List valueList = new - * ArrayList(); for(Object val:arr) { valueList.add(val); } return - * valueList; } - * - * public static List converArrayToList(double[] arr) { if(null == - * arr || arr.length < 1) { return null; } List valueList = new - * ArrayList(); for(Object val:arr) { valueList.add(val); } return - * valueList; } - * - * public static List converArrayToList(boolean[] arr) { if(null == - * arr || arr.length < 1) { return null; } List valueList = new - * ArrayList(); for(Object val:arr) { valueList.add(val); } return - * valueList; } - * - * public static List converArrayToList(String[] arr) { if(null == - * arr || arr.length < 1) { return null; } List valueList = new - * ArrayList(); for(Object val:arr) { valueList.add(val); } return - * valueList; } - */ + public static Set splitStringByComma(String text) { + Set tokenSet = null; + if (null != text) { + String[] token = text.split(","); + if (null != token) { + tokenSet = new HashSet(); + for (String tok : token) { + tok = tok.trim(); + if (tok.length() > 0) { + tokenSet.add(tok); + } + } + } + } + return tokenSet; + } + + public static String getSimulatorErrorString(Exception e, String info) { + if (null == e) { + return null; + } + String detail; + if (e instanceof SimulatorException) { + SimulatorException simEx = (SimulatorException) e; + detail = simEx.message() + "\n"; + detail += "Exception Type: " + simEx.getClass().getSimpleName() + + "\n"; + detail += "Error code: " + simEx.code().toString(); + } else { + detail = info + "\n"; + detail += "Exception Type: " + e.getClass().getSimpleName() + "\n"; + detail += "Message: " + e.getMessage(); + } + return detail; + } } \ No newline at end of file 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 index 255d9f1..e61d484 100644 --- 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 @@ -57,6 +57,7 @@ import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Table; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.part.ViewPart; +import org.oic.simulator.client.SimulatorRemoteResource.VerificationType; /** * This class manages and shows the attribute view in the perspective. @@ -100,8 +101,6 @@ public class AttributeView extends ViewPart { @Override public void run() { - System.out - .println("AttributeView: onResourceSelectionChange"); resourceInSelection = resource; // Set visibility of manual and automation controls @@ -110,14 +109,11 @@ public class AttributeView extends ViewPart { // Update the attribute table if (null != attTblViewer && !attTblViewer.getControl().isDisposed()) { - System.out.println("viewer is alive"); updateViewer(getData(resource)); } // Update the observe status updateObserve(resource); - - // Update the pay-load details if any } }); } @@ -131,30 +127,20 @@ public class AttributeView extends ViewPart { @Override public void run() { - - System.out.println("AttributeView: onGetCompleted"); if (null == resource) { return; } // Update the attribute table if (resourceInSelection != resource) { - System.out - .println("AttributeView: get response arrived for a different resource"); return; } updateViewer(getData(resource)); // Update the observe status updateObserve(resource); - - // Update the pay-load details if any } }); } - - @Override - public void onGetFailed(RemoteResource resource) { - } }; putUIListener = new IPutUIListener() { @@ -165,30 +151,20 @@ public class AttributeView extends ViewPart { @Override public void run() { - - System.out.println("AttributeView: onPutCompleted"); if (null == resource) { return; } // Update the attribute table if (resourceInSelection != resource) { - System.out - .println("AttributeView: put response arrived for a different resource"); return; } updateViewer(getData(resource)); // Update the observe status updateObserve(resource); - - // Update the pay-load details if any } }); } - - @Override - public void onPutFailed(RemoteResource resource) { - } }; postUIListener = new IPostUIListener() { @@ -199,30 +175,20 @@ public class AttributeView extends ViewPart { @Override public void run() { - - System.out.println("AttributeView: onPostCompleted"); if (null == resource) { return; } // Update the attribute table if (resourceInSelection != resource) { - System.out - .println("AttributeView: post response arrived for a different resource"); return; } updateViewer(getData(resource)); // Update the observe status updateObserve(resource); - - // Update the pay-load details if any } }); } - - @Override - public void onPostFailed(RemoteResource resource) { - } }; observeUIListener = new IObserveUIListener() { @@ -233,30 +199,20 @@ public class AttributeView extends ViewPart { @Override public void run() { - - System.out.println("AttributeView: onObserveCompleted"); if (null == resource) { return; } // Update the attribute table if (resourceInSelection != resource) { - System.out - .println("AttributeView: observe response arrived for a different resource"); return; } updateViewer(getData(resource)); // Update the observe status updateObserve(resource); - - // Update the pay-load details if any } }); } - - @Override - public void onObserveFailed(RemoteResource resource) { - } }; verificationUIListener = new IVerificationUIListener() { @@ -268,7 +224,7 @@ public class AttributeView extends ViewPart { @Override public void run() { - changeReqBtnVisibility(autoType, false); + // changeReqBtnVisibility(autoType, false); } }); } @@ -280,7 +236,7 @@ public class AttributeView extends ViewPart { @Override public void run() { - changeReqBtnVisibility(autoType, true); + // changeReqBtnVisibility(autoType, true); } }); } @@ -292,7 +248,7 @@ public class AttributeView extends ViewPart { @Override public void run() { - changeReqBtnVisibility(autoType, true); + // changeReqBtnVisibility(autoType, true); } }); } @@ -306,15 +262,10 @@ public class AttributeView extends ViewPart { @Override public void run() { - - System.out - .println("AttributeView: onConfigurationUploaded"); if (null == resource) { return; } if (resourceInSelection != resource) { - System.out - .println("AttributeView: config upload response arrived for a different resource"); return; } if (!automateButton.isDisposed()) { @@ -348,7 +299,6 @@ public class AttributeView extends ViewPart { } Map attMap = resource .getResourceAttributesMap(); - System.out.println("AttributeView: \n" + attMap); return attMap; } @@ -370,12 +320,14 @@ public class AttributeView extends ViewPart { } private void updateObserve(RemoteResource resource) { - if (null == resource) { + if (null == resource || observeResButton.isDisposed()) { return; } boolean observed = resource.isObserved(); - if (!observeResButton.isDisposed()) { - observeResButton.setSelection(observed); + if (observed) { + observeResButton.setText(Constants.STOP_OBSERVE); + } else { + observeResButton.setText(Constants.OBSERVE); } } @@ -383,7 +335,7 @@ public class AttributeView extends ViewPart { public void createPartControl(Composite parent) { Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE); - parent.setLayout(new GridLayout(2, false)); + parent.setLayout(new GridLayout()); GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); parent.setLayoutData(gd); @@ -402,9 +354,7 @@ public class AttributeView extends ViewPart { setupAttributeTable(attGroup); - setupMessageArea(parent); - - setupResourceLevelOpsArea(parent); + setupRequestControls(parent); setUIListeners(); @@ -419,20 +369,19 @@ public class AttributeView extends ViewPart { } } - private void setupMessageArea(Composite parent) { + private void setupRequestControls(Composite parent) { GridData gd; Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE); - Group msgTypesGrp = new Group(parent, SWT.NONE); + Composite opsComp = new Composite(parent, SWT.NONE); gd = new GridData(); gd.grabExcessHorizontalSpace = true; gd.horizontalAlignment = SWT.FILL; - msgTypesGrp.setLayoutData(gd); - GridLayout grid = new GridLayout(3, false); - msgTypesGrp.setLayout(grid); - msgTypesGrp.setText("Request Types"); - msgTypesGrp.setBackground(color); + opsComp.setLayoutData(gd); + GridLayout grid = new GridLayout(5, false); + opsComp.setLayout(grid); + opsComp.setBackground(color); - getButton = new Button(msgTypesGrp, SWT.PUSH); + getButton = new Button(opsComp, SWT.PUSH); getButton.setText("GET"); gd = new GridData(); gd.grabExcessHorizontalSpace = true; @@ -440,7 +389,7 @@ public class AttributeView extends ViewPart { gd.widthHint = 50; getButton.setLayoutData(gd); - putButton = new Button(msgTypesGrp, SWT.PUSH); + putButton = new Button(opsComp, SWT.PUSH); putButton.setText("PUT"); gd = new GridData(); gd.grabExcessHorizontalSpace = true; @@ -448,41 +397,27 @@ public class AttributeView extends ViewPart { gd.widthHint = 50; putButton.setLayoutData(gd); - postButton = new Button(msgTypesGrp, SWT.PUSH); + postButton = new Button(opsComp, SWT.PUSH); postButton.setText("POST"); gd = new GridData(); gd.grabExcessHorizontalSpace = true; gd.horizontalAlignment = SWT.FILL; gd.widthHint = 50; postButton.setLayoutData(gd); - } - private void setupResourceLevelOpsArea(Composite parent) { - GridData gd; - Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE); - Group resOpsGrp = new Group(parent, SWT.NONE); + observeResButton = new Button(opsComp, SWT.PUSH); + observeResButton.setText(Constants.OBSERVE); gd = new GridData(); gd.grabExcessHorizontalSpace = true; gd.horizontalAlignment = SWT.FILL; - resOpsGrp.setLayoutData(gd); - GridLayout grid = new GridLayout(2, false); - resOpsGrp.setLayout(grid); - resOpsGrp.setText("Resource-Level Operations"); - resOpsGrp.setBackground(color); + observeResButton.setLayoutData(gd); - automateButton = new Button(resOpsGrp, SWT.PUSH); + automateButton = new Button(opsComp, SWT.PUSH); automateButton.setText("Automation"); gd = new GridData(); gd.grabExcessHorizontalSpace = true; gd.horizontalAlignment = SWT.FILL; automateButton.setLayoutData(gd); - - observeResButton = new Button(resOpsGrp, SWT.CHECK); - observeResButton.setText("Observe"); - gd = new GridData(); - gd.grabExcessHorizontalSpace = true; - gd.horizontalAlignment = SWT.FILL; - observeResButton.setLayoutData(gd); } private void setupAttributeTable(Group attGroup) { @@ -631,12 +566,29 @@ public class AttributeView extends ViewPart { observeResButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { - boolean checked = observeResButton.getSelection(); - if (checked) { - resourceManager.sendObserveRequest(resourceInSelection); + boolean result; + if (observeResButton.getText().equals(Constants.OBSERVE)) { + result = resourceManager + .sendObserveRequest(resourceInSelection); + if (result) { + observeResButton.setText(Constants.STOP_OBSERVE); + } else { + MessageDialog.openError(Display.getDefault() + .getActiveShell(), "Observe failed", + "Failed to observe the resource. Try again."); + } } else { - resourceManager - .sendCancelObserveRequest(resourceInSelection); + result = resourceManager.sendCancelObserveRequest( + resourceInSelection, true); + if (result) { + observeResButton.setText(Constants.OBSERVE); + } else { + MessageDialog + .openError(Display.getDefault() + .getActiveShell(), + "Cancel Observe failed", + "Failed to stop observing the resource. Try again."); + } } } }); @@ -657,15 +609,123 @@ public class AttributeView extends ViewPart { if (null == autoStatus) { return; } + + int startCount = 0; + int stopCount = 0; + boolean startGet, startPut, startPost; + boolean stopGet, stopPut, stopPost; + startGet = startPut = startPost = false; + stopGet = stopPut = stopPost = false; + String status = null; + String startMsg = "Verification will be started for: "; + String stopMsg = "Verification will be stopped for: "; VerificationDialog ad = new VerificationDialog(Display .getDefault().getActiveShell(), autoStatus); - ad.open(); + if (ad.open() == Window.OK) { + Map oldStatus = resourceManager + .getAutomationStatus(resource); + if (null == oldStatus || oldStatus.size() < 1) { + status = "Failed to perform the requested operation."; + } else { + // GET + if (oldStatus.get(Constants.GET) != autoStatus + .get(Constants.GET)) { + if (autoStatus.get(Constants.GET)) { + startMsg += Constants.GET; + startCount++; + startGet = true; + } else { + stopMsg += Constants.GET; + stopCount++; + stopGet = true; + } + } + // PUT + if (oldStatus.get(Constants.PUT) != autoStatus + .get(Constants.PUT)) { + if (autoStatus.get(Constants.PUT)) { + if (startCount == 1) { + startMsg += ", "; + } + startMsg += Constants.PUT; + startCount++; + startPut = true; + } else { + if (stopCount == 1) { + stopMsg += ", "; + } + stopMsg += Constants.PUT; + stopCount++; + stopPut = true; + } + + } + // POST + if (oldStatus.get(Constants.POST) != autoStatus + .get(Constants.POST)) { + if (autoStatus.get(Constants.POST)) { + if (startCount > 0) { + startMsg += ", "; + } + startMsg += Constants.POST; + startCount++; + startPost = true; + } else { + if (stopCount > 0) { + stopMsg += ", "; + } + stopMsg += Constants.POST; + stopCount++; + stopPost = true; + } + } + if (startCount > 0) { + status = startMsg + "."; + } + if (stopCount > 0) { + if (startCount <= 0) { + status = stopMsg; + } else { + status += "\n" + stopMsg + "."; + } + } + } + if (startCount == 0 && stopCount == 0) { + MessageDialog.openInformation(Display + .getDefault().getActiveShell(), + "Verification", "No New Changes."); + } else { + boolean answer = MessageDialog.openQuestion( + Display.getDefault().getActiveShell(), + "Verification", status + + "\nDo you want to proceed?"); + if (answer) { + if (startGet || stopGet) + automate(VerificationType.GET, + autoStatus.get(Constants.GET)); + if (startPut || stopPut) + automate(VerificationType.PUT, + autoStatus.get(Constants.PUT)); + if (startPost || stopPost) + automate(VerificationType.POST, + autoStatus.get(Constants.POST)); + } + } + } } }); } }); } + private void automate(VerificationType type, boolean start) { + if (start) { + resourceManager.startAutomationRequest(type, resourceInSelection); + } else { + resourceManager.stopAutomationRequest(type, resourceInSelection); + } + } + private void addManagerListeners() { resourceManager .addResourceSelectionChangedUIListener(resourceSelectionChangedListener); 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 index 3c4d76e..a2a7d2e 100644 --- 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 @@ -21,6 +21,7 @@ import java.io.FileWriter; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; +import java.util.Date; import java.util.HashMap; import java.util.List; @@ -444,7 +445,13 @@ public class LogView extends ViewPart { out.close(); } } catch (IOException e) { - System.out.println("Error occurred during close."); + Activator + .getDefault() + .getLogManager() + .log(Level.ERROR.ordinal(), + new Date(), + "[" + e.getClass().getSimpleName() + + "]" + e.getMessage()); } } } 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 index ae9fa40..acf8933 100644 --- 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 @@ -19,6 +19,7 @@ package oic.simulator.clientcontroller.view; import java.util.List; import oic.simulator.clientcontroller.Activator; +import oic.simulator.clientcontroller.listener.IDevicePlatformInfoUIListener; import oic.simulator.clientcontroller.listener.IResourceSelectionChangedUIListener; import oic.simulator.clientcontroller.manager.ResourceManager; import oic.simulator.clientcontroller.remoteresource.MetaProperty; @@ -30,10 +31,14 @@ import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TableViewerColumn; import org.eclipse.jface.viewers.Viewer; import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.CTabFolder; +import org.eclipse.swt.custom.CTabItem; +import org.eclipse.swt.graphics.Color; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Table; import org.eclipse.ui.part.ViewPart; @@ -44,7 +49,9 @@ public class MetaPropertiesView extends ViewPart { public static final String VIEW_ID = "oic.simulator.clientcontroller.view.metaproperties"; - private TableViewer tableViewer; + private TableViewer defaultTblViewer; + private TableViewer deviceTblViewer; + private TableViewer platformTblViewer; private final String[] columnHeaders = { "Property", "Value" }; @@ -52,9 +59,15 @@ public class MetaPropertiesView extends ViewPart { private final Integer[] columnWidth = { 150, 150 }; private IResourceSelectionChangedUIListener resourceSelectionChangedListener; + private IDevicePlatformInfoUIListener devicePlatformInfoUIListener; private ResourceManager resourceManager; + private CTabFolder folder; + private CTabItem defaultPropTab; + private CTabItem devicePropTab; + private CTabItem platformPropTab; + public MetaPropertiesView() { resourceManager = Activator.getDefault().getResourceManager(); @@ -67,8 +80,37 @@ public class MetaPropertiesView extends ViewPart { @Override public void run() { - if (null != tableViewer) { - updateViewer(getData(resource)); + updateUI(resource); + } + }); + } + }; + + devicePlatformInfoUIListener = new IDevicePlatformInfoUIListener() { + + @Override + public void onPlatformInfoFound() { + Display.getDefault().asyncExec(new Runnable() { + + @Override + public void run() { + if (null != deviceTblViewer) { + updateViewer(deviceTblViewer, getDevicePropData()); + } + } + }); + + } + + @Override + public void onDeviceInfoFound() { + Display.getDefault().asyncExec(new Runnable() { + + @Override + public void run() { + if (null != platformTblViewer) { + updateViewer(platformTblViewer, + getPlatformPropData()); } } }); @@ -76,48 +118,164 @@ public class MetaPropertiesView extends ViewPart { }; } + private void updateUI(final RemoteResource resource) { + if (null != defaultTblViewer) { + updateViewer(defaultTblViewer, getDefaultPropData(resource)); + } + if (null != deviceTblViewer) { + updateViewer(deviceTblViewer, getDevicePropData()); + } + if (null != platformTblViewer) { + updateViewer(platformTblViewer, getPlatformPropData()); + } + } + @Override public void createPartControl(Composite parent) { - parent.setLayout(new GridLayout(1, false)); + parent.setLayout(new GridLayout()); + GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); + parent.setLayoutData(gd); + + // Create a Tab Folder. + folder = new CTabFolder(parent, SWT.BORDER); + gd = new GridData(SWT.FILL, SWT.FILL, true, true); + folder.setLayoutData(gd); + folder.setSimple(false); + folder.setUnselectedCloseVisible(false); + folder.setUnselectedImageVisible(false); + + createDefaultPropertiesTab(); + + createDevicePropertiesTab(); + + createPlatformPropertiesTab(); + + folder.setSelection(defaultPropTab); + + addManagerListeners(); + + // Check whether there is any resource selected already + updateUI(null); + } + + private void createDefaultPropertiesTab() { + defaultPropTab = new CTabItem(folder, SWT.NULL); + defaultPropTab.setText("Default"); + + // Adding the group to the folder. + Group propGroup = new Group(folder, SWT.NONE); - tableViewer = new TableViewer(parent, SWT.SINGLE | SWT.H_SCROLL + Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE); + propGroup.setBackground(color); + + propGroup.setLayout(new GridLayout()); + GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); + propGroup.setLayoutData(gd); + + defaultTblViewer = new TableViewer(propGroup, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER); - createColumns(tableViewer); + createColumns(defaultTblViewer); - // make lines and header visible - final Table table = tableViewer.getTable(); + // Make lines and header visible + final Table table = defaultTblViewer.getTable(); table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); table.setHeaderVisible(true); table.setLinesVisible(true); - tableViewer.setContentProvider(new PropertycontentProvider()); + defaultTblViewer.setContentProvider(new PropertycontentProvider()); - addManagerListeners(); + defaultPropTab.setControl(propGroup); + } - // Check whether there is any resource selected already - List propertyList = getData(null); - if (null != propertyList) { - updateViewer(propertyList); - } + private void createDevicePropertiesTab() { + devicePropTab = new CTabItem(folder, SWT.NULL); + devicePropTab.setText("Device"); + + // Adding the group to the folder. + Group propGroup = new Group(folder, SWT.NONE); + + Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE); + propGroup.setBackground(color); + + propGroup.setLayout(new GridLayout()); + GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); + propGroup.setLayoutData(gd); + + deviceTblViewer = new TableViewer(propGroup, SWT.SINGLE | SWT.H_SCROLL + | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER); + + createColumns(deviceTblViewer); + + // Make lines and header visible + final Table table = deviceTblViewer.getTable(); + table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + table.setHeaderVisible(true); + table.setLinesVisible(true); + + deviceTblViewer.setContentProvider(new PropertycontentProvider()); + + devicePropTab.setControl(propGroup); + } + + private void createPlatformPropertiesTab() { + platformPropTab = new CTabItem(folder, SWT.NULL); + platformPropTab.setText("Platform"); + // Adding the group to the folder. + Group propGroup = new Group(folder, SWT.NONE); + + Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE); + propGroup.setBackground(color); + + propGroup.setLayout(new GridLayout()); + GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); + propGroup.setLayoutData(gd); + + platformTblViewer = new TableViewer(propGroup, SWT.SINGLE + | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER); + + createColumns(platformTblViewer); + + // Make lines and header visible + final Table table = platformTblViewer.getTable(); + table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + table.setHeaderVisible(true); + table.setLinesVisible(true); + + platformTblViewer.setContentProvider(new PropertycontentProvider()); + + platformPropTab.setControl(propGroup); } - private List getData(RemoteResource resource) { + private List getDefaultPropData(RemoteResource resource) { if (null == resource) { resource = Activator.getDefault().getResourceManager() .getCurrentResourceInSelection(); } List metaPropertyList = resourceManager - .getMetaProperties(resource); + .getDefaultProperties(resource); return metaPropertyList; } - private void updateViewer(List metaPropertyList) { - if (null != tableViewer) { - Table tbl = tableViewer.getTable(); + private List getDevicePropData() { + List metaPropertyList = resourceManager + .getDeviceProperties(); + return metaPropertyList; + } + + private List getPlatformPropData() { + List metaPropertyList = resourceManager + .getPlatformProperties(); + return metaPropertyList; + } + + private void updateViewer(TableViewer tblViewer, + List metaPropertyList) { + if (null != tblViewer) { + Table tbl = tblViewer.getTable(); if (null != metaPropertyList) { - tableViewer.setInput(metaPropertyList.toArray()); + tblViewer.setInput(metaPropertyList.toArray()); if (!tbl.isDisposed()) { tbl.setLinesVisible(true); } @@ -167,6 +325,8 @@ public class MetaPropertiesView extends ViewPart { private void addManagerListeners() { resourceManager .addResourceSelectionChangedUIListener(resourceSelectionChangedListener); + resourceManager + .addDevicePlatformInfoUIListener(devicePlatformInfoUIListener); } class PropertycontentProvider implements IStructuredContentProvider { @@ -183,7 +343,6 @@ public class MetaPropertiesView extends ViewPart { public Object[] getElements(Object element) { return (Object[]) element; } - } @Override 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 index 2082a42..b059a4d 100644 --- 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 @@ -60,6 +60,7 @@ import org.eclipse.ui.PlatformUI; import org.eclipse.ui.dialogs.FilteredTree; import org.eclipse.ui.dialogs.PatternFilter; import org.eclipse.ui.part.ViewPart; +import org.oic.simulator.SimulatorException; /** * This class manages and shows the resource manager view in the perspective. @@ -97,7 +98,6 @@ public class ResourceManagerView extends ViewPart { @Override public void onNewResourceFound(final RemoteResource resource) { - System.out.println("View: onNewResourceFound"); if (null == resource) { return; } @@ -123,16 +123,12 @@ public class ResourceManagerView extends ViewPart { // Close the find dialog if (null != findDialog) { - boolean status = findDialog.close(); - System.out - .println("dialog close status: " + status); + findDialog.close(); } // Close the refresh dialog if (null != refreshDialog) { - boolean status = refreshDialog.close(); - System.out - .println("dialog close status: " + status); + refreshDialog.close(); } } }); @@ -182,11 +178,6 @@ public class ResourceManagerView extends ViewPart { folder.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { - /* - * CTabItem selectedTab = folder.getSelection(); if(selectedTab - * == foundResTab) { System.out.println("Found resources tab"); - * } else { System.out.println("Favorite resources tab"); } - */ // Tab is switched. treeViewer.setSelection(null); favTreeViewer.setSelection(null); @@ -276,68 +267,10 @@ public class ResourceManagerView extends ViewPart { for (int index = 0; index < items.length; index++) { items[index].dispose(); } - MenuItem uploadRAMLItem = new MenuItem(menu, SWT.NONE); - uploadRAMLItem.setText("Upload RAML Configuration"); - uploadRAMLItem - .addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - // Open the RAML configuration dialog if - // RAML file is not yet uploaded for the - // currently selected resource - RemoteResource resource = resourceManager - .getCurrentResourceInSelection(); - if (null == resource) { - return; - } - if (!resource.isConfigUploaded()) { - // Open the dialog in a separate - // UI thread. - PlatformUI.getWorkbench() - .getDisplay() - .syncExec(new Thread() { - @Override - public void run() { - LoadRAMLDialog ramlDialog = new LoadRAMLDialog( - Display.getDefault() - .getActiveShell()); - if (ramlDialog - .open() != Window.OK) { - return; - } - String configFilePath = ramlDialog - .getConfigFilePath(); - if (null == configFilePath - || configFilePath - .length() < 1) { - MessageDialog - .openInformation( - Display.getDefault() - .getActiveShell(), - "Invalid RAML Config path", - "Configuration file path is invalid."); - return; - } - resourceManager - .setConfigFilePath( - resourceManager - .getCurrentResourceInSelection(), - configFilePath); - } - }); - } else { - MessageDialog - .openInformation(Display - .getDefault() - .getActiveShell(), - "Already Uploaded", - "Configuration file for the selected resource is already uploaded"); - } - } - }); + setupUploadRamlMenuItem(menu); - RemoteResource resource = resourceManager - .getCurrentResourceInSelection(); + final RemoteResource resource = (RemoteResource) ((IStructuredSelection) treeViewer + .getSelection()).getFirstElement(); if (null == resource) { return; } @@ -349,17 +282,11 @@ public class ResourceManagerView extends ViewPart { .addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { - RemoteResource resource = (RemoteResource) ((IStructuredSelection) treeViewer - .getSelection()) - .getFirstElement(); - if (null == resource) { - return; - } - System.out.println("Selected resource:" - + resource.getResourceURI()); if (!resource.isFavorite()) { resourceManager .addResourcetoFavorites(resource); + resourceManager + .addResourceURItoFavorites(resource); } else { resourceManager .removeResourceFromFavorites(resource); @@ -422,6 +349,9 @@ public class ResourceManagerView extends ViewPart { for (int index = 0; index < items.length; index++) { items[index].dispose(); } + + setupUploadRamlMenuItem(menu); + MenuItem addToFavMenuItem = new MenuItem(menu, SWT.NONE); addToFavMenuItem.setText("Remove from favorites"); addToFavMenuItem @@ -447,6 +377,73 @@ public class ResourceManagerView extends ViewPart { } } + private void setupUploadRamlMenuItem(Menu menu) { + MenuItem uploadRAMLItem = new MenuItem(menu, SWT.NONE); + uploadRAMLItem.setText("Upload RAML Configuration"); + uploadRAMLItem.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + // Open the RAML configuration dialog if + // RAML file is not yet uploaded for the + // currently selected resource + RemoteResource resource = resourceManager + .getCurrentResourceInSelection(); + if (null == resource) { + return; + } + if (resource.isConfigUploaded()) { + boolean answer = MessageDialog + .openQuestion( + Display.getDefault().getActiveShell(), + "Upload Another RAML", + "This resource is already configured with RAML.\n" + + "Do you want to upload a new configuration?"); + if (!answer) { + return; + } + } + // Open the dialog in a separate + // UI thread. + PlatformUI.getWorkbench().getDisplay().syncExec(new Thread() { + @Override + public void run() { + LoadRAMLDialog ramlDialog = new LoadRAMLDialog(Display + .getDefault().getActiveShell()); + if (ramlDialog.open() != Window.OK) { + return; + } + String configFilePath = ramlDialog.getConfigFilePath(); + if (null == configFilePath + || configFilePath.length() < 1) { + MessageDialog.openInformation(Display.getDefault() + .getActiveShell(), + "Invalid RAML Config path", + "Configuration file path is invalid."); + return; + } + try { + boolean result = resourceManager.setConfigFilePath( + resourceManager + .getCurrentResourceInSelection(), + configFilePath); + if (!result) { + MessageDialog + .openInformation(Display.getDefault() + .getActiveShell(), + "Operation failed", + "Failed to obtain the details from the given RAML."); + } + } catch (SimulatorException e) { + MessageDialog.openInformation(Display.getDefault() + .getActiveShell(), "Invalid RAML", + "Given configuration file is invalid."); + } + } + }); + } + }); + } + private void addUIListeners() { findResButton.addSelectionListener(new SelectionAdapter() { @Override @@ -467,38 +464,37 @@ public class ResourceManagerView extends ViewPart { Set searchTypes = findWizard .getSearchTypes(); - if (null != searchTypes) { - System.out.println(searchTypes); - // Call native method to clear existing - // resources of - // the given search types. - resourceManager.deleteResources(searchTypes); - - // Update the tree - treeViewer.refresh(); - favTreeViewer.refresh(); - - // Call native method to find Resources - boolean result = resourceManager - .findResourceRequest(searchTypes); - if (result) { - searchUIOperation(false); - } else { - MessageDialog - .openError(Display.getDefault() - .getActiveShell(), - "Find Resource status", - "Operation failed due to some problems in core layer."); - } - - // Store this information for refresh - // functionality - resourceManager - .setLastKnownSearchTypes(searchTypes); + // Delete cached details of resources based on the + // given search types. + // If there are no resource types to search, then + // all resources + // will be deleted. + resourceManager.deleteResources(searchTypes); + + // Update the tree + treeViewer.refresh(); + favTreeViewer.refresh(); - // Change the refresh visibility - refreshButton.setEnabled(true); + // Call native method to find Resources + boolean result = resourceManager + .findResourceRequest(searchTypes); + if (result) { + searchUIOperation(false); + } else { + MessageDialog + .openError(Display.getDefault() + .getActiveShell(), + "Find Resource status", + "Operation failed due to some problems in core layer."); } + + // Store this information for refresh + // functionality + resourceManager + .setLastKnownSearchTypes(searchTypes); + + // Change the refresh visibility + refreshButton.setEnabled(true); } } }); @@ -510,13 +506,12 @@ public class ResourceManagerView extends ViewPart { public void widgetSelected(SelectionEvent e) { Set searchTypes = resourceManager .getLastKnownSearchTypes(); - if (null == searchTypes) { - return; - } setFoundResource(false); - // Call native method to clear existing resources of the given - // search types. + // Delete cached details of resources based on the given search + // types. + // If there are no resource types to search, then all resources + // will be deleted. resourceManager.deleteResources(searchTypes); // Update the tree @@ -554,8 +549,6 @@ public class ResourceManagerView extends ViewPart { if (null == resource) { return; } - System.out.println("Selected resource: " - + resource.getResourceURI()); resourceManager.resourceSelectionChanged(resource); } } @@ -608,7 +601,6 @@ public class ResourceManagerView extends ViewPart { try { Thread.sleep(Constants.FIND_RESOURCES_TIMEOUT * 1000); } catch (InterruptedException e) { - System.out.println("Interrupted during sleep."); return; } @@ -695,7 +687,6 @@ class TreeContentProvider implements ITreeContentProvider { @Override public Object[] getElements(Object parent) { - System.out.println("Inside getElements()"); List resourceList = Activator.getDefault() .getResourceManager().getResourceList(); return resourceList.toArray(); @@ -731,7 +722,6 @@ class FavTreeContentProvider implements ITreeContentProvider { @Override public Object[] getElements(Object parent) { - System.out.println("Inside getElements()"); List resourceList = Activator.getDefault() .getResourceManager().getFavResourceList(); return resourceList.toArray(); @@ -753,14 +743,11 @@ class TreeLabelProvider extends LabelProvider { @Override public String getText(Object element) { RemoteResource resource = (RemoteResource) element; - return resource.getResourceURI(); + return resource.getRemoteResourceRef().getURI(); } @Override public Image getImage(Object element) { - RemoteResource resource = (RemoteResource) element; - ResourceManager resourceManager = Activator.getDefault() - .getResourceManager(); - return resourceManager.getImage(resource.getResourceURI()); + return null; } } \ No newline at end of file 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 index 6316674..eeda973 100644 --- 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 @@ -16,14 +16,13 @@ package oic.simulator.clientcontroller.view.dialogs; -import java.util.HashSet; import java.util.Set; import oic.simulator.clientcontroller.utils.Constants; +import oic.simulator.clientcontroller.utils.Utility; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; @@ -41,24 +40,19 @@ import org.eclipse.swt.widgets.Text; */ public class FindResourcePage extends WizardPage { - private Button stdResTypeRbtn; - private CCombo resourceTypeCmb; - private Button cusResTypeRbtn; + private Button allRbtn; + private Button resTypeRbtn; private Text resTypeTxt; - private Label stdRTypeLbl; - private Label cusRTypeLbl; + private Label resTypeLbl; private Set typesToSearch; - private String dummyRType; - protected FindResourcePage() { super("Find Resource"); } @Override public void createControl(Composite parent) { - setPageComplete(false); setTitle(Constants.FIND_PAGE_TITLE); setMessage(Constants.FIND_PAGE_MESSAGE); @@ -69,7 +63,7 @@ public class FindResourcePage extends WizardPage { compContent.setLayoutData(gd); Group configGroup = new Group(compContent, SWT.NONE); - gridLayout = new GridLayout(1, false); + gridLayout = new GridLayout(2, false); gridLayout.verticalSpacing = 10; gridLayout.marginTop = 5; configGroup.setLayout(gridLayout); @@ -79,41 +73,26 @@ public class FindResourcePage extends WizardPage { configGroup.setLayoutData(gd); configGroup.setText("Resource Type"); - stdResTypeRbtn = new Button(configGroup, SWT.RADIO); - stdResTypeRbtn.setText("Standard OIC Resources"); - - Composite stdConfigComp = new Composite(configGroup, SWT.NONE); - stdConfigComp.setLayout(new GridLayout(2, false)); + allRbtn = new Button(configGroup, SWT.RADIO); + allRbtn.setText("All"); gd = new GridData(); - gd.horizontalAlignment = SWT.FILL; - gd.grabExcessHorizontalSpace = true; - stdConfigComp.setLayoutData(gd); - - stdRTypeLbl = new Label(stdConfigComp, SWT.NONE); - stdRTypeLbl.setText("ResourceType:"); - stdRTypeLbl.setEnabled(false); + gd.horizontalSpan = 2; + allRbtn.setLayoutData(gd); + allRbtn.setSelection(true); - resourceTypeCmb = new CCombo(stdConfigComp, SWT.READ_ONLY | SWT.BORDER); + resTypeRbtn = new Button(configGroup, SWT.RADIO); + resTypeRbtn.setText("Specific Resource types (seperated by commas)"); gd = new GridData(); - gd.widthHint = 150; - resourceTypeCmb.setLayoutData(gd); - resourceTypeCmb.setEnabled(false); + gd.horizontalSpan = 2; + resTypeRbtn.setLayoutData(gd); - cusResTypeRbtn = new Button(configGroup, SWT.RADIO); - cusResTypeRbtn.setText("Custom Resources"); + resTypeLbl = new Label(configGroup, SWT.NONE); + resTypeLbl.setText("Resource Types:"); + resTypeLbl.setEnabled(false); - Composite cusConfigComp = new Composite(configGroup, SWT.NONE); - cusConfigComp.setLayout(new GridLayout(2, false)); - gd = new GridData(); - gd.horizontalAlignment = SWT.FILL; - gd.grabExcessHorizontalSpace = true; - cusConfigComp.setLayoutData(gd); - - cusRTypeLbl = new Label(cusConfigComp, SWT.NONE); - cusRTypeLbl.setText("Enter ResourceType:"); - cusRTypeLbl.setEnabled(false); - - resTypeTxt = new Text(cusConfigComp, SWT.BORDER); + resTypeTxt = new Text(configGroup, SWT.BORDER); + resTypeTxt.setToolTipText("Ex: sample.light, hall.fridge"); + resTypeTxt.setMessage("Ex: sample.light, hall.fridge"); gd = new GridData(); gd.minimumWidth = 200; gd.horizontalAlignment = SWT.FILL; @@ -121,143 +100,58 @@ public class FindResourcePage extends WizardPage { resTypeTxt.setLayoutData(gd); resTypeTxt.setEnabled(false); - populateDataInUI(); - addUIListeners(); setControl(compContent); } - private void populateDataInUI() { - // Populate Standard resource-types in Combo - populateResourceTypeCombo(); - } - - private void populateResourceTypeCombo() { - /* - * List configList; configList = - * Activator.getDefault().getManager().getResourceConfigurationList(); - * if(null != configList) { Iterator itr = - * configList.iterator(); while(itr.hasNext()) { - * resourceTypeCmb.add(itr.next()); } } - */ - - // TODO: Temporarily adding a resourceType for testing - // resourceTypeCmb.add("oic.r.light"); - // Currently for standard resources we are using resource type as sample.light. - resourceTypeCmb.add("sample.light"); - - // By default, selecting the first item in the resourceType combo - if (resourceTypeCmb.getItemCount() > 0) { - resourceTypeCmb.select(0); - // TODO: Get the RAML configuration file path of the selected - // resource - // configFilePath = - // Activator.getManager().getConfigFilePath(resourceTypeCmb.getItem(0)); - } - } - private void addUIListeners() { - stdResTypeRbtn.addSelectionListener(new SelectionAdapter() { + allRbtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { - // Clear the existing items from the search list - if (null != typesToSearch) - typesToSearch.clear(); - - // Set the configFilePath to the first item in the combo - if (resourceTypeCmb.getItemCount() > 0) { - resourceTypeCmb.select(0); - addSearchType(resourceTypeCmb.getText()); - } - - setPageComplete(isSelectionDone()); - + typesToSearch = null; + setPageComplete(true); // Change the visibility of widgets - changeVisibility(true); + changeVisibility(false); } }); - cusResTypeRbtn.addSelectionListener(new SelectionAdapter() { + resTypeRbtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { - // Clear the existing items from the search list - if (null != typesToSearch) - typesToSearch.clear(); - - addSearchType(resTypeTxt.getText()); - - setPageComplete(isSelectionDone()); + String typeText = resTypeTxt.getText(); + if (null != typeText && typeText.length() > 0) { + typesToSearch = Utility.splitStringByComma(typeText); + } + if (null != typesToSearch && typesToSearch.size() > 0) { + setPageComplete(true); + } else { + setPageComplete(false); + } // Change the visibility of widgets - changeVisibility(false); - + changeVisibility(true); resTypeTxt.setFocus(); } }); - resourceTypeCmb.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - int index = resourceTypeCmb.getSelectionIndex(); - if (index < 0) { - return; - } - String resourceType = resourceTypeCmb.getItem(index); - addSearchType(resourceType); - setPageComplete(isSelectionDone()); - } - }); - resTypeTxt.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { - String resourceType = resTypeTxt.getText(); - if (null != dummyRType) { - removeSearchType(dummyRType); + String typeText = resTypeTxt.getText(); + typesToSearch = Utility.splitStringByComma(typeText); + if (null != typesToSearch && typesToSearch.size() > 0) { + setPageComplete(true); + } else { + setPageComplete(false); } - dummyRType = resourceType; - addSearchType(resourceType); - setPageComplete(isSelectionDone()); } }); } private void changeVisibility(boolean standard) { - stdRTypeLbl.setEnabled(standard); - resourceTypeCmb.setEnabled(standard); - cusRTypeLbl.setEnabled(!standard); - resTypeTxt.setEnabled(!standard); - } - - private boolean isSelectionDone() { - if (null == typesToSearch || typesToSearch.size() < 1) { - return false; - } - return true; - } - - private void addSearchType(String resourceType) { - if (null == resourceType) - return; - resourceType = resourceType.trim(); - if (resourceType.length() < 1) { - return; - } - if (null == typesToSearch) { - typesToSearch = new HashSet(); - } - typesToSearch.add(resourceType); - } - - private void removeSearchType(String resourceType) { - if (null == resourceType || null == typesToSearch) - return; - resourceType = resourceType.trim(); - if (resourceType.length() < 1) { - return; - } - typesToSearch.remove(resourceType); + resTypeLbl.setEnabled(standard); + resTypeTxt.setEnabled(standard); } public Set getSearchTypes() { 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 index d19e1d4..90ace2b 100644 --- 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 @@ -16,8 +16,11 @@ package oic.simulator.clientcontroller.view.dialogs; +import java.io.FileInputStream; + import oic.simulator.clientcontroller.utils.Constants; +import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.TitleAreaDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; @@ -100,10 +103,11 @@ public class LoadRAMLDialog extends TitleAreaDialog { .getWorkbench().getDisplay().getActiveShell(), SWT.NONE); fileDialog .setFilterExtensions(Constants.BROWSE_RAML_FILTER_EXTENSIONS); - configFilePath = fileDialog.open(); - if (null == configFilePath) { - System.out.println("Config file path is null"); + String path = fileDialog.open(); + if (null == path) { configFilePath = ""; + } else { + configFilePath = path; } locationTxt.setText(configFilePath); } @@ -115,6 +119,25 @@ public class LoadRAMLDialog extends TitleAreaDialog { } @Override + protected void okPressed() { + configFilePath = locationTxt.getText(); + if (null == configFilePath) { + return; + } + try { + new FileInputStream(configFilePath); + } catch (Exception e) { + MessageDialog + .openError(getShell(), "Invalid File", + "File doesn't exist. Either the file path or file name is invalid."); + // TODO: Instead of MessageDialog, errors may be shown on wizard + // itself. + return; + } + close(); + } + + @Override public boolean isHelpAvailable() { return false; } 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 index 26c11b4..2e9bc3c 100644 --- 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 @@ -16,27 +16,31 @@ package oic.simulator.clientcontroller.view.dialogs; +import java.util.Iterator; import java.util.List; import oic.simulator.clientcontroller.Activator; +import oic.simulator.clientcontroller.manager.ResourceManager; import oic.simulator.clientcontroller.remoteresource.PutPostAttributeModel; import oic.simulator.clientcontroller.utils.Constants; import org.eclipse.jface.dialogs.IDialogConstants; +import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.TitleAreaDialog; import org.eclipse.jface.viewers.CellEditor; import org.eclipse.jface.viewers.CheckboxCellEditor; import org.eclipse.jface.viewers.ColumnLabelProvider; +import org.eclipse.jface.viewers.ComboBoxCellEditor; import org.eclipse.jface.viewers.EditingSupport; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.StyledCellLabelProvider; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TableViewerColumn; -import org.eclipse.jface.viewers.TextCellEditor; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerCell; import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.graphics.Image; @@ -45,9 +49,9 @@ import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Table; -import org.eclipse.swt.widgets.Text; /** * This dialog is used for generating a POST request. @@ -61,7 +65,7 @@ public class PostRequestDialog extends TitleAreaDialog { private final Integer[] attTblColWidth = { 200, 200, 50 }; private List modelList = null; - + public PostRequestDialog(Shell parentShell, List modelList) { super(parentShell); @@ -139,6 +143,7 @@ public class PostRequestDialog extends TitleAreaDialog { } } }); + attValue.setEditingSupport(new AttributeValueEditor(attTblViewer)); TableViewerColumn updateColumn = new TableViewerColumn(tableViewer, @@ -203,62 +208,97 @@ public class PostRequestDialog extends TitleAreaDialog { class AttributeValueEditor extends EditingSupport { private final TableViewer viewer; - private final CellEditor editor; - private final Text txt; + private CCombo comboBox; + public AttributeValueEditor(TableViewer viewer) { super(viewer); this.viewer = viewer; - editor = new TextCellEditor(viewer.getTable()); - txt = (Text)editor.getControl(); - if(null != txt) { - txt.addModifyListener(new ModifyListener() { + } + + @Override + protected boolean canEdit(Object arg0) { + return true; + } + + @Override + protected CellEditor getCellEditor(Object element) { + PutPostAttributeModel attributeInSelection = (PutPostAttributeModel) element; + + String values[] = null; + List valueSet = attributeInSelection.getValues(); + values = convertListToStringArray(valueSet); + + ComboBoxCellEditor comboEditor = new ComboBoxCellEditor( + viewer.getTable(), values); + comboBox = (CCombo) comboEditor.getControl(); + if (null != comboBox) { + comboBox.addModifyListener(new ModifyListener() { @Override - public void modifyText(ModifyEvent e) { - IStructuredSelection selection = (IStructuredSelection)AttributeValueEditor.this.viewer.getSelection(); - PutPostAttributeModel att = (PutPostAttributeModel)selection.getFirstElement(); - if(null == att) { + public void modifyText(ModifyEvent e) { + IStructuredSelection selection = (IStructuredSelection) AttributeValueEditor.this.viewer + .getSelection(); + PutPostAttributeModel att = (PutPostAttributeModel) selection + .getFirstElement(); + if (null == att) { return; } - String newValue = txt.getText(); - if(null != newValue && !newValue.isEmpty()) { + String newValue = comboBox.getText(); + if (null != newValue && !newValue.isEmpty()) { att.setModified(true); - } - else { + } else { att.setModified(false); } AttributeValueEditor.this.viewer.update(att, null); } }); - } - } - - @Override - protected boolean canEdit(Object arg0) { - return true; - } - - @Override - protected CellEditor getCellEditor(Object element) { - return editor; + return comboEditor; } @Override protected Object getValue(Object element) { - PutPostAttributeModel model = (PutPostAttributeModel) element; - return model.getAttValue(); + int indexOfItem = 0; + PutPostAttributeModel att = (PutPostAttributeModel) element; + String valueString = att.getAttValue(); + List valueSet = att.getValues(); + if (null != valueSet) { + indexOfItem = valueSet.indexOf(valueString); + } + if (indexOfItem == -1) { + indexOfItem = 0; + } + return indexOfItem; } @Override protected void setValue(Object element, Object value) { - PutPostAttributeModel model = (PutPostAttributeModel) element; - // Compare the actual value and the new value - // If there is a change, then its corresponding check box should be - // checked. - String newValue = String.valueOf(value); - model.setAttValue(newValue); + PutPostAttributeModel att = (PutPostAttributeModel) element; + int index; + try { + index = Integer.parseInt(String.valueOf(value)); + } catch (NumberFormatException nfe) { + index = -1; + } + String newValue; + if (index == -1) { + newValue = comboBox.getText(); + att.prependNewValue(newValue); + } else { + newValue = att.getValues().get(index); + } + att.setAttValue(newValue); viewer.update(element, null); } + + public String[] convertListToStringArray(List valueList) { + String[] strArr; + if (null != valueList && valueList.size() > 0) { + strArr = valueList.toArray(new String[1]); + } else { + strArr = new String[1]; + } + return strArr; + } } class UpdateEditor extends EditingSupport { @@ -289,9 +329,30 @@ public class PostRequestDialog extends TitleAreaDialog { @Override protected void setValue(Object element, Object value) { PutPostAttributeModel model = (PutPostAttributeModel) element; - boolean status = (boolean) value; + boolean status = (Boolean) value; model.setModified(status); viewer.update(element, null); } } + + @Override + protected void okPressed() { + String value; + PutPostAttributeModel attModel; + Iterator itr; + itr = modelList.iterator(); + while (itr.hasNext()) { + attModel = itr.next(); + if (null == attModel) { + return; + } + value = attModel.getAttValue(); + if (null == value || value.isEmpty()) { + MessageDialog.openError(Display.getDefault().getActiveShell(), + "Empty value", "Attribute value should not be empty."); + return; + } + } + close(); + } } 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 index 3ba0c87..69dbeeb 100644 --- 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 @@ -16,27 +16,31 @@ package oic.simulator.clientcontroller.view.dialogs; +import java.util.Iterator; import java.util.List; import oic.simulator.clientcontroller.remoteresource.PutPostAttributeModel; import org.eclipse.jface.dialogs.IDialogConstants; +import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.TitleAreaDialog; import org.eclipse.jface.viewers.CellEditor; +import org.eclipse.jface.viewers.ComboBoxCellEditor; import org.eclipse.jface.viewers.EditingSupport; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.StyledCellLabelProvider; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TableViewerColumn; -import org.eclipse.jface.viewers.TextCellEditor; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerCell; import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Table; @@ -148,12 +152,11 @@ public class PutRequestDialog extends TitleAreaDialog { class AttributeValueEditor extends EditingSupport { private final TableViewer viewer; - private final CellEditor editor; + private CCombo comboBox; public AttributeValueEditor(TableViewer viewer) { super(viewer); this.viewer = viewer; - editor = new TextCellEditor(viewer.getTable()); } @Override @@ -163,21 +166,62 @@ public class PutRequestDialog extends TitleAreaDialog { @Override protected CellEditor getCellEditor(Object element) { - return editor; + PutPostAttributeModel attributeInSelection = (PutPostAttributeModel) element; + + String values[] = null; + List valueSet = attributeInSelection.getValues(); + values = convertListToStringArray(valueSet); + + ComboBoxCellEditor comboEditor = new ComboBoxCellEditor( + viewer.getTable(), values); + comboBox = (CCombo) comboEditor.getControl(); + return comboEditor; } @Override protected Object getValue(Object element) { - PutPostAttributeModel model = (PutPostAttributeModel) element; - return model.getAttValue(); + int indexOfItem = 0; + PutPostAttributeModel att = (PutPostAttributeModel) element; + String valueString = att.getAttValue(); + List valueSet = att.getValues(); + if (null != valueSet) { + indexOfItem = valueSet.indexOf(valueString); + } + if (indexOfItem == -1) { + indexOfItem = 0; + } + return indexOfItem; } @Override protected void setValue(Object element, Object value) { - PutPostAttributeModel model = (PutPostAttributeModel) element; - model.setAttValue(String.valueOf(value)); + PutPostAttributeModel att = (PutPostAttributeModel) element; + int index; + try { + index = Integer.parseInt(String.valueOf(value)); + } catch (NumberFormatException nfe) { + index = -1; + } + if (index == -1) { + String customValue = comboBox.getText(); + att.prependNewValue(customValue); + att.setAttValue(customValue); + } else { + String attValue = att.getValues().get(index); + att.setAttValue(attValue); + } viewer.update(element, null); } + + public String[] convertListToStringArray(List valueList) { + String[] strArr; + if (null != valueList && valueList.size() > 0) { + strArr = valueList.toArray(new String[1]); + } else { + strArr = new String[1]; + } + return strArr; + } } public List getUpdatedModel() { @@ -202,4 +246,25 @@ public class PutRequestDialog extends TitleAreaDialog { } return super.createButton(parent, id, label, defaultButton); } + + @Override + protected void okPressed() { + String value; + PutPostAttributeModel attModel; + Iterator itr; + itr = modelList.iterator(); + while (itr.hasNext()) { + attModel = itr.next(); + if (null == attModel) { + return; + } + value = attModel.getAttValue(); + if (null == value || value.isEmpty()) { + MessageDialog.openError(Display.getDefault().getActiveShell(), + "Empty value", "Attribute value should not be empty."); + return; + } + } + close(); + } } 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 index a221760..b6ab69f 100644 --- 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 @@ -20,12 +20,9 @@ import java.util.ArrayList; import java.util.Map; import java.util.Set; -import oic.simulator.clientcontroller.Activator; -import oic.simulator.clientcontroller.manager.ResourceManager; import oic.simulator.clientcontroller.utils.Constants; import org.eclipse.jface.dialogs.IDialogConstants; -import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.TrayDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; @@ -35,7 +32,6 @@ import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Shell; @@ -89,38 +85,18 @@ public class VerificationDialog extends TrayDialog { @Override public void widgetSelected(SelectionEvent e) { - boolean checked = checkbox.getSelection(); - boolean answer = MessageDialog.openQuestion(Display - .getDefault().getActiveShell(), "Verification", - "Do you want to " - + (checked ? "enable" : "disable") - + " the verification?"); - if (!answer) { - checkbox.setSelection(!checked); - checked = !checked; - } else { - ResourceManager resourceManager = Activator - .getDefault().getResourceManager(); - String reqTypeTxt = checkbox.getText(); - int reqType; - if (reqTypeTxt.equals("Get")) { - reqType = Constants.GET_AUTOMATION_INDEX; - } else if (reqTypeTxt.equals("Put")) { - reqType = Constants.PUT_AUTOMATION_INDEX; - } else {// if(reqTypeTxt.equals("Post")) { - reqType = Constants.POST_AUTOMATION_INDEX; - } - if (checked) { - resourceManager.startAutomationRequest(reqType, - resourceManager - .getCurrentResourceInSelection()); - } else { - resourceManager.stopAutomationRequest(reqType, - resourceManager - .getCurrentResourceInSelection()); - } + Button btn = (Button) e.getSource(); + if (null == btn) { + return; + } + String btnText = btn.getText(); + if (btnText.equalsIgnoreCase(Constants.GET)) { + automationStatus.put(Constants.GET, btn.getSelection()); + } else if (btnText.equalsIgnoreCase(Constants.PUT)) { + automationStatus.put(Constants.PUT, btn.getSelection()); + } else if (btnText.equalsIgnoreCase(Constants.POST)) { + automationStatus.put(Constants.POST, btn.getSelection()); } - automationStatus.put(str, checked); } }); } @@ -139,4 +115,8 @@ public class VerificationDialog extends TrayDialog { public boolean isHelpAvailable() { return false; } + + public Map getAutomationStatus() { + return automationStatus; + } } 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 index ca80ad1..d2abfbb 100644 --- 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 @@ -50,7 +50,12 @@ public class LogLabelProvider extends LabelProvider implements } else if (columnIndex == 1) { return dateFormat.format(entry.getDate()); } else { - return entry.getMessage(); + String msg = entry.getMessage(); + int pos = msg.indexOf('\n'); + if (pos != -1) { + msg = msg.substring(0, pos); + } + return msg; } } 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 index 81110b0..ac2e8ed 100644 --- 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 @@ -58,7 +58,7 @@ public class LoggerCallback implements ILogger { Calendar calendar; calendar = Calendar.getInstance(); - calendar.set(Calendar.HOUR, h); + calendar.set(Calendar.HOUR_OF_DAY, h); calendar.set(Calendar.MINUTE, m); calendar.set(Calendar.SECOND, s); diff --git a/service/simulator/java/eclipse-plugin/README.txt b/service/simulator/java/eclipse-plugin/README.txt index f79c607..046db29 100644 --- a/service/simulator/java/eclipse-plugin/README.txt +++ b/service/simulator/java/eclipse-plugin/README.txt @@ -1,26 +1,68 @@ Eclipse plug-in +----------------- -Pre-requisites --------------- - 1.Build the IoTivity project for linux: - Run the "scons" command in iotivity home directory. - It generates the libraries in ~/iotivity/out/linux//release directory. - 2.Copy the libraries mentioned below into the libs folder of the plug-in project. - Required libraries: libSimulatorManager.so, liboc.so, liboctbstack.so, and liboc_logger.so - 3.Import the Simulator Java SDK project from ~/iotivity/service/simulator/java/sdk/ into Eclipse IDE as given below. - File -> Import -> Select 'Existing projects into Workspace' under General category -> click next -> Browse to the above mentioned location -> - click Finish. - Export the sdk project as JAR file. - Right click the project -> Export -> select 'JAR file' option under Java -> Next -> Finish. - Copy the JAR file into the libs folder of the plug-in project. - -Steps to run the plug-in ------------------------- - 1.Import the plug-in project from ~/iotivity/service/simulator/java/eclipse-plugin/ into Eclipse IDE as given below. - File -> Import -> Select 'Existing projects into Workspace' under General category -> click next -> Browse to the above mentioned location -> - click Finish. - 2.Set the LD_LIBRARY_PATH environment variable - Right click the project -> Properties -> Run/Debug Settings -> Edit -> select 'Environment' tab -> click on 'Select' -> check LD_LIBRARY_PATH option -> Ok. - Edit the LD_LIBRARY_PATH and add the complete path to the libs folder of the plug-in project -> Apply -> OK. - Then Apply -> OK to close the properties window. - 3.Right click the project -> Run As Eclipse Application. \ No newline at end of file + +Pre-requisites to launch Eclipse plug-in +------------------------------------------ + +1.Eclipse IDE with PDE(Plug-in Development Environment) support. + +2.Execute the "scons SIMULATOR=1" command from the IoTivity home +directory in the terminal to build Simulator specific libraries along +with the iotivity native libraries. + +3.Simulator application requires liboc.so, liboctbstack.so and +liboc_logger.so native libraries and libSimulatorManager.so, +libRamlParser.so simulator specific libraries, all of which are +generated in ~/iotivity/out/linux//release directory. + + +Setting up and launching the Eclipse plug-in projects +-------------------------------------------------------- + +1. Import the below projects into Eclipse IDE using File -> Import -> +Select 'Existing projects into Workspace' under General category -> click +next -> Browse to the location as given below -> Click Finish. + +i) Service Provider Plugin: +~/iotivity/service/simulator/java/eclipse-plugin/ServiceProviderPlugin + +ii) Client Controller Plugin: +~/iotivity/service/simulator/java/eclipse-plugin/ClientControllerPlugin + +iii) Simulator Java SDK: ~/iotivity/service/simulator/java/sdk + + +2. Right click the Simulator Java SDK project -> Export -> select +'JAR file' option under Java -> Next -> Select the export destination as +ClientControllerPlugin\libs\Simulator.jar and ServiceProviderPlugin\libs\Simulator.jar -> Finish. + + +3. Copy the libraries libSimulatorManager.so, libRamlParser.so, liboc.so, +liboctbstack.so, and liboc_logger.so generated previously in +~/iotivity/out/linux//release directory into the libs folder of both the plug-in projects. + + +4. Set the LD_LIBRARY_PATH environment variable. Right click any plug-in project -> Properties -> +Run/Debug Settings. To configure the LD_LIBRARY_PATH, there needs to be a launch configuration. +We may choose to use the existing launch configuration or create a new launch configuration. +If no launch configurations exist, then a new one has to be created. +To create a new launch configuration, select 'New' from Run/Debug settings -> +select 'Eclipse Application' as the configuration type -> OK. It opens a new window for editing +the launch configuration -> Change the launch configuration name(optional) -> Apply -> OK to close +the Edit Configuration window. + +From Run/Debug settings, Choose a launch configuration and press Edit -> select 'Environment' tab +-> Click on 'Select' -> check LD_LIBRARY_PATH option -> OK. Edit the LD_LIBRARY_PATH and add the +complete path upto the libs folder of the plug-in project +( ~/iotivity/service/simulator/java/eclipse-plugin/ClientControllerPlugin/libs) +-> Apply -> OK. Then Apply -> OK to close the properties window. + + +5. Right click the project -> Run as Eclipse Application -> If it prompts for a configuration, +then select the one which was configured in the LD_LIBRARY_PATH in the previous step. + + +Note: To switch the iotivity stack for conformance, need to build the latest iotivity code and +replace liboc.so, liboctbstack.so, and liboc_logger.so native libraries in libs folder of +respective plug-in applications. diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/build.properties b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/build.properties index 3db1138..8dc5385 100644 --- a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/build.properties +++ b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/build.properties @@ -5,5 +5,4 @@ bin.includes = META-INF/,\ icons/,\ plugin.xml,\ libs/,\ - resource/ diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/collection_resource.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/collection_resource.gif new file mode 100644 index 0000000000000000000000000000000000000000..173661c5df720bae9e5d2f653d63f41cdf8cf895 GIT binary patch literal 361 zcmZ?wbhEHb6krfwSjxcg|Ig{I8{(HPF#G>&#m{ehUpgvkts(ZoXSwd@U&{d;a0#m1iDRRW+|aJ8{qTrgdi?w6y%E9#H(r!pOy7&!EEq z1Ry^#u(chSU*Mr5Ro~E{z+k~QnfXA&%Rj7aEpN7HX-M$3H7$^G5D{W^Suo2*x*zT1JxBUO-k( tUQSk^UqNx5!c=}G*)2-^_D#wvs_mWpY7%OF_GJ}SPBnE6q3(_h)&QMW!&?9V literal 0 HcmV?d00001 diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/device.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/device.gif new file mode 100644 index 0000000000000000000000000000000000000000..e3ecc5535cd4d72cbb9cce9843f054714992babe GIT binary patch literal 572 zcmZ?wbhEHb6krfwc*el+^XH!*KmY#t`6sb(R%Yd*uiyWqS1ibDSW(=%wxVle!=#$il~ZV0ViA6l~}v}$E&<+9MqrP=*^t7qTaBgaDX>Dt7 zvr_Nw=~cIC*5H{uWh#$GvnH?8oVjy(HJi1BoE(`LnB*9l7zMPObp@UHxj9&v9n@F_ zb(-~son#LkJ|wKyEHAN{pNo^7jagj8pxIE;Nyg4j=BA9jsA02_l9MW*m>AzHF)5>F x6J=!;Woa8_TkDU;&6cMB{wrj$teN;Ypie+CN5rIp+1+Z^fkBi(2c!yQCj+Zb zf@)uiXOPdSfM** h5ol{>QpnV0=-tA+A)|B0xlPr6>u + id="oic.simulator.serviceprovider.view.devplatinfo"> diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/resource/Light/simple-light-error.json b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/resource/Light/simple-light-error.json deleted file mode 100644 index ceea4eb..0000000 --- a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/resource/Light/simple-light-error.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "id": "simple.light#", - "$schema": "http://json-schema.org/draft-04/schema#", - "title": "Simple Light", - "$ref": "#/definitions/light", - "definitions": { - "light": { - "type": "object", - "properties": { - "resourceType": { - "type": "string", - "description": "Description about resource type", - "default": "sample.light" - }, - "intensity": { - "type": "string", - "description": "ReadOnly, Comma separated min,max values for intensity on this device", - "default": "1,20" - } - } - } - } -} diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/resource/Light/simple-light.json b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/resource/Light/simple-light.json deleted file mode 100644 index e850b70..0000000 --- a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/resource/Light/simple-light.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "id": "simple.light#", - "$schema": "http://json-schema.org/schema#", - "title": "Simple Light", - "$ref": "#/definitions/light", - "definitions": { - "light": { - "type": "object", - "properties": { - "resourceType": { - "type": "string", - "description": "Description about resource type", - "default": "sample.light" - }, - "power": { - "type": "string", - "description": "Light status", - "default": "on", - "enum": ["on","off"], - "update_frequency": 1000 - }, - "intensity": { - "type": "integer", - "description": "brightness of the light", - "default": 1, - "minimum": 1, - "maximum": 20, - "update_frequency": 1001 - } - } - } - }, - "required": [ "resourceType", "power" ] -} \ No newline at end of file diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/resource/Light/simple-light.raml b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/resource/Light/simple-light.raml deleted file mode 100644 index 3725c6b..0000000 --- a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/resource/Light/simple-light.raml +++ /dev/null @@ -1,81 +0,0 @@ -#%RAML 0.8 -title: Simple Light -version: v1.0-20150910 -schemas: - - LightSchema: !include simple-light.json - LightSchemaError: !include simple-light-error.json - -/sample/light: - description: Resource to be exposed by any Simple Device that can act as Light. - displayName: Simple Light - get: - responses: - 200: - body: - application/json: - schema: LightSchema - example: | - { - "resourceType": "sample.light", - "power": "off" - } - put: - body: - application/json: - schema: LightSchema - example: | - { - "power": "off", - "intensity": 5 - } - responses: - 200: - body: - application/json: - schema: LightSchema - example: | - { - "power": "off", - "intensity": 5 - } - 403: - description: | - This response is generated by the Server when the client sends: - An update with an out of range property value for intensity. - The server responds with the range property illustrating the error. - body: - application/json: - schema: LightSchemaError - example: | - { - "range": "1,20" - } - post: - body: - application/json: - schema: LightSchema - example: | - { - "power": "off" - } - responses: - 200: - body: - application/json: - schema: LightSchema - example: | - { - "power": "off" - } - 403: - description: | - This response is generated by the Server when the client sends: - An update with an out of range property value for intensity. - The server responds with the range property illustrating the error. - body: - application/json: - schema: LightSchemaError - example: | - { - "range": "1,20" - } 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 index f392bc8..9861d77 100644 --- 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 @@ -50,7 +50,12 @@ public class LogLabelProvider extends LabelProvider implements } else if (columnIndex == 1) { return dateFormat.format(entry.getDate()); } else { - return entry.getMessage(); + String msg = entry.getMessage(); + int pos = msg.indexOf('\n'); + if (pos != -1) { + msg = msg.substring(0, pos); + } + return msg; } } 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 index 215fb5f..395a744 100644 --- 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 @@ -16,12 +16,14 @@ package oic.simulator.serviceprovider.listener; +import oic.simulator.serviceprovider.model.SingleResource; + /** * Interface through which the automation events are notified to the UI * listeners. */ public interface IAutomationUIListener { - public void onResourceAutomationStart(String resourceURI); + public void onResourceAutomationStart(SingleResource resource); - public void onAutomationComplete(String resourceURI, String attName); + public void onAutomationComplete(SingleResource resource, String attName); } 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 index 3beb52a..a3bde63 100644 --- 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 @@ -16,10 +16,12 @@ package oic.simulator.serviceprovider.listener; +import oic.simulator.serviceprovider.model.Resource; + /** * Interface through which the resource observer events are sent to the UI * listeners. */ public interface IObserverListChangedUIListener { - public void onObserverListChanged(String resourceURI); + public void onObserverListChanged(Resource resource); } diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IPropertiesChangedUIListener.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IPropertiesChangedUIListener.java new file mode 100644 index 0000000..864d5c0 --- /dev/null +++ b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IPropertiesChangedUIListener.java @@ -0,0 +1,27 @@ +/* + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package oic.simulator.serviceprovider.listener; + +/** + * Interface through which the resource property change UI events are sent to + * the other UI listeners. + */ +public interface IPropertiesChangedUIListener { + public void onResourcePropertyChange(); + + public void onDevicePropertyChange(); +} \ No newline at end of file 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 index b5eb331..fac61eb 100644 --- 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 @@ -16,12 +16,16 @@ package oic.simulator.serviceprovider.listener; +import oic.simulator.serviceprovider.model.ResourceType; + /** * Interface through which the resource creation/deletion events are sent to the * UI listeners. */ public interface IResourceListChangedUIListener { - public void onResourceCreation(); + public void onResourceCreation(ResourceType type); + + public void onResourceDeletion(ResourceType type); - public void onResourceDeletion(); + public void onResourceListUpdate(ResourceType type); } \ No newline at end of file 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 index b778e0e..e55539d 100644 --- 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 @@ -16,17 +16,12 @@ package oic.simulator.serviceprovider.listener; -import java.util.Set; - -import oic.simulator.serviceprovider.resource.ModelChangeNotificationType; -import oic.simulator.serviceprovider.resource.LocalResourceAttribute; +import oic.simulator.serviceprovider.model.Resource; /** * Interface through which the resource model change events are sent to the UI * listeners. */ public interface IResourceModelChangedUIListener { - public void onResourceModelChange( - ModelChangeNotificationType notificationType, String resourceURI, - Set valueChangeSet); + public void onResourceModelChange(Resource resource); } diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IResourceSelectionChangedUIListener.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/ISelectionChangedUIListener.java similarity index 74% rename from service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IResourceSelectionChangedUIListener.java rename to service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/ISelectionChangedUIListener.java index dc891da..f4c9c14 100644 --- 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/ISelectionChangedUIListener.java @@ -16,10 +16,15 @@ package oic.simulator.serviceprovider.listener; +import oic.simulator.serviceprovider.model.Device; +import oic.simulator.serviceprovider.model.Resource; + /** * Interface through which the resource selection UI event is sent to the other * UI listeners. */ -public interface IResourceSelectionChangedUIListener { - public void onResourceSelectionChange(); +public interface ISelectionChangedUIListener { + public void onResourceSelectionChange(Resource resource); + + public void onDeviceSelectionChange(Device dev); } \ No newline at end of file diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/manager/Data.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/manager/Data.java new file mode 100644 index 0000000..17517f1 --- /dev/null +++ b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/manager/Data.java @@ -0,0 +1,294 @@ +/* + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package oic.simulator.serviceprovider.manager; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import oic.simulator.serviceprovider.model.CollectionResource; +import oic.simulator.serviceprovider.model.Device; +import oic.simulator.serviceprovider.model.Resource; +import oic.simulator.serviceprovider.model.SingleResource; + +public class Data { + private Map singleResourceMap; + + private Map collectionResourceMap; + + private Map deviceMap; + + // Holds resource type as key and a resource URI set as values. + // Helps in performing operations based on resource type. + private Map> resTypeToResUriMap; + + public Data() { + singleResourceMap = new HashMap(); + collectionResourceMap = new HashMap(); + deviceMap = new HashMap(); + resTypeToResUriMap = new HashMap>(); + } + + public synchronized void addResource(Resource resource) { + if (null == resource) { + return; + } + if (resource instanceof SingleResource) { + singleResourceMap.put(resource.getResourceURI(), + (SingleResource) resource); + } else { + collectionResourceMap.put(resource.getResourceURI(), + (CollectionResource) resource); + } + addToTypeAndUriMap(resource); + } + + public synchronized void addToTypeAndUriMap(Resource resource) { + if (null == resource) { + return; + } + Set resTypes = resource.getResourceTypes(); + if (null == resTypes || resTypes.isEmpty()) { + return; + } + String uri = resource.getResourceURI(); + if (null == uri || uri.isEmpty()) { + return; + } + Iterator itr = resTypes.iterator(); + String rType; + Set newTypeSet; + while (itr.hasNext()) { + rType = itr.next(); + newTypeSet = resTypeToResUriMap.get(rType); + if (null == newTypeSet) { + newTypeSet = new HashSet(); + resTypeToResUriMap.put(rType, newTypeSet); + } + newTypeSet.add(uri); + } + } + + public void addDevice(Device dev) { + if (null == dev) { + return; + } + synchronized (deviceMap) { + deviceMap.put(dev.getDeviceName(), dev); + } + } + + public synchronized void deleteResource(Resource resource) { + if (null == resource) { + return; + } + if (resource instanceof SingleResource) { + singleResourceMap.remove(resource.getResourceURI()); + } else { + collectionResourceMap.remove(resource.getResourceURI()); + } + removeFromTypeAndUriMap(resource); + } + + public synchronized void deleteDevice(Device dev) { + if (null == dev) { + return; + } + deviceMap.remove(dev.getDeviceName()); + } + + public synchronized void removeFromTypeAndUriMap(Resource resource) { + if (null == resource) { + return; + } + Set resTypes = resource.getResourceTypes(); + if (null == resTypes || resTypes.isEmpty()) { + return; + } + String uri = resource.getResourceURI(); + if (null == uri || uri.isEmpty()) { + return; + } + Iterator itr = resTypes.iterator(); + String rType; + Set newTypeSet; + while (itr.hasNext()) { + rType = itr.next(); + newTypeSet = resTypeToResUriMap.get(rType); + if (null != newTypeSet) { + newTypeSet.remove(uri); + } + if (null == newTypeSet || newTypeSet.isEmpty()) { + resTypeToResUriMap.remove(rType); + } + } + } + + public List getSingleResources() { + List resources; + synchronized (singleResourceMap) { + if (singleResourceMap.isEmpty()) { + return null; + } + resources = new ArrayList(); + Set uriSet = singleResourceMap.keySet(); + Iterator itr = uriSet.iterator(); + while (itr.hasNext()) { + resources.add(singleResourceMap.get(itr.next())); + } + } + return resources; + } + + public List getCollectionResources() { + List resources; + synchronized (collectionResourceMap) { + if (collectionResourceMap.isEmpty()) { + return null; + } + resources = new ArrayList(); + Set uriSet = collectionResourceMap.keySet(); + Iterator itr = uriSet.iterator(); + while (itr.hasNext()) { + resources.add(collectionResourceMap.get(itr.next())); + } + } + return resources; + } + + public List getResources() { + if (singleResourceMap.isEmpty() && collectionResourceMap.isEmpty()) { + return null; + } + List resourceList = new ArrayList(); + synchronized (singleResourceMap) { + Set uriSet = singleResourceMap.keySet(); + Iterator itr = uriSet.iterator(); + while (itr.hasNext()) { + resourceList.add(singleResourceMap.get(itr.next())); + } + } + synchronized (collectionResourceMap) { + Set uriSet = collectionResourceMap.keySet(); + Iterator itr = uriSet.iterator(); + while (itr.hasNext()) { + resourceList.add(collectionResourceMap.get(itr.next())); + } + } + return resourceList; + } + + public List getDevices() { + List devices; + synchronized (deviceMap) { + if (deviceMap.isEmpty()) { + return null; + } + devices = new ArrayList(); + Set uriSet = deviceMap.keySet(); + Iterator itr = uriSet.iterator(); + while (itr.hasNext()) { + devices.add(deviceMap.get(itr.next())); + } + } + return devices; + } + + public synchronized boolean isResourceExist(String resourceURI) { + if (null == resourceURI || resourceURI.isEmpty()) { + return false; + } + if ((null != singleResourceMap && singleResourceMap + .containsKey(resourceURI)) + || (null != collectionResourceMap && collectionResourceMap + .containsKey(resourceURI))) { + return true; + } + return false; + } + + public synchronized boolean isAnyResourceExist() { + return ((null != singleResourceMap && !singleResourceMap.isEmpty()) || (null != collectionResourceMap && !collectionResourceMap + .isEmpty())); + } + + public void changeResourceURI(Resource resource, String curURI, + String newURI) { + if (null == resource || null == curURI || null == newURI) { + return; + } + if (resource instanceof SingleResource) { + synchronized (singleResourceMap) { + singleResourceMap.remove(curURI); + singleResourceMap.put(newURI, (SingleResource) resource); + } + } else { + synchronized (collectionResourceMap) { + collectionResourceMap.remove(curURI); + collectionResourceMap + .put(newURI, (CollectionResource) resource); + } + } + resource.setResourceURI(newURI); + } + + public void changeDeviceName(Device dev, String curName, String newName) { + if (null == dev || null == curName || null == newName) { + return; + } + synchronized (deviceMap) { + deviceMap.remove(curName); + deviceMap.put(newName, dev); + } + dev.setDeviceName(newName); + } + + public SingleResource getSingleResourceByURI(String resourceURI) { + if (null == resourceURI) { + return null; + } + SingleResource res; + synchronized (singleResourceMap) { + res = singleResourceMap.get(resourceURI); + } + return res; + } + + public CollectionResource getCollectionResourceByURI(String resourceURI) { + if (null == resourceURI) { + return null; + } + CollectionResource res; + synchronized (collectionResourceMap) { + res = collectionResourceMap.get(resourceURI); + } + return res; + } + + public Resource getResourceByURI(String resourceURI) { + Resource res = getSingleResourceByURI(resourceURI); + if (null == res) { + res = getCollectionResourceByURI(resourceURI); + } + return res; + } + +} 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 index ee700d1..9e58424 100644 --- 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 @@ -56,8 +56,13 @@ public class ImageManager { .createFromURL(bundle.getEntry("icons/button_pressed.PNG"))); // Resource icons based on the resource type - r.put(Constants.SAMPLE_LIGHT, ImageDescriptor.createFromURL(bundle - .getEntry("/icons/light_16x16.png"))); + r.put(Constants.SINGLE_RESOURCE, ImageDescriptor.createFromURL(bundle + .getEntry("/icons/single_resource.gif"))); + r.put(Constants.COLLECTION_RESOURCE, ImageDescriptor + .createFromURL(bundle + .getEntry("/icons/collection_resource.gif"))); + r.put(Constants.DEVICE, ImageDescriptor.createFromURL(bundle + .getEntry("/icons/device.gif"))); // Log View related icons r.put(Constants.DEBUG_LOG, ImageDescriptor.createFromURL(bundle 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 index e7ca9a9..765d87c 100644 --- 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 @@ -26,11 +26,13 @@ import oic.simulator.logger.LoggerCallback; import oic.simulator.serviceprovider.Activator; import oic.simulator.serviceprovider.listener.ILogUIListener; import oic.simulator.serviceprovider.utils.Constants; +import oic.simulator.serviceprovider.utils.Utility; import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.swt.graphics.Image; import org.oic.simulator.ILogger; import org.oic.simulator.ILogger.Level; +import org.oic.simulator.SimulatorException; import org.oic.simulator.SimulatorManager; /** @@ -55,7 +57,14 @@ public class LogManager { // Set the logger callback with the native layer logger = new LoggerCallback(); - SimulatorManager.setLogger(logger); + try { + SimulatorManager.setLogger(logger); + } catch (SimulatorException e) { + log(Level.ERROR.ordinal(), + new Date(), + "Failed to register the logger.\n" + + Utility.getSimulatorErrorString(e, null)); + } } private static class LogManagerSynchronizerThread implements Runnable { 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 index e6cca32..3e80941 100644 --- 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 @@ -20,41 +20,44 @@ import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; -import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.Vector; import oic.simulator.serviceprovider.Activator; -import oic.simulator.serviceprovider.listener.IAutomationUIListener; -import oic.simulator.serviceprovider.listener.IObserverListChangedUIListener; -import oic.simulator.serviceprovider.listener.IResourceListChangedUIListener; -import oic.simulator.serviceprovider.listener.IResourceModelChangedUIListener; -import oic.simulator.serviceprovider.listener.IResourceSelectionChangedUIListener; -import oic.simulator.serviceprovider.resource.LocalResourceAttribute; -import oic.simulator.serviceprovider.resource.MetaProperty; -import oic.simulator.serviceprovider.resource.ModelChangeNotificationType; -import oic.simulator.serviceprovider.resource.SimulatorResource; -import oic.simulator.serviceprovider.resource.StandardConfiguration; +import oic.simulator.serviceprovider.model.CollectionResource; +import oic.simulator.serviceprovider.model.Device; +import oic.simulator.serviceprovider.model.LocalResourceAttribute; +import oic.simulator.serviceprovider.model.MetaProperty; +import oic.simulator.serviceprovider.model.Resource; +import oic.simulator.serviceprovider.model.ResourceType; +import oic.simulator.serviceprovider.model.SRMItem; +import oic.simulator.serviceprovider.model.SingleResource; import oic.simulator.serviceprovider.utils.Constants; import oic.simulator.serviceprovider.utils.Utility; -import org.eclipse.swt.graphics.Image; -import org.oic.simulator.IAutomation; +import org.oic.simulator.AttributeProperty; +import org.oic.simulator.AttributeProperty.Type; +import org.oic.simulator.AttributeValue; +import org.oic.simulator.AttributeValue.TypeInfo; +import org.oic.simulator.AttributeValue.ValueType; import org.oic.simulator.ILogger.Level; -import org.oic.simulator.ResourceAttribute; -import org.oic.simulator.ResourceAttribute.Range; -import org.oic.simulator.ResourceAttribute.Type; +import org.oic.simulator.PlatformInfo; import org.oic.simulator.SimulatorException; import org.oic.simulator.SimulatorManager; +import org.oic.simulator.SimulatorResourceAttribute; import org.oic.simulator.SimulatorResourceModel; -import org.oic.simulator.serviceprovider.AutomationType; -import org.oic.simulator.serviceprovider.IObserver; -import org.oic.simulator.serviceprovider.IResourceModelChangedListener; -import org.oic.simulator.serviceprovider.ObserverInfo; -import org.oic.simulator.serviceprovider.SimulatorResourceServer; +import org.oic.simulator.server.Observer; +import org.oic.simulator.server.SimulatorCollectionResource; +import org.oic.simulator.server.SimulatorResource; +import org.oic.simulator.server.SimulatorResource.AutoUpdateListener; +import org.oic.simulator.server.SimulatorResource.AutoUpdateType; +import org.oic.simulator.server.SimulatorResource.ObserverListener; +import org.oic.simulator.server.SimulatorResource.ResourceModelChangeListener; +import org.oic.simulator.server.SimulatorSingleResource; /** * This class acts as an interface between the simulator java SDK and the @@ -65,49 +68,67 @@ import org.oic.simulator.serviceprovider.SimulatorResourceServer; */ public class ResourceManager { - private Map> resourceMap; + private Data data; - private Map> orderedResourceUriMap; + private Resource currentResourceInSelection; - private Map displayNameMap; + private Device currentDeviceInSelection; - private StandardConfiguration stdConfig; + private ResourceModelChangeListener resourceModelChangeListener; - private SimulatorResource currentResourceInSelection; + private AutoUpdateListener automationListener; - private List resourceListChangedUIListeners; + private ObserverListener observer; - private List resourceSelectionChangedUIListeners; + private NotificationSynchronizerThread synchronizerThread; - private List resourceModelChangedUIListeners; + private Thread threadHandle; - private List automationUIListeners; - - private List observerUIListeners; - - private IResourceModelChangedListener resourceModelChangeListener; - - private IAutomation automationListener; - - private IObserver observer; - - private NotificationSynchronizerThread synchronizerThread; - - private Thread threadHandle; + private String deviceName; + private PlatformInfo platformInfo; public ResourceManager() { - resourceMap = new HashMap>(); - orderedResourceUriMap = new HashMap>(); - displayNameMap = new HashMap(); - stdConfig = new StandardConfiguration(); + data = new Data(); - resourceListChangedUIListeners = new ArrayList(); - resourceSelectionChangedUIListeners = new ArrayList(); - resourceModelChangedUIListeners = new ArrayList(); - automationUIListeners = new ArrayList(); - observerUIListeners = new ArrayList(); + // Set the default device and platform information + deviceName = "IoTivity Simulator"; + try { + SimulatorManager.setDeviceInfo(deviceName); + } catch (SimulatorException e) { + Activator + .getDefault() + .getLogManager() + .log(Level.ERROR.ordinal(), + new Date(), + "Error while registering the device info.\n" + + Utility.getSimulatorErrorString(e, null)); + } + + platformInfo = new PlatformInfo(); + platformInfo.setPlatformID("Samsung Platform Identifier"); + platformInfo.setManufacturerName("Samsung"); + platformInfo.setManufacturerUrl("www.samsung.com"); + platformInfo.setModelNumber("Samsung Model Num01"); + platformInfo.setDateOfManufacture("2015-09-10T11:10:30Z"); + platformInfo.setPlatformVersion("PlatformVersion01"); + platformInfo.setOperationSystemVersion("OSVersion01"); + platformInfo.setHardwareVersion("HardwareVersion01"); + platformInfo.setFirmwareVersion("FirwareVersion01"); + platformInfo.setSupportUrl("http://www.samsung.com/support"); + platformInfo.setSystemTime("2015-09-10T11:10:30Z"); + try { + SimulatorManager.setPlatformInfo(platformInfo); + } catch (SimulatorException e) { + Activator + .getDefault() + .getLogManager() + .log(Level.ERROR.ordinal(), + new Date(), + "Error while registering the platform info.\n" + + Utility.getSimulatorErrorString(e, null)); + } - resourceModelChangeListener = new IResourceModelChangedListener() { + resourceModelChangeListener = new ResourceModelChangeListener() { @Override public void onResourceModelChanged(final String resourceURI, @@ -119,59 +140,44 @@ public class ResourceManager { if (null == resourceURI || null == resourceModelN) { return; } - SimulatorResource resource = getSimulatorResourceByURI(resourceURI); + + Resource resource = data.getResourceByURI(resourceURI); if (null == resource) { return; } - ModelChangeNotificationType notificationType; - // Fetch the resource attributes - Map resourceAttributeMapNew; - resourceAttributeMapNew = fetchResourceAttributesFromModel(resourceModelN); - if (null == resourceAttributeMapNew) { - resource.setResourceAttributesMap(null); - resourceModelChangedUINotification( - ModelChangeNotificationType.NO_ATTRIBUTES_IN_MODEL, - resourceURI, null); - return; - } + resource.setResourceModel(resourceModelN); - // Update the resource with new model data - Map resourceAttributeMapOld; - resourceAttributeMapOld = resource - .getResourceAttributesMap(); - if (null == resourceAttributeMapOld) { - resource.setResourceAttributesMap(resourceAttributeMapNew); - resourceModelChangedUINotification( - ModelChangeNotificationType.ATTRIBUTE_ADDED, - resourceURI, null); - return; - } - Set valueChangeSet = new HashSet(); - notificationType = compareAndUpdateLocalAttributes( - resourceAttributeMapOld, - resourceAttributeMapNew, valueChangeSet); - if (notificationType != ModelChangeNotificationType.NONE) { - // Update the UI listeners - resourceModelChangedUINotification( - notificationType, resourceURI, - valueChangeSet); + // 7. Fetch the resource attributes. + Map resourceAttributeMap; + try { + resourceAttributeMap = fetchResourceAttributesFromModel(resourceModelN); + if (null != resourceAttributeMap) { + resource.setResourceAttributes(resourceAttributeMap); + } + } catch (SimulatorException e) { + // TODO Auto-generated catch block + e.printStackTrace(); } + + UiListenerHandler.getInstance() + .resourceModelChangedUINotification(resource); } }); } }; - automationListener = new IAutomation() { + automationListener = new AutoUpdateListener() { @Override - public void onAutomationComplete(final String resourceURI, + public void onUpdateComplete(final String resourceURI, final int automationId) { synchronizerThread.addToQueue(new Runnable() { @Override public void run() { - SimulatorResource resource = getSimulatorResourceByURI(resourceURI); + SingleResource resource = data + .getSingleResourceByURI(resourceURI); if (null == resource) { return; } @@ -180,7 +186,9 @@ public class ResourceManager { if (resource.isResourceAutomationInProgress()) { changeResourceLevelAutomationStatus(resource, false); // Notify the UI listeners - automationCompleteUINotification(resourceURI, null); + UiListenerHandler.getInstance() + .automationCompleteUINotification(resource, + null); } else if (resource.isAttributeAutomationInProgress()) { // Find the attribute with the given automation id LocalResourceAttribute attribute; @@ -190,30 +198,37 @@ public class ResourceManager { attribute.setAutomationInProgress(false); resource.setAttributeAutomationInProgress(isAnyAttributeInAutomation(resource)); // Notify the UI listeners - automationCompleteUINotification(resourceURI, - attribute.getAttributeName()); + UiListenerHandler + .getInstance() + .automationCompleteUINotification( + resource, + attribute + .getResourceAttributeRef() + .name()); + } else { + // TODO: Temporarily reset the attribute + // automation status to false for making + // resource-level automation work after + // attribute-level automations. + resource.setAttributeAutomationInProgress(false); } - } else { - // Ignoring the notification as there are no - // known automation for the current resource. } } }); } }; - observer = new IObserver() { + observer = new ObserverListener() { - @Override public void onObserverChanged(final String resourceURI, - final int status, final ObserverInfo observer) { + final int status, final Observer observer) { new Thread() { @Override public void run() { if (null == resourceURI || null == observer) { return; } - SimulatorResource resource = getSimulatorResourceByURI(resourceURI); + Resource resource = data.getResourceByURI(resourceURI); if (null == resource) { return; } @@ -224,10 +239,21 @@ public class ResourceManager { resource.removeObserverInfo(observer); } // Notify the UI listeners - observerListChangedUINotification(resourceURI); + UiListenerHandler.getInstance() + .observerListChangedUINotification(resource); } }.start(); } + + @Override + public void onObserverAdded(String resourceURI, Observer observer) { + onObserverChanged(resourceURI, 0, observer); + } + + @Override + public void onObserverRemoved(String resourceURI, Observer observer) { + onObserverChanged(resourceURI, 1, observer); + } }; synchronizerThread = new NotificationSynchronizerThread(); @@ -277,900 +303,1319 @@ public class ResourceManager { } } - // This method gives a list of available RAML resource configurations. - public Map getResourceConfigurationList() { - return stdConfig.getStandardResourceConfigurationList(); + public String getDeviceName() { + return deviceName; } - public String getConfigFilePath(String fileName) { - return stdConfig.getFilePath(fileName); + public void setDeviceName(String deviceName) { + this.deviceName = deviceName; + try { + SimulatorManager.setDeviceInfo(deviceName); + } catch (SimulatorException e) { + Activator + .getDefault() + .getLogManager() + .log(Level.ERROR.ordinal(), + new Date(), + "Error while registering the device info.\n" + + Utility.getSimulatorErrorString(e, null)); + } + } + + public List getPlatformInfo() { + List metaProperties = new ArrayList(); + metaProperties.add(new MetaProperty(Constants.PLATFORM_ID, platformInfo + .getPlatformID())); + metaProperties.add(new MetaProperty(Constants.PLATFORM_MANUFAC_NAME, + platformInfo.getManufacturerName())); + metaProperties.add(new MetaProperty(Constants.PLATFORM_MANUFAC_URL, + platformInfo.getManufacturerUrl())); + metaProperties.add(new MetaProperty(Constants.PLATFORM_MODEL_NO, + platformInfo.getModelNumber())); + metaProperties.add(new MetaProperty(Constants.PLATFORM_DATE_OF_MANUFAC, + platformInfo.getDateOfManufacture())); + metaProperties.add(new MetaProperty(Constants.PLATFORM_VERSION, + platformInfo.getPlatformVersion())); + metaProperties.add(new MetaProperty(Constants.PLATFORM_OS_VERSION, + platformInfo.getOperationSystemVersion())); + metaProperties.add(new MetaProperty( + Constants.PLATFORM_HARDWARE_VERSION, platformInfo + .getHardwareVersion())); + metaProperties.add(new MetaProperty( + Constants.PLATFORM_FIRMWARE_VERSION, platformInfo + .getFirmwareVersion())); + metaProperties.add(new MetaProperty(Constants.PLATFORM_SUPPORT_URL, + platformInfo.getSupportUrl())); + metaProperties.add(new MetaProperty(Constants.PLATFORM_SYSTEM_TIME, + platformInfo.getSystemTime())); + return metaProperties; + } + + public void setPlatformInfo(List metaProperties) { + if (null == metaProperties || metaProperties.size() < 1) { + return; + } + Iterator itr = metaProperties.iterator(); + MetaProperty prop; + String propName; + String propValue; + while (itr.hasNext()) { + prop = itr.next(); + propName = prop.getPropName(); + propValue = prop.getPropValue(); + if (propName.equals(Constants.PLATFORM_ID)) { + platformInfo.setPlatformID(propValue); + } else if (propName.equals(Constants.PLATFORM_MANUFAC_NAME)) { + platformInfo.setManufacturerName(propValue); + } else if (propName.equals(Constants.PLATFORM_MANUFAC_URL)) { + platformInfo.setManufacturerUrl(propValue); + } else if (propName.equals(Constants.PLATFORM_MODEL_NO)) { + platformInfo.setModelNumber(propValue); + } else if (propName.equals(Constants.PLATFORM_DATE_OF_MANUFAC)) { + platformInfo.setDateOfManufacture(propValue); + } else if (propName.equals(Constants.PLATFORM_VERSION)) { + platformInfo.setPlatformVersion(propValue); + } else if (propName.equals(Constants.PLATFORM_OS_VERSION)) { + platformInfo.setOperationSystemVersion(propValue); + } else if (propName.equals(Constants.PLATFORM_HARDWARE_VERSION)) { + platformInfo.setHardwareVersion(propValue); + } else if (propName.equals(Constants.PLATFORM_FIRMWARE_VERSION)) { + platformInfo.setFirmwareVersion(propValue); + } else if (propName.equals(Constants.PLATFORM_SUPPORT_URL)) { + platformInfo.setSupportUrl(propValue); + } else if (propName.equals(Constants.PLATFORM_SYSTEM_TIME)) { + platformInfo.setSystemTime(propValue); + } + } + try { + SimulatorManager.setPlatformInfo(platformInfo); + } catch (SimulatorException e) { + Activator + .getDefault() + .getLogManager() + .log(Level.ERROR.ordinal(), + new Date(), + "Error while registering the platform info.\n" + + Utility.getSimulatorErrorString(e, null)); + } } - public void addResourceListChangedUIListener( - IResourceListChangedUIListener resourceListChangedUIListener) { - synchronized (resourceListChangedUIListeners) { - resourceListChangedUIListeners.add(resourceListChangedUIListener); - } + public synchronized Resource getCurrentResourceInSelection() { + return currentResourceInSelection; } - public void addResourceSelectionChangedUIListener( - IResourceSelectionChangedUIListener resourceSelectionChangedUIListener) { - synchronized (resourceSelectionChangedUIListeners) { - resourceSelectionChangedUIListeners - .add(resourceSelectionChangedUIListener); - } + public synchronized void setCurrentResourceInSelection(Resource resource) { + this.currentResourceInSelection = resource; } - public void addResourceModelChangedUIListener( - IResourceModelChangedUIListener resourceModelChangedUIListener) { - synchronized (resourceModelChangedUIListeners) { - resourceModelChangedUIListeners.add(resourceModelChangedUIListener); - } + public synchronized Device getCurrentDeviceInSelection() { + return currentDeviceInSelection; } - public void addAutomationUIListener( - IAutomationUIListener automationUIListener) { - synchronized (automationUIListeners) { - automationUIListeners.add(automationUIListener); - } + public synchronized void setCurrentDeviceInSelection(Device dev) { + this.currentDeviceInSelection = dev; } - public void addObserverListChangedUIListener( - IObserverListChangedUIListener observerListChangedUIListener) { - synchronized (observerUIListeners) { - observerUIListeners.add(observerListChangedUIListener); - } + public boolean isResourceExist(String resourceURI) { + return data.isResourceExist(resourceURI); } - public void removeResourceListChangedUIListener( - IResourceListChangedUIListener listener) { - synchronized (resourceListChangedUIListeners) { - if (null != listener && resourceListChangedUIListeners.size() > 0) { - resourceListChangedUIListeners.remove(listener); - } - } + public boolean isAnyResourceExist() { + return data.isAnyResourceExist(); } - public void removeResourceSelectionChangedUIListener( - IResourceSelectionChangedUIListener listener) { - synchronized (resourceSelectionChangedUIListeners) { - if (null != listener - && resourceSelectionChangedUIListeners.size() > 0) { - resourceSelectionChangedUIListeners.remove(listener); - } + public boolean createSingleResource(SingleResource resource) + throws SimulatorException { + if (null == resource) { + return false; } - } + String resType = (String) resource.getResourceTypes().toArray()[0]; + try { + // 1. Create the resource. + SimulatorResource jSimulatorResource = SimulatorManager + .createResource(SimulatorResource.Type.SINGLE, + resource.getResourceName(), + resource.getResourceURI(), resType); + if (null == jSimulatorResource + || !(jSimulatorResource instanceof SimulatorSingleResource)) { + return false; + } + SimulatorSingleResource jSimulatorSingleResource = (SimulatorSingleResource) jSimulatorResource; + resource.setSimulatorResource(jSimulatorSingleResource); - public void removeResourceModelChangedUIListener( - IResourceModelChangedUIListener listener) { - synchronized (resourceModelChangedUIListeners) { - if (null != listener && resourceModelChangedUIListeners.size() > 0) { - resourceModelChangedUIListeners.remove(listener); + // 2. Cancel observable property if requested by user. + if (!resource.isObservable()) { + jSimulatorSingleResource.setObservable(false); } - } - } - public void removeAutomationUIListener(IAutomationUIListener listener) { - synchronized (automationUIListeners) { - if (null != listener && automationUIListeners.size() > 0) { - automationUIListeners.remove(listener); + // 3. Set the model change listener. + jSimulatorSingleResource + .setResourceModelChangeListener(resourceModelChangeListener); + + // 4. Set the observer listener if the resource is observable. + if (resource.isObservable()) { + jSimulatorSingleResource.setObserverListener(observer); } - } - } - public void removeObserverListChangedUIListener( - IObserverListChangedUIListener listener) { - synchronized (observerUIListeners) { - if (null != listener && observerUIListeners.size() > 0) { - observerUIListeners.remove(listener); + // 5. Add attributes. + Map attributes = resource + .getResourceAttributes(); + if (null != attributes && !attributes.isEmpty()) { + Set keySet = attributes.keySet(); + Iterator itr = keySet.iterator(); + + String attName; + LocalResourceAttribute localAtt; + SimulatorResourceAttribute simResAtt; + + while (itr.hasNext()) { + attName = itr.next(); + localAtt = attributes.get(attName); + if (null == localAtt) { + continue; + } + simResAtt = localAtt.getResourceAttributeRef(); + if (null == simResAtt) { + continue; + } + jSimulatorSingleResource.addAttribute(simResAtt); + } + + // 6. Get the resource model java object reference. + resource.setResourceModel(jSimulatorSingleResource + .getResourceModel()); } + + // 7. Register the resource with the platform. + jSimulatorSingleResource.start(); + resource.setStarted(true); + } catch (SimulatorException e) { + Activator + .getDefault() + .getLogManager() + .log(Level.ERROR.ordinal(), new Date(), + Utility.getSimulatorErrorString(e, null)); + throw e; } - } - public synchronized SimulatorResource getCurrentResourceInSelection() { - return currentResourceInSelection; - } + // 8. Add to local cache. + data.addResource(resource); - public synchronized void setCurrentResourceInSelection( - SimulatorResource resource) { - this.currentResourceInSelection = resource; + // 9. Update UI listeners + UiListenerHandler.getInstance().resourceCreatedUINotification( + ResourceType.SINGLE); + + return true; } - private void addResourceUriToOrderedMap(String resourceType, - String resourceURI) { - if (null != resourceURI && null != resourceType) { - synchronized (orderedResourceUriMap) { - ArrayList uriListForType = orderedResourceUriMap - .get(resourceType); - if (null == uriListForType) { - uriListForType = new ArrayList(); - orderedResourceUriMap.put(resourceType, uriListForType); - } - uriListForType.add(resourceURI); + public boolean createCollectionResource(CollectionResource resource) + throws SimulatorException { + if (null == resource) { + return false; + } + String resType = (String) resource.getResourceTypes().toArray()[0]; + try { + // 1. Create the resource. + SimulatorResource jSimulatorResource = SimulatorManager + .createResource(SimulatorResource.Type.COLLECTION, + resource.getResourceName(), + resource.getResourceURI(), resType); + if (null == jSimulatorResource + || !(jSimulatorResource instanceof SimulatorCollectionResource)) { + return false; + } + SimulatorCollectionResource jSimulatorCollectionResource = (SimulatorCollectionResource) jSimulatorResource; + resource.setSimulatorResource(jSimulatorCollectionResource); + + // 2. Cancel observable property if requested by user. + if (!resource.isObservable()) { + jSimulatorCollectionResource.setObservable(false); + } + + // 3. Set the observer listener if the resource is observable. + if (resource.isObservable()) { + jSimulatorCollectionResource.setObserverListener(observer); } + + // 4. Set the model change listener. + jSimulatorCollectionResource + .setResourceModelChangeListener(resourceModelChangeListener); + + // 5. Register the resource with the platform. + jSimulatorCollectionResource.start(); + resource.setStarted(true); + } catch (SimulatorException e) { + Activator + .getDefault() + .getLogManager() + .log(Level.ERROR.ordinal(), new Date(), + Utility.getSimulatorErrorString(e, null)); + throw e; } + + // 6. Add to local cache. + data.addResource(resource); + + // 7. Update UI listeners + UiListenerHandler.getInstance().resourceCreatedUINotification( + ResourceType.COLLECTION); + + return true; } - private void removeResourceUriFromOrderedMap(String resourceType, - String resourceURI) { - synchronized (orderedResourceUriMap) { - if (null != resourceURI && null != resourceType) { - ArrayList uriListForType = orderedResourceUriMap - .get(resourceType); - if (null != uriListForType) { - uriListForType.remove(resourceURI); - if (uriListForType.size() < 1) { - orderedResourceUriMap.remove(resourceType); - } - } - } else if (null != resourceType) { - orderedResourceUriMap.remove(resourceType); + public Resource createResourceByRAML(String configFilePath) + throws SimulatorException { + Resource resource = null; + try { + // 1. Create the resource + SimulatorResource jSimulatorResource = SimulatorManager + .createResource(configFilePath); + if (null == jSimulatorResource) { + return null; + } + if (jSimulatorResource instanceof SimulatorSingleResource) { + resource = new SingleResource(); } else { - orderedResourceUriMap.clear(); + resource = new CollectionResource(); } - } - } + resource.setSimulatorResource(jSimulatorResource); - private void addResourceToMap(SimulatorResource simulatorResource) { - if (null != simulatorResource) { - synchronized (resourceMap) { - Map resourceTypeMap; - resourceTypeMap = resourceMap.get(simulatorResource - .getResourceType()); - if (null == resourceTypeMap) { - resourceTypeMap = new HashMap(); - resourceMap.put(simulatorResource.getResourceType(), - resourceTypeMap); - } - resourceTypeMap.put(simulatorResource.getResourceURI(), - simulatorResource); + // 2. Fetch and locally store the resource name and uri. + String uri = jSimulatorResource.getURI(); + if (null == uri || uri.trim().isEmpty()) { + return null; } - } - } + resource.setResourceURI(uri.trim()); - private void addResourceToMap(String resourceType, - Map newResourceTypeMap) { - if (null != resourceType && null != newResourceTypeMap) { - synchronized (resourceMap) { - Map resourceTypeMap = resourceMap - .get(resourceType); - if (null != resourceTypeMap) { - resourceTypeMap.putAll(newResourceTypeMap); - } else { - resourceMap.put(resourceType, newResourceTypeMap); - } + String name = jSimulatorResource.getName(); + if (null == name || name.trim().isEmpty()) { + return null; } + resource.setResourceName(name.trim()); + } catch (SimulatorException e) { + Activator + .getDefault() + .getLogManager() + .log(Level.ERROR.ordinal(), new Date(), + Utility.getSimulatorErrorString(e, null)); + throw e; } + return resource; } - private void removeResourceFromMap(String resourceType, String resourceURI) { - if (null != resourceURI && null != resourceType) { - synchronized (resourceMap) { - Map resourceTypeMap = resourceMap - .get(resourceType); - if (null != resourceTypeMap) { - resourceTypeMap.remove(resourceURI); - if (resourceTypeMap.size() < 1) { - resourceMap.remove(resourceType); - } + /** + * This method can set/change the resource uri and name of an already + * created resource which is not yet registered with the platform. This + * method registers the model change and observer listeners, registers the + * resource, fetches the resource attributes, updates the local cache and + * notifies the UI listeners. + */ + public boolean completeSingleResourceCreationByRAML(Resource resource, + String uri, String name, boolean multiInstance) + throws SimulatorException { + if (null == resource || !(resource instanceof SingleResource)) { + return false; + } + try { + SingleResource singleRes = (SingleResource) resource; + + SimulatorSingleResource jSimulatorSingleResource = (SimulatorSingleResource) resource + .getSimulatorResource(); + if (null == jSimulatorSingleResource) { + return false; + } + + // 1. Update resource URI and Name if they are changed. + String newUri = uri.trim(); + String newName = name.trim(); + + if (multiInstance) { + singleRes.setResourceURI(newUri); + singleRes.setResourceName(newName); + } else { + if (!singleRes.getResourceURI().equals(newUri)) { + jSimulatorSingleResource.setURI(newUri); + singleRes.setResourceURI(newUri); + } + if (!singleRes.getResourceName().equals(newName)) { + jSimulatorSingleResource.setName(newName); + singleRes.setResourceName(newName); } } - } - } - public boolean isResourceExist(String resourceURI) { - boolean result = false; - if (null != resourceURI) { - SimulatorResource resource = getSimulatorResourceByURI(resourceURI); - if (null != resource) { - result = true; + // 2. Set the model change listener. + jSimulatorSingleResource + .setResourceModelChangeListener(resourceModelChangeListener); + + // 3. Set the observer listener if the resource is observable. + if (jSimulatorSingleResource.isObservable()) { + jSimulatorSingleResource.setObserverListener(observer); + singleRes.setObservable(true); } - } - return result; - } - public void addResourceDisplayName(String displayName, String completeURI) { - synchronized (displayNameMap) { - displayNameMap.put(displayName, completeURI); - } - } + // 4. Fetch the resource model. + SimulatorResourceModel jResModel = jSimulatorSingleResource + .getResourceModel(); + if (null == jResModel) { + return false; + } + singleRes.setResourceModel(jResModel); + + // 5. Fetch the basic details of the resource. + singleRes.addResourceType(jSimulatorSingleResource + .getResourceType()); + singleRes + .setResourceInterfaces(Utility + .convertVectorToSet(jSimulatorSingleResource + .getInterface())); + + // 6. Register the resource with the platform. + jSimulatorSingleResource.start(); + singleRes.setStarted(true); + + // 7. Fetch the resource attributes. + Map resourceAttributeMap; + resourceAttributeMap = fetchResourceAttributesFromModel(jResModel); + if (null != resourceAttributeMap) { + singleRes.setResourceAttributes(resourceAttributeMap); + } - public void removeResourceDisplayName(String displayName) { - synchronized (displayNameMap) { - displayNameMap.remove(displayName); - } - } + // 8. Add to local cache. + data.addResource(singleRes); - public boolean isDisplayName(String displayName) { - boolean exist = false; - synchronized (displayNameMap) { - exist = displayNameMap.containsKey(displayName); + // 9. Update UI listeners for single instance creation + if (!multiInstance) + UiListenerHandler.getInstance().resourceCreatedUINotification( + ResourceType.SINGLE); + } catch (SimulatorException e) { + Activator + .getDefault() + .getLogManager() + .log(Level.ERROR.ordinal(), new Date(), + Utility.getSimulatorErrorString(e, null)); + throw e; } - return exist; + return true; } - public String getCompleteUriFromDisplayName(String displayName) { - String completeURI = null; - synchronized (displayNameMap) { - completeURI = displayNameMap.get(displayName); + /** + * This method can set/change the resource uri and name of an already + * created resource which is not yet registered with the platform. This + * method registers the model change and observer listeners, registers the + * resource, fetches the resource attributes, updates the local cache and + * notifies the UI listeners. + */ + public boolean completeCollectionResourceCreationByRAML(Resource resource, + String uri, String name) throws SimulatorException { + if (null == resource || !(resource instanceof CollectionResource)) { + return false; } - return completeURI; - } + try { + CollectionResource collectionRes = (CollectionResource) resource; - public void createResource(final String configFilePath) { - new Thread() { - @Override - public void run() { - SimulatorResourceServer resourceServerN; - try { - resourceServerN = SimulatorManager.createResource( - configFilePath, resourceModelChangeListener); - } catch (SimulatorException e) { - Activator - .getDefault() - .getLogManager() - .log(Level.ERROR.ordinal(), - new Date(), - "[" + e.getClass().getSimpleName() + "]" - + e.code().toString() + "-" - + e.message()); - return; - } - SimulatorResource simulatorResource; - simulatorResource = fetchResourceData(resourceServerN); - if (null != simulatorResource) { - String uri = simulatorResource.getResourceURI(); - addResourceToMap(simulatorResource); - addResourceUriToOrderedMap( - simulatorResource.getResourceType(), uri); - resourceCreatedUINotification(); - - // Form the display URI - String displayName = Utility.uriToDisplayName(uri); - if (null != displayName) { - addResourceDisplayName(displayName, uri); - } else { - Activator - .getDefault() - .getLogManager() - .log(Level.ERROR.ordinal(), - new Date(), - "Converting the URI to display format for " - + uri + "failed!"); - } + SimulatorCollectionResource jSimulatorCollectionResource = (SimulatorCollectionResource) resource + .getSimulatorResource(); + if (null == jSimulatorCollectionResource) { + return false; + } - // Set the observer for the created resource - try { - resourceServerN.setObserverCallback(observer); - } catch (SimulatorException e) { - Activator - .getDefault() - .getLogManager() - .log(Level.ERROR.ordinal(), - new Date(), - "[" + e.getClass().getSimpleName() - + "]" + e.code().toString() - + "-" + e.message()); - } + // 1. Update resource URI and Name if they are changed. + String newUri = uri.trim(); + String newName = name.trim(); - // Print the resource data - simulatorResource.printResourceInfo(); - } + if (!collectionRes.getResourceURI().equals(newUri)) { + jSimulatorCollectionResource.setURI(newUri); + collectionRes.setResourceURI(newUri); } - }.start(); + if (!collectionRes.getResourceName().equals(newName)) { + jSimulatorCollectionResource.setName(newName); + collectionRes.setResourceName(newName); + } + + // 2. Set the model change listener. + jSimulatorCollectionResource + .setResourceModelChangeListener(resourceModelChangeListener); + + // 3. Fetch the resource model. + SimulatorResourceModel jResModel = jSimulatorCollectionResource + .getResourceModel(); + if (null == jResModel) { + return false; + } + collectionRes.setResourceModel(jResModel); + + // 4. Fetch the basic details of the resource. + collectionRes.addResourceType(jSimulatorCollectionResource + .getResourceType()); + collectionRes.setResourceInterfaces(Utility + .convertVectorToSet(jSimulatorCollectionResource + .getInterface())); + + // 5. Set the observer listener if the resource is observable. + if (jSimulatorCollectionResource.isObservable()) { + jSimulatorCollectionResource.setObserverListener(observer); + collectionRes.setObservable(true); + } + + // 6. Register the resource with the platform. + jSimulatorCollectionResource.start(); + collectionRes.setStarted(true); + + // 7. Fetch the resource attributes. + Map resourceAttributeMap; + resourceAttributeMap = fetchResourceAttributesFromModel(jResModel); + if (null != resourceAttributeMap) { + collectionRes.setResourceAttributes(resourceAttributeMap); + } + + // 6. Add to local cache. + data.addResource(collectionRes); + + // 7. Update UI listeners for single instance creation + UiListenerHandler.getInstance().resourceCreatedUINotification( + ResourceType.COLLECTION); + } catch (SimulatorException e) { + Activator + .getDefault() + .getLogManager() + .log(Level.ERROR.ordinal(), new Date(), + Utility.getSimulatorErrorString(e, null)); + throw e; + } + return true; } - public void createResource(final String configFilePath, - final int noOfInstances) { - new Thread() { - @Override - public void run() { - Map resourceTypeMap; - SimulatorResourceServer[] simulatorResourceServers = null; + public int createSingleResourceMultiInstances(String configFile, int count) + throws SimulatorException { + int createCount = 0; + try { + Vector jSimulatorResources = SimulatorManager + .createResource(configFile, count); + if (null == jSimulatorResources || jSimulatorResources.size() < 1) { + return 0; + } + SimulatorSingleResource jResource; + SingleResource resource; + boolean result; + for (SimulatorResource jSimulatorResource : jSimulatorResources) { + jResource = (SimulatorSingleResource) jSimulatorResource; + resource = new SingleResource(); + resource.setSimulatorResource(jResource); try { - simulatorResourceServers = SimulatorManager.createResource( - configFilePath, noOfInstances, - resourceModelChangeListener); - } catch (SimulatorException e) { + result = completeSingleResourceCreationByRAML(resource, + jResource.getURI(), jResource.getName(), true); + if (result) { + createCount++; + } + } catch (SimulatorException eInner) { Activator .getDefault() .getLogManager() .log(Level.ERROR.ordinal(), new Date(), - "[" + e.getClass().getSimpleName() + "]" - + e.code().toString() + "-" - + e.message()); - return; - } - if (null == simulatorResourceServers) { - return; - } - resourceTypeMap = new HashMap(); - SimulatorResource resource; - String uri; - String displayName; - for (SimulatorResourceServer resourceServerN : simulatorResourceServers) { - resource = fetchResourceData(resourceServerN); - if (null != resource) { - uri = resource.getResourceURI(); - resourceTypeMap.put(uri, resource); - addResourceUriToOrderedMap(resource.getResourceType(), - uri); - - // Form the display URI - displayName = Utility.uriToDisplayName(uri); - if (null != displayName) { - addResourceDisplayName(displayName, uri); - } else { - Activator - .getDefault() - .getLogManager() - .log(Level.ERROR.ordinal(), - new Date(), - "Converting the URI to display format for " - + uri + "failed!"); - } - } - // Set the observer for the created resource - try { - resourceServerN.setObserverCallback(observer); - } catch (SimulatorException e) { - Activator - .getDefault() - .getLogManager() - .log(Level.ERROR.ordinal(), - new Date(), - "[" + e.getClass().getSimpleName() - + "]" + e.code().toString() - + "-" + e.message()); - } - } - - // Find the resourceType and add it to the local data - // structure and notify UI Listeners - if (resourceTypeMap.size() > 0) { - String resourceType; - Set uriSet = resourceTypeMap.keySet(); - Iterator itr = uriSet.iterator(); - if (itr.hasNext()) { - SimulatorResource simResource = resourceTypeMap.get(itr - .next()); - if (null != simResource) { - resourceType = simResource.getResourceType(); - - addResourceToMap(resourceType, resourceTypeMap); - resourceCreatedUINotification(); - } - } + Utility.getSimulatorErrorString(eInner, + null)); } } - }.start(); + if (createCount > 0) { + UiListenerHandler.getInstance().resourceCreatedUINotification( + ResourceType.SINGLE); + } + } catch (SimulatorException eOuter) { + Activator + .getDefault() + .getLogManager() + .log(Level.ERROR.ordinal(), new Date(), + Utility.getSimulatorErrorString(eOuter, null)); + throw eOuter; + } + return createCount; } - private SimulatorResource fetchResourceData( - SimulatorResourceServer resourceServerN) { - SimulatorResource simulatorResource = null; - if (null != resourceServerN) { - simulatorResource = new SimulatorResource(); - simulatorResource.setResourceServer(resourceServerN); - simulatorResource.setResourceURI(resourceServerN.getURI()); - simulatorResource - .setResourceType(resourceServerN.getResourceType()); - simulatorResource.setResourceName(resourceServerN.getName()); - simulatorResource.setResourceInterface(resourceServerN - .getInterfaceType()); - - SimulatorResourceModel resourceModelN; - try { - resourceModelN = resourceServerN.getModel(); - } catch (SimulatorException e) { - Activator - .getDefault() - .getLogManager() - .log(Level.ERROR.ordinal(), - new Date(), - "[" + e.getClass().getSimpleName() + "]" - + e.code().toString() + "-" - + e.message()); - return null; - } - if (null != resourceModelN) { - simulatorResource.setResourceModel(resourceModelN); + public void createDevice(String deviceName, Set childs) { + // 1. Create device + Device dev = new Device(); + dev.setDeviceName(deviceName); + data.addDevice(dev); - // Fetch the resource attributes - Map resourceAttributeMap; - resourceAttributeMap = fetchResourceAttributesFromModel(resourceModelN); - if (null != resourceAttributeMap) { - simulatorResource - .setResourceAttributesMap(resourceAttributeMap); - } - } - } - return simulatorResource; + // 2. Add children to device + if (null != childs && !childs.isEmpty()) + addResourceToDevice(dev, childs); + + // 3. Update ui listeners + UiListenerHandler.getInstance().resourceListUpdateUINotification( + ResourceType.DEVICE); } private Map fetchResourceAttributesFromModel( - SimulatorResourceModel resourceModelN) { + SimulatorResourceModel jResModel) throws SimulatorException { Map resourceAttributeMap = null; - if (null != resourceModelN) { - Map attributeMapN; - try { - attributeMapN = resourceModelN.getAttributes(); - } catch (SimulatorException e) { - Activator - .getDefault() - .getLogManager() - .log(Level.ERROR.ordinal(), - new Date(), - "[" + e.getClass().getSimpleName() + "]" - + e.code().toString() + "-" - + e.message()); - return null; - } - if (null != attributeMapN) { + if (null != jResModel) { + Map jAttributeMap; + jAttributeMap = jResModel.getAttributes(); + if (null != jAttributeMap) { resourceAttributeMap = new HashMap(); - - Set attNameSet = attributeMapN.keySet(); + Iterator itr = jAttributeMap.keySet().iterator(); String attName; - ResourceAttribute attributeN; - LocalResourceAttribute attribute; - Iterator attNameItr = attNameSet.iterator(); - while (attNameItr.hasNext()) { - attName = attNameItr.next(); - attributeN = attributeMapN.get(attName); - if (null != attributeN) { - attribute = new LocalResourceAttribute(); - attribute.setResourceAttribute(attributeN); - - // Set the attribute value - Object valueObj = attributeN.getValue(); - if (null != valueObj) { - attribute.setAttributeValue(valueObj); - } + SimulatorResourceAttribute jResAtt; + LocalResourceAttribute localAtt; + while (itr.hasNext()) { + attName = itr.next(); + if (null != attName) { + jResAtt = jAttributeMap.get(attName); + if (null != jResAtt) { + localAtt = new LocalResourceAttribute(); - // Set the attribute value list. - attribute.setAttValues(getValueList(attributeN)); + localAtt.setResourceAttributeRef(jResAtt); - // Initially disabling the automation - attribute.setAutomationInProgress(false); + // Initially disabling the automation + localAtt.setAutomationInProgress(false); - // TODO: Temporarily setting the interval to 500. - // This value should come from the native layer. - // Native implementation is in progress. - attribute - .setAutomationUpdateInterval(Constants.DEFAULT_AUTOMATION_INTERVAL); + // Assigning the default automation interval + localAtt.setAutomationUpdateInterval(Constants.DEFAULT_AUTOMATION_INTERVAL); - // Setting the default automation type - attribute - .setAutomationType(Constants.DEFAULT_AUTOMATION_TYPE); + // Setting the default automation type + localAtt.setAutomationType(Constants.DEFAULT_AUTOMATION_TYPE); - resourceAttributeMap.put(attName, attribute); + resourceAttributeMap.put(attName, localAtt); + } } } } } return resourceAttributeMap; + } // This method gives all known possible values of the attribute in string // format. It takes allowed values or range of values whichever is available - private List getValueList(ResourceAttribute attributeN) { - Object[] allowedValues = attributeN.getAllowedValues(); + private List getValueList(SimulatorResourceAttribute attributeN) { + AttributeProperty attProp = attributeN.property(); + if (null == attProp) { + return null; + } List valueList = new ArrayList(); - if (null != allowedValues && allowedValues.length > 0) { - for (Object value : allowedValues) { - if (null != value) { - valueList.add(String.valueOf(value)); - } - } - } else { - Type valueType = attributeN.getBaseType(); - Range range = attributeN.getRange(); - if (null != range) { - Object min = range.getMin(); - Object max = range.getMax(); - if (valueType == Type.INT) { - int minI = (Integer) min; - int maxI = (Integer) max; - for (int value = minI; value <= maxI; value++) { - valueList.add(String.valueOf(value)); - } - } else if (valueType == Type.DOUBLE) { - double minD = (Double) min; - double maxD = (Double) max; - for (double value = minD; value <= maxD; value++) { - valueList.add(String.valueOf(value)); + Type valuesType = attProp.type(); + if (valuesType == Type.VALUESET) { + Object[] allowedValues = attProp.valueSet(); + if (null != allowedValues && allowedValues.length > 0) { + for (Object value : allowedValues) { + if (null != value) { + valueList.add(String.valueOf(((AttributeValue) value) + .get())); } } } + } else if (valuesType == Type.RANGE) { + double minD = attProp.min(); + double maxD = attProp.max(); + for (double value = minD; value <= maxD; value++) { + valueList.add(String.valueOf(value)); + } } - Object attValue = attributeN.getValue(); + Object attValue = attributeN.value().get(); if (valueList.size() < 1 && null != attValue) { valueList.add(String.valueOf(attValue)); } return valueList; } - public void deleteResourceByURI(final String resourceURI) { - if (null != resourceURI) { - new Thread() { - @Override - public void run() { - SimulatorResource resource = getSimulatorResourceByURI(resourceURI); - if (null != resource) { - String resourceType = resource.getResourceType(); + public List getResourceList() { + List resourceList = data.getResources(); + if (null == resourceList) { + return null; + } + // Sort the list + Collections.sort(resourceList, Utility.resourceComparator); + + return resourceList; + } - // Unregister the resource from the platform - deleteResource(resource); + public List getSingleResourceList() { + List resourceList = data.getSingleResources(); + if (null == resourceList) { + return null; + } + // Sort the list + Collections.sort(resourceList, Utility.singleResourceComparator); - // Delete from the local data structure - deleteLocalResourceDetails(resourceType, resourceURI); + return resourceList; + } - // Notify the UI listener for removing this resource - // from UI - resourceDeletedUINotification(); + public List getCollectionResourceList() { + List resourceList = data.getCollectionResources(); + if (null == resourceList) { + return null; + } + // Sort the list + Collections.sort(resourceList, Utility.collectionResourceComparator); - if (null != currentResourceInSelection - && resource == currentResourceInSelection) { - // Listeners might query the resource being deleted - // if exists. So set the currently selection to - // null. - setCurrentResourceInSelection(null); + return resourceList; + } - // Notify all observers for resource selection - // change event - resourceSelectionChangedUINotification(); - } - } - } - }.start(); - } - } - - private SimulatorResource getSimulatorResourceByURI(String resourceURI) { - SimulatorResource resource = null; - if (null != resourceURI) { - synchronized (resourceMap) { - Set typeSet = resourceMap.keySet(); - Iterator typeItr = typeSet.iterator(); - String resourceType; - Map resourceTypeMap; - while (typeItr.hasNext()) { - resourceType = typeItr.next(); - resourceTypeMap = resourceMap.get(resourceType); - if (null != resourceTypeMap) { - resource = resourceTypeMap.get(resourceURI); - if (null != resource) { - break; - } - } - } + public List getDeviceList() { + List deviceList = data.getDevices(); + if (null == deviceList) { + return null; + } + // Sort the list + Collections.sort(deviceList, Utility.deviceComparator); + return deviceList; + } + + // Returns the number of resources which are added properly to the + // collection. + public int addResourceToCollection(CollectionResource collectionParent, + Set childs) { + if (null == collectionParent || null == childs || childs.isEmpty()) { + return -1; + } + Iterator itr = childs.iterator(); + Resource res; + int count = childs.size(); + while (itr.hasNext()) { + res = itr.next(); + try { + addResourceToCollection(collectionParent, res); + } catch (SimulatorException e) { + count--; } } - return resource; + return count; } - private void deleteResource(SimulatorResource resource) { - if (null != resource) { - SimulatorResourceServer resourceServerN = resource - .getResourceServer(); - if (null != resourceServerN) { - try { - SimulatorManager.deleteResource(resourceServerN); - } catch (SimulatorException e) { - Activator - .getDefault() - .getLogManager() - .log(Level.ERROR.ordinal(), - new Date(), - "[" + e.getClass().getSimpleName() + "]" - + e.code().toString() + "-" - + e.message()); - } + public void addResourceToCollection(CollectionResource collectionParent, + Resource child) throws SimulatorException { + if (null == collectionParent || null == child) { + return; + } + try { + // 1. Add child to collection + collectionParent.addChildResource(child); + + // 2. Add a reference to the collection in the child + if (child instanceof SingleResource) { + ((SingleResource) child) + .addCollectionMembership(collectionParent); + } else { + ((CollectionResource) child).addMembership(collectionParent); + } + } catch (SimulatorException e) { + Activator + .getDefault() + .getLogManager() + .log(Level.ERROR.ordinal(), new Date(), + Utility.getSimulatorErrorString(e, null)); + throw e; + } + } + + public int addResourceToCollection(Set collections, + Resource child) { + if (null == collections || collections.isEmpty() || null == child) { + return -1; + } + Iterator itr = collections.iterator(); + CollectionResource res; + int count = collections.size(); + while (itr.hasNext()) { + res = itr.next(); + try { + addResourceToCollection(res, child); + } catch (SimulatorException e) { + count--; } } + return count; } - public void deleteResourceByType(final String resourceType) { - if (null != resourceType) { - new Thread() { - @Override - public void run() { - // Unregister the resources from the platform - deleteResource(resourceType); + public void addResourceToDevice(Device dev, Set childs) { + // 1. Add children to the device. + dev.addChildResource(childs); + + // 2. Add a reference to the device in all children. + Iterator itr = childs.iterator(); + Resource res; + while (itr.hasNext()) { + res = itr.next(); + if (res instanceof SingleResource) { + ((SingleResource) res).addDeviceMembership(dev); + } else { + ((CollectionResource) res).addDeviceMembership(dev); + } + } + } - // Delete from the local data structure - deleteLocalResourceDetails(resourceType, null); + public void addResourceToDevice(Device dev, Resource child) { + // 1. Add child to the device. + dev.addChildResource(child); - // Notify the UI listener for removing this resource from UI - resourceDeletedUINotification(); + // 2. Add a reference to the device in the child. + if (child instanceof SingleResource) { + ((SingleResource) child).addDeviceMembership(dev); + } else { + ((CollectionResource) child).addDeviceMembership(dev); + } + } - if (null != currentResourceInSelection - && resourceType.equals(currentResourceInSelection - .getResourceType())) { - // Listeners might query the resource being deleted if - // exists. So set the currently selection to null. - setCurrentResourceInSelection(null); + public void addResourceToDevice(Set devices, Resource child) { + // 1. Add device reference in child. + if (child instanceof SingleResource) + ((SingleResource) child).addDeviceMembership(devices); + else + ((CollectionResource) child).addDeviceMembership(devices); - // Notify all observers for resource selection change - // event - resourceSelectionChangedUINotification(); - } - } - }.start(); + // 2. Add a reference to the child in all devices. + Iterator itr = devices.iterator(); + Device dev; + while (itr.hasNext()) { + dev = itr.next(); + dev.addChildResource(child); } } - private void deleteResource(String resourceType) { - if (null != resourceType) { + public int removeResourceFromCollection( + Set collections, Resource resource) { + // 1. Remove the reference of resource from all the collections. + Iterator itr = collections.iterator(); + CollectionResource colRes; + int count = collections.size(); + while (itr.hasNext()) { + colRes = itr.next(); try { - SimulatorManager.deleteResources(resourceType); + removeResourceFromCollection(colRes, resource); } catch (SimulatorException e) { - Activator - .getDefault() - .getLogManager() - .log(Level.ERROR.ordinal(), - new Date(), - "[" + e.getClass().getSimpleName() + "]" - + e.code().toString() + "-" - + e.message()); + count--; } } + return count; + } - public void deleteAllResources() { - new Thread() { - @Override - public void run() { - // Unregister the resources from the platform - deleteResource(); + public void removeResourceFromDevice(Set devices, Resource resource) { + // 1. Remove the reference of resource from all the devices. + Iterator itr = devices.iterator(); + Device dev; + while (itr.hasNext()) { + dev = itr.next(); + dev.removeChildResource(resource); + } - // Delete from the local data structure - deleteLocalResourceDetails(null, null); + // 2. Remove the reference of devices from the resource. + resource.removeDeviceMembership(devices); + } - // Notify the UI listener for removing this resource from UI - resourceDeletedUINotification(); + // Returns the count of resources removed from the collection + public int removeResourcesFromCollection(CollectionResource colRes, + Set resources) { + Iterator itr = resources.iterator(); + Resource res; + int count = resources.size(); + while (itr.hasNext()) { + res = itr.next(); + try { + removeResourceFromCollection(colRes, res); + } catch (SimulatorException e) { + count--; + } + } + return count; + } - // Listeners might query the resource being deleted if exists. - // So set the currently selection to null. - setCurrentResourceInSelection(null); + public void removeResourcesFromDevice(Device dev, Set resources) { + Iterator itr = resources.iterator(); + Resource res; + while (itr.hasNext()) { + res = itr.next(); + res.removeDeviceMembership(dev); + } + dev.removeChildResource(resources); + } - // Notify all observers for resource selection change event - resourceSelectionChangedUINotification(); + public void removeResourceFromCollection(CollectionResource parent, + Resource child) throws SimulatorException { + try { + // 1. Remove the child from the parent + parent.removeChildResource(child); + + // 2. Remove the reference to parent from child + if (child instanceof SingleResource) { + ((SingleResource) child).removeCollectionMembership(parent); + } else { + ((CollectionResource) child).removeMembership(parent); } - }.start(); + } catch (SimulatorException e) { + Activator + .getDefault() + .getLogManager() + .log(Level.ERROR.ordinal(), new Date(), + Utility.getSimulatorErrorString(e, null)); + throw e; + } } - private void deleteResource() { + public void removeResourceFromDevice(Device parent, Resource child) { + // 1. Remove the reference to parent from child + child.removeDeviceMembership(parent); + + // 2. Remove the child from the parent + parent.removeChildResource(child); + } + + public void removeSingleResources(Set resources) + throws SimulatorException { + if (null == resources) { + return; + } + Iterator itr = resources.iterator(); + while (itr.hasNext()) { + removeResource(itr.next()); + } + } + + public void removeCollectionResources(Set resources) + throws SimulatorException { + if (null == resources) { + return; + } + Iterator itr = resources.iterator(); + while (itr.hasNext()) { + removeResource(itr.next()); + } + } + + public void removeResource(Resource res) throws SimulatorException { + // 1. Unregister the resource from the platform. + SimulatorResource simRes = res.getSimulatorResource(); try { - SimulatorManager.deleteResources(null); + simRes.stop(); } catch (SimulatorException e) { Activator .getDefault() .getLogManager() - .log(Level.ERROR.ordinal(), - new Date(), - "[" + e.getClass().getSimpleName() + "]" - + e.code().toString() + "-" + e.message()); + .log(Level.ERROR.ordinal(), new Date(), + Utility.getSimulatorErrorString(e, null)); + throw e; } - } - private void deleteLocalResourceDetails(String resourceType, - String resourceURI) { - if (null != resourceType && null != resourceURI) { - removeResourceFromMap(resourceType, resourceURI); - removeResourceUriFromOrderedMap(resourceType, resourceURI); + Set collectionMembership; + Set deviceMembership; + + if (res instanceof SingleResource) { + collectionMembership = ((SingleResource) res) + .getCollectionMembership(); + deviceMembership = ((SingleResource) res).getDeviceMembership(); } else { - synchronized (resourceMap) { - if (null != resourceType) { - removeResourceUriFromOrderedMap(resourceType, null); - resourceMap.remove(resourceType); - } else { - resourceMap.clear(); - removeResourceUriFromOrderedMap(null, null); - } - } + collectionMembership = ((CollectionResource) res).getMembership(); + deviceMembership = ((CollectionResource) res).getDeviceMembership(); + } + + // 2. Delete from the collections to which this resource is a member. + if (null != collectionMembership && !collectionMembership.isEmpty()) { + removeResourceFromCollection(collectionMembership, res); } - // Remove the display name from the map - if (null != resourceURI) { - String dispName = Utility.uriToDisplayName(resourceURI); - if (null != dispName) - removeResourceDisplayName(dispName); + + // 3. Delete from the devices to which this resource is a member. + if (null != deviceMembership && !deviceMembership.isEmpty()) { + removeResourceFromDevice(deviceMembership, res); } + + // 4. Delete this resource + data.deleteResource(res); } - private void resourceCreatedUINotification() { - synchronized (resourceListChangedUIListeners) { - if (resourceListChangedUIListeners.size() > 0) { - IResourceListChangedUIListener listener; - Iterator listenerItr = resourceListChangedUIListeners - .iterator(); - while (listenerItr.hasNext()) { - listener = listenerItr.next(); - if (null != listener) { - listener.onResourceCreation(); - } - } + public void removeDevice(Device dev) { + Set childs = dev.getChildResources(); + if (null != childs && !childs.isEmpty()) { + // 1. Remove the reference from all the children. + Iterator itr = childs.iterator(); + Resource res; + while (itr.hasNext()) { + res = itr.next(); + res.removeDeviceMembership(dev); } } + // 2. Delete the device. + data.deleteDevice(dev); } - private void resourceDeletedUINotification() { - synchronized (resourceListChangedUIListeners) { - if (resourceListChangedUIListeners.size() > 0) { - IResourceListChangedUIListener listener; - Iterator listenerItr = resourceListChangedUIListeners - .iterator(); - while (listenerItr.hasNext()) { - listener = listenerItr.next(); - if (null != listener) { - listener.onResourceDeletion(); - } - } + public boolean isUriUnique(List properties) { + if (null == properties) { + return false; + } + MetaProperty prop; + Iterator itr = properties.iterator(); + while (itr.hasNext()) { + prop = itr.next(); + if (prop.getPropName().equals(Constants.RESOURCE_URI)) { + String uri = prop.getPropValue(); + return !data.isResourceExist(uri); } } + return false; } - private void resourceSelectionChangedUINotification() { - synchronized (resourceSelectionChangedUIListeners) { - if (resourceSelectionChangedUIListeners.size() > 0) { - IResourceSelectionChangedUIListener listener; - Iterator listenerItr = resourceSelectionChangedUIListeners - .iterator(); - while (listenerItr.hasNext()) { - listener = listenerItr.next(); - if (null != listener) { - listener.onResourceSelectionChange(); - } - } - } + public List getCollectionsForAddingToSingleResource( + SingleResource resource) { + List collectionResources = data + .getCollectionResources(); + if (null == collectionResources || collectionResources.isEmpty()) { + return null; } + + Set collectionMembership; + collectionMembership = resource.getCollectionMembership(); + if (null == collectionMembership || collectionMembership.isEmpty()) { + return collectionResources; + } + + if (collectionMembership.size() == collectionResources.size()) { + return null; + } + + collectionResources.removeAll(collectionMembership); + + // Sort the list + Collections.sort(collectionResources, + Utility.collectionResourceComparator); + + return collectionResources; } - private void resourceModelChangedUINotification( - ModelChangeNotificationType notificationType, String resourceURI, - Set valueChangeSet) { - synchronized (resourceModelChangedUIListeners) { - if (resourceModelChangedUIListeners.size() > 0 - && notificationType != ModelChangeNotificationType.NONE - && null != resourceURI) { - IResourceModelChangedUIListener listener; - Iterator listenerItr = resourceModelChangedUIListeners - .iterator(); - while (listenerItr.hasNext()) { - listener = listenerItr.next(); - if (null != listener) { - listener.onResourceModelChange(notificationType, - resourceURI, valueChangeSet); - } - } - } + public List getSingleTypeResourcesForAddingToCollectionResource( + CollectionResource colRes) { + List singleResources = data.getSingleResources(); + if (null == singleResources || singleResources.isEmpty()) { + return null; + } + + Set childs; + childs = colRes.getSingleTypeChildResources(); + if (null == childs || childs.isEmpty()) { + return singleResources; + } + + if (childs.size() == singleResources.size()) { + return null; } + + singleResources.removeAll(childs); + + // Sort the list + Collections.sort(singleResources, Utility.singleResourceComparator); + + return singleResources; } - private void resourceAutomationStartedUINotification(String resourceURI) { - synchronized (automationUIListeners) { - if (automationUIListeners.size() > 0 && null != resourceURI) { - IAutomationUIListener listener; - Iterator listenerItr = automationUIListeners - .iterator(); - while (listenerItr.hasNext()) { - listener = listenerItr.next(); - if (null != listener) { - listener.onResourceAutomationStart(resourceURI); - } - } - } + public List getSingleTypeResourcesForAddingToDevice( + Device dev) { + List singleResources = data.getSingleResources(); + if (null == singleResources || singleResources.isEmpty()) { + return null; + } + + Set childs; + childs = dev.getSingleTypeChildResources(); + if (null == childs || childs.isEmpty()) { + return singleResources; } + + if (childs.size() == singleResources.size()) { + return null; + } + + singleResources.removeAll(childs); + + // Sort the list + Collections.sort(singleResources, Utility.singleResourceComparator); + + return singleResources; } - private void automationCompleteUINotification(String resourceURI, - String attName) { - synchronized (automationUIListeners) { - if (automationUIListeners.size() > 0 && null != resourceURI) { - IAutomationUIListener listener; - Iterator listenerItr = automationUIListeners - .iterator(); - while (listenerItr.hasNext()) { - listener = listenerItr.next(); - if (null != listener) { - listener.onAutomationComplete(resourceURI, attName); - } - } - } + public List getCollectionTypeResourcesForAddingToCollectionResource( + CollectionResource colRes) { + List collectionResources = data + .getCollectionResources(); + if (null == collectionResources || collectionResources.isEmpty()) { + return null; } + + // Remove the colRes from the list + collectionResources.remove(colRes); + + Set childs; + childs = colRes.getCollectionTypeChildResources(); + if (null == childs || childs.isEmpty()) { + return collectionResources; + } + + if (childs.size() == collectionResources.size()) { + return null; + } + + collectionResources.removeAll(childs); + + // Sort the list + Collections.sort(collectionResources, + Utility.collectionResourceComparator); + + return collectionResources; } - private void observerListChangedUINotification(String resourceURI) { - synchronized (observerUIListeners) { - if (observerUIListeners.size() > 0 && null != resourceURI) { - IObserverListChangedUIListener listener; - Iterator listenerItr = observerUIListeners - .iterator(); - while (listenerItr.hasNext()) { - listener = listenerItr.next(); - if (null != listener) { - listener.onObserverListChanged(resourceURI); - } - } - } + public List getCollectionTypeResourcesForAddingToDevice( + Device dev) { + List collectionResources = data + .getCollectionResources(); + if (null == collectionResources || collectionResources.isEmpty()) { + return null; } + + Set childs; + childs = dev.getCollectionTypeChildResources(); + if (null == childs || childs.isEmpty()) { + return collectionResources; + } + + if (childs.size() == collectionResources.size()) { + return null; + } + + collectionResources.removeAll(childs); + + // Sort the list + Collections.sort(collectionResources, + Utility.collectionResourceComparator); + + return collectionResources; } - public List getResourceTypeList() { - List typeList = null; - synchronized (resourceMap) { - if (resourceMap.size() > 0) { - typeList = new ArrayList(); - Set typeSet = resourceMap.keySet(); - Iterator typeItr = typeSet.iterator(); - while (typeItr.hasNext()) { - typeList.add(typeItr.next()); - } - } + public List getDevicesForAddingToResource(Resource resource) { + List devices = data.getDevices(); + if (null == devices || devices.isEmpty()) { + return null; } - return typeList; + + Set deviceMembership; + if (resource instanceof SingleResource) { + deviceMembership = ((SingleResource) resource) + .getDeviceMembership(); + } else { + deviceMembership = ((CollectionResource) resource) + .getDeviceMembership(); + } + if (null == deviceMembership || deviceMembership.isEmpty()) { + return devices; + } + + if (devices.size() == deviceMembership.size()) { + return null; + } + + devices.removeAll(deviceMembership); + + // Sort the list + Collections.sort(devices, Utility.deviceComparator); + + return devices; } - public boolean isTypeExist(String resType) { - synchronized (resourceMap) { - if (resourceMap.containsKey(resType)) { - return true; - } + public List getResourceReferences( + SingleResource resource) { + List resources = Utility + .getCollectionResourceListFromSet(resource + .getCollectionMembership()); + if (null == resources || resources.isEmpty()) { + return null; } - return false; + + Collections.sort(resources, Utility.collectionResourceComparator); + + return resources; } - public List getURIList() { - List list = null; - synchronized (orderedResourceUriMap) { - Set typeSet = orderedResourceUriMap.keySet(); - List typeList = Utility.convertSetToList(typeSet); - if (null == typeList || typeList.size() < 1) { - return list; - } - list = new ArrayList(); + public List getDeviceReferences(Resource resource) { + Set deviceMembership; + if (resource instanceof SingleResource) { + deviceMembership = ((SingleResource) resource) + .getDeviceMembership(); + } else { + deviceMembership = ((CollectionResource) resource) + .getDeviceMembership(); + } - // Sort the types - Collections.sort(typeList); + List devices = Utility.getDeviceListFromSet(deviceMembership); + if (null == devices || devices.isEmpty()) { + return null; + } - // Add all URIs to the output list - Iterator typeItr = typeList.iterator(); - while (typeItr.hasNext()) { - List l = orderedResourceUriMap.get(typeItr.next()); - if (null != l) { - list.addAll(l); + Collections.sort(devices, Utility.deviceComparator); + + return devices; + } + + public List getSingleTypeChilds(CollectionResource colRes) { + Set childs = colRes.getSingleTypeChildResources(); + return Utility.getSingleResourceListFromSet(childs); + } + + public List getSingleTypeChilds(Device dev) { + Set childs = dev.getSingleTypeChildResources(); + return Utility.getSingleResourceListFromSet(childs); + } + + public List getCollectionTypeChilds( + CollectionResource colRes) { + Set childs = colRes + .getCollectionTypeChildResources(); + return Utility.getCollectionResourceListFromSet(childs); + } + + public List getCollectionTypeChilds(Device dev) { + Set childs = dev.getCollectionTypeChildResources(); + return Utility.getCollectionResourceListFromSet(childs); + } + + /* + * public void deleteResourceByURI(String resourceURI) { if (null != + * resourceURI) { Resource resource = + * getSimulatorResourceByURI(resourceURI); if (null != resource) { // + * Unregister the resource from the platform deleteResource(resource); + * + * // Delete from the local data structure deleteLocalResourceDetails(null, + * resourceURI); + * + * // Notify the UI listener for removing this resource // from UI // + * resourceDeletedUINotification(); if (resource == + * getCurrentResourceInSelection()) { // Listeners might query the resource + * being deleted // if exists. So set the currently selection to // null. + * setCurrentResourceInSelection(null); + * + * // Notify all observers for resource selection // change event // + * resourceSelectionChangedUINotification(); } } } } + * + * private SingleResource getSimulatorResourceByURI(String resourceURI) { + * SingleResource resource = null; if (null != resourceURI) { synchronized + * (resourceMap) { resource = resourceMap.get(resourceURI); } } return + * resource; } + * + * private void deleteResource(SingleResource resource) { if (null != + * resource) { SimulatorResourceServer resourceServerN = resource + * .getResourceServer(); if (null != resourceServerN) { try { + * SimulatorManager.deleteResource(resourceServerN); } catch + * (SimulatorException e) { Activator .getDefault() .getLogManager() + * .log(Level.ERROR.ordinal(), new Date(), + * Utility.getSimulatorErrorString(e, null)); } } } } + * + * public void deleteResourceByType(final String resourceType) { + * System.out.println(resourceType + "to be deleted."); if (null != + * resourceType) { new Thread() { + * + * @Override public void run() { // Unregister the resources from the + * platform deleteResource(resourceType); + * + * // Delete from the local data structure + * deleteLocalResourceDetails(resourceType, null); + * + * // Notify the UI listener for removing this resource from UI + * resourceDeletedUINotification(); + * + * if (null != currentResourceInSelection && + * currentResourceInSelection.getResourceTypes() .contains(resourceType)) { + * // Listeners might query the resource being deleted if // exists. So set + * the currently selection to null. setCurrentResourceInSelection(null); + * + * // Notify all observers for resource selection change // event + * resourceSelectionChangedUINotification(null); } } }.start(); } } + * + * private void deleteResource(String resourceType) { if (null != + * resourceType) { try { SimulatorManager.deleteResources(resourceType); } + * catch (SimulatorException e) { Activator .getDefault() .getLogManager() + * .log(Level.ERROR.ordinal(), new Date(), + * Utility.getSimulatorErrorString(e, null)); } } } + * + * public void deleteAllResources() { new Thread() { + * + * @Override public void run() { // Unregister the resources from the + * platform deleteResource(); + * + * // Delete from the local data structure deleteLocalResourceDetails(null, + * null); + * + * // Notify the UI listener for removing this resource from UI + * resourceDeletedUINotification(); + * + * // Listeners might query the resource being deleted if exists. // So set + * the currently selection to null. setCurrentResourceInSelection(null); + * + * // Notify all observers for resource selection change event + * resourceSelectionChangedUINotification(null); } }.start(); } + * + * private void deleteResource() { try { + * SimulatorManager.deleteResources(null); } catch (SimulatorException e) { + * Activator .getDefault() .getLogManager() .log(Level.ERROR.ordinal(), new + * Date(), Utility.getSimulatorErrorString(e, null)); } } + * + * private void deleteLocalResourceDetails(String resourceType, String + * resourceURI) { synchronized (resourceMap) { if (null == resourceType && + * null == resourceURI) { resourceMap.clear(); } else if (null != + * resourceType) { Set uriSet = resourceMap.keySet(); if (null == + * uriSet) { return; } String uri; SingleResource simpleRes; + * Iterator uriItr = uriSet.iterator(); while (uriItr.hasNext()) { + * uri = uriItr.next(); simpleRes = resourceMap.get(uri); if + * (simpleRes.getResourceTypes().contains(resourceType)) { uriItr.remove(); + * } } } else { removeResourceFromMap(resourceURI); } } } + * + * + * + * public Set getResourceTypeList() { Set types = null; + * synchronized (resourceMap) { if (resourceMap.size() > 0) { types = new + * TreeSet(); Set typeSet = resourceMap.keySet(); + * Iterator typeItr = typeSet.iterator(); SingleResource resource; + * while (typeItr.hasNext()) { resource = resourceMap.get(typeItr.next()); + * Set subTypes = resource.getResourceTypes(); + * types.addAll(subTypes); } } } return types; } + */ + + public void resourceSelectionChanged(final Resource selectedResource) { + new Thread() { + @Override + public void run() { + + setCurrentDeviceInSelection(null); + + if (null != selectedResource) { + setCurrentResourceInSelection(selectedResource); + } else { + setCurrentResourceInSelection(null); } + // Notify all observers for resource selection change event + UiListenerHandler.getInstance() + .resourceSelectionChangedUINotification( + selectedResource); } - } - return list; + }.start(); } - public void resourceSelectionChanged(final String selectedItem) { + public void deviceSelectionChanged(final Device selectedDevice) { new Thread() { @Override public void run() { - // Check whether the item selected is a resource or resource - // category - if (isTypeExist(selectedItem)) { - // Given item is a resource Type - setCurrentResourceInSelection(null); + + setCurrentResourceInSelection(null); + + if (null != selectedDevice) { + setCurrentDeviceInSelection(selectedDevice); } else { - // Given item is a resource URI - SimulatorResource resource = getSimulatorResourceByURI(selectedItem); - if (null != resource) { - setCurrentResourceInSelection(resource); - } else { - setCurrentResourceInSelection(null); - } + setCurrentDeviceInSelection(null); } // Notify all observers for resource selection change event - resourceSelectionChangedUINotification(); + UiListenerHandler.getInstance() + .deviceSelectionChangedUINotification(selectedDevice); } }.start(); } - public List getMetaProperties(SimulatorResource resource) { + public List getMetaProperties(Resource resource) { if (null != resource) { String propName; String propValue; @@ -1179,13 +1624,12 @@ public class ResourceManager { for (int index = 0; index < Constants.META_PROPERTY_COUNT; index++) { propName = Constants.META_PROPERTIES[index]; - if (propName.equals(Constants.RESOURCE_URI)) { + if (propName.equals(Constants.RESOURCE_NAME)) { + propValue = resource.getResourceName(); + } else if (propName.equals(Constants.RESOURCE_URI)) { propValue = resource.getResourceURI(); } else if (propName.equals(Constants.RESOURCE_TYPE)) { - propValue = resource.getResourceType(); - } else if (propName.equals(Constants.CONNECTIVITY_TYPE)) { - // TODO: Temporarily ignoring till the implementation. - propValue = null; + propValue = resource.getResourceTypes().toString(); } else { propValue = null; } @@ -1193,17 +1637,228 @@ public class ResourceManager { metaPropertyList.add(new MetaProperty(propName, propValue)); } } + return metaPropertyList; + } + return null; + } + public List getMetaProperties(Device dev) { + if (null != dev) { + List metaPropertyList = new ArrayList(); + metaPropertyList.add(new MetaProperty(Constants.DEVICE_NAME, dev + .getDeviceName())); return metaPropertyList; } return null; } - public List getAttributes(SimulatorResource resource) { + public boolean startResource(Resource resource) throws SimulatorException { + if (null == resource) { + return false; + } + SimulatorResource server = resource.getSimulatorResource(); + if (null == server) { + return false; + } + try { + server.start(); + resource.setStarted(true); + } catch (SimulatorException e) { + Activator + .getDefault() + .getLogManager() + .log(Level.ERROR.ordinal(), + new Date(), + "There is an error while starting the resource.\n" + + Utility.getSimulatorErrorString(e, null)); + throw e; + } + return true; + } + + public boolean stopResource(Resource resource) throws SimulatorException { + if (null == resource) { + return false; + } + SimulatorResource server = resource.getSimulatorResource(); + if (null == server) { + return false; + } + try { + server.stop(); + resource.setStarted(false); + } catch (SimulatorException e) { + Activator + .getDefault() + .getLogManager() + .log(Level.ERROR.ordinal(), + new Date(), + "There is an error while stopping the resource.\n" + + Utility.getSimulatorErrorString(e, null)); + throw e; + } + return true; + } + + public boolean changeResourceName(Resource resource, String newName) + throws SimulatorException { + if (null == resource || null == newName) { + return false; + } + + if (!stopResource(resource)) { + return false; + } + + SimulatorResource server = resource.getSimulatorResource(); + try { + server.setName(newName); + resource.setResourceName(newName); + } catch (SimulatorException e) { + Activator + .getDefault() + .getLogManager() + .log(Level.ERROR.ordinal(), + new Date(), + "There is an error while changing the resource name.\n" + + Utility.getSimulatorErrorString(e, null)); + throw e; + } + + if (!startResource(resource)) { + return false; + } + + return true; + } + + public boolean changeDeviceName(Device dev, String newName) { + if (null == dev || null == newName) { + return false; + } + data.changeDeviceName(dev, dev.getDeviceName(), newName); + return true; + } + + public boolean changeResourceURI(Resource resource, String newURI) + throws SimulatorException { + if (null == resource || null == newURI) { + return false; + } + + if (!stopResource(resource)) { + return false; + } + + String curURI = resource.getResourceURI(); + SimulatorResource server = resource.getSimulatorResource(); + try { + server.setURI(newURI); + data.changeResourceURI(resource, curURI, newURI); + } catch (SimulatorException e) { + Activator + .getDefault() + .getLogManager() + .log(Level.ERROR.ordinal(), + new Date(), + "There is an error while changing the resource URI.\n" + + Utility.getSimulatorErrorString(e, null)); + throw e; + } + + if (!startResource(resource)) { + return false; + } + return true; + } + + public boolean updateResourceProperties(Resource resource, + List properties, boolean uriChanged, + boolean nameChanged) throws SimulatorException { + if (null == resource || null == properties) { + return false; + } + + // Updating the properties + Iterator itr = properties.iterator(); + MetaProperty property; + String propName; + String propValue; + String resName = null; + String resURI = null; + while (itr.hasNext()) { + property = itr.next(); + if (null == property) { + continue; + } + propName = property.getPropName(); + propValue = property.getPropValue(); + if (propName.equals(Constants.RESOURCE_NAME)) { + resName = propValue; + } else if (propName.equals(Constants.RESOURCE_URI)) { + resURI = propValue; + } + } + + if (nameChanged) { + if (!changeResourceName(resource, resName)) { + return false; + } + + // Notify UI Listeners + UiListenerHandler.getInstance().propertiesChangedUINotification( + Resource.class); + } + + if (uriChanged) { + if (!changeResourceURI(resource, resURI)) { + return false; + } + } + + return true; + } + + public boolean updateDeviceProperties(Device dev, + List properties) { + if (null == dev || null == properties) { + return false; + } + + // Updating the properties + Iterator itr = properties.iterator(); + MetaProperty property; + String propName; + String propValue; + String devName = null; + while (itr.hasNext()) { + property = itr.next(); + if (null == property) { + continue; + } + propName = property.getPropName(); + propValue = property.getPropValue(); + if (propName.equals(Constants.DEVICE_NAME)) { + devName = propValue; + } + } + + if (!changeDeviceName(dev, devName)) { + return false; + } + + // Notify UI Listeners + UiListenerHandler.getInstance().propertiesChangedUINotification( + Device.class); + + return true; + } + + public List getAttributes(Resource resource) { List attList = null; if (null != resource) { Map attMap = resource - .getResourceAttributesMap(); + .getResourceAttributes(); if (null != attMap && attMap.size() > 0) { attList = new ArrayList(); Set attNameSet = attMap.keySet(); @@ -1219,137 +1874,313 @@ public class ResourceManager { } } } - return attList; + return attList; + } + + public List getAttributes( + SimulatorResourceModel model) { + List attList = null; + if (null != model) { + Map attMap = model + .getAttributes(); + if (null != attMap && attMap.size() > 0) { + attList = new ArrayList(); + Set attNameSet = attMap.keySet(); + String attName; + SimulatorResourceAttribute attribute; + Iterator attNameItr = attNameSet.iterator(); + while (attNameItr.hasNext()) { + attName = attNameItr.next(); + attribute = attMap.get(attName); + if (null != attribute) { + attList.add(attribute); + } + } + } + } + return attList; + } + + public List getIndexedAttributes(SimulatorResourceModel[] model) { + List indexedAttList = null; + if (null != model && model.length > 0) { + indexedAttList = new ArrayList(); + int i = 0; + for (SimulatorResourceModel m : model) { + indexedAttList.add(new SRMItem(i++, m)); + } + } + return indexedAttList; + } + + public void attributeValueUpdated(SingleResource resource, + String attributeName, AttributeValue value) { + if (null != resource && null != attributeName && null != value) { + SimulatorSingleResource simRes = (SimulatorSingleResource) resource + .getSimulatorResource(); + if (null != simRes) { + try { + simRes.updateAttribute(attributeName, value); + } catch (SimulatorException e) { + Activator + .getDefault() + .getLogManager() + .log(Level.ERROR.ordinal(), new Date(), + Utility.getSimulatorErrorString(e, null)); + } + } + } + } + + /* + * private ModelChangeNotificationType compareAndUpdateLocalAttributes( + * Map resourceAttributeMapOld, Map resourceAttributeMapNew, + * Set valueChangeSet) { ModelChangeNotificationType + * notificationType = ModelChangeNotificationType.NONE; if (null != + * resourceAttributeMapOld && null != resourceAttributeMapNew) { Set + * oldMapKeySet = resourceAttributeMapOld.keySet(); Iterator + * 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 remainingAttSet = resourceAttributeMapNew.keySet(); + * Iterator remainingAttItr = remainingAttSet.iterator(); + * LocalResourceAttribute attribute; while (remainingAttItr.hasNext()) { + * attName = remainingAttItr.next(); if (null != attName) { attribute = + * resourceAttributeMapNew.get(attName); if (null != attribute) { + * resourceAttributeMapOld.put(attName, attribute); } } } notificationType = + * ModelChangeNotificationType.ATTRIBUTE_ADDED; } } return notificationType; + * } + */ + + // TODO: This method should get the status from the native layer. + public boolean isResourceStarted(Resource resource) { + if (null == resource) { + return false; + } + return resource.isStarted(); + } + + public boolean isPropertyValueInvalid(Resource resource, + List properties, String propName) { + if (null == resource || null == properties || null == propName) { + return false; + } + boolean invalid = false; + MetaProperty prop; + Iterator itr = properties.iterator(); + while (itr.hasNext()) { + prop = itr.next(); + if (prop.getPropName().equals(propName)) { + String value = prop.getPropValue(); + if (null == value || value.trim().isEmpty()) { + invalid = true; + } + } + } + return invalid; + } + + public boolean isPropertyValueInvalid(Device dev, + List properties, String propName) { + if (null == dev || null == properties || null == propName) { + return false; + } + boolean invalid = false; + MetaProperty prop; + Iterator itr = properties.iterator(); + while (itr.hasNext()) { + prop = itr.next(); + if (prop.getPropName().equals(propName)) { + String value = prop.getPropValue(); + if (null == value || value.trim().isEmpty()) { + invalid = true; + } + } + } + return invalid; + } + + public boolean isPropValueChanged(Resource resource, + List properties, String propName) { + if (null == resource || null == properties || null == propName) { + return false; + } + boolean changed = false; + MetaProperty prop; + String oldValue; + Iterator itr = properties.iterator(); + while (itr.hasNext()) { + prop = itr.next(); + if (prop.getPropName().equals(propName)) { + oldValue = getPropertyValueFromResource(resource, propName); + if (null != oldValue && !prop.getPropValue().equals(oldValue)) { + changed = true; + } + break; + } + } + return changed; + } + + public boolean isPropValueChanged(Device dev, + List properties, String propName) { + if (null == dev || null == properties || null == propName) { + return false; + } + boolean changed = false; + MetaProperty prop; + String oldValue; + Iterator itr = properties.iterator(); + while (itr.hasNext()) { + prop = itr.next(); + if (prop.getPropName().equals(propName)) { + oldValue = dev.getDeviceName(); + if (null != oldValue && !prop.getPropValue().equals(oldValue)) { + changed = true; + } + break; + } + } + return changed; + } + + private String getPropertyValueFromResource(Resource resource, + String propName) { + if (null == resource || null == propName) { + return null; + } + if (propName.equals(Constants.RESOURCE_URI)) { + return resource.getResourceURI(); + } else if (propName.equals(Constants.RESOURCE_NAME)) { + return resource.getResourceName(); + } else if (propName.equals(Constants.RESOURCE_TYPE)) { + return resource.getResourceTypes().toString(); + } else { + return null; + } } - public void attributeValueUpdated(SimulatorResource resource, - String attributeName, String value) { - if (null != resource && null != attributeName && null != value) { - SimulatorResourceServer server = resource.getResourceServer(); - if (null != server) { - LocalResourceAttribute att = resource - .getAttribute(attributeName); - if (null == att) { - return; - } - Type baseType = att.getAttValBaseType(); - try { - if (baseType == Type.STRING) { - server.updateAttributeString(attributeName, value); - } else if (baseType == Type.INT) { - int val; - try { - val = Integer.parseInt(value); - server.updateAttributeInteger(attributeName, val); - } catch (NumberFormatException nfe) { - return; - } - } else if (baseType == Type.DOUBLE) { - double val; - try { - val = Double.parseDouble(value); - server.updateAttributeDouble(attributeName, val); - } catch (NumberFormatException nfe) { - return; - } - } else if (baseType == Type.BOOL) { - boolean val; - val = Boolean.parseBoolean(value); - server.updateAttributeBoolean(attributeName, val); - } - } catch (SimulatorException e) { - Activator - .getDefault() - .getLogManager() - .log(Level.ERROR.ordinal(), - new Date(), - "[" + e.getClass().getSimpleName() + "]" - + e.code().toString() + "-" - + e.message()); + public boolean isURIChanged(Resource resource, List properties) { + if (null == resource || null == properties) { + return false; + } + boolean changed = false; + MetaProperty prop; + Iterator itr = properties.iterator(); + while (itr.hasNext()) { + prop = itr.next(); + if (prop.getPropName().equals(Constants.RESOURCE_URI)) { + if (!prop.getPropValue().equals(resource.getResourceURI())) { + changed = true; } + break; } } + return changed; } - private ModelChangeNotificationType compareAndUpdateLocalAttributes( - Map resourceAttributeMapOld, - Map resourceAttributeMapNew, - Set valueChangeSet) { - ModelChangeNotificationType notificationType = ModelChangeNotificationType.NONE; - if (null != resourceAttributeMapOld && null != resourceAttributeMapNew) { - Set oldMapKeySet = resourceAttributeMapOld.keySet(); - Iterator attributeMapOldItr = oldMapKeySet.iterator(); - String attName; - LocalResourceAttribute attributeOld; - LocalResourceAttribute attributeNew; - Object attValueOld; - Object attValueNew; - String oldValueStr; - String newValueStr; - while (attributeMapOldItr.hasNext()) { - attName = attributeMapOldItr.next(); - if (resourceAttributeMapNew.containsKey(attName)) { - attributeOld = resourceAttributeMapOld.get(attName); - attributeNew = resourceAttributeMapNew.get(attName); - // Copy the attribute value from new to old if the value - // has been changed - // Comparing only the attribute's value considering the - // fact that only the value can be changed - if (null != attributeOld && null != attributeNew) { - attValueOld = attributeOld.getAttributeValue(); - attValueNew = attributeNew.getAttributeValue(); - - oldValueStr = String.valueOf(attValueOld); - newValueStr = String.valueOf(attValueNew); - - if (null != oldValueStr && null != newValueStr) { - if (!oldValueStr.equals(newValueStr)) { - attributeOld.setAttributeValue(attValueNew); - notificationType = ModelChangeNotificationType.ATTRIBUTE_VALUE_CHANGED; - valueChangeSet.add(attributeOld); - } - } - } - resourceAttributeMapNew.remove(attName); - } else { - // Attribute doesn't exist in the new model. Hence - // removing it from the model. - resourceAttributeMapOld.remove(attName); - notificationType = ModelChangeNotificationType.ATTRIBUTE_REMOVED; - } + public boolean startResource(SingleResource resource) { + if (null == resource || resource.isStarted()) { + return false; + } + boolean result; + SimulatorResource server = resource.getSimulatorResource(); + if (null == server) { + result = false; + } else { + try { + server.start(); + resource.setStarted(true); + result = true; + } catch (SimulatorException e) { + Activator + .getDefault() + .getLogManager() + .log(Level.ERROR.ordinal(), new Date(), + Utility.getSimulatorErrorString(e, null)); + result = false; } - // Check for new attributes in the new model - if (resourceAttributeMapNew.size() > 0) { - Set remainingAttSet = resourceAttributeMapNew.keySet(); - Iterator remainingAttItr = remainingAttSet.iterator(); - LocalResourceAttribute attribute; - while (remainingAttItr.hasNext()) { - attName = remainingAttItr.next(); - if (null != attName) { - attribute = resourceAttributeMapNew.get(attName); - if (null != attribute) { - resourceAttributeMapOld.put(attName, attribute); - } - } - } - notificationType = ModelChangeNotificationType.ATTRIBUTE_ADDED; + } + return result; + } + + public boolean stopResource(SingleResource resource) { + if (null == resource || !resource.isStarted()) { + return false; + } + boolean result; + SimulatorResource server = resource.getSimulatorResource(); + if (null == server) { + result = false; + } else { + try { + server.stop(); + resource.setStarted(false); + result = true; + } catch (SimulatorException e) { + Activator + .getDefault() + .getLogManager() + .log(Level.ERROR.ordinal(), new Date(), + Utility.getSimulatorErrorString(e, null)); + result = false; } } - return notificationType; + return result; + } + + public boolean isAttHasRangeOrAllowedValues(SimulatorResourceAttribute att) { + if (null == att) { + return false; + } + AttributeProperty prop = att.property(); + if (null == prop) { + return false; + } + Type attProp = prop.type(); + if (attProp == Type.UNKNOWN) { + return false; + } + return true; } - public int startAutomation(SimulatorResource resource, - LocalResourceAttribute attribute, AutomationType autoType, + public int startAutomation(SingleResource resource, + LocalResourceAttribute attribute, AutoUpdateType autoType, int autoUpdateInterval) { int autoId = -1; if (null != resource && null != attribute) { - SimulatorResourceServer resourceServerN = resource - .getResourceServer(); - if (null != resourceServerN) { - String attrName = attribute.getAttributeName(); + SimulatorSingleResource server = (SimulatorSingleResource) resource + .getSimulatorResource(); + if (null != server) { + String attrName = attribute.getResourceAttributeRef().name(); try { - autoId = resourceServerN.startAttributeAutomation(attrName, - autoType, autoUpdateInterval, automationListener); + autoId = server.startAttributeUpdation(attrName, autoType, + autoUpdateInterval, automationListener); } catch (SimulatorException e) { Activator .getDefault() @@ -1375,14 +2206,14 @@ public class ResourceManager { return autoId; } - public void stopAutomation(SimulatorResource resource, + public void stopAutomation(SingleResource resource, LocalResourceAttribute att, int autoId) { if (null != resource) { - SimulatorResourceServer resourceServerN = resource - .getResourceServer(); - if (null != resourceServerN) { + SimulatorSingleResource server = (SimulatorSingleResource) resource + .getSimulatorResource(); + if (null != server) { try { - resourceServerN.stopAutomation(autoId); + server.stopUpdation(autoId); } catch (SimulatorException e) { Activator .getDefault() @@ -1401,113 +2232,55 @@ public class ResourceManager { } } - private boolean isAnyAttributeInAutomation(SimulatorResource resource) { + public boolean startResourceAutomationUIRequest(AutoUpdateType autoType, + int autoUpdateInterval, final SingleResource resource) { if (null == resource) { return false; } - Map attMap = resource - .getResourceAttributesMap(); - if (null == attMap) { - return false; - } boolean status = false; - Set keySet = attMap.keySet(); - Iterator 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 attributeMap = resource - .getResourceAttributesMap(); - if (null != attributeMap) { - Set attNameSet = attributeMap.keySet(); - Iterator attNameItr = attNameSet.iterator(); - String attName; - LocalResourceAttribute attribute; - while (attNameItr.hasNext()) { - attName = attNameItr.next(); - if (null != attName) { - attribute = attributeMap.get(attName); - if (null != attribute) { - if (attribute.isAutomationInProgress() - && (attribute.getAutomationId() == automationId)) { - targetAttribute = attribute; - break; - } - } - } - } + changeResourceLevelAutomationStatus(resource, true); + // Invoke the native automation method + SimulatorSingleResource resourceServer = (SimulatorSingleResource) resource + .getSimulatorResource(); + if (null != resourceServer) { + int autoId = -1; + try { + autoId = resourceServer.startResourceUpdation(autoType, + autoUpdateInterval, automationListener); + } catch (SimulatorException e) { + Activator + .getDefault() + .getLogManager() + .log(Level.ERROR.ordinal(), new Date(), + Utility.getSimulatorErrorString(e, null)); + autoId = -1; } - } - return targetAttribute; - } + if (-1 == autoId) { + // Automation request failed and hence status is being + // rolled back + changeResourceLevelAutomationStatus(resource, false); + } else { + // Automation request accepted. + resource.setAutomationId(autoId); - public boolean startResourceAutomationUIRequest(final String resourceURI) { - if (null == resourceURI) { - return false; - } - boolean status = false; - SimulatorResource resource = getSimulatorResourceByURI(resourceURI); - if (null != resource) { - changeResourceLevelAutomationStatus(resource, true); - - // Invoke the native automation method - SimulatorResourceServer resourceServer = resource - .getResourceServer(); - if (null != resourceServer) { - // TODO: Temporarily handling the normal one-time automation for - // resources - int autoId = -1; - try { - autoId = resourceServer.startResourceAutomation( - AutomationType.NORMAL, 500, automationListener); - } catch (SimulatorException e) { - Activator - .getDefault() - .getLogManager() - .log(Level.ERROR.ordinal(), - new Date(), - "[" + e.getClass().getSimpleName() + "]" - + e.code().toString() + "-" - + e.message()); - autoId = -1; - } - if (-1 == autoId) { - // Automation request failed and hence status is being - // rolled back - changeResourceLevelAutomationStatus(resource, false); - } else { - // Automation request accepted. - resource.setAutomationId(autoId); - - // Notify the UI listeners in a different thread. - Thread notifyThread = new Thread() { - public void run() { - resourceAutomationStartedUINotification(resourceURI); - }; + // Notify the UI listeners in a different thread. + Thread notifyThread = new Thread() { + public void run() { + UiListenerHandler.getInstance() + .resourceAutomationStartedUINotification( + resource); }; - notifyThread.setPriority(Thread.MAX_PRIORITY); - notifyThread.start(); + }; + notifyThread.setPriority(Thread.MAX_PRIORITY); + notifyThread.start(); - status = true; - } + status = true; } } return status; } - public boolean stopResourceAutomationUIRequest(final String resourceURI) { - SimulatorResource resource = getSimulatorResourceByURI(resourceURI); + public boolean stopResourceAutomationUIRequest(final SingleResource resource) { if (null == resource) { return false; } @@ -1515,40 +2288,62 @@ public class ResourceManager { if (-1 == autoId) { return false; } - SimulatorResourceServer resourceServer = resource.getResourceServer(); + SimulatorSingleResource resourceServer = (SimulatorSingleResource) resource + .getSimulatorResource(); if (null == resourceServer) { return false; } // Call native method try { - resourceServer.stopAutomation(autoId); + resourceServer.stopUpdation(autoId); } catch (SimulatorException e) { Activator .getDefault() .getLogManager() - .log(Level.ERROR.ordinal(), - new Date(), - "[" + e.getClass().getSimpleName() + "]" - + e.code().toString() + "-" + e.message()); + .log(Level.ERROR.ordinal(), new Date(), + Utility.getSimulatorErrorString(e, null)); return false; } // Notify the UI Listeners. Invoke the automation complete callback. Thread stopThread = new Thread() { public void run() { - automationListener.onAutomationComplete(resourceURI, autoId); + automationListener.onUpdateComplete(resource.getResourceURI(), + autoId); } }; stopThread.start(); return true; } + private boolean isAnyAttributeInAutomation(SingleResource resource) { + if (null == resource) { + return false; + } + Map attMap = resource + .getResourceAttributes(); + if (null == attMap) { + return false; + } + boolean status = false; + Set keySet = attMap.keySet(); + Iterator attItr = keySet.iterator(); + while (attItr.hasNext()) { + LocalResourceAttribute attribute = attMap.get(attItr.next()); + if (attribute.isAutomationInProgress()) { + status = true; + break; + } + } + return status; + } + // Changes the automation state of the resource and its attributes - private void changeResourceLevelAutomationStatus( - SimulatorResource resource, boolean status) { + private void changeResourceLevelAutomationStatus(SingleResource resource, + boolean status) { Map attributeMap = resource - .getResourceAttributesMap(); + .getResourceAttributes(); if (null != attributeMap) { Set attrNameSet = attributeMap.keySet(); Iterator attrNameItr = attrNameSet.iterator(); @@ -1565,82 +2360,207 @@ public class ResourceManager { resource.setResourceAutomationInProgress(status); } - public boolean isResourceAutomationStarted(String resourceURI) { - boolean status = false; - if (null == resourceURI) { - return status; - } - - SimulatorResource resource = getSimulatorResourceByURI(resourceURI); + private LocalResourceAttribute getAttributeWithGivenAutomationId( + SingleResource resource, int automationId) { + LocalResourceAttribute targetAttribute = null; if (null != resource) { - status = resource.isResourceAutomationInProgress(); + Map attributeMap = resource + .getResourceAttributes(); + if (null != attributeMap) { + Set attNameSet = attributeMap.keySet(); + Iterator attNameItr = attNameSet.iterator(); + String attName; + LocalResourceAttribute attribute; + while (attNameItr.hasNext()) { + attName = attNameItr.next(); + if (null != attName) { + attribute = attributeMap.get(attName); + if (null != attribute) { + if (attribute.isAutomationInProgress() + && (attribute.getAutomationId() == automationId)) { + targetAttribute = attribute; + break; + } + } + } + } + } } - return status; + return targetAttribute; } - public boolean isAttributeAutomationStarted(String resourceURI) { + public boolean isResourceAutomationStarted(SingleResource resource) { boolean status = false; - if (null == resourceURI) { - return status; - } - SimulatorResource resource = getSimulatorResourceByURI(resourceURI); if (null != resource) { - status = resource.isAttributeAutomationInProgress(); + status = resource.isResourceAutomationInProgress(); } return status; } - public LocalResourceAttribute getAttributeByResourceURI(String uri, - String attName) { - if (null == uri || null == attName) { - return null; - } - SimulatorResource resource = getSimulatorResourceByURI(uri); + public boolean isAttributeAutomationStarted(SingleResource resource) { if (null == resource) { + return false; + } + return resource.isAttributeAutomationInProgress(); + } + + public LocalResourceAttribute getAttributeByResourceURI( + SingleResource resource, String attName) { + if (null == resource || null == attName) { return null; } Map attMap = resource - .getResourceAttributesMap(); + .getResourceAttributes(); if (null == attMap) { return null; } return attMap.get(attName); } - public void notifyObserverRequest(SimulatorResource res, int observerId) { - if (null == res) { + public void notifyObserverRequest(Resource resource, int observerId) { + if (null == resource) { return; } - SimulatorResourceServer server = res.getResourceServer(); - if (null == server) { + SimulatorResource simulatorResource = resource.getSimulatorResource(); + if (null == simulatorResource) { return; } try { - server.notifyObserver(observerId); + simulatorResource.notifyObserver(observerId); } catch (SimulatorException e) { Activator .getDefault() .getLogManager() - .log(Level.ERROR.ordinal(), - new Date(), - "[" + e.getClass().getSimpleName() + "]" - + e.code().toString() + "-" + e.message()); + .log(Level.ERROR.ordinal(), new Date(), + Utility.getSimulatorErrorString(e, null)); } } - public Image getImage(String resourceURI) { - if (null == resourceURI) { + public void shutdown() { + threadHandle.interrupt(); + } + + public List getAllValuesOfAttribute(SimulatorResourceAttribute att) { + if (null == att) { return null; } - SimulatorResource resource = getSimulatorResourceByURI(resourceURI); - if (null == resource) { + + AttributeValue val = att.value(); + if (null == val) { + return null; + } + + TypeInfo type = val.typeInfo(); + + AttributeProperty prop = att.property(); + if (null == prop) { + return null; + } + + List values = new ArrayList(); + + Type valuesType = prop.type(); + + if (valuesType == Type.UNKNOWN) { + // Adding the default value + values.add(Utility.getAttributeValueAsString(val)); + return values; + } + + if (type.mType != ValueType.RESOURCEMODEL) { + if (type.mType == ValueType.ARRAY) { + if (type.mDepth == 1) { + AttributeProperty childProp = prop.getChildProperty(); + if (null != childProp) { + valuesType = childProp.type(); + if (valuesType == Type.RANGE) { + List list = getRangeForPrimitiveNonArrayAttributes( + childProp, type.mBaseType); + if (null != list) { + values.addAll(list); + } + } else if (valuesType == Type.VALUESET) { + List list = getAllowedValuesForPrimitiveNonArrayAttributes( + childProp.valueSet(), type.mBaseType); + if (null != list) { + values.addAll(list); + } + } + } + } + } else { + if (valuesType == Type.RANGE) { + List list = getRangeForPrimitiveNonArrayAttributes( + prop, type.mType); + if (null != list) { + values.addAll(list); + } + } else if (valuesType == Type.VALUESET) { + List list = getAllowedValuesForPrimitiveNonArrayAttributes( + prop.valueSet(), type.mType); + if (null != list) { + values.addAll(list); + } + } + } + } + + return values; + } + + public List getRangeForPrimitiveNonArrayAttributes( + AttributeProperty prop, ValueType type) { + if (null == prop) { return null; } - return Activator.getDefault().getImageRegistry() - .get(resource.getResourceType()); + + if (type == ValueType.ARRAY || type == ValueType.RESOURCEMODEL) { + return null; + } + + List values = new ArrayList(); + switch (type) { + case INTEGER: + int min = (int) prop.min(); + int max = (int) prop.max(); + for (int iVal = min; iVal <= max; iVal++) { + values.add(String.valueOf(iVal)); + } + break; + case DOUBLE: + double minD = (double) prop.min(); + double maxD = (double) prop.max(); + for (double iVal = minD; iVal <= maxD; iVal = iVal + 1.0) { + values.add(String.valueOf(iVal)); + } + break; + default: + } + return values; } - public void shutdown() { - threadHandle.interrupt(); + public List getAllowedValuesForPrimitiveNonArrayAttributes( + AttributeValue[] attValues, ValueType type) { + if (null == attValues || attValues.length < 1) { + return null; + } + + if (type == ValueType.ARRAY || type == ValueType.RESOURCEMODEL) { + return null; + } + + Object obj; + List values = new ArrayList(); + for (AttributeValue val : attValues) { + if (null == val) { + continue; + } + obj = val.get(); + if (null == obj) { + continue; + } + values.add(String.valueOf(obj)); + } + return values; } } \ No newline at end of file diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/manager/UiListenerHandler.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/manager/UiListenerHandler.java new file mode 100644 index 0000000..8d1535f --- /dev/null +++ b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/manager/UiListenerHandler.java @@ -0,0 +1,325 @@ +/* + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package oic.simulator.serviceprovider.manager; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import oic.simulator.serviceprovider.listener.IAutomationUIListener; +import oic.simulator.serviceprovider.listener.IObserverListChangedUIListener; +import oic.simulator.serviceprovider.listener.IPropertiesChangedUIListener; +import oic.simulator.serviceprovider.listener.IResourceListChangedUIListener; +import oic.simulator.serviceprovider.listener.IResourceModelChangedUIListener; +import oic.simulator.serviceprovider.listener.ISelectionChangedUIListener; +import oic.simulator.serviceprovider.model.Device; +import oic.simulator.serviceprovider.model.Resource; +import oic.simulator.serviceprovider.model.ResourceType; +import oic.simulator.serviceprovider.model.SingleResource; + +public class UiListenerHandler { + + private static UiListenerHandler uiHandler; + + private List resourceListChangedUIListeners; + + private List selectionChangedUIListeners; + + private List resourceModelChangedUIListeners; + + private List automationUIListeners; + + private List observerUIListeners; + + private List propertiesChangedUIListeners; + + private UiListenerHandler() { + resourceListChangedUIListeners = new ArrayList(); + selectionChangedUIListeners = new ArrayList(); + resourceModelChangedUIListeners = new ArrayList(); + automationUIListeners = new ArrayList(); + observerUIListeners = new ArrayList(); + propertiesChangedUIListeners = new ArrayList(); + } + + public static UiListenerHandler getInstance() { + if (null == uiHandler) { + uiHandler = new UiListenerHandler(); + } + return uiHandler; + } + + public void addResourceListChangedUIListener( + IResourceListChangedUIListener resourceListChangedUIListener) { + synchronized (resourceListChangedUIListeners) { + resourceListChangedUIListeners.add(resourceListChangedUIListener); + } + } + + public void addResourceSelectionChangedUIListener( + ISelectionChangedUIListener resourceSelectionChangedUIListener) { + synchronized (selectionChangedUIListeners) { + selectionChangedUIListeners.add(resourceSelectionChangedUIListener); + } + } + + public void addResourceModelChangedUIListener( + IResourceModelChangedUIListener resourceModelChangedUIListener) { + synchronized (resourceModelChangedUIListeners) { + resourceModelChangedUIListeners.add(resourceModelChangedUIListener); + } + } + + public void addAutomationUIListener( + IAutomationUIListener automationUIListener) { + synchronized (automationUIListeners) { + automationUIListeners.add(automationUIListener); + } + } + + public void addObserverListChangedUIListener( + IObserverListChangedUIListener observerListChangedUIListener) { + synchronized (observerUIListeners) { + observerUIListeners.add(observerListChangedUIListener); + } + } + + public void addResourcePropertiesChangedUIListener( + IPropertiesChangedUIListener resourcePropertiesChangedUIListener) { + synchronized (propertiesChangedUIListeners) { + propertiesChangedUIListeners + .add(resourcePropertiesChangedUIListener); + } + } + + public void removeResourceListChangedUIListener( + IResourceListChangedUIListener listener) { + synchronized (resourceListChangedUIListeners) { + if (null != listener && resourceListChangedUIListeners.size() > 0) { + resourceListChangedUIListeners.remove(listener); + } + } + } + + public void removeResourceSelectionChangedUIListener( + ISelectionChangedUIListener listener) { + synchronized (selectionChangedUIListeners) { + if (null != listener && selectionChangedUIListeners.size() > 0) { + selectionChangedUIListeners.remove(listener); + } + } + } + + public void removeResourceModelChangedUIListener( + IResourceModelChangedUIListener listener) { + synchronized (resourceModelChangedUIListeners) { + if (null != listener && resourceModelChangedUIListeners.size() > 0) { + resourceModelChangedUIListeners.remove(listener); + } + } + } + + public void removeAutomationUIListener(IAutomationUIListener listener) { + synchronized (automationUIListeners) { + if (null != listener && automationUIListeners.size() > 0) { + automationUIListeners.remove(listener); + } + } + } + + public void removeObserverListChangedUIListener( + IObserverListChangedUIListener listener) { + synchronized (observerUIListeners) { + if (null != listener && observerUIListeners.size() > 0) { + observerUIListeners.remove(listener); + } + } + } + + public void removeResourcePropertiesChangedUIListener( + IPropertiesChangedUIListener resourcePropertiesChangedUIListener) { + synchronized (propertiesChangedUIListeners) { + propertiesChangedUIListeners + .remove(resourcePropertiesChangedUIListener); + } + } + + public void resourceCreatedUINotification(ResourceType type) { + synchronized (resourceListChangedUIListeners) { + if (resourceListChangedUIListeners.size() > 0) { + IResourceListChangedUIListener listener; + Iterator listenerItr = resourceListChangedUIListeners + .iterator(); + while (listenerItr.hasNext()) { + listener = listenerItr.next(); + if (null != listener) { + listener.onResourceCreation(type); + } + } + } + } + } + + public void resourceDeletedUINotification(ResourceType type) { + synchronized (resourceListChangedUIListeners) { + if (resourceListChangedUIListeners.size() > 0) { + IResourceListChangedUIListener listener; + Iterator listenerItr = resourceListChangedUIListeners + .iterator(); + while (listenerItr.hasNext()) { + listener = listenerItr.next(); + if (null != listener) { + listener.onResourceDeletion(type); + } + } + } + } + } + + public void resourceListUpdateUINotification(ResourceType type) { + synchronized (resourceListChangedUIListeners) { + if (resourceListChangedUIListeners.size() > 0) { + IResourceListChangedUIListener listener; + Iterator listenerItr = resourceListChangedUIListeners + .iterator(); + while (listenerItr.hasNext()) { + listener = listenerItr.next(); + if (null != listener) { + listener.onResourceListUpdate(type); + } + } + } + } + } + + public void resourceSelectionChangedUINotification(Resource resource) { + synchronized (selectionChangedUIListeners) { + if (selectionChangedUIListeners.size() > 0) { + ISelectionChangedUIListener listener; + Iterator listenerItr = selectionChangedUIListeners + .iterator(); + while (listenerItr.hasNext()) { + listener = listenerItr.next(); + if (null != listener) { + listener.onResourceSelectionChange(resource); + } + } + } + } + } + + public void deviceSelectionChangedUINotification(Device dev) { + synchronized (selectionChangedUIListeners) { + if (selectionChangedUIListeners.size() > 0) { + ISelectionChangedUIListener listener; + Iterator listenerItr = selectionChangedUIListeners + .iterator(); + while (listenerItr.hasNext()) { + listener = listenerItr.next(); + if (null != listener) { + listener.onDeviceSelectionChange(dev); + } + } + } + } + } + + public void resourceModelChangedUINotification(Resource resource) { + synchronized (resourceModelChangedUIListeners) { + if (resourceModelChangedUIListeners.size() > 0 && null != resource) { + IResourceModelChangedUIListener listener; + Iterator listenerItr = resourceModelChangedUIListeners + .iterator(); + while (listenerItr.hasNext()) { + listener = listenerItr.next(); + if (null != listener) { + listener.onResourceModelChange(resource); + } + } + } + } + } + + public void resourceAutomationStartedUINotification(SingleResource resource) { + synchronized (automationUIListeners) { + if (automationUIListeners.size() > 0 && null != resource) { + IAutomationUIListener listener; + Iterator listenerItr = automationUIListeners + .iterator(); + while (listenerItr.hasNext()) { + listener = listenerItr.next(); + if (null != listener) { + listener.onResourceAutomationStart(resource); + } + } + } + } + } + + public void automationCompleteUINotification(SingleResource resource, + String attName) { + synchronized (automationUIListeners) { + if (automationUIListeners.size() > 0 && null != resource) { + IAutomationUIListener listener; + Iterator listenerItr = automationUIListeners + .iterator(); + while (listenerItr.hasNext()) { + listener = listenerItr.next(); + if (null != listener) { + listener.onAutomationComplete(resource, attName); + } + } + } + } + } + + public void observerListChangedUINotification(Resource resource) { + synchronized (observerUIListeners) { + if (observerUIListeners.size() > 0 && null != resource) { + IObserverListChangedUIListener listener; + Iterator listenerItr = observerUIListeners + .iterator(); + while (listenerItr.hasNext()) { + listener = listenerItr.next(); + if (null != listener) { + listener.onObserverListChanged(resource); + } + } + } + } + } + + public void propertiesChangedUINotification(Class targetClass) { + synchronized (propertiesChangedUIListeners) { + if (propertiesChangedUIListeners.size() > 0) { + IPropertiesChangedUIListener listener; + Iterator listenerItr = propertiesChangedUIListeners + .iterator(); + while (listenerItr.hasNext()) { + listener = listenerItr.next(); + if (null != listener) { + if (targetClass == Resource.class) { + listener.onResourcePropertyChange(); + } else { + listener.onDevicePropertyChange(); + } + } + } + } + } + } +} diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/AttributeHelper.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/AttributeHelper.java new file mode 100644 index 0000000..50d6a49 --- /dev/null +++ b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/AttributeHelper.java @@ -0,0 +1,364 @@ +/* + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package oic.simulator.serviceprovider.model; + +import java.util.HashSet; +import java.util.Set; + +import oic.simulator.serviceprovider.utils.Constants; +import oic.simulator.serviceprovider.utils.Utility; + +import org.oic.simulator.AttributeProperty; +import org.oic.simulator.AttributeProperty.Type; +import org.oic.simulator.AttributeValue; +import org.oic.simulator.AttributeValue.ValueType; +import org.oic.simulator.SimulatorResourceAttribute; + +public class AttributeHelper { + private String attributeName; + private String attributeType; + private String min; + private String max; + private Set allowedValues; + private String attributeDflValue; + + private Type validValuesType; + + public AttributeHelper() { + allowedValues = new HashSet(); + setValidValuesType(Type.UNKNOWN); + min = max = ""; + } + + public AttributeHelper clone() { + AttributeHelper att = new AttributeHelper(); + att.setAttributeName(attributeName); + att.setAttributeType(attributeType); + att.setMin(min); + att.setMax(max); + if (null != allowedValues) { + Set values = new HashSet(); + values.addAll(allowedValues); + att.setAllowedValues(values); + } + att.setAttributeDflValue(attributeDflValue); + att.setValidValuesType(validValuesType); + return att; + } + + public String toString() { + return attributeName + "," + attributeType + "," + attributeDflValue + + "," + validValuesType + ",(" + min + max + "),(" + + allowedValues + ")"; + } + + public String getAttributeName() { + return attributeName; + } + + public void setAttributeName(String attributeName) { + this.attributeName = attributeName; + } + + public String getAttributeType() { + return attributeType; + } + + public void setAttributeType(String attributeType) { + this.attributeType = attributeType; + } + + public String getMin() { + return min; + } + + public void setMin(String min) { + this.min = min; + } + + public String getMax() { + return max; + } + + public void setMax(String max) { + this.max = max; + } + + public Set getAllowedValues() { + return allowedValues; + } + + public void setAllowedValues(Set allowedValues) { + this.allowedValues = allowedValues; + } + + public void addValueToAllowedValues(String value) { + if (null != value && value.trim().length() > 0) { + if (null == allowedValues) { + allowedValues = new HashSet(); + } + allowedValues.add(value); + } + } + + public void removeValueFromAllowedValues(String value) { + if (null != allowedValues && null != value && value.trim().length() > 0) { + allowedValues.remove(value); + } + } + + public void removeAllCustomValues() { + allowedValues.clear(); + } + + public String getAttributeDflValue() { + return attributeDflValue; + } + + public void setAttributeDflValue(String attributeDflValue) { + this.attributeDflValue = attributeDflValue; + } + + public Type getValidValuesType() { + return validValuesType; + } + + public void setValidValuesType(Type validValuesType) { + this.validValuesType = validValuesType; + } + + public boolean isValueValid(String value, String type) { + if (null == value || value.trim().length() < 1 || null == type + || type.trim().length() < 1) + return false; + if (type.equalsIgnoreCase(Constants.INT)) { + return isIntValue(value); + } else if (type.equalsIgnoreCase(Constants.DOUBLE)) { + return isDoubleValue(value); + } else if (type.equalsIgnoreCase(Constants.BOOL)) { + return isBoolValue(value); + } + return true; + } + + public boolean isBoolValue(String value) { + boolean isBool = false; + if (null != value + && (value.equalsIgnoreCase("true") || value + .equalsIgnoreCase("false"))) { + isBool = true; + } + return isBool; + } + + public boolean isIntValue(String value) { + boolean isInt = true; + try { + Integer.parseInt(value); + } catch (Exception e) { + isInt = false; + } + return isInt; + } + + public boolean isDoubleValue(String value) { + boolean isDouble = true; + try { + Double.parseDouble(value); + } catch (Exception e) { + isDouble = false; + } + return isDouble; + } + + public boolean isRangeValid(String minStr, String maxStr, String type) { + if (null == type || type.trim().isEmpty()) { + return false; + } + boolean result = true; + if (type.equals(Constants.INT)) { + int min, max; + try { + min = Integer.parseInt(minStr); + max = Integer.parseInt(maxStr); + if (max <= min) { + result = false; + } + } catch (Exception e) { + result = false; + } + } else if (type.equals(Constants.DOUBLE)) { + double min, max; + try { + min = Double.parseDouble(minStr); + max = Double.parseDouble(maxStr); + if (max <= min) { + result = false; + } + } catch (Exception e) { + result = false; + } + } + return result; + } + + public boolean isDefaultValueValid(String value) { + if (null == attributeType || attributeType.trim().isEmpty()) { + return false; + } + boolean result = true; + if (attributeType.equals(Constants.STRING)) { + if (validValuesType == Type.VALUESET && null != allowedValues) { + result = allowedValues.contains(value); + } else { + result = true; + } + } else if (attributeType.equals(Constants.BOOL)) { + String val = value.toLowerCase(); + if (!(val.equals("true") || val.equals("false"))) { + result = false; + } + } else { + if (validValuesType == Type.RANGE) { + if (attributeType.equals(Constants.INT)) { + int min, max, dflValue; + try { + min = Integer.parseInt(this.min); + max = Integer.parseInt(this.max); + dflValue = Integer.parseInt(value); + if (dflValue < min || dflValue > max) { + result = false; + } + } catch (Exception e) { + result = false; + } + } else if (attributeType.equals(Constants.DOUBLE)) { + double min, max, dflValue; + try { + min = Double.parseDouble(this.min); + max = Double.parseDouble(this.max); + dflValue = Double.parseDouble(value); + if (dflValue < min || dflValue > max) { + result = false; + } + } catch (Exception e) { + result = false; + } + } + } else if (validValuesType == Type.VALUESET + && null != allowedValues && !allowedValues.isEmpty()) { + result = allowedValues.contains(value); + } + } + return result; + } + + public void setAllowedValuesByArray(String[] cusItems) { + if (null == cusItems) { + return; + } + for (String item : cusItems) { + addValueToAllowedValues(item); + } + } + + public boolean isAllowedValueExist(String[] items, String value) { + if (null == items || items.length < 1 || null == value + || value.isEmpty()) + return false; + for (String item : items) { + if (value.equalsIgnoreCase(item)) { + return true; + } + } + return false; + } + + public LocalResourceAttribute convertToLocalResourceAttribute() { + LocalResourceAttribute attribute = new LocalResourceAttribute(); + + // Initially disabling the automation + attribute.setAutomationInProgress(false); + + // Assigning the default automation interval + attribute + .setAutomationUpdateInterval(Constants.DEFAULT_AUTOMATION_INTERVAL); + + // Setting the default automation type + attribute.setAutomationType(Constants.DEFAULT_AUTOMATION_TYPE); + + AttributeValue attValue = null; + AttributeProperty attProperty = null; + SimulatorResourceAttribute simResAtt; + + ValueType valueType = Utility.getAttributeTypeEnum(attributeType); + switch (valueType) { + case INTEGER: + attValue = new AttributeValue( + Integer.parseInt(attributeDflValue)); + if (validValuesType == Type.VALUESET) { + attProperty = new AttributeProperty( + Utility.convertSetToArrayInt(Utility + .convertSetStringToSetObject(allowedValues, + valueType))); + } else if (validValuesType == Type.RANGE) { + attProperty = new AttributeProperty( + Double.parseDouble(min), Double.parseDouble(max)); + } else { + attProperty = null; + } + case DOUBLE: + attValue = new AttributeValue( + Double.parseDouble(attributeDflValue)); + if (validValuesType == Type.VALUESET) { + attProperty = new AttributeProperty( + Utility.convertSetToArrayDouble(Utility + .convertSetStringToSetObject(allowedValues, + valueType))); + } else if (validValuesType == Type.RANGE) { + attProperty = new AttributeProperty( + Double.parseDouble(min), Double.parseDouble(max)); + } else { + attProperty = null; + } + break; + case BOOLEAN: + attValue = new AttributeValue( + Boolean.parseBoolean(attributeDflValue)); + boolean[] arr = { true, false }; + attProperty = new AttributeProperty(arr); + break; + case STRING: + attValue = new AttributeValue(attributeDflValue); + if (validValuesType == Type.VALUESET) { + attProperty = new AttributeProperty( + Utility.convertSetToArrayString(Utility + .convertSetStringToSetObject(allowedValues, + valueType))); + } else { + attProperty = null; + } + break; + default: + break; + } + simResAtt = new SimulatorResourceAttribute(attributeName, attValue, + attProperty); + attribute.setResourceAttributeRef(simResAtt); + return attribute; + } +} \ No newline at end of file diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/AutomationSettingHelper.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/AutomationSettingHelper.java similarity index 63% rename from service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/AutomationSettingHelper.java rename to service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/AutomationSettingHelper.java index 0136296..9a456b9 100644 --- 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/model/AutomationSettingHelper.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package oic.simulator.serviceprovider.resource; +package oic.simulator.serviceprovider.model; import java.util.ArrayList; import java.util.Iterator; @@ -22,7 +22,7 @@ import java.util.List; import oic.simulator.serviceprovider.utils.Constants; -import org.oic.simulator.serviceprovider.AutomationType; +import org.oic.simulator.server.SimulatorResource.AutoUpdateType; /** * This is a helper class for providing the automation settings information to @@ -67,36 +67,44 @@ public class AutomationSettingHelper { LocalResourceAttribute attribute) { List settingList = null; boolean invalidSetting; - if (null != attribute) { - settingList = new ArrayList(); - 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); + + settingList = new ArrayList(); + for (int count = 0; count < Constants.AUTOMATION_SETTINGS_COUNT; count++) { + invalidSetting = false; + AutomationSettingHelper setting = new AutomationSettingHelper(); + if (Constants.AUTOMATION_SETTINGS[count] + .equals(Constants.AUTOMATION_TYPE)) { + setting.setSettingID(Constants.AUTOMATION_TYPE); + if (null != attribute) { setting.setSettingValue(attribute.getAutomationType() .toString()); - List valueList = new ArrayList(); - 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); + } else { + setting.setSettingValue(AutoUpdateType.ONE_TIME.toString()); + } + List valueList = new ArrayList(); + valueList.add(AutoUpdateType.ONE_TIME.toString()); + valueList.add(AutoUpdateType.REPEAT.toString()); + setting.setAllowedValues(valueList); + } else if (Constants.AUTOMATION_SETTINGS[count] + .equals(Constants.UPDATE_INTERVAL_IN_MS)) { + setting.setSettingID(Constants.UPDATE_INTERVAL_IN_MS); + if (null != attribute) { setting.setSettingValue(String.valueOf(attribute .getAutomationUpdateInterval())); - List valueList = new ArrayList(); - for (int index = 1; index <= 10; index++) { - valueList.add(String.valueOf(index * 500)); - } - setting.setAllowedValues(valueList); } else { - invalidSetting = true; + setting.setSettingValue(String + .valueOf(Constants.DEFAULT_AUTOMATION_INTERVAL)); } - if (!invalidSetting) { - settingList.add(setting); + List valueList = new ArrayList(); + 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; diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/CollectionResource.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/CollectionResource.java new file mode 100644 index 0000000..ff41152 --- /dev/null +++ b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/CollectionResource.java @@ -0,0 +1,221 @@ +/* + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package oic.simulator.serviceprovider.model; + +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; + +import org.oic.simulator.SimulatorException; +import org.oic.simulator.server.SimulatorCollectionResource; +import org.oic.simulator.server.SimulatorResource; + +public class CollectionResource extends Resource { + private Set childResources; + private Set supportedResourceTypes; + + private Set membership; + + public CollectionResource() { + childResources = new HashSet(); + supportedResourceTypes = new HashSet(); + membership = new HashSet(); + setDeviceMembership(new HashSet()); + } + + public Set getSupportedResourceTypes() { + return supportedResourceTypes; + } + + public void setSupportedResourceTypes(Set supportedResourceTypes) { + this.supportedResourceTypes = supportedResourceTypes; + } + + public void addSupportedResourceType(String rType) { + if (null == supportedResourceTypes) { + supportedResourceTypes = new HashSet(); + } + supportedResourceTypes.add(rType); + } + + public void removeSupportedResourceType(String rType) { + if (null != supportedResourceTypes) { + supportedResourceTypes.remove(rType); + } + } + + public Set getChildResources() { + return childResources; + } + + public Set getSingleTypeChildResources() { + if (null == childResources || childResources.isEmpty()) { + return null; + } + Set resultSet = new HashSet(); + Iterator itr = childResources.iterator(); + Resource res; + while (itr.hasNext()) { + res = itr.next(); + if (null != res) { + if (res instanceof SingleResource) { + resultSet.add((SingleResource) res); + } + } + } + return resultSet; + } + + public Set getCollectionTypeChildResources() { + if (null == childResources || childResources.isEmpty()) { + return null; + } + Set resultSet = new HashSet(); + Iterator itr = childResources.iterator(); + Resource res; + while (itr.hasNext()) { + res = itr.next(); + if (null != res) { + if (res instanceof CollectionResource) { + resultSet.add((CollectionResource) res); + } + } + } + return resultSet; + } + + public void setChildResources(Set childResources) { + this.childResources = childResources; + } + + public void addChildResource(Resource resource) throws SimulatorException { + if (null == resource) { + return; + } + if (null == childResources) { + childResources = new HashSet(); + } + + // Native call to add child resource + SimulatorResource simRes; + simRes = resource.getSimulatorResource(); + ((SimulatorCollectionResource) simulatorResource) + .addChildResource(simRes); + + childResources.add(resource); + } + + public void addChildResource(Set resources) + throws SimulatorException { + if (null == resources || resources.isEmpty()) { + return; + } + if (null == childResources) { + childResources = new HashSet(); + } + + // Native call to add child resource + SimulatorResource simRes; + Resource res; + Iterator itr = resources.iterator(); + while (itr.hasNext()) { + res = itr.next(); + simRes = res.getSimulatorResource(); + ((SimulatorCollectionResource) simulatorResource) + .addChildResource(simRes); + + childResources.add(res); + } + } + + public void removeChildResource(Resource resource) + throws SimulatorException { + if (null == resource || null == childResources) { + return; + } + + // Native call to add child resource + SimulatorResource simRes; + simRes = resource.getSimulatorResource(); + ((SimulatorCollectionResource) simulatorResource) + .removeChildResource(simRes); + + childResources.remove(resource); + } + + public void removeChildResource(Set resources) + throws SimulatorException { + if (null == resources || null == childResources) { + return; + } + + // Native call to add child resource + SimulatorResource simRes; + Resource res; + Iterator itr = resources.iterator(); + while (itr.hasNext()) { + res = itr.next(); + simRes = res.getSimulatorResource(); + ((SimulatorCollectionResource) simulatorResource) + .removeChildResource(simRes); + + childResources.remove(res); + } + } + + public Set getMembership() { + return membership; + } + + public void setMembership(Set membership) { + this.membership = membership; + } + + public void addMembership(CollectionResource resource) { + if (null == resource) { + return; + } + if (null == membership) { + membership = new HashSet(); + } + membership.add(resource); + } + + public void addMembership(Set resources) { + if (null == resources) { + return; + } + if (null == membership) { + membership = new HashSet(); + } + membership.addAll(resources); + } + + public void removeMembership(CollectionResource resource) { + if (null == resource || null == membership) { + return; + } + membership.remove(resource); + } + + public void removeMembership(Set collections) { + if (null == collections || null == membership) { + return; + } + membership.removeAll(collections); + } +} \ No newline at end of file diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/DeleteCategory.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/DeleteCategory.java similarity index 93% rename from service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/DeleteCategory.java rename to service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/DeleteCategory.java index 336d82d..831c65f 100644 --- 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/model/DeleteCategory.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package oic.simulator.serviceprovider.resource; +package oic.simulator.serviceprovider.model; /** * Enumerates different types of supported delete operations. diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/Device.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/Device.java new file mode 100644 index 0000000..f1a9879 --- /dev/null +++ b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/Device.java @@ -0,0 +1,117 @@ +/* + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package oic.simulator.serviceprovider.model; + +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; + +public class Device { + private String deviceName; + + private Set childResources; + + public Device() { + childResources = new HashSet(); + } + + public String getDeviceName() { + return deviceName; + } + + public void setDeviceName(String deviceName) { + this.deviceName = deviceName; + } + + public Set getChildResources() { + return childResources; + } + + public void setChildResources(Set childResources) { + this.childResources = childResources; + } + + public void addChildResource(Resource resource) { + if (null == resource) { + return; + } + if (null == childResources) { + childResources = new HashSet(); + } + childResources.add(resource); + } + + public void addChildResource(Set resources) { + if (null == resources) { + return; + } + if (null == childResources) { + childResources = new HashSet(); + } + childResources.addAll(resources); + } + + public void removeChildResource(Resource resource) { + if (null == resource || null == childResources) { + return; + } + childResources.remove(resource); + } + + public void removeChildResource(Set resources) { + if (null == resources || null == childResources) { + return; + } + childResources.removeAll(resources); + } + + public Set getSingleTypeChildResources() { + if (null == childResources || childResources.isEmpty()) { + return null; + } + Set resultSet = new HashSet(); + Iterator itr = childResources.iterator(); + Resource res; + while (itr.hasNext()) { + res = itr.next(); + if (null != res) { + if (res instanceof SingleResource) { + resultSet.add((SingleResource) res); + } + } + } + return resultSet; + } + + public Set getCollectionTypeChildResources() { + if (null == childResources || childResources.isEmpty()) { + return null; + } + Set resultSet = new HashSet(); + Iterator itr = childResources.iterator(); + Resource res; + while (itr.hasNext()) { + res = itr.next(); + if (null != res) { + if (res instanceof CollectionResource) { + resultSet.add((CollectionResource) res); + } + } + } + return resultSet; + } +} \ No newline at end of file diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/LocalResourceAttribute.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/LocalResourceAttribute.java new file mode 100644 index 0000000..e958fa1 --- /dev/null +++ b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/LocalResourceAttribute.java @@ -0,0 +1,78 @@ +/* + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package oic.simulator.serviceprovider.model; + +import org.oic.simulator.SimulatorResourceAttribute; +import org.oic.simulator.server.SimulatorResource.AutoUpdateType; + +/** + * This class represents an attribute in the simulated resource. + */ +public class LocalResourceAttribute { + + // Java SDK object reference + private SimulatorResourceAttribute resourceAttributeRef; + + private int automationId; + + private boolean automationInProgress; + + private int automationUpdateInterval; + + private AutoUpdateType automationType; + + public SimulatorResourceAttribute getResourceAttributeRef() { + return resourceAttributeRef; + } + + public void setResourceAttributeRef( + SimulatorResourceAttribute resourceAttribute) { + this.resourceAttributeRef = resourceAttribute; + } + + public int getAutomationId() { + return automationId; + } + + public void setAutomationId(int automationId) { + this.automationId = automationId; + } + + public boolean isAutomationInProgress() { + return automationInProgress; + } + + public void setAutomationInProgress(boolean automationInProgress) { + this.automationInProgress = automationInProgress; + } + + public int getAutomationUpdateInterval() { + return automationUpdateInterval; + } + + public void setAutomationUpdateInterval(int automationUpdateInterval) { + this.automationUpdateInterval = automationUpdateInterval; + } + + public AutoUpdateType getAutomationType() { + return automationType; + } + + public void setAutomationType(AutoUpdateType automationType) { + this.automationType = automationType; + } +} \ No newline at end of file diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/MetaProperty.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/MetaProperty.java similarity index 96% rename from service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/MetaProperty.java rename to service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/MetaProperty.java index 61881b1..6dd4c7b 100644 --- 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/model/MetaProperty.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package oic.simulator.serviceprovider.resource; +package oic.simulator.serviceprovider.model; /** * This is a helper class for showing the meta properties of resources such as 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/model/ModelChangeNotificationType.java similarity index 94% rename from service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/ModelChangeNotificationType.java rename to service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/ModelChangeNotificationType.java index 0a1b17a..a5e624c 100644 --- 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/model/ModelChangeNotificationType.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package oic.simulator.serviceprovider.resource; +package oic.simulator.serviceprovider.model; /** * Enumerates the different types of operations for model change notifications. 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/model/ObserverDetail.java similarity index 77% rename from service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/ObserverDetail.java rename to service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/ObserverDetail.java index b581a6e..63e1568 100644 --- 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/model/ObserverDetail.java @@ -14,23 +14,23 @@ * limitations under the License. */ -package oic.simulator.serviceprovider.resource; +package oic.simulator.serviceprovider.model; -import org.oic.simulator.serviceprovider.ObserverInfo; +import org.oic.simulator.server.Observer; /** * This class holds observer details of resources. */ public class ObserverDetail { - private ObserverInfo observerInfo; - private boolean isClicked; + private Observer observerInfo; + private boolean isClicked; - public ObserverInfo getObserverInfo() { + public Observer getObserverInfo() { return observerInfo; } - public void setObserverInfo(ObserverInfo observerInfo) { + public void setObserverInfo(Observer observerInfo) { this.observerInfo = observerInfo; } diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/Resource.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/Resource.java new file mode 100644 index 0000000..5772cc2 --- /dev/null +++ b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/Resource.java @@ -0,0 +1,260 @@ +/* + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package oic.simulator.serviceprovider.model; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import org.oic.simulator.SimulatorResourceModel; +import org.oic.simulator.server.Observer; +import org.oic.simulator.server.SimulatorResource; + +public abstract class Resource { + + // Java SDK object reference + SimulatorResource simulatorResource; + private SimulatorResourceModel resourceModel; + + private String resourceURI; + private String resourceName; + private Set resourceTypes; + private Set resourceInterfaces; + private boolean started; + private boolean observable; + + private Set deviceMembership; + + private Map attributes; + + private Map observers; + + public Resource() { + resourceTypes = new HashSet(); + resourceInterfaces = new HashSet(); + observers = new HashMap(); + } + + public SimulatorResource getSimulatorResource() { + return simulatorResource; + } + + public void setSimulatorResource(SimulatorResource simulatorResource) { + this.simulatorResource = simulatorResource; + } + + public SimulatorResourceModel getResourceModel() { + return resourceModel; + } + + public void setResourceModel(SimulatorResourceModel resourceModel) { + this.resourceModel = resourceModel; + } + + public String getResourceURI() { + return resourceURI; + } + + public void setResourceURI(String resourceURI) { + this.resourceURI = resourceURI; + } + + public String getResourceName() { + return resourceName; + } + + public void setResourceName(String resourceName) { + this.resourceName = resourceName; + } + + public Set getResourceTypes() { + return resourceTypes; + } + + public void setResourceTypes(Set resourceTypes) { + this.resourceTypes = resourceTypes; + } + + public Set getResourceInterfaces() { + return resourceInterfaces; + } + + public void setResourceInterfaces(Set resourceInterfaces) { + this.resourceInterfaces = resourceInterfaces; + } + + public boolean isStarted() { + return started; + } + + public void setStarted(boolean started) { + this.started = started; + } + + public boolean isObservable() { + return observable; + } + + public void setObservable(boolean observable) { + this.observable = observable; + } + + public void addResourceType(String resType) { + if (null == resType) { + return; + } + if (null == resourceTypes) { + resourceTypes = new HashSet(); + } + resourceTypes.add(resType); + } + + public void removeResourceType(String resType) { + if (null == resType || null == resourceTypes) { + return; + } + resourceTypes.remove(resType); + } + + public boolean isResourceTypeExist(String resType) { + if (null == resType || null == resourceTypes) { + return false; + } + return resourceTypes.contains(resType); + } + + public void addInterfaceType(String ifType) { + if (null == ifType) { + return; + } + if (null == resourceInterfaces) { + resourceInterfaces = new HashSet(); + } + resourceInterfaces.add(ifType); + } + + public void removeInterfaceType(String ifType) { + if (null == ifType || null == resourceInterfaces) { + return; + } + resourceInterfaces.remove(ifType); + } + + public boolean isInterfaceTypeExist(String ifType) { + if (null == ifType || null == resourceInterfaces) { + return false; + } + return resourceInterfaces.contains(ifType); + } + + public Map getObserver() { + return observers; + } + + public void addObserverInfo(Observer observer) { + if (null == observer) { + return; + } + int id = observer.getId(); + if (!observers.containsKey(id)) { + ObserverDetail obsDetail = new ObserverDetail(); + obsDetail.setObserverInfo(observer); + observers.put(id, obsDetail); + } + } + + public void removeObserverInfo(Observer observer) { + if (null == observer) { + return; + } + observers.remove(observer.getId()); + } + + public Set getDeviceMembership() { + return deviceMembership; + } + + public void setDeviceMembership(Set deviceMembership) { + this.deviceMembership = deviceMembership; + } + + public void addDeviceMembership(Device dev) { + if (null == dev) { + return; + } + if (null == deviceMembership) { + deviceMembership = new HashSet(); + } + deviceMembership.add(dev); + } + + public void addDeviceMembership(Set devices) { + if (null == devices) { + return; + } + if (null == deviceMembership) { + deviceMembership = new HashSet(); + } + deviceMembership.addAll(devices); + } + + public void removeDeviceMembership(Device dev) { + if (null == dev || null == deviceMembership) { + return; + } + deviceMembership.remove(dev); + } + + public void removeDeviceMembership(Set devices) { + if (null == devices || null == deviceMembership) { + return; + } + deviceMembership.removeAll(devices); + } + + public boolean isMemberOfAnyDevice() { + if (null == deviceMembership || deviceMembership.isEmpty()) { + return false; + } + return true; + } + + public Map getResourceAttributes() { + return attributes; + } + + public void setResourceAttributes( + Map attributes) { + this.attributes = attributes; + } + + // Added for debugging purpose + public void printResourceInfo() { + System.out.println("Resource URI: " + getResourceURI()); + System.out.println("Resource Name: " + getResourceName()); + System.out.println("Resource types: " + getResourceTypes()); + System.out.println("Resource Interfaces: " + getResourceInterfaces()); + System.out.println("Resource Attributes:-"); + /* + * if (null != resourceAttributesMap) { Iterator attItr = + * resourceAttributesMap.keySet().iterator(); while (attItr.hasNext()) { + * resourceAttributesMap.get(attItr.next()) .printAttributeDetails();; } + * } + */ + } +} diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/ResourceCategory.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/ResourceCategory.java new file mode 100644 index 0000000..b932abc --- /dev/null +++ b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/ResourceCategory.java @@ -0,0 +1,21 @@ +/* + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package oic.simulator.serviceprovider.model; + +public enum ResourceCategory { + SIMPLE, COLLECTION +} diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/ResourceType.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/ResourceType.java new file mode 100644 index 0000000..f9ec137 --- /dev/null +++ b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/ResourceType.java @@ -0,0 +1,21 @@ +/* + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package oic.simulator.serviceprovider.model; + +public enum ResourceType { + SINGLE, COLLECTION, DEVICE +} diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/ResourceModelObject.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/SRMItem.java similarity index 53% rename from service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/ResourceModelObject.java rename to service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/SRMItem.java index b636d6a..f003e3a 100644 --- a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/ResourceModelObject.java +++ b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/SRMItem.java @@ -14,36 +14,32 @@ * limitations under the License. */ -package org.oic.simulator.test; +package oic.simulator.serviceprovider.model; import org.oic.simulator.SimulatorResourceModel; -/** - * This class implements methods for setting/getting - * resource model. - */ -public class ResourceModelObject -{ - private String resourceURI; - private SimulatorResourceModel resourceModel; - - public void setResourceURI(String resourceURI) - { - this.resourceURI = resourceURI; +public class SRMItem { + private int index; + private SimulatorResourceModel model; + + public SRMItem(int index, SimulatorResourceModel model) { + this.index = index; + this.model = model; + } + + public int getIndex() { + return index; } - public String getResourceURI() - { - return resourceURI; + public void setIndex(int index) { + this.index = index; } - public void setResourceModel(SimulatorResourceModel resourceModel) - { - this.resourceModel = resourceModel; + public SimulatorResourceModel getModel() { + return model; } - public SimulatorResourceModel getResourceModel() - { - return resourceModel; + public void setModel(SimulatorResourceModel model) { + this.model = model; } } diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/SerializedServiceProvider.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/SerializedServiceProvider.java new file mode 100644 index 0000000..6db7486 --- /dev/null +++ b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/SerializedServiceProvider.java @@ -0,0 +1,167 @@ +/* + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package oic.simulator.serviceprovider.model; + +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; +import java.util.List; +import java.util.Map; + +public class SerializedServiceProvider implements Serializable { + + public class SerializedAttribute implements Serializable { + + public String getName() { + return m_name; + } + + public void setName(String name) { + this.m_name = name; + } + + public Object getValue() { + return m_value; + } + + public void setValue(Object value) { + this.m_value = value; + } + + public String getType() { + return m_type; + } + + public void setType(String type) { + this.m_type = type; + } + + public int getMin() { + return m_min; + } + + public void setMin(int min) { + this.m_min = min; + } + + public int getMax() { + return m_max; + } + + public void setMax(int max) { + this.m_max = max; + } + + public Object getAllowedValues() { + return m_AllowedValues; + } + + public void setAllowedValues(Object allowedValues) { + this.m_AllowedValues = allowedValues; + } + + private String m_name = null; + private Object m_value = null; + private String m_type = null; + private int m_min = 0; + private int m_max = 0; + private Object m_AllowedValues = null; + } + + public String getResourceName() { + return m_resourceName; + } + + public void setResourceName(String resourceName) { + this.m_resourceName = resourceName; + } + + public String getUri() { + return m_uri; + } + + public void setUri(String uri) { + this.m_uri = uri; + } + + public String getResourceType() { + return m_resourceType; + } + + public void setResourceType(String resourceType) { + this.m_resourceType = resourceType; + } + + public List getInterfaceType() { + return m_interfaceType; + } + + public void setInterfaceType(List interfaceType) { + this.m_interfaceType = interfaceType; + } + + public Map getResourceAttributesMap() { + return m_resourceAttributesMap; + } + + public void setResourceAttributesMap( + Map resourceAttributesMap) { + this.m_resourceAttributesMap = resourceAttributesMap; + } + + public void serialize(String filePath) throws SimulatorPluginException { + try { + FileOutputStream fileOut = new FileOutputStream(filePath); + ObjectOutputStream out = new ObjectOutputStream(fileOut); + out.writeObject(this); + out.close(); + fileOut.close(); + } catch (IOException i) { + throw new SimulatorPluginException( + "Failed to Serialize data : IOException"); + } + } + + public static SerializedServiceProvider deSerialize(String filePath) + throws SimulatorPluginException { + SerializedServiceProvider r = null; + try { + FileInputStream fileIn = new FileInputStream(filePath); + ObjectInputStream in = new ObjectInputStream(fileIn); + r = (SerializedServiceProvider) in.readObject(); + in.close(); + fileIn.close(); + } catch (IOException i) { + throw new SimulatorPluginException( + "Failed to DeSerialize data : IOException"); + } catch (ClassNotFoundException c) { + throw new SimulatorPluginException( + "Failed to DeSerialize data : ClassNotFound"); + } + return r; + } + + private String m_resourceName; + private String m_uri; + private String m_resourceType; + private List m_interfaceType; + private Map m_resourceAttributesMap; + +} \ No newline at end of file diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/SimulatorPluginException.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/SimulatorPluginException.java new file mode 100644 index 0000000..92af95f --- /dev/null +++ b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/SimulatorPluginException.java @@ -0,0 +1,33 @@ +/* + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package oic.simulator.serviceprovider.model; + +/** + * This class represents the plug-in level exceptions. + */ +@SuppressWarnings("serial") +public class SimulatorPluginException extends Exception { + String msg; + + public SimulatorPluginException(String msg) { + this.msg = msg; + } + + public String toString() { + return msg; + } +} diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/SingleResource.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/SingleResource.java new file mode 100644 index 0000000..899bc60 --- /dev/null +++ b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/model/SingleResource.java @@ -0,0 +1,173 @@ +/* + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package oic.simulator.serviceprovider.model; + +import java.util.HashSet; +import java.util.Set; + +import org.oic.simulator.server.SimulatorResource.AutoUpdateType; + +/** + * This class represents a simulated resource. It maintains all the necessary + * information about the resource. + */ +public class SingleResource extends Resource { + private Set collectionMembership; + + private boolean getAllowed; + + private boolean putAllowed; + + private boolean postAllowed; + + private int automationId; + + private boolean resourceAutomationInProgress; + + private boolean attributeAutomationInProgress; + + private int automationUpdateInterval; + + private AutoUpdateType automationType; + + public SingleResource() { + setCollectionMembership(new HashSet()); + } + + public Set getCollectionMembership() { + return collectionMembership; + } + + public void setCollectionMembership( + Set collectionMembership) { + this.collectionMembership = collectionMembership; + } + + public void addCollectionMembership(CollectionResource resource) { + if (null == resource) { + return; + } + if (null == collectionMembership) { + collectionMembership = new HashSet(); + } + collectionMembership.add(resource); + } + + public void addCollectionMembership(Set resources) { + if (null == resources) { + return; + } + if (null == collectionMembership) { + collectionMembership = new HashSet(); + } + collectionMembership.addAll(resources); + } + + public void removeCollectionMembership(CollectionResource resource) { + if (null == resource || null == collectionMembership) { + return; + } + collectionMembership.remove(resource); + } + + public void removeCollectionMembership(Set collections) { + if (null == collections || null == collectionMembership) { + return; + } + collectionMembership.removeAll(collections); + } + + public boolean isMemberOfAnyCollection() { + if (null == collectionMembership || collectionMembership.isEmpty()) { + return false; + } + return true; + } + + public boolean isGetAllowed() { + return getAllowed; + } + + public void setGetAllowed(boolean getAllowed) { + this.getAllowed = getAllowed; + } + + public boolean isPutAllowed() { + return putAllowed; + } + + public void setPutAllowed(boolean putAllowed) { + this.putAllowed = putAllowed; + } + + public boolean isPostAllowed() { + return postAllowed; + } + + public void setPostAllowed(boolean postAllowed) { + this.postAllowed = postAllowed; + } + + public int getAutomationUpdateInterval() { + return automationUpdateInterval; + } + + public void setAutomationUpdateInterval(int automationUpdateInterval) { + this.automationUpdateInterval = automationUpdateInterval; + } + + public AutoUpdateType getAutomationType() { + return automationType; + } + + public void setAutomationType(AutoUpdateType automationType) { + this.automationType = automationType; + } + + public int getAutomationId() { + return automationId; + } + + public void setAutomationId(int automationId) { + this.automationId = automationId; + } + + public boolean isResourceAutomationInProgress() { + return resourceAutomationInProgress; + } + + public void setResourceAutomationInProgress( + boolean resourceAutomationInProgress) { + this.resourceAutomationInProgress = resourceAutomationInProgress; + } + + public boolean isAttributeAutomationInProgress() { + return attributeAutomationInProgress; + } + + public void setAttributeAutomationInProgress( + boolean attributeAutomationInProgress) { + this.attributeAutomationInProgress = attributeAutomationInProgress; + } + + /* + * public LocalResourceAttribute getAttribute(String attributeName) { if + * (null == attributeName || null == resourceAttributesMap || + * resourceAttributesMap.size() < 1) { return null; } return + * resourceAttributesMap.get(attributeName); } + */ +} \ No newline at end of file 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 index 079f645..e24a456 100644 --- 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 @@ -19,7 +19,7 @@ package oic.simulator.serviceprovider.perspective; import oic.simulator.serviceprovider.view.AttributeView; import oic.simulator.serviceprovider.view.LogView; import oic.simulator.serviceprovider.view.MetaPropertiesView; -import oic.simulator.serviceprovider.view.MultiResourceOrchestrationView; +import oic.simulator.serviceprovider.view.DevicePlatformInfoView; import oic.simulator.serviceprovider.view.ResourceManagerView; import oic.simulator.serviceprovider.view.ResourceObserverView; @@ -58,7 +58,7 @@ public class PerspectiveFactory implements IPerspectiveFactory { factory.getEditorArea()); factory.addView(LogView.VIEW_ID, IPageLayout.BOTTOM, 0.65f, AttributeView.VIEW_ID); - factory.addView(MultiResourceOrchestrationView.VIEW_ID, - IPageLayout.RIGHT, 0.6f, AttributeView.VIEW_ID); + factory.addView(DevicePlatformInfoView.VIEW_ID, IPageLayout.RIGHT, + 0.6f, AttributeView.VIEW_ID); } } \ No newline at end of file diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/LocalResourceAttribute.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/LocalResourceAttribute.java deleted file mode 100644 index c04b07e..0000000 --- a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/LocalResourceAttribute.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package oic.simulator.serviceprovider.resource; - -import java.util.List; - -import org.oic.simulator.ResourceAttribute; -import org.oic.simulator.ResourceAttribute.Range; -import org.oic.simulator.ResourceAttribute.Type; -import org.oic.simulator.serviceprovider.AutomationType; - -/** - * This class represents an attribute in the simulated resource. - */ -public class LocalResourceAttribute { - - // Native object reference - private ResourceAttribute resourceAttribute; - - private Object attributeValue; - private List 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 getAttValues() { - return attValues; - } - - public void setAttValues(List 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/SimulatorResource.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/SimulatorResource.java deleted file mode 100644 index 38d9730..0000000 --- a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/SimulatorResource.java +++ /dev/null @@ -1,205 +0,0 @@ -/* - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package oic.simulator.serviceprovider.resource; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import org.oic.simulator.SimulatorResourceModel; -import org.oic.simulator.serviceprovider.AutomationType; -import org.oic.simulator.serviceprovider.ObserverInfo; -import org.oic.simulator.serviceprovider.SimulatorResourceServer; - -/** - * This class represents a simulated resource. It maintains all the necessary - * information about the resource. - */ -public class SimulatorResource { - private String resourceURI; - private String resourceName; - private String resourceType; - private String resourceInterface; - - // Native Object references - private SimulatorResourceServer resourceServer; - private SimulatorResourceModel resourceModel; - - private int automationId; - - private boolean resourceAutomationInProgress; - - private boolean attributeAutomationInProgress; - - private int automationUpdateInterval; - - private AutomationType automationType; - - private Map resourceAttributesMap; - - private Map observers; - - public SimulatorResource() { - observers = new HashMap(); - } - - 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 getResourceAttributesMap() { - return resourceAttributesMap; - } - - public void setResourceAttributesMap( - Map 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 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 attItr = resourceAttributesMap.keySet().iterator(); - while (attItr.hasNext()) { - resourceAttributesMap.get(attItr.next()) - .printAttributeDetails();; - } - } - } - - public LocalResourceAttribute getAttribute(String attributeName) { - if (null == attributeName || null == resourceAttributesMap - || resourceAttributesMap.size() < 1) { - return null; - } - return resourceAttributesMap.get(attributeName); - } - -} \ No newline at end of file diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/StandardConfiguration.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/StandardConfiguration.java deleted file mode 100644 index 4a3035c..0000000 --- a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/StandardConfiguration.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package oic.simulator.serviceprovider.resource; - -import java.io.File; -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.util.Date; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Map; - -import oic.simulator.serviceprovider.Activator; -import oic.simulator.serviceprovider.utils.Constants; - -import org.eclipse.core.runtime.FileLocator; -import org.oic.simulator.ILogger.Level; - -/** - * Class which loads and maintains the standard RAML configuration file list. - */ -public class StandardConfiguration { - - // A map of filename of standard resources as the key and the complete - // location of the file(including the filename) as the value. - Map stdConfigFiles; - - public StandardConfiguration() { - stdConfigFiles = new HashMap(); - populateStandardConfigurationList(); - } - - private void populateStandardConfigurationList() { - Enumeration 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 getStandardResourceConfigurationList() { - return stdConfigFiles; - } - - public void setStandardResourceConfigurationList( - Map stdConfigFiles) { - this.stdConfigFiles = stdConfigFiles; - } - - public String getFilePath(String fileName) { - return stdConfigFiles.get(fileName); - } -} \ No newline at end of file diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/utils/AttributeValueBuilder.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/utils/AttributeValueBuilder.java new file mode 100644 index 0000000..fdebf0e --- /dev/null +++ b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/utils/AttributeValueBuilder.java @@ -0,0 +1,266 @@ +/* + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package oic.simulator.serviceprovider.utils; + +import java.util.Vector; + +import org.oic.simulator.AttributeValue; + +public class AttributeValueBuilder { + public static AttributeValue build(String valueString, + AttributeValue.ValueType valueType) { + int depth = findDepth(valueString); + if (0 == depth) { + return handleDepth0(valueString, valueType); + } else if (1 == depth) { + return handleDepth1(valueString, valueType); + } else if (2 == depth) { + return handleDepth2(valueString, valueType); + } else if (3 == depth) { + return handleDepth3(valueString, valueType); + } + + return null; + } + + private static int findDepth(String value) { + int depth = 0; + for (char ch : value.toCharArray()) { + if (ch == '[') + depth++; + else + break; + } + + return depth; + } + + private static boolean isValidSyntax(String value) { + int count = 0; + for (char ch : value.toCharArray()) { + if (ch == '[') + count++; + if (ch == ']') + count--; + } + + if (count == 0) + return true; + return false; + + } + + private static AttributeValue handleDepth0(String valueString, + AttributeValue.ValueType valueType) { + valueString = valueString.trim(); + if (0 != findDepth(valueString)) + return null; + + if (valueType == AttributeValue.ValueType.INTEGER) + return new AttributeValue(Integer.parseInt(valueString)); + else if (valueType == AttributeValue.ValueType.DOUBLE) + return new AttributeValue(Double.parseDouble(valueString)); + else if (valueType == AttributeValue.ValueType.BOOLEAN) + return new AttributeValue(Boolean.parseBoolean(valueString)); + else if (valueType == AttributeValue.ValueType.STRING) + return new AttributeValue(valueString); + return null; + } + + private static String[] splitIntoArrays(String value) { + Vector values = new Vector(); + String valueString = new String(value); + valueString = valueString.substring(valueString.indexOf('[') + 1, + valueString.lastIndexOf(']')); + + int count = 0; + int startPos = 0; + char[] charArray = valueString.toCharArray(); + for (int index = 0; index < charArray.length; index++) { + if (charArray[index] == '[' && 0 == count++) { + startPos = index; + } + + if (charArray[index] == ']' && 0 == --count) { + values.add(valueString.substring(startPos, index + 1)); + } + } + + String[] result = new String[values.size()]; + values.toArray(result); + return result; + } + + private static AttributeValue handleDepth1(String valueString, + AttributeValue.ValueType valueType) { + valueString = valueString.trim(); + if (1 != findDepth(valueString) || false == isValidSyntax(valueString)) + return null; + + valueString = valueString.substring(valueString.indexOf('[') + 1, + valueString.lastIndexOf(']')); + String[] valuesString = valueString.split(","); + if (null == valuesString || 0 == valuesString.length) + return null; + + if (valueType == AttributeValue.ValueType.INTEGER) { + Integer[] result = new Integer[valuesString.length]; + for (int index = 0; index < valuesString.length; index++) { + Integer value = (Integer) handleDepth0(valuesString[index], + valueType).get(); + if (null == value) + return null; + result[index] = value; + } + return new AttributeValue(result); + } else if (valueType == AttributeValue.ValueType.DOUBLE) { + Double[] result = new Double[valuesString.length]; + for (int index = 0; index < valuesString.length; index++) { + Double value = (Double) handleDepth0(valuesString[index], + valueType).get(); + if (null == value) + return null; + result[index] = value; + } + return new AttributeValue(result); + } else if (valueType == AttributeValue.ValueType.BOOLEAN) { + Boolean[] result = new Boolean[valuesString.length]; + for (int index = 0; index < valuesString.length; index++) { + Boolean value = (Boolean) handleDepth0(valuesString[index], + valueType).get(); + if (null == value) + return null; + result[index] = value; + } + return new AttributeValue(result); + } else if (valueType == AttributeValue.ValueType.STRING) { + return new AttributeValue(valuesString); + } + + return null; + } + + private static AttributeValue handleDepth2(String valueString, + AttributeValue.ValueType valueType) { + valueString = valueString.trim(); + if (2 != findDepth(valueString) || false == isValidSyntax(valueString)) + return null; + + String[] valuesString = splitIntoArrays(valueString); + if (null == valuesString || 0 == valuesString.length) + return null; + + if (valueType == AttributeValue.ValueType.INTEGER) { + Integer[][] result = new Integer[valuesString.length][]; + for (int index = 0; index < valuesString.length; index++) { + Integer[] value = (Integer[]) handleDepth1(valuesString[index], + valueType).get(); + if (null == value) + return null; + result[index] = value; + } + return new AttributeValue(result); + } else if (valueType == AttributeValue.ValueType.DOUBLE) { + Double[][] result = new Double[valuesString.length][]; + for (int index = 0; index < valuesString.length; index++) { + Double[] value = (Double[]) handleDepth1(valuesString[index], + valueType).get(); + if (null == value) + return null; + result[index] = value; + } + return new AttributeValue(result); + } else if (valueType == AttributeValue.ValueType.BOOLEAN) { + Boolean[][] result = new Boolean[valuesString.length][]; + for (int index = 0; index < valuesString.length; index++) { + Boolean[] value = (Boolean[]) handleDepth1(valuesString[index], + valueType).get(); + if (null == value) + return null; + result[index] = value; + } + return new AttributeValue(result); + } else if (valueType == AttributeValue.ValueType.STRING) { + String[][] result = new String[valuesString.length][]; + for (int index = 0; index < valuesString.length; index++) { + String[] value = (String[]) handleDepth1(valuesString[index], + valueType).get(); + if (null == value) + return null; + result[index] = value; + } + return new AttributeValue(result); + } + + return null; + } + + public static AttributeValue handleDepth3(String valueString, + AttributeValue.ValueType valueType) { + valueString = valueString.trim(); + if (3 != findDepth(valueString) || false == isValidSyntax(valueString)) + return null; + + String[] valuesString = splitIntoArrays(valueString); + if (null == valuesString || 0 == valuesString.length) + return null; + + if (valueType == AttributeValue.ValueType.INTEGER) { + Integer[][][] result = new Integer[valuesString.length][][]; + for (int index = 0; index < valuesString.length; index++) { + Integer[][] value = (Integer[][]) handleDepth2( + valuesString[index], valueType).get(); + if (null == value) + return null; + result[index] = value; + } + return new AttributeValue(result); + } else if (valueType == AttributeValue.ValueType.DOUBLE) { + Double[][][] result = new Double[valuesString.length][][]; + for (int index = 0; index < valuesString.length; index++) { + Double[][] value = (Double[][]) handleDepth2( + valuesString[index], valueType).get(); + if (null == value) + return null; + result[index] = value; + } + return new AttributeValue(result); + } else if (valueType == AttributeValue.ValueType.BOOLEAN) { + Boolean[][][] result = new Boolean[valuesString.length][][]; + for (int index = 0; index < valuesString.length; index++) { + Boolean[][] value = (Boolean[][]) handleDepth2( + valuesString[index], valueType).get(); + if (null == value) + return null; + result[index] = value; + } + return new AttributeValue(result); + } else if (valueType == AttributeValue.ValueType.STRING) { + String[][][] result = new String[valuesString.length][][]; + for (int index = 0; index < valuesString.length; index++) { + String[][] value = (String[][]) handleDepth2( + valuesString[index], valueType).get(); + if (null == value) + return null; + result[index] = value; + } + return new AttributeValue(result); + } + + return null; + } +} 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 index 09fecfc..ef56513 100644 --- 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 @@ -16,7 +16,7 @@ package oic.simulator.serviceprovider.utils; -import org.oic.simulator.serviceprovider.AutomationType; +import org.oic.simulator.server.SimulatorResource.AutoUpdateType; /** * This class maintains all constants which are used throughout the service @@ -24,84 +24,146 @@ import org.oic.simulator.serviceprovider.AutomationType; */ public class Constants { - public static final String CONFIG_DIRECTORY_PATH = "/resource"; + public static final String INT = "Int"; + public static final String DOUBLE = "Double"; + public static final String BOOL = "Bool"; + public static final String STRING = "String"; + public static final String UNKNOWN = "Unknown"; - public static final String UNDERSCORE = "_"; - public static final String FORWARD_SLASH = "/"; + public static final String CONFIG_DIRECTORY_PATH = "/resource"; - public static final String OIC_PREFIX = "/oic/r"; - public static final String SIMULATOR = "simulator"; + public static final String UNDERSCORE = "_"; + public static final String FORWARD_SLASH = "/"; - public static final String RESOURCE_URI = "Resource URI"; - public static final String RESOURCE_TYPE = "Resource Type"; - public static final String RESOURCE_UID = "Resource ID"; - public static final String CONNECTIVITY_TYPE = "Connectivity Type"; + public static final String OIC_PREFIX = "/oic/r"; + public static final String SIMULATOR = "simulator"; - public static final String[] META_PROPERTIES = { - RESOURCE_URI, RESOURCE_TYPE, CONNECTIVITY_TYPE }; + public static final String RESOURCE_URI = "Resource URI"; + public static final String RESOURCE_TYPE = "Resource Type"; + public static final String RESOURCE_TYPES = "Resource Types"; + public static final String RESOURCE_NAME = "Resource Name"; + public static final String DEVICE_NAME = "Device Name"; + public static final String RESOURCE_UID = "Resource ID"; + public static final String CONNECTIVITY_TYPE = "Connectivity Type"; - public static final int META_PROPERTY_COUNT = META_PROPERTIES.length; + public static final String[] META_PROPERTIES = { + RESOURCE_NAME, RESOURCE_URI, RESOURCE_TYPE }; - public static final String ENABLE = "Enable"; - public static final String DISABLE = "Disable"; - public static final String ENABLED = "Enabled"; - public static final String DISABLED = "Disabled"; + public static final int META_PROPERTY_COUNT = META_PROPERTIES.length; - public static final String AUTOMATION = "Automation"; - public static final String AUTOMATION_TYPE = "Automation Type"; - public static final String UPDATE_INTERVAL_IN_MS = "Update Interval(ms)"; + public static final String ENABLE = "Enable"; + public static final String DISABLE = "Disable"; + public static final String ENABLED = "Enabled"; + public static final String DISABLED = "Disabled"; - public static final String[] AUTOMATION_SETTINGS = { - AUTOMATION_TYPE, UPDATE_INTERVAL_IN_MS }; + public static final String AUTOMATION = "Automation"; + public static final String AUTOMATION_TYPE = "Automation Type"; + public static final String UPDATE_INTERVAL_IN_MS = "Update Interval(ms)"; - public static final int AUTOMATION_SETTINGS_COUNT = AUTOMATION_SETTINGS.length; + public static final String[] AUTOMATION_SETTINGS = { + AUTOMATION_TYPE, UPDATE_INTERVAL_IN_MS }; - public static final String START_RESOURCE_AUTOMATION = "Start Automation"; - public static final String STOP_RESOURCE_AUTOMATION = "Stop Automation"; + public static final int AUTOMATION_SETTINGS_COUNT = AUTOMATION_SETTINGS.length; - public static final int DISPLAY_RESOURCE_URI_TOKEN_COUNT = 2; + public static final String START_RESOURCE_AUTOMATION = "Start Automation"; + public static final String STOP_RESOURCE_AUTOMATION = "Stop Automation"; - public static final AutomationType DEFAULT_AUTOMATION_TYPE = AutomationType.NORMAL; + public static final int DISPLAY_RESOURCE_URI_TOKEN_COUNT = 2; - public static final int DEFAULT_AUTOMATION_INTERVAL = 500; + public static final AutoUpdateType DEFAULT_AUTOMATION_TYPE = AutoUpdateType.ONE_TIME; - public static final int PROPER_LOG_TIME_TOKEN_LENGTH = 3; + public static final int DEFAULT_AUTOMATION_INTERVAL = 500; - public static final String[] BROWSE_RAML_FILTER_EXTENSIONS = new String[] { "*.raml" }; - public static final String[] SAVE_LOG_FILTER_EXTENSIONS = new String[] { - "*.log", "*" }; + public static final int PROPER_LOG_TIME_TOKEN_LENGTH = 3; - public static final int LOG_SIZE = 1000; + public static final String[] BROWSE_RAML_FILTER_EXTENSIONS = new String[] { "*.raml" }; + public static final String[] SAVE_LOG_FILTER_EXTENSIONS = new String[] { + "*.log", "*" }; - public static final String INFO_LOG = "info_log"; - public static final String WARNING_LOG = "warning_log"; - public static final String ERROR_LOG = "error_log"; - public static final String DEBUG_LOG = "debug_log"; - public static final String UNKNOWN_LOG = "unknown_log"; + public static final int LOG_SIZE = 1000; - public static final String INFO = "Info"; - public static final String WARNING = "Warning"; - public static final String ERROR = "Error"; - public static final String DEBUG = "Debug"; - public static final String UNKNOWN = "Unknown"; + public static final String INFO_LOG = "info_log"; + public static final String WARNING_LOG = "warning_log"; + public static final String ERROR_LOG = "error_log"; + public static final String DEBUG_LOG = "debug_log"; + public static final String UNKNOWN_LOG = "unknown_log"; - public static final String CHECKED = "Checked"; - public static final String UNCHECKED = "Unchecked"; - public static final String NOTIFY_BUTTON_SELECTED = "Notify_Selected"; - public static final String NOTIFY_BUTTON_UNSELECTED = "Notify_Unselected"; + public static final String INFO = "Info"; + public static final String WARNING = "Warning"; + public static final String ERROR = "Error"; + public static final String DEBUG = "Debug"; - public static final String CREATE_PAGE_TITLE = "Create Resource"; - public static final String CREATE_PAGE_MESSAGE = "Select a standard resource or custom resource to be created"; + public static final String CHECKED = "Checked"; + public static final String UNCHECKED = "Unchecked"; + public static final String NOTIFY_BUTTON_SELECTED = "Notify_Selected"; + public static final String NOTIFY_BUTTON_UNSELECTED = "Notify_Unselected"; - public static final String DELETE_PAGE_TITLE = "Delete Resource"; - public static final String DELETE_PAGE_MESSAGE = "Select the resource(s) to be deleted"; + public static final String CREATE_PAGE_TITLE = "Create Resource"; + public static final String CREATE_PAGE_MESSAGE = "Create a resource from RAML file"; - public static final String RAML_FILE_PREFIX = "/resource/"; + public static final String DELETE_PAGE_TITLE = "Delete Resource"; + public static final String DELETE_PAGE_MESSAGE = "Select the resource(s) to be deleted"; - public static final String RAML_FILE_EXTENSION = ".raml"; - public static final String JSON_FILE_EXTENSION = ".json"; + public static final String RAML_FILE_PREFIX = "/resource/"; - public static final String SPLIT_BY_DOT_PATTERN = "\\."; + public static final String RAML_FILE_EXTENSION = ".raml"; + public static final String JSON_FILE_EXTENSION = ".json"; + + public static final String SPLIT_BY_DOT_PATTERN = "\\."; + + // Platform information + public static final String PLATFORM_ID = "Id"; + public static final String PLATFORM_MANUFAC_NAME = "Manufacturer Name"; + public static final String PLATFORM_MANUFAC_URL = "Manufacturer URL"; + public static final String PLATFORM_MODEL_NO = "Model Number"; + public static final String PLATFORM_DATE_OF_MANUFAC = "Date of Manufacture"; + public static final String PLATFORM_VERSION = "Version"; + public static final String PLATFORM_OS_VERSION = "OS Version"; + public static final String PLATFORM_HARDWARE_VERSION = "HardWare Version"; + public static final String PLATFORM_FIRMWARE_VERSION = "Firmware Version"; + public static final String PLATFORM_SUPPORT_URL = "Support URL"; + public static final String PLATFORM_SYSTEM_TIME = "System Time"; + + public static final String SAMPLE_LIGHT = "sample.light"; + + public static final String UPDATE_PROP_PAGE_TITLE = "Update Properties"; + public static final String UPDATE_PROP_PAGE_MESSAGE = "Update the default values of resource properties"; + + public static final String START_STOP_PAGE_TITLE = "Start/Stop Resource"; + public static final String START_STOP_PAGE_MESSAGE = "This page allows to start or stop the created resource(s)"; + + public static final String START_RESOURCE = "Start Resource"; + public static final String STOP_RESOURCE = "Stop Resource"; + + public static final String DELETE_RESOURCE = "Delete Resource"; + + public static final String MAIN_PAGE_TITLE = "Create Resource"; + public static final String MAIN_PAGE_MESSAGE = "Simple resource or Collection resource"; + + public static final String SIMPLE_PAGE_TITLE = "Create Simple Resource"; + public static final String SIMPLE_PAGE_MESSAGE = "Either manually or from RAML file"; + + public static final String SIMPLE_RESOURCE_BASIC_DETAILS_PAGE_TITLE = "Create Simple Resource(Step 1 of 3)"; + public static final String SIMPLE_RESOURCE_BASIC_DETAILS_PAGE_MESSAGE = "Fill basic details of the resource"; + + public static final String SIMPLE_RESOURCE_ADD_ATTRIBUTE_PAGE_TITLE = "Create Simple Resource(Step 2 of 3)"; + public static final String SIMPLE_RESOURCE_ADD_ATTRIBUTE_PAGE_MESSAGE = "Add attributes to the resource"; + + public static final String SIMPLE_RESOURCE_OTHER_DETAILS_PAGE_TITLE = "Create Simple Resource(Step 3 of 3)"; + public static final String SIMPLE_RESOURCE_OTHER_DETAILS_PAGE_MESSAGE = "Fill other details of the resource"; + + public static final String COLLECTION_RESOURCE_BASIC_DETAILS_PAGE_TITLE1 = "Create Collection Resource"; + public static final String COLLECTION_RESOURCE_BASIC_DETAILS_PAGE_TITLE2 = "Create Collection Resource(Step 1 of 2)"; + public static final String COLLECTION_RESOURCE_BASIC_DETAILS_PAGE_MESSAGE = "Fill basic details of the resource"; + + public static final String COLLECTION_RESOURCE_ADD_OTHER_RESOURCES_PAGE_TITLE = "Create Collection Resource(Step 2 of 2)"; + public static final String COLLECTION_RESOURCE_ADD_OTHER_RESOURCES_PAGE_MESSAGE = "Add other resources to this collection resource"; + + public static final String CREATE_DEVICE_PAGE_TITLE = "Create Device"; + public static final String CREATE_DEVICE_PAGE_MESSAGE = "Create a logical device which holds a group of resources"; + + public static final String DEVICE = "Create Device"; + public static final String SINGLE_RESOURCE = "Single Resource"; + public static final String COLLECTION_RESOURCE = "Collection Resource"; - public static final String SAMPLE_LIGHT = "sample.light"; } \ No newline at end of file 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 index 4c053d3..73d559c 100644 --- 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 @@ -17,27 +17,36 @@ package oic.simulator.serviceprovider.utils; import java.util.ArrayList; +import java.util.Comparator; +import java.util.Date; +import java.util.Enumeration; +import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; +import java.util.Vector; + +import oic.simulator.serviceprovider.Activator; +import oic.simulator.serviceprovider.model.CollectionResource; +import oic.simulator.serviceprovider.model.Device; +import oic.simulator.serviceprovider.model.LocalResourceAttribute; +import oic.simulator.serviceprovider.model.Resource; +import oic.simulator.serviceprovider.model.SingleResource; + +import org.oic.simulator.AttributeValue; +import org.oic.simulator.AttributeValue.TypeInfo; +import org.oic.simulator.AttributeValue.ValueType; +import org.oic.simulator.ILogger.Level; +import org.oic.simulator.InvalidArgsException; +import org.oic.simulator.SimulatorException; +import org.oic.simulator.SimulatorResourceAttribute; +import org.oic.simulator.SimulatorResourceModel; /** * This class has common utility methods. */ public class Utility { - public static String uriToDisplayName(String uri) { - String result = null; - if (null != uri) { - String tokens[] = uri.split(Constants.FORWARD_SLASH); - if (null != tokens && tokens.length > 2) { - result = tokens[tokens.length - 3] + Constants.UNDERSCORE - + tokens[tokens.length - 1]; - } - } - return result; - } - public static String fileNameToDisplay(String fileName) { if (null == fileName || fileName.length() < 1) { return null; @@ -100,9 +109,18 @@ public class Utility { if (null != value) { try { result = Integer.parseInt(value); - } catch (NumberFormatException nfe) { - System.out - .println("Getting UpdateInterval from string failed!"); + } catch (NumberFormatException e) { + Activator + .getDefault() + .getLogManager() + .log(Level.ERROR.ordinal(), + new Date(), + getSimulatorErrorString( + e, + "Update interval convertion failed." + + "Taking the default value(" + + Constants.DEFAULT_AUTOMATION_INTERVAL + + ")")); } } return result; @@ -119,4 +137,669 @@ public class Utility { } return list; } + + public static List getSingleResourceListFromSet( + Set resources) { + if (null == resources) { + return null; + } + List list = new ArrayList(); + Iterator typeItr = resources.iterator(); + while (typeItr.hasNext()) { + list.add(typeItr.next()); + } + return list; + } + + public static List getCollectionResourceListFromSet( + Set resources) { + if (null == resources) { + return null; + } + List list = new ArrayList(); + Iterator typeItr = resources.iterator(); + while (typeItr.hasNext()) { + list.add(typeItr.next()); + } + return list; + } + + public static List getDeviceListFromSet(Set devices) { + if (null == devices) { + return null; + } + List list = new ArrayList(); + Iterator typeItr = devices.iterator(); + while (typeItr.hasNext()) { + list.add(typeItr.next()); + } + return list; + } + + public static Set convertVectorToSet(Vector vector) { + if (null == vector || vector.isEmpty()) { + return null; + } + Set resultSet = new HashSet(); + Enumeration e = vector.elements(); + while (e.hasMoreElements()) { + resultSet.add(e.nextElement().toString()); + } + return resultSet; + } + + public static String getSimulatorErrorString(Exception e, String info) { + if (null == e) { + return null; + } + String detail; + if (e instanceof SimulatorException) { + SimulatorException simEx = (SimulatorException) e; + detail = simEx.message() + "\n"; + detail += "Exception Type: " + simEx.getClass().getSimpleName() + + "\n"; + detail += "Error code: " + simEx.code().toString(); + } else { + detail = info + "\n"; + detail += "Exception Type: " + e.getClass().getSimpleName() + "\n"; + detail += "Message: " + e.getMessage(); + } + return detail; + } + + public static Set getAttributeTypes() { + Set attTypes = new HashSet(); + ValueType[] types = ValueType.values(); + if (null != types) { + attTypes.add(Constants.INT); + attTypes.add(Constants.DOUBLE); + attTypes.add(Constants.BOOL); + attTypes.add(Constants.STRING); + } + return attTypes; + } + + public static ValueType getAttributeTypeEnum(String type) { + if (null != type && type.trim().length() > 0) { + if (type.equalsIgnoreCase(Constants.INT)) { + return ValueType.INTEGER; + } + if (type.equalsIgnoreCase(Constants.DOUBLE)) { + return ValueType.DOUBLE; + } + if (type.equalsIgnoreCase(Constants.BOOL)) { + return ValueType.BOOLEAN; + } + if (type.equalsIgnoreCase(Constants.STRING)) { + return ValueType.STRING; + } + } + return ValueType.UNKNOWN; + } + + public static int[] convertSetToArrayInt(Set allowedValues) { + if (null == allowedValues || allowedValues.size() < 1) { + return null; + } + int[] arr = new int[allowedValues.size()]; + Iterator itr = allowedValues.iterator(); + try { + int i = 0; + while (itr.hasNext()) { + arr[i++] = (int) itr.next(); + } + } catch (Exception e) { + return null; + } + return arr; + } + + public static double[] convertSetToArrayDouble(Set allowedValues) { + if (null == allowedValues || allowedValues.size() < 1) { + return null; + } + double[] arr = new double[allowedValues.size()]; + Iterator itr = allowedValues.iterator(); + try { + int i = 0; + while (itr.hasNext()) { + arr[i++] = (double) itr.next(); + } + } catch (Exception e) { + return null; + } + return arr; + } + + public static boolean[] convertSetToArrayBoolean(Set allowedValues) { + if (null == allowedValues || allowedValues.size() < 1) { + return null; + } + boolean[] arr = new boolean[allowedValues.size()]; + Iterator itr = allowedValues.iterator(); + try { + int i = 0; + while (itr.hasNext()) { + arr[i++] = (boolean) itr.next(); + } + } catch (Exception e) { + return null; + } + return arr; + } + + public static String[] convertSetToArrayString(Set allowedValues) { + if (null == allowedValues || allowedValues.size() < 1) { + return null; + } + String[] arr = new String[allowedValues.size()]; + Iterator itr = allowedValues.iterator(); + try { + int i = 0; + while (itr.hasNext()) { + arr[i++] = (String) itr.next(); + } + } catch (Exception e) { + return null; + } + return arr; + } + + public static Vector convertSetToVectorInt( + Set allowedValues) { + if (null == allowedValues || allowedValues.size() < 1) { + return null; + } + Vector resultVec = new Vector(); + Iterator itr = allowedValues.iterator(); + try { + while (itr.hasNext()) { + resultVec.add((Integer) itr.next()); + } + } catch (Exception e) { + return null; + } + return resultVec; + } + + public static Vector convertSetToVectorDouble( + Set allowedValues) { + if (null == allowedValues || allowedValues.size() < 1) { + return null; + } + Vector resultVec = new Vector(); + Iterator itr = allowedValues.iterator(); + try { + while (itr.hasNext()) { + resultVec.add((Double) itr.next()); + } + } catch (Exception e) { + return null; + } + return resultVec; + } + + public static Vector convertSetToVectorString( + Set allowedValues) { + if (null == allowedValues || allowedValues.size() < 1) { + return null; + } + Vector resultVec = new Vector(); + Iterator itr = allowedValues.iterator(); + try { + while (itr.hasNext()) { + resultVec.add((String) itr.next()); + } + } catch (Exception e) { + return null; + } + return resultVec; + } + + public static Set convertSetStringToSetObject(Set values, + ValueType type) { + if (null == values || values.isEmpty()) { + return null; + } + Set resultSet = new HashSet(); + if (type.equals(Constants.INT)) { + int val; + Iterator itr = values.iterator(); + while (itr.hasNext()) { + try { + val = Integer.parseInt(itr.next()); + resultSet.add(val); + } catch (NumberFormatException nfe) { + // Added for safety. Nothing to do. + } + } + } else if (type.equals(Constants.DOUBLE)) { + double val; + Iterator itr = values.iterator(); + while (itr.hasNext()) { + try { + val = Double.parseDouble(itr.next()); + resultSet.add(val); + } catch (NumberFormatException nfe) { + // Added for safety. Nothing to do. + } + } + } else if (type.equals(Constants.BOOL)) { + resultSet.add(true); + resultSet.add(false); + } else { + Iterator itr = values.iterator(); + while (itr.hasNext()) { + resultSet.add(itr.next()); + } + } + return resultSet; + } + + public static List convertSingleTypeResourceListToBaseType( + List resources) { + if (null == resources || resources.isEmpty()) { + return null; + } + List resultSet = new ArrayList(); + Iterator itr = resources.iterator(); + while (itr.hasNext()) { + resultSet.add(itr.next()); + } + return resultSet; + } + + public static List convertCollectionTypeResourceListToBaseType( + List resources) { + if (null == resources || resources.isEmpty()) { + return null; + } + List resultSet = new ArrayList(); + Iterator itr = resources.iterator(); + while (itr.hasNext()) { + resultSet.add(itr.next()); + } + return resultSet; + } + + public static Comparator resourceComparator = new Comparator() { + public int compare( + Resource res1, + Resource res2) { + String s1 = res1 + .getResourceName(); + String s2 = res2 + .getResourceName(); + + String s1Part = s1 + .replaceAll( + "\\d", + ""); + String s2Part = s2 + .replaceAll( + "\\d", + ""); + + if (s1Part + .equalsIgnoreCase(s2Part)) { + return extractInt(s1) + - extractInt(s2); + } + return s1 + .compareTo(s2); + } + + int extractInt( + String s) { + String num = s + .replaceAll( + "\\D", + ""); + // return + // 0 + // if + // no + // digits + // found + return num + .isEmpty() ? 0 + : Integer + .parseInt(num); + } + }; + + public static Comparator singleResourceComparator = new Comparator() { + public int compare( + SingleResource res1, + SingleResource res2) { + String s1 = res1 + .getResourceName(); + String s2 = res2 + .getResourceName(); + + String s1Part = s1 + .replaceAll( + "\\d", + ""); + String s2Part = s2 + .replaceAll( + "\\d", + ""); + + if (s1Part + .equalsIgnoreCase(s2Part)) { + return extractInt(s1) + - extractInt(s2); + } + return s1 + .compareTo(s2); + } + + int extractInt( + String s) { + String num = s + .replaceAll( + "\\D", + ""); + // return + // 0 + // if + // no + // digits + // found + return num + .isEmpty() ? 0 + : Integer + .parseInt(num); + } + }; + + public static Comparator collectionResourceComparator = new Comparator() { + public int compare( + CollectionResource res1, + CollectionResource res2) { + String s1 = res1 + .getResourceName(); + String s2 = res2 + .getResourceName(); + + String s1Part = s1 + .replaceAll( + "\\d", + ""); + String s2Part = s2 + .replaceAll( + "\\d", + ""); + + if (s1Part + .equalsIgnoreCase(s2Part)) { + return extractInt(s1) + - extractInt(s2); + } + return s1 + .compareTo(s2); + } + + int extractInt( + String s) { + String num = s + .replaceAll( + "\\D", + ""); + // return + // 0 + // if + // no + // digits + // found + return num + .isEmpty() ? 0 + : Integer + .parseInt(num); + } + }; + + public static Comparator deviceComparator = new Comparator() { + public int compare( + Device res1, + Device res2) { + String s1 = res1 + .getDeviceName(); + String s2 = res2 + .getDeviceName(); + + String s1Part = s1 + .replaceAll( + "\\d", + ""); + String s2Part = s2 + .replaceAll( + "\\d", + ""); + + if (s1Part + .equalsIgnoreCase(s2Part)) { + return extractInt(s1) + - extractInt(s2); + } + return s1 + .compareTo(s2); + } + + int extractInt( + String s) { + String num = s + .replaceAll( + "\\D", + ""); + // return + // 0 + // if + // no + // digits + // found + return num + .isEmpty() ? 0 + : Integer + .parseInt(num); + } + }; + + // This method only works for attributes whose values are of type int, + // double, bool, string and 1-D array of primitive types + public static String getAttributeValueAsString(AttributeValue val) { + if (null == val) { + return null; + } + Object value = val.get(); + if (null == value) { + return null; + } + TypeInfo type = val.typeInfo(); + if (type.mType == ValueType.RESOURCEMODEL + || (type.mType == ValueType.ARRAY && type.mBaseType == ValueType.RESOURCEMODEL) + || (type.mType == ValueType.ARRAY && type.mDepth > 1)) { + return null; + } + if (type.mType == ValueType.ARRAY) { + if (type.mBaseType == ValueType.INTEGER) { + Integer[] values = (Integer[]) value; + if (null == values || values.length < 1) { + return null; + } + List list = new ArrayList(); + for (Integer i : values) { + list.add(i); + } + return list.toString(); + } else if (type.mBaseType == ValueType.DOUBLE) { + Double[] values = (Double[]) value; + if (null == values || values.length < 1) { + return null; + } + List list = new ArrayList(); + for (Double i : values) { + list.add(i); + } + return list.toString(); + } else if (type.mBaseType == ValueType.BOOLEAN) { + Boolean[] values = (Boolean[]) value; + if (null == values || values.length < 1) { + return null; + } + List list = new ArrayList(); + for (Boolean i : values) { + list.add(i); + } + return list.toString(); + } else if (type.mBaseType == ValueType.STRING) { + String[] values = (String[]) value; + if (null == values || values.length < 1) { + return null; + } + List list = new ArrayList(); + for (String i : values) { + list.add(i); + } + return list.toString(); + } else { + return null; + } + } else { + return String.valueOf(value); + } + } + + public static List getDummyAttributes() { + List attributes = null; + attributes = new ArrayList(); + + // Integer attribute + SimulatorResourceAttribute attribute = new SimulatorResourceAttribute( + "integer", new AttributeValue(2), null); + attributes.add(addAttribute(attribute)); + + // Boolean attribute + attribute = new SimulatorResourceAttribute("boolean", + new AttributeValue(false), null); + attributes.add(addAttribute(attribute)); + + // String attribute + attribute = new SimulatorResourceAttribute("string", + new AttributeValue("india"), null); + attributes.add(addAttribute(attribute)); + + // Integer array attribute + int iarr[] = { 1, 2, 3 }; + attribute = new SimulatorResourceAttribute("integerArr", + new AttributeValue(iarr), null); + attributes.add(addAttribute(attribute)); + + // Double array attribute + double darr[] = { 1.5, 2.51, 3.15 }; + attribute = new SimulatorResourceAttribute("doubleArr", + new AttributeValue(darr), null); + attributes.add(addAttribute(attribute)); + + // Boolean array attribute + boolean barr[] = { false, true, false }; + attribute = new SimulatorResourceAttribute("boolArr", + new AttributeValue(barr), null); + attributes.add(addAttribute(attribute)); + + // String array attribute + String sarr[] = { "senthil", "muruga", "sriram" }; + attribute = new SimulatorResourceAttribute("stringArr", + new AttributeValue(sarr), null); + attributes.add(addAttribute(attribute)); + + // Model type complex attribute + attribute = new SimulatorResourceAttribute("subAtt1", + new AttributeValue("chennai"), null); + SimulatorResourceModel model = new SimulatorResourceModel(); + try { + model.addAttribute(attribute); + } catch (InvalidArgsException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + attribute = new SimulatorResourceAttribute("subAtt2", + new AttributeValue("madurai"), null); + try { + model.addAttribute(attribute); + } catch (InvalidArgsException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + SimulatorResourceModel subModel = new SimulatorResourceModel(); + try { + subModel.addAttribute(attribute); + } catch (InvalidArgsException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + attribute = new SimulatorResourceAttribute("modelsubAtt3", + new AttributeValue(subModel), null); + try { + model.addAttribute(attribute); + } catch (InvalidArgsException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + SimulatorResourceAttribute modelAtt = new SimulatorResourceAttribute( + "modelAtt1", new AttributeValue(model)); + attributes.add(addAttribute(modelAtt)); + + // 1-D array of model + attribute = new SimulatorResourceAttribute("subAtt1", + new AttributeValue("chennai"), null); + SimulatorResourceModel[] modelArr = new SimulatorResourceModel[2]; + model = new SimulatorResourceModel(); + try { + model.addAttribute(attribute); + modelArr[0] = model; + } catch (InvalidArgsException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + attribute = new SimulatorResourceAttribute("subAtt2", + new AttributeValue("madurai"), null); + model = new SimulatorResourceModel(); + try { + model.addAttribute(attribute); + modelArr[1] = model; + } catch (InvalidArgsException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + modelAtt = new SimulatorResourceAttribute("modelAtt2", + new AttributeValue(modelArr)); + attributes.add(addAttribute(modelAtt)); + + return attributes; + } + + private static LocalResourceAttribute addAttribute( + SimulatorResourceAttribute att) { + LocalResourceAttribute localAtt = new LocalResourceAttribute(); + + localAtt = new LocalResourceAttribute(); + + localAtt.setResourceAttributeRef(att); + + // Initially disabling the automation + localAtt.setAutomationInProgress(false); + + // Assigning the default automation interval + localAtt.setAutomationUpdateInterval(Constants.DEFAULT_AUTOMATION_INTERVAL); + + // Setting the default automation type + localAtt.setAutomationType(Constants.DEFAULT_AUTOMATION_TYPE); + + return localAtt; + } + } \ No newline at end of file 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 index 5b8e299..1544fb6 100644 --- 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 @@ -20,9 +20,13 @@ import java.util.List; import oic.simulator.serviceprovider.Activator; import oic.simulator.serviceprovider.manager.ResourceManager; -import oic.simulator.serviceprovider.resource.AutomationSettingHelper; -import oic.simulator.serviceprovider.resource.LocalResourceAttribute; -import oic.simulator.serviceprovider.resource.SimulatorResource; +import oic.simulator.serviceprovider.model.AutomationSettingHelper; +import oic.simulator.serviceprovider.model.CollectionResource; +import oic.simulator.serviceprovider.model.LocalResourceAttribute; +import oic.simulator.serviceprovider.model.Resource; +import oic.simulator.serviceprovider.model.SRMItem; +import oic.simulator.serviceprovider.model.SingleResource; +import oic.simulator.serviceprovider.utils.AttributeValueBuilder; import oic.simulator.serviceprovider.utils.Utility; import oic.simulator.serviceprovider.view.dialogs.AutomationSettingDialog; @@ -31,7 +35,8 @@ import org.eclipse.jface.viewers.CellEditor; import org.eclipse.jface.viewers.CheckboxCellEditor; import org.eclipse.jface.viewers.ComboBoxCellEditor; import org.eclipse.jface.viewers.EditingSupport; -import org.eclipse.jface.viewers.TableViewer; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.window.Window; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CCombo; @@ -39,7 +44,16 @@ import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.MessageBox; -import org.oic.simulator.serviceprovider.AutomationType; +import org.eclipse.swt.widgets.Tree; +import org.eclipse.swt.widgets.TreeItem; +import org.oic.simulator.AttributeProperty; +import org.oic.simulator.AttributeValue; +import org.oic.simulator.AttributeValue.TypeInfo; +import org.oic.simulator.AttributeValue.ValueType; +import org.oic.simulator.InvalidArgsException; +import org.oic.simulator.SimulatorResourceAttribute; +import org.oic.simulator.SimulatorResourceModel; +import org.oic.simulator.server.SimulatorResource.AutoUpdateType; /** * This class provides editing support to the resources attributes table in the @@ -50,23 +64,22 @@ public class AttributeEditingSupport { private AttributeValueEditor attValueEditor; private AutomationEditor automationEditor; - public AttributeValueEditor createAttributeValueEditor(TableViewer viewer) { + public AttributeValueEditor createAttributeValueEditor(TreeViewer viewer) { attValueEditor = new AttributeValueEditor(viewer); return attValueEditor; } - public AutomationEditor createAutomationEditor(TableViewer viewer) { + public AutomationEditor createAutomationEditor(TreeViewer viewer) { automationEditor = new AutomationEditor(viewer); return automationEditor; } class AttributeValueEditor extends EditingSupport { - private final TableViewer viewer; - private LocalResourceAttribute attributeInSelection; - private CCombo comboBox; + private final TreeViewer viewer; + private CCombo comboBox; - public AttributeValueEditor(TableViewer viewer) { + public AttributeValueEditor(TreeViewer viewer) { super(viewer); this.viewer = viewer; } @@ -77,49 +90,130 @@ public class AttributeEditingSupport { } @Override - protected CellEditor getCellEditor(Object element) { - attributeInSelection = (LocalResourceAttribute) element; + protected CellEditor getCellEditor(final Object element) { + ResourceManager resourceManager = Activator.getDefault() + .getResourceManager(); + + Resource res = resourceManager.getCurrentResourceInSelection(); + if (null == res) { + return null; + } + + // If selected resource is a collection, then editor support is not + // required. + if (res instanceof CollectionResource) { + return null; + } + + final SimulatorResourceAttribute att; + if (element instanceof SimulatorResourceAttribute + || element instanceof LocalResourceAttribute) { + if (element instanceof LocalResourceAttribute) { + LocalResourceAttribute localAtt = (LocalResourceAttribute) element; + att = localAtt.getResourceAttributeRef(); + } else { + att = (SimulatorResourceAttribute) element; + } + } else { + return null; + } + + if (null == att) { + return null; + } + + final AttributeValue val = att.value(); + if (null == val) { + return null; + } + + final TypeInfo type = val.typeInfo(); + if (type.mType == ValueType.RESOURCEMODEL + || (type.mType == ValueType.ARRAY && type.mBaseType == ValueType.RESOURCEMODEL)) { + return null; + } + + AttributeProperty prop = att.property(); + if (null == prop) { + return null; + } + + if (!resourceManager.isAttHasRangeOrAllowedValues(att)) { + return null; + } // CellEditor is not required as the automation is in progress. - if (attributeInSelection.isAutomationInProgress()) { + if (element instanceof LocalResourceAttribute + && ((LocalResourceAttribute) element) + .isAutomationInProgress()) { return null; } String values[] = null; - List valueSet = attributeInSelection.getAttValues(); + List valueSet = resourceManager + .getAllValuesOfAttribute(att); values = convertListToStringArray(valueSet); - ComboBoxCellEditor comboEditor = new ComboBoxCellEditor( - viewer.getTable(), values, SWT.READ_ONLY); + ComboBoxCellEditor comboEditor; + if (type.mType == ValueType.ARRAY) { + comboEditor = new ComboBoxCellEditor(viewer.getTree(), values); + } else { + comboEditor = new ComboBoxCellEditor(viewer.getTree(), values, + SWT.READ_ONLY); + } comboBox = (CCombo) comboEditor.getControl(); comboBox.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent event) { - String oldValue = String.valueOf(attributeInSelection - .getAttributeValue()); + if (type.mType == ValueType.ARRAY) { + return; + } + String oldValue = String.valueOf(Utility + .getAttributeValueAsString(val)); String newValue = comboBox.getText(); if (!oldValue.equals(newValue)) { - attributeInSelection.setAttributeValue(newValue); - MessageBox dialog = new MessageBox(viewer.getTable() - .getShell(), SWT.ICON_QUESTION | SWT.OK - | SWT.CANCEL); - dialog.setText("Confirm action"); - dialog.setMessage("Do you want to modify the value?"); - int retval = dialog.open(); - if (retval != SWT.OK) { - attributeInSelection.setAttributeValue(oldValue); + // Get the AttriuteValue from the string + AttributeValue value = AttributeValueBuilder.build( + newValue, type.mBaseType); + TypeInfo resTypeInfo = value.typeInfo(); + if (null == value || type.mDepth != resTypeInfo.mDepth + || type.mType != resTypeInfo.mType + || type.mBaseType != resTypeInfo.mBaseType) { + MessageBox dialog = new MessageBox(viewer.getTree() + .getShell(), SWT.ICON_ERROR | SWT.OK); + dialog.setText("Invalid Value"); + dialog.setMessage("Given value is invalid"); + dialog.open(); } else { - ResourceManager resourceManager; - resourceManager = Activator.getDefault() - .getResourceManager(); - SimulatorResource resource = resourceManager - .getCurrentResourceInSelection(); - resourceManager.attributeValueUpdated(resource, - attributeInSelection.getAttributeName(), - newValue); + updateAttributeValue(att, value); + MessageBox dialog = new MessageBox(viewer.getTree() + .getShell(), SWT.ICON_QUESTION | SWT.OK + | SWT.CANCEL); + dialog.setText("Confirm action"); + dialog.setMessage("Do you want to modify the value?"); + int retval = dialog.open(); + if (retval != SWT.OK) { + value = AttributeValueBuilder.build(oldValue, + type.mBaseType); + updateAttributeValue(att, value); + } else { + ResourceManager resourceManager; + resourceManager = Activator.getDefault() + .getResourceManager(); + + Resource resource = resourceManager + .getCurrentResourceInSelection(); + + AttributeValue resultValue = getResultantValue(value); + + resourceManager.attributeValueUpdated( + (SingleResource) resource, att.name(), + resultValue); + + } } - viewer.update(attributeInSelection, null); + viewer.update(element, null); comboBox.setVisible(false); } } @@ -130,9 +224,23 @@ public class AttributeEditingSupport { @Override protected Object getValue(Object element) { int indexOfItem = 0; - LocalResourceAttribute att = (LocalResourceAttribute) element; - String valueString = String.valueOf(att.getAttributeValue()); - List valueSet = att.getAttValues(); + SimulatorResourceAttribute att; + + if (element instanceof LocalResourceAttribute) { + LocalResourceAttribute localAtt = (LocalResourceAttribute) element; + att = localAtt.getResourceAttributeRef(); + if (null == att) { + return 0; + } + } else if (element instanceof SimulatorResourceAttribute) { + att = (SimulatorResourceAttribute) element; + } else { + return 0; + } + + String valueString = Utility.getAttributeValueAsString(att.value()); + List valueSet = Activator.getDefault().getResourceManager() + .getAllValuesOfAttribute(att); if (null != valueSet) { indexOfItem = valueSet.indexOf(valueString); } @@ -144,11 +252,81 @@ public class AttributeEditingSupport { @Override protected void setValue(Object element, Object value) { - Object valueObj = attributeInSelection.getAttributeValue(); - if (null == valueObj) + SimulatorResourceAttribute att; + + if (element instanceof LocalResourceAttribute) { + LocalResourceAttribute localAtt = (LocalResourceAttribute) element; + att = localAtt.getResourceAttributeRef(); + if (null == att) { + return; + } + } else if (element instanceof SimulatorResourceAttribute) { + att = (SimulatorResourceAttribute) element; + } else { + return; + } + + AttributeValue val = att.value(); + if (null == val) { return; - String attValue = String.valueOf(valueObj); - ((LocalResourceAttribute) element).setAttributeValue(attValue); + } + TypeInfo type = val.typeInfo(); + if (type.mType == ValueType.ARRAY) { + int index; + try { + index = Integer.parseInt(String.valueOf(value)); + } catch (NumberFormatException nfe) { + index = -1; + } + if (index == -1) { + String oldValue = String.valueOf(Utility + .getAttributeValueAsString(val)); + String newValue = comboBox.getText(); + if (!oldValue.equals(newValue)) { + // Get the AttriuteValue from the string + AttributeValue attValue = AttributeValueBuilder.build( + newValue, type.mBaseType); + TypeInfo resTypeInfo = attValue.typeInfo(); + if (null == attValue + || type.mDepth != resTypeInfo.mDepth + || type.mType != resTypeInfo.mType + || type.mBaseType != resTypeInfo.mBaseType) { + MessageBox dialog = new MessageBox(viewer.getTree() + .getShell(), SWT.ICON_ERROR | SWT.OK); + dialog.setText("Invalid Value"); + dialog.setMessage("Given value is invalid"); + dialog.open(); + } else { + updateAttributeValue(att, attValue); + MessageBox dialog = new MessageBox(viewer.getTree() + .getShell(), SWT.ICON_QUESTION | SWT.OK + | SWT.CANCEL); + dialog.setText("Confirm action"); + dialog.setMessage("Do you want to modify the value?"); + int retval = dialog.open(); + if (retval != SWT.OK) { + attValue = AttributeValueBuilder.build( + oldValue, type.mBaseType); + updateAttributeValue(att, attValue); + } else { + ResourceManager resourceManager; + resourceManager = Activator.getDefault() + .getResourceManager(); + + Resource resource = resourceManager + .getCurrentResourceInSelection(); + + AttributeValue resultValue = getResultantValue(attValue); + + resourceManager.attributeValueUpdated( + (SingleResource) resource, att.name(), + resultValue); + } + } + } + } + } + viewer.update(element, null); } @@ -161,13 +339,119 @@ public class AttributeEditingSupport { } return strArr; } + + public void updateAttributeValue(SimulatorResourceAttribute att, + AttributeValue value) { + att.setValue(value); + + IStructuredSelection selection = (IStructuredSelection) viewer + .getSelection(); + if (null == selection) { + return; + } + + Object obj = selection.getFirstElement(); + if (null == obj) { + return; + } + + Tree t = viewer.getTree(); + TreeItem item = t.getSelection()[0]; + if (null == item) { + return; + } + TreeItem parent = item.getParentItem(); + + // Get the parent model + if (null == parent) { + // Top-level attribute + Resource res = Activator.getDefault().getResourceManager() + .getCurrentResourceInSelection(); + if (null == res) { + return; + } + SimulatorResourceModel model = res.getResourceModel(); + if (null == model) { + return; + } + try { + model.setAttributeValue(att.name(), value); + } catch (InvalidArgsException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } else { + SimulatorResourceModel model; + Object data = parent.getData(); + if (null == data) { + return; + } + if (data instanceof SRMItem) { + model = ((SRMItem) data).getModel(); + } else { + SimulatorResourceAttribute parentAtt; + if (data instanceof LocalResourceAttribute) { + parentAtt = ((LocalResourceAttribute) data) + .getResourceAttributeRef(); + } else { + parentAtt = (SimulatorResourceAttribute) data; + } + model = (SimulatorResourceModel) parentAtt.value().get(); + } + try { + model.setAttributeValue(att.name(), value); + } catch (InvalidArgsException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + + public AttributeValue getResultantValue(AttributeValue newValue) { + AttributeValue val = null; + IStructuredSelection selection = (IStructuredSelection) viewer + .getSelection(); + if (null == selection) { + return null; + } + + Object obj = selection.getFirstElement(); + if (null == obj) { + return null; + } + + Tree t = viewer.getTree(); + TreeItem item = t.getSelection()[0]; + if (null == item) { + return null; + } + + TreeItem parent = item.getParentItem(); + if (null == parent) { + Object data = item.getData(); + // SimulatorResourceAttribute att = + // ((LocalResourceAttribute)data).getResourceAttributeRef(); + val = newValue; + } else { + while (parent.getParentItem() != null) { + parent = parent.getParentItem(); + } + // Parent will point to the top-level attribute of type + // LocalResourceAttribute + Object data = parent.getData(); + val = ((LocalResourceAttribute) data).getResourceAttributeRef() + .value(); + } + + return val; + } } class AutomationEditor extends EditingSupport { - private final TableViewer viewer; + private final TreeViewer viewer; - public AutomationEditor(TableViewer viewer) { + public AutomationEditor(TreeViewer viewer) { super(viewer); this.viewer = viewer; } @@ -182,11 +466,41 @@ public class AttributeEditingSupport { // CellEditor is not required as the automation is in progress. ResourceManager resourceManager = Activator.getDefault() .getResourceManager(); - SimulatorResource resource = resourceManager - .getCurrentResourceInSelection(); - if (null != resource && resource.isResourceAutomationInProgress()) { + Resource resource = resourceManager.getCurrentResourceInSelection(); + + if (null == resource) { return null; } + + if (resource instanceof CollectionResource) { + return null; + } + if (((SingleResource) resource).isResourceAutomationInProgress()) { + return null; + } + + SimulatorResourceAttribute att = null; + if (element instanceof LocalResourceAttribute) { + LocalResourceAttribute localAtt = (LocalResourceAttribute) element; + att = localAtt.getResourceAttributeRef(); + } + + if (null == att) { + return null; + } + + AttributeValue val = att.value(); + if (null == val) { + return null; + } + + TypeInfo type = val.typeInfo(); + + if (type.mType == ValueType.RESOURCEMODEL + || type.mType == ValueType.ARRAY) { + return null; + } + return new CheckboxCellEditor(null, SWT.CHECK | SWT.READ_ONLY); } @@ -202,8 +516,7 @@ public class AttributeEditingSupport { .getResourceManager(); // As automation depends on the current resource in selection, its // presence is being checked. - SimulatorResource resource = resourceManager - .getCurrentResourceInSelection(); + Resource resource = resourceManager.getCurrentResourceInSelection(); if (null == resource) { return; } @@ -219,18 +532,18 @@ public class AttributeEditingSupport { // Open the settings dialog AutomationSettingDialog dialog = new AutomationSettingDialog( - viewer.getTable().getShell(), automationSettings); + viewer.getTree().getShell(), automationSettings); dialog.create(); if (dialog.open() == Window.OK) { String automationType = dialog.getAutomationType(); String updateFreq = dialog.getUpdateFrequency(); - AutomationType autoType = AutomationType + AutoUpdateType autoType = AutoUpdateType .valueOf(automationType); int updFreq = Utility .getUpdateIntervalFromString(updateFreq); - int autoId = resourceManager.startAutomation(resource, att, - autoType, updFreq); + int autoId = resourceManager.startAutomation( + (SingleResource) resource, att, autoType, updFreq); if (autoId == -1) { MessageDialog.openInformation(Display.getDefault() .getActiveShell(), "Automation Status", @@ -241,7 +554,7 @@ public class AttributeEditingSupport { } } else { // Stop the automation - resourceManager.stopAutomation(resource, att, + resourceManager.stopAutomation((SingleResource) resource, att, att.getAutomationId()); MessageDialog.openInformation(Display.getDefault() .getActiveShell(), "Automation Status", 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 index d4443b4..f81bda6 100644 --- 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 @@ -17,25 +17,29 @@ package oic.simulator.serviceprovider.view; import java.util.List; -import java.util.Set; +import java.util.Map; import oic.simulator.serviceprovider.Activator; import oic.simulator.serviceprovider.listener.IAutomationUIListener; import oic.simulator.serviceprovider.listener.IResourceModelChangedUIListener; -import oic.simulator.serviceprovider.listener.IResourceSelectionChangedUIListener; +import oic.simulator.serviceprovider.listener.ISelectionChangedUIListener; import oic.simulator.serviceprovider.manager.ResourceManager; -import oic.simulator.serviceprovider.resource.LocalResourceAttribute; -import oic.simulator.serviceprovider.resource.ModelChangeNotificationType; -import oic.simulator.serviceprovider.resource.SimulatorResource; +import oic.simulator.serviceprovider.manager.UiListenerHandler; +import oic.simulator.serviceprovider.model.CollectionResource; +import oic.simulator.serviceprovider.model.Device; +import oic.simulator.serviceprovider.model.LocalResourceAttribute; +import oic.simulator.serviceprovider.model.Resource; +import oic.simulator.serviceprovider.model.SRMItem; +import oic.simulator.serviceprovider.model.SingleResource; import oic.simulator.serviceprovider.utils.Constants; +import oic.simulator.serviceprovider.utils.Utility; -import org.eclipse.jface.viewers.ColumnLabelProvider; -import org.eclipse.jface.viewers.IStructuredContentProvider; -import org.eclipse.jface.viewers.StyledCellLabelProvider; -import org.eclipse.jface.viewers.TableViewer; -import org.eclipse.jface.viewers.TableViewerColumn; +import org.eclipse.jface.viewers.ILabelProviderListener; +import org.eclipse.jface.viewers.ITableLabelProvider; +import org.eclipse.jface.viewers.ITreeContentProvider; +import org.eclipse.jface.viewers.TreeViewer; +import org.eclipse.jface.viewers.TreeViewerColumn; import org.eclipse.jface.viewers.Viewer; -import org.eclipse.jface.viewers.ViewerCell; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Image; @@ -44,81 +48,90 @@ import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; -import org.eclipse.swt.widgets.Table; +import org.eclipse.swt.widgets.Tree; +import org.eclipse.swt.widgets.TreeColumn; import org.eclipse.ui.part.ViewPart; +import org.oic.simulator.AttributeValue; +import org.oic.simulator.AttributeValue.TypeInfo; +import org.oic.simulator.AttributeValue.ValueType; +import org.oic.simulator.SimulatorResourceAttribute; +import org.oic.simulator.SimulatorResourceModel; /** * This class manages and shows the attribute view in the perspective. */ public class AttributeView extends ViewPart { - public static final String VIEW_ID = "oic.simulator.serviceprovider.view.attribute"; + public static final String VIEW_ID = "oic.simulator.serviceprovider.view.attribute"; - private TableViewer attTblViewer; + private TreeViewer attViewer; - private AttributeEditingSupport attributeEditor; + private AttributeEditingSupport attributeEditor; - private IResourceSelectionChangedUIListener resourceSelectionChangedListener; - private IResourceModelChangedUIListener resourceModelChangedUIListener; - private IAutomationUIListener automationUIListener; + private ISelectionChangedUIListener resourceSelectionChangedListener; + private IResourceModelChangedUIListener resourceModelChangedUIListener; + private IAutomationUIListener automationUIListener; - private final String[] attTblHeaders = { "Name", - "Value", "Automation" }; - private final Integer[] attTblColWidth = { 150, 190, - 150 }; + private final String[] attTblHeaders = { "Name", "Value", + "Automation" }; + private final Integer[] attTblColWidth = { 150, 190, 150 }; - private ResourceManager resourceManager; + private ResourceManager resourceManager; public AttributeView() { resourceManager = Activator.getDefault().getResourceManager(); - resourceSelectionChangedListener = new IResourceSelectionChangedUIListener() { + resourceSelectionChangedListener = new ISelectionChangedUIListener() { @Override - public void onResourceSelectionChange() { + public void onResourceSelectionChange(final Resource resource) { Display.getDefault().asyncExec(new Runnable() { - @Override public void run() { - if (null != attTblViewer) { - updateViewer(getData()); - SimulatorResource resource = resourceManager - .getCurrentResourceInSelection(); - Table tbl = attTblViewer.getTable(); - if (!tbl.isDisposed()) { + if (null != attViewer) { + updateViewer(getData(resource)); + Tree tree = attViewer.getTree(); + if (!tree.isDisposed()) { if (null != resource - && resource - .isResourceAutomationInProgress()) { - tbl.setEnabled(false); + && (resource instanceof SingleResource && ((SingleResource) resource) + .isResourceAutomationInProgress())) { + tree.setEnabled(false); } else { - tbl.setEnabled(true); + tree.setEnabled(true); } } } } }); } + + @Override + public void onDeviceSelectionChange(Device dev) { + Display.getDefault().asyncExec(new Runnable() { + @Override + public void run() { + updateViewer(null); + } + }); + } }; resourceModelChangedUIListener = new IResourceModelChangedUIListener() { @Override - public void onResourceModelChange( - final ModelChangeNotificationType notificationType, - final String resourceURI, - final Set valueChangeSet) { + public void onResourceModelChange(final Resource resource) { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { // Handle the notification only if it is for the current // resource in selection - SimulatorResource resource = resourceManager + Resource resourceInSelection = resourceManager .getCurrentResourceInSelection(); - if (null == resource) { + if (null == resourceInSelection) { return; } - if (!resourceURI.equals(resource.getResourceURI())) { + if (resource != resourceInSelection) { // This notification is for a different resource // whose attributes are not // currently not being shown in UI. So ignoring this @@ -127,17 +140,11 @@ public class AttributeView extends ViewPart { } // Refresh the table viewers which will display // the updated values - if (null != attTblViewer) { - if (notificationType == ModelChangeNotificationType.ATTRIBUTE_ADDED - || notificationType == ModelChangeNotificationType.ATTRIBUTE_REMOVED) { - updateViewer(getData()); - } else if (notificationType == ModelChangeNotificationType.NO_ATTRIBUTES_IN_MODEL) { - attTblViewer.setInput(null); - } else if (notificationType == ModelChangeNotificationType.ATTRIBUTE_VALUE_CHANGED) { - if (null != valueChangeSet) { - attTblViewer.update( - valueChangeSet.toArray(), null); - } + if (null != attViewer) { + if (resource instanceof CollectionResource) { + updateViewer(getData(resource)); + } else { + updateViewer(getData(resource)); } } } @@ -148,33 +155,32 @@ public class AttributeView extends ViewPart { automationUIListener = new IAutomationUIListener() { @Override - public void onResourceAutomationStart(final String resourceURI) { + public void onResourceAutomationStart(final SingleResource resource) { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { - if (null == resourceURI) { + if (null == resource) { return; } - SimulatorResource resource = resourceManager + Resource resourceInSelection = resourceManager .getCurrentResourceInSelection(); - if (null == resource) { + if (null == resourceInSelection) { return; } - String uri = resource.getResourceURI(); // Checking whether attributes view is currently // displaying the attributes of the // resource whose automation has just started - if (null != uri && uri.equals(resourceURI)) { - Table tbl; - tbl = attTblViewer.getTable(); - if (!tbl.isDisposed()) { - attTblViewer.refresh(); + if (resource == resourceInSelection) { + Tree tree; + tree = attViewer.getTree(); + if (!tree.isDisposed()) { + attViewer.refresh(); // Disabling the table to prevent interactions // during the automation - tbl.setEnabled(false); - tbl.deselectAll(); + tree.setEnabled(false); + tree.deselectAll(); } } } @@ -182,7 +188,7 @@ public class AttributeView extends ViewPart { } @Override - public void onAutomationComplete(final String resourceURI, + public void onAutomationComplete(final SingleResource resource, final String attName) { // This method notifies the completion of attribute level // automation. @@ -190,40 +196,39 @@ public class AttributeView extends ViewPart { @Override public void run() { - if (null == resourceURI) { + if (null == resource) { return; } // Check if the given resourceURI is the uri of the // resource whose attributes are currently being // displayed by this view. - SimulatorResource resource = resourceManager + Resource resourceInSelection = resourceManager .getCurrentResourceInSelection(); - if (null == resource) { + if (null == resourceInSelection) { return; } - String uri = resource.getResourceURI(); - if (null == uri || !uri.equals(resourceURI)) { + if (resource != resourceInSelection) { return; } - Table tbl; - tbl = attTblViewer.getTable(); - if (!tbl.isDisposed()) { + Tree tree; + tree = attViewer.getTree(); + if (!tree.isDisposed()) { if (null != attName) { // Attribute level automation has stopped LocalResourceAttribute att = resourceManager - .getAttributeByResourceURI(resourceURI, + .getAttributeByResourceURI(resource, attName); if (null == att) { return; } else { - attTblViewer.update(att, null); + attViewer.update(att, null); } } else { // Resource level automation has stopped // Enabling the table which was disabled at the // beginning of automation - tbl.setEnabled(true); - attTblViewer.refresh(); + tree.setEnabled(true); + attViewer.refresh(); } } } @@ -247,114 +252,74 @@ public class AttributeView extends ViewPart { attGroup.setText("Attributes"); attGroup.setBackground(color); - attTblViewer = new TableViewer(attGroup, SWT.SINGLE | SWT.H_SCROLL - | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER); + Tree addressTree = new Tree(attGroup, SWT.SINGLE | SWT.BORDER + | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION); + addressTree.setHeaderVisible(true); + + attViewer = new TreeViewer(addressTree); - createAttributeColumns(attTblViewer); + createAttributeColumns(attViewer); // make lines and header visible - Table table = attTblViewer.getTable(); - table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - table.setHeaderVisible(true); - table.setLinesVisible(true); + Tree tree = attViewer.getTree(); + tree.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + tree.setHeaderVisible(true); + tree.setLinesVisible(true); - attTblViewer.setContentProvider(new AttributeContentProvider()); + attViewer.setContentProvider(new AttributeContentProvider()); + attViewer.setLabelProvider(new AttributeLabelProvider()); addManagerListeners(); // Check whether there is any resource selected already - List propertyList = getData(); + List propertyList = getData(resourceManager + .getCurrentResourceInSelection()); if (null != propertyList) { updateViewer(propertyList); } } - public void createAttributeColumns(TableViewer tableViewer) { + public void createAttributeColumns(TreeViewer viewer) { + Tree tree = viewer.getTree(); attributeEditor = new AttributeEditingSupport(); - TableViewerColumn attName = new TableViewerColumn(tableViewer, SWT.NONE); - attName.getColumn().setWidth(attTblColWidth[0]); - attName.getColumn().setText(attTblHeaders[0]); - attName.setLabelProvider(new StyledCellLabelProvider() { - @Override - public void update(ViewerCell cell) { - Object element = cell.getElement(); - if (element instanceof LocalResourceAttribute) { - LocalResourceAttribute attribute = (LocalResourceAttribute) element; - if (null != attribute) { - cell.setText(attribute.getAttributeName()); - } - } - } - }); - - TableViewerColumn attValue = new TableViewerColumn(tableViewer, - SWT.NONE); - attValue.getColumn().setWidth(attTblColWidth[1]); - attValue.getColumn().setText(attTblHeaders[1]); - attValue.setLabelProvider(new ColumnLabelProvider() { - @Override - public String getText(Object element) { - if (element instanceof LocalResourceAttribute) { - LocalResourceAttribute attribute = (LocalResourceAttribute) element; - if (null != attribute) { - Object val = attribute.getAttributeValue(); - if (null != val) { - return String.valueOf(val); - } - } - } - return ""; - } - }); - attValue.setEditingSupport(attributeEditor - .createAttributeValueEditor(attTblViewer)); - - TableViewerColumn automation = new TableViewerColumn(tableViewer, - SWT.NONE); - automation.getColumn().setWidth(attTblColWidth[2]); - automation.getColumn().setText(attTblHeaders[2]); - automation.setLabelProvider(new ColumnLabelProvider() { - @Override - public String getText(Object element) { - LocalResourceAttribute att = (LocalResourceAttribute) element; - if (att.isAutomationInProgress()) { - return Constants.ENABLED; - } - return Constants.DISABLED; - } - - @Override - public Image getImage(Object element) { - LocalResourceAttribute att = (LocalResourceAttribute) element; - if (att.isAutomationInProgress()) { - return Activator.getDefault().getImageRegistry() - .get(Constants.CHECKED); - } else { - return Activator.getDefault().getImageRegistry() - .get(Constants.UNCHECKED); - } - } - }); - automation.setEditingSupport(attributeEditor - .createAutomationEditor(attTblViewer)); + TreeColumn attName = new TreeColumn(tree, SWT.NONE); + attName.setWidth(attTblColWidth[0]); + attName.setText(attTblHeaders[0]); + + TreeColumn attValue = new TreeColumn(tree, SWT.NONE); + attValue.setWidth(attTblColWidth[1]); + attValue.setText(attTblHeaders[1]); + TreeViewerColumn attValueVwrCol = new TreeViewerColumn(attViewer, + attValue); + attValueVwrCol.setEditingSupport(attributeEditor + .createAttributeValueEditor(attViewer)); + + TreeColumn automation = new TreeColumn(tree, SWT.NONE); + automation.setWidth(attTblColWidth[2]); + automation.setText(attTblHeaders[2]); + TreeViewerColumn automationVwrCol = new TreeViewerColumn(attViewer, + automation); + automationVwrCol.setEditingSupport(attributeEditor + .createAutomationEditor(attViewer)); } private void addManagerListeners() { - resourceManager - .addResourceSelectionChangedUIListener(resourceSelectionChangedListener); - resourceManager - .addResourceModelChangedUIListener(resourceModelChangedUIListener); - resourceManager.addAutomationUIListener(automationUIListener); + UiListenerHandler.getInstance().addResourceSelectionChangedUIListener( + resourceSelectionChangedListener); + UiListenerHandler.getInstance().addResourceModelChangedUIListener( + resourceModelChangedUIListener); + UiListenerHandler.getInstance().addAutomationUIListener( + automationUIListener); } - private List getData() { - SimulatorResource resourceInSelection = resourceManager - .getCurrentResourceInSelection(); - if (null != resourceInSelection) { + private List getData(Resource resource) { + if (null != resource) { List attList = resourceManager - .getAttributes(resourceInSelection); + .getAttributes((Resource) resource); + // List attList = + // Utility.getDummyAttributes(); return attList; } else { return null; @@ -362,27 +327,25 @@ public class AttributeView extends ViewPart { } private void updateViewer(List attList) { - Table tbl; + Tree tree = attViewer.getTree();; if (null != attList) { - tbl = attTblViewer.getTable(); - if (null != tbl && !tbl.isDisposed()) { - tbl.setLinesVisible(true); - attTblViewer.setInput(attList.toArray()); + if (null != tree && !tree.isDisposed()) { + tree.setLinesVisible(true); + attViewer.setInput(attList.toArray()); } } else { // Clear the attributes table viewer - if (null != attTblViewer) { - tbl = attTblViewer.getTable(); - if (null != tbl && !tbl.isDisposed()) { + if (null != attViewer) { + if (null != tree && !tree.isDisposed()) { // tbl.deselectAll(); - tbl.removeAll(); - tbl.setLinesVisible(false); + tree.removeAll(); + tree.setLinesVisible(false); } } } } - class AttributeContentProvider implements IStructuredContentProvider { + class AttributeContentProvider implements ITreeContentProvider { @Override public void dispose() { @@ -393,8 +356,248 @@ public class AttributeView extends ViewPart { } @Override + public Object[] getChildren(Object element) { + if (element instanceof SimulatorResourceAttribute + || element instanceof LocalResourceAttribute) { + SimulatorResourceAttribute att; + if (element instanceof LocalResourceAttribute) { + LocalResourceAttribute localAtt = (LocalResourceAttribute) element; + att = localAtt.getResourceAttributeRef(); + if (null == att) { + return new Object[1]; + } + } else { + att = (SimulatorResourceAttribute) element; + } + AttributeValue val = att.value(); + if (null == val) { + return new Object[1]; + } + TypeInfo type = val.typeInfo(); + if (type.mType == ValueType.RESOURCEMODEL) { + SimulatorResourceModel model = (SimulatorResourceModel) val + .get(); + if (null == model) { + return new Object[1]; + } + return resourceManager.getAttributes(model).toArray(); + } else if (type.mType == ValueType.ARRAY + && type.mBaseType == ValueType.RESOURCEMODEL + && type.mDepth == 1) { + SimulatorResourceModel[] model = (SimulatorResourceModel[]) val + .get(); + if (null == model || model.length < 1) { + return new Object[1]; + } + return resourceManager.getIndexedAttributes(model) + .toArray(); + } + } else if (element instanceof SRMItem) { + SRMItem item = (SRMItem) element; + SimulatorResourceModel model = (SimulatorResourceModel) item + .getModel(); + if (null == model) { + return new Object[1]; + } + return resourceManager.getAttributes(model).toArray(); + } + return new Object[1]; + } + + @Override public Object[] getElements(Object element) { - return (Object[]) element; + Object[] elements = (Object[]) element; + return elements; + } + + @Override + public Object getParent(Object element) { + return null; + } + + @Override + public boolean hasChildren(Object element) { + if (element instanceof SimulatorResourceAttribute + || element instanceof LocalResourceAttribute) { + SimulatorResourceAttribute att; + if (element instanceof LocalResourceAttribute) { + LocalResourceAttribute localAtt = (LocalResourceAttribute) element; + att = localAtt.getResourceAttributeRef(); + if (null == att) { + return false; + } + } else { + att = (SimulatorResourceAttribute) element; + } + AttributeValue val = att.value(); + if (null == val) { + return false; + } + TypeInfo type = val.typeInfo(); + if (type.mType == ValueType.RESOURCEMODEL) { + SimulatorResourceModel model = (SimulatorResourceModel) val + .get(); + if (null == model) { + return false; + } + Map attributes = model + .getAttributes(); + if (null != attributes && attributes.size() > 0) { + return true; + } + } else if (type.mType == ValueType.ARRAY + && type.mBaseType == ValueType.RESOURCEMODEL + && type.mDepth == 1) { + SimulatorResourceModel[] model = (SimulatorResourceModel[]) val + .get(); + if (null != model && model.length > 0) { + return true; + } + } + } else if (element instanceof SRMItem) { + SRMItem srmItem = (SRMItem) element; + SimulatorResourceModel model = srmItem.getModel(); + if (null == model) { + return false; + } + Map attributes = model + .getAttributes(); + if (null != attributes && attributes.size() > 0) { + return true; + } + } + return false; + } + } + + class AttributeLabelProvider implements ITableLabelProvider { + + @Override + public void addListener(ILabelProviderListener arg0) { + } + + @Override + public void dispose() { + } + + @Override + public boolean isLabelProperty(Object arg0, String arg1) { + return false; + } + + @Override + public void removeListener(ILabelProviderListener arg0) { + + } + + @Override + public Image getColumnImage(Object element, int col) { + if (col == 2) { + if (element instanceof SimulatorResourceAttribute + || element instanceof LocalResourceAttribute) { + SimulatorResourceAttribute att; + if (element instanceof LocalResourceAttribute) { + LocalResourceAttribute localAtt = (LocalResourceAttribute) element; + att = localAtt.getResourceAttributeRef(); + } else { + att = (SimulatorResourceAttribute) element; + } + AttributeValue val = att.value(); + if (null == val) { + return null; + } + TypeInfo type = val.typeInfo(); + if (type.mType == ValueType.RESOURCEMODEL + || type.mType == ValueType.ARRAY) { + return null; + } + if (element instanceof LocalResourceAttribute) { + if (!resourceManager.isAttHasRangeOrAllowedValues(att)) { + System.out.println("No range or allowed values"); + return null; + } + if (((LocalResourceAttribute) element) + .isAutomationInProgress()) { + return Activator.getDefault().getImageRegistry() + .get(Constants.CHECKED); + } + return Activator.getDefault().getImageRegistry() + .get(Constants.UNCHECKED); + } + return null; + } + } + return null; + } + + @Override + public String getColumnText(Object element, int col) { + if (element instanceof SimulatorResourceAttribute + || element instanceof LocalResourceAttribute) { + SimulatorResourceAttribute att; + if (element instanceof LocalResourceAttribute) { + LocalResourceAttribute localAtt = (LocalResourceAttribute) element; + att = localAtt.getResourceAttributeRef(); + } else { + att = (SimulatorResourceAttribute) element; + } + AttributeValue val = att.value(); + if (null == val) { + return ""; + } + TypeInfo type = val.typeInfo(); + switch (col) { + case 0: + return att.name(); + case 1: + if (!(type.mType == ValueType.RESOURCEMODEL || (type.mType == ValueType.ARRAY && type.mBaseType == ValueType.RESOURCEMODEL))) { + String value = Utility + .getAttributeValueAsString(val); + if (null == value) { + value = ""; + } + return value; + } else { + return ""; + } + case 2: + Resource res = resourceManager + .getCurrentResourceInSelection(); + if (null != res && res instanceof CollectionResource) { + return "-"; + } + + if (type.mType == ValueType.RESOURCEMODEL + || type.mType == ValueType.ARRAY) { + return ""; + } + if (element instanceof LocalResourceAttribute) { + if (!resourceManager + .isAttHasRangeOrAllowedValues(att)) { + System.out + .println("No range or allowed values"); + return "Read Only"; + } + if (((LocalResourceAttribute) element) + .isAutomationInProgress()) { + return Constants.ENABLED; + } + return Constants.DISABLED; + } + return "NA"; + } + } else if (element instanceof SRMItem) { + SRMItem item = (SRMItem) element; + switch (col) { + case 0: + return "[" + item.getIndex() + "]"; + case 1: + return ""; + case 2: + return ""; + } + } + return null; } } @@ -403,19 +606,22 @@ public class AttributeView extends ViewPart { public void dispose() { // Unregister the selection listener if (null != resourceSelectionChangedListener) { - resourceManager - .removeResourceSelectionChangedUIListener(resourceSelectionChangedListener); + UiListenerHandler.getInstance() + .removeResourceSelectionChangedUIListener( + resourceSelectionChangedListener); } // Unregister the model change listener if (null != resourceModelChangedUIListener) { - resourceManager - .removeResourceModelChangedUIListener(resourceModelChangedUIListener); + UiListenerHandler.getInstance() + .removeResourceModelChangedUIListener( + resourceModelChangedUIListener); } // Unregister the automation complete listener if (null != automationUIListener) { - resourceManager.removeAutomationUIListener(automationUIListener); + UiListenerHandler.getInstance().removeAutomationUIListener( + automationUIListener); } super.dispose(); diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/DevicePlatformInfoView.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/DevicePlatformInfoView.java new file mode 100644 index 0000000..b8ebf77 --- /dev/null +++ b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/DevicePlatformInfoView.java @@ -0,0 +1,377 @@ +/* + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package oic.simulator.serviceprovider.view; + +import java.util.List; + +import oic.simulator.serviceprovider.Activator; +import oic.simulator.serviceprovider.model.MetaProperty; + +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.viewers.CellEditor; +import org.eclipse.jface.viewers.ColumnLabelProvider; +import org.eclipse.jface.viewers.EditingSupport; +import org.eclipse.jface.viewers.IStructuredContentProvider; +import org.eclipse.jface.viewers.StyledCellLabelProvider; +import org.eclipse.jface.viewers.TableViewer; +import org.eclipse.jface.viewers.TableViewerColumn; +import org.eclipse.jface.viewers.TextCellEditor; +import org.eclipse.jface.viewers.Viewer; +import org.eclipse.jface.viewers.ViewerCell; +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.CTabFolder; +import org.eclipse.swt.custom.CTabItem; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Group; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Table; +import org.eclipse.swt.widgets.Text; +import org.eclipse.ui.part.ViewPart; + +/** + * This class is used to set the platform and device information. The + * information is only one per stack and hence only one instance can be + * stored/used at a time. + */ +public class DevicePlatformInfoView extends ViewPart { + + public static final String VIEW_ID = "oic.simulator.serviceprovider.view.devplatinfo"; + + private final String[] columnHeaders = { "Property", "Value" }; + + private final Integer[] columnWidth = { 150, 150 }; + + private List metaProperties; + + private boolean enable_edit; + + private Text deviceNameTxt; + private Button devEditBtn; + private Button devCancelBtn; + private Button platEditBtn; + private Button platCancelBtn; + + private TableViewer platformTblViewer; + + private CTabFolder folder; + private CTabItem devicePropTab; + private CTabItem platformPropTab; + + @Override + public void createPartControl(Composite parent) { + parent.setLayout(new GridLayout()); + GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); + parent.setLayoutData(gd); + + // Create a Tab Folder. + folder = new CTabFolder(parent, SWT.BORDER); + gd = new GridData(SWT.FILL, SWT.FILL, true, true); + folder.setLayoutData(gd); + folder.setSimple(false); + folder.setUnselectedCloseVisible(false); + folder.setUnselectedImageVisible(false); + + createDevicePropertiesTab(); + + createPlatformPropertiesTab(); + + folder.setSelection(devicePropTab); + + metaProperties = getPlatformPropData(); + + updateViewer(metaProperties); + } + + private void createDevicePropertiesTab() { + devicePropTab = new CTabItem(folder, SWT.NULL); + devicePropTab.setText("Device"); + + // Adding the group to the folder. + Group propGroup = new Group(folder, SWT.NONE); + + Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE); + propGroup.setBackground(color); + + propGroup.setLayout(new GridLayout(2, false)); + GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); + gd.horizontalIndent = 5; + gd.verticalIndent = 5; + propGroup.setLayoutData(gd); + + Label devNameLbl = new Label(propGroup, SWT.NULL); + devNameLbl.setText("Device Name"); + gd = new GridData(); + gd.horizontalAlignment = SWT.FILL; + gd.grabExcessHorizontalSpace = true; + gd.horizontalSpan = 2; + devNameLbl.setLayoutData(gd); + + deviceNameTxt = new Text(propGroup, SWT.BORDER); + deviceNameTxt.setText(Activator.getDefault().getResourceManager() + .getDeviceName()); + gd = new GridData(); + gd.horizontalAlignment = SWT.FILL; + gd.grabExcessHorizontalSpace = true; + gd.horizontalSpan = 2; + deviceNameTxt.setLayoutData(gd); + deviceNameTxt.setEnabled(false); + + devEditBtn = new Button(propGroup, SWT.PUSH); + devEditBtn.setText("Edit"); + gd = new GridData(); + gd.widthHint = 50; + devEditBtn.setLayoutData(gd); + devEditBtn.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + if (devEditBtn.getText().equals("Edit")) { + deviceNameTxt.setEnabled(true); + devCancelBtn.setEnabled(true); + + deviceNameTxt.selectAll(); + deviceNameTxt.setFocus(); + devEditBtn.setText("Save"); + } else { + String devName = deviceNameTxt.getText(); + if (null == devName || devName.trim().length() < 1) { + MessageDialog.openError(Display.getDefault() + .getActiveShell(), "Invalid Device Name", + "Device name is Invalid!!"); + deviceNameTxt.setFocus(); + return; + } + Activator.getDefault().getResourceManager() + .setDeviceName(devName); + deviceNameTxt.setEnabled(false); + devCancelBtn.setEnabled(false); + devEditBtn.setText("Edit"); + } + } + }); + + devCancelBtn = new Button(propGroup, SWT.PUSH); + devCancelBtn.setText("Cancel"); + devCancelBtn.setEnabled(false); + gd = new GridData(); + gd.widthHint = 70; + devCancelBtn.setLayoutData(gd); + devCancelBtn.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + deviceNameTxt.setText(Activator.getDefault() + .getResourceManager().getDeviceName()); + deviceNameTxt.setEnabled(false); + devCancelBtn.setEnabled(false); + devEditBtn.setText("Edit"); + } + }); + + devicePropTab.setControl(propGroup); + } + + private void createPlatformPropertiesTab() { + platformPropTab = new CTabItem(folder, SWT.NULL); + platformPropTab.setText("Platform"); + + // Adding the group to the folder. + Group propGroup = new Group(folder, SWT.NONE); + + Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE); + propGroup.setBackground(color); + + propGroup.setLayout(new GridLayout(2, false)); + GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); + propGroup.setLayoutData(gd); + + platformTblViewer = new TableViewer(propGroup, SWT.SINGLE + | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER); + + createColumns(platformTblViewer); + + // Make lines and header visible + final Table table = platformTblViewer.getTable(); + table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + table.setHeaderVisible(true); + table.setLinesVisible(true); + gd = new GridData(SWT.FILL, SWT.FILL, true, true); + gd.horizontalSpan = 2; + table.setLayoutData(gd); + + platformTblViewer.setContentProvider(new PropertycontentProvider()); + + platEditBtn = new Button(propGroup, SWT.PUSH); + platEditBtn.setText("Edit"); + gd = new GridData(); + gd.widthHint = 50; + platEditBtn.setLayoutData(gd); + platEditBtn.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + if (platEditBtn.getText().equals("Edit")) { + platCancelBtn.setEnabled(true); + platEditBtn.setText("Save"); + enable_edit = true; + } else { + Activator.getDefault().getResourceManager() + .setPlatformInfo(metaProperties); + platCancelBtn.setEnabled(false); + platEditBtn.setText("Edit"); + enable_edit = false; + } + } + }); + + platCancelBtn = new Button(propGroup, SWT.PUSH); + platCancelBtn.setText("Cancel"); + platCancelBtn.setEnabled(false); + gd = new GridData(); + gd.widthHint = 70; + platCancelBtn.setLayoutData(gd); + platCancelBtn.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + metaProperties = getPlatformPropData(); + updateViewer(metaProperties); + + platCancelBtn.setEnabled(false); + platEditBtn.setText("Edit"); + enable_edit = false; + } + }); + + platformPropTab.setControl(propGroup); + } + + public void createColumns(TableViewer tableViewer) { + TableViewerColumn propName = new TableViewerColumn(tableViewer, + SWT.NONE); + propName.getColumn().setWidth(columnWidth[0]); + propName.getColumn().setText(columnHeaders[0]); + propName.setLabelProvider(new StyledCellLabelProvider() { + @Override + public void update(ViewerCell cell) { + MetaProperty prop = (MetaProperty) cell.getElement(); + cell.setText(prop.getPropName()); + super.update(cell); + } + }); + + TableViewerColumn propValue = new TableViewerColumn(tableViewer, + SWT.NONE); + propValue.getColumn().setWidth(columnWidth[1]); + propValue.getColumn().setText(columnHeaders[1]); + propValue.setLabelProvider(new ColumnLabelProvider() { + @Override + public String getText(Object element) { + MetaProperty prop = (MetaProperty) element; + if (null != prop) { + return prop.getPropValue(); + } else { + return ""; + } + } + }); + propValue.setEditingSupport(new PropValueEditor(platformTblViewer)); + } + + class PropertycontentProvider implements IStructuredContentProvider { + + @Override + public void dispose() { + } + + @Override + public void inputChanged(Viewer arg0, Object arg1, Object arg2) { + } + + @Override + public Object[] getElements(Object element) { + return (Object[]) element; + } + } + + private List getPlatformPropData() { + List metaPropertyList = Activator.getDefault() + .getResourceManager().getPlatformInfo(); + return metaPropertyList; + } + + private void updateViewer(List metaPropertyList) { + if (null != platformTblViewer) { + Table tbl = platformTblViewer.getTable(); + if (null != metaPropertyList) { + platformTblViewer.setInput(metaPropertyList.toArray()); + if (!tbl.isDisposed()) { + tbl.setLinesVisible(true); + } + } else { + if (!tbl.isDisposed()) { + tbl.removeAll(); + tbl.setLinesVisible(false); + } + } + } + } + + class PropValueEditor extends EditingSupport { + + private final TableViewer viewer; + + public PropValueEditor(TableViewer viewer) { + super(viewer); + this.viewer = viewer; + } + + @Override + protected boolean canEdit(Object element) { + return true; + } + + @Override + protected CellEditor getCellEditor(Object element) { + if (!enable_edit) { + return null; + } + CellEditor editor = new TextCellEditor(viewer.getTable()); + return editor; + } + + @Override + protected Object getValue(Object element) { + return ((MetaProperty) element).getPropValue(); + } + + @Override + protected void setValue(Object element, Object value) { + MetaProperty prop = (MetaProperty) element; + prop.setPropValue(String.valueOf(value)); + viewer.update(element, null); + } + + } + + @Override + public void setFocus() { + } +} \ No newline at end of file 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 index 8f8ff18..c8f6668 100644 --- 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 @@ -19,57 +19,92 @@ package oic.simulator.serviceprovider.view; import java.util.List; import oic.simulator.serviceprovider.Activator; -import oic.simulator.serviceprovider.listener.IResourceSelectionChangedUIListener; +import oic.simulator.serviceprovider.listener.ISelectionChangedUIListener; import oic.simulator.serviceprovider.manager.ResourceManager; -import oic.simulator.serviceprovider.resource.MetaProperty; -import oic.simulator.serviceprovider.resource.SimulatorResource; - +import oic.simulator.serviceprovider.manager.UiListenerHandler; +import oic.simulator.serviceprovider.model.Device; +import oic.simulator.serviceprovider.model.MetaProperty; +import oic.simulator.serviceprovider.model.Resource; +import oic.simulator.serviceprovider.utils.Constants; + +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.viewers.CellEditor; import org.eclipse.jface.viewers.ColumnLabelProvider; +import org.eclipse.jface.viewers.EditingSupport; import org.eclipse.jface.viewers.IStructuredContentProvider; +import org.eclipse.jface.viewers.StyledCellLabelProvider; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TableViewerColumn; +import org.eclipse.jface.viewers.TextCellEditor; import org.eclipse.jface.viewers.Viewer; +import org.eclipse.jface.viewers.ViewerCell; import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Table; import org.eclipse.ui.part.ViewPart; +import org.oic.simulator.SimulatorException; /** * This class manages and shows the meta properties view in the perspective. */ public class MetaPropertiesView extends ViewPart { - public static final String VIEW_ID = "oic.simulator.serviceprovider.view.metaproperties"; + public static final String VIEW_ID = "oic.simulator.serviceprovider.view.metaproperties"; + + private TableViewer tableViewer; + + private final String[] columnHeaders = { "Property", "Value" }; - private TableViewer tableViewer; + private final Integer[] columnWidth = { 150, 150 }; - private final String[] columnHeaders = { "Property", - "Value" }; + private ISelectionChangedUIListener resourceSelectionChangedListener; - private final Integer[] columnWidth = { 150, 150 }; + private ResourceManager resourceManagerRef; - private IResourceSelectionChangedUIListener resourceSelectionChangedListener; + private List properties; - private ResourceManager resourceManagerRef; + private boolean enable_edit; + private Button editBtn; + private Button cancelBtn; public MetaPropertiesView() { resourceManagerRef = Activator.getDefault().getResourceManager(); - resourceSelectionChangedListener = new IResourceSelectionChangedUIListener() { + resourceSelectionChangedListener = new ISelectionChangedUIListener() { @Override - public void onResourceSelectionChange() { + public void onResourceSelectionChange(final Resource resource) { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { if (null != tableViewer) { - updateViewer(getData()); + properties = getData(resource); + updateViewer(properties); } + updateEditControls(resource); + } + }); + } + + @Override + public void onDeviceSelectionChange(final Device dev) { + Display.getDefault().asyncExec(new Runnable() { + + @Override + public void run() { + if (null != tableViewer) { + properties = getData(dev); + updateViewer(properties); + } + updateEditControls(dev); } }); } @@ -77,8 +112,8 @@ public class MetaPropertiesView extends ViewPart { } @Override - public void createPartControl(Composite parent) { - parent.setLayout(new GridLayout(1, false)); + public void createPartControl(final Composite parent) { + parent.setLayout(new GridLayout(2, false)); tableViewer = new TableViewer(parent, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER); @@ -87,28 +122,211 @@ public class MetaPropertiesView extends ViewPart { // Make lines and header visible final Table table = tableViewer.getTable(); - table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); + gd.horizontalSpan = 2; + table.setLayoutData(gd); table.setHeaderVisible(true); table.setLinesVisible(true); tableViewer.setContentProvider(new PropertycontentProvider()); + editBtn = new Button(parent, SWT.PUSH); + editBtn.setText("Edit"); + gd = new GridData(); + gd.widthHint = 50; + editBtn.setLayoutData(gd); + editBtn.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + if (editBtn.getText().equals("Edit")) { + cancelBtn.setEnabled(true); + editBtn.setText("Save"); + enable_edit = true; + } else { + boolean result = false; + Resource resourceInSelection = resourceManagerRef + .getCurrentResourceInSelection(); + if (null != resourceInSelection) { + + // Null Check + result = resourceManagerRef.isPropertyValueInvalid( + resourceInSelection, properties, + Constants.RESOURCE_URI); + if (result) { + MessageDialog.openError(parent.getShell(), + "Invalid Input", "Resource URI is invalid."); + return; + } + + result = resourceManagerRef.isPropertyValueInvalid( + resourceInSelection, properties, + Constants.RESOURCE_NAME); + if (result) { + MessageDialog.openError(parent.getShell(), + "Invalid Input", + "Resource Name is invalid."); + return; + } + + boolean update = false; + boolean uriChange = false; + boolean nameChange = false; + if (resourceManagerRef.isPropValueChanged( + resourceInSelection, properties, + Constants.RESOURCE_NAME)) { + update = true; + nameChange = true; + } + if (resourceManagerRef.isPropValueChanged( + resourceInSelection, properties, + Constants.RESOURCE_URI)) { + // Check whether the new URI is unique. + if (!resourceManagerRef.isUriUnique(properties)) { + MessageDialog.openError(parent.getShell(), + "Resource URI in use", + "Resource URI is in use. Please try a different URI."); + return; + } + + update = true; + uriChange = true; + + if (resourceManagerRef + .isResourceStarted(resourceInSelection)) { + update = MessageDialog.openQuestion( + parent.getShell(), "Save Details", + "Resource will be restarted to take the changes." + + " Do you want to continue?"); + if (!update) { + return; + } + } + } + if (update) { + try { + result = Activator + .getDefault() + .getResourceManager() + .updateResourceProperties( + resourceManagerRef + .getCurrentResourceInSelection(), + properties, uriChange, + nameChange); + } catch (SimulatorException ex) { + result = false; + } + if (result) { + MessageDialog.openInformation( + parent.getShell(), "Operation status", + "Resource properties updated."); + } else { + MessageDialog.openInformation( + parent.getShell(), "Operation status", + "Failed to update the resource properties."); + + // Reset the old property values. + properties = getData(resourceManagerRef + .getCurrentResourceInSelection()); + updateViewer(properties); + } + } + } else { + Device dev = resourceManagerRef + .getCurrentDeviceInSelection(); + + // Null check + result = resourceManagerRef.isPropertyValueInvalid(dev, + properties, Constants.DEVICE_NAME); + if (result) { + MessageDialog.openError(parent.getShell(), + "Invalid Input", "Device Name is invalid."); + return; + } + + if (resourceManagerRef.isPropValueChanged(dev, + properties, Constants.DEVICE_NAME)) { + resourceManagerRef.updateDeviceProperties(dev, + properties); + } + + } + cancelBtn.setEnabled(false); + editBtn.setText("Edit"); + enable_edit = false; + } + } + }); + + cancelBtn = new Button(parent, SWT.PUSH); + cancelBtn.setText("Cancel"); + cancelBtn.setEnabled(false); + gd = new GridData(); + gd.widthHint = 70; + cancelBtn.setLayoutData(gd); + cancelBtn.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + Resource res = resourceManagerRef + .getCurrentResourceInSelection(); + if (null != res) { + properties = getData(res); + } else { + Device dev = resourceManagerRef + .getCurrentDeviceInSelection(); + if (null != dev) { + properties = getData(dev); + } + } + updateViewer(properties); + + cancelBtn.setEnabled(false); + editBtn.setText("Edit"); + enable_edit = false; + } + }); + addManagerListeners(); // Check whether there is any resource selected already - List propertyList = getData(); - if (null != propertyList) { - updateViewer(propertyList); + Resource resource = resourceManagerRef.getCurrentResourceInSelection(); + properties = getData(resource); + if (null != properties) { + updateViewer(properties); } + updateEditControls(resource); + } + private void updateEditControls(Object obj) { + if (!editBtn.isDisposed() && !cancelBtn.isDisposed()) { + + if (editBtn.getText().equals("Save")) { + editBtn.setText("Edit"); + enable_edit = false; + } + + if (null == obj) { + editBtn.setEnabled(false); + } else { + editBtn.setEnabled(true); + } + cancelBtn.setEnabled(false); + } + } + + private List getData(Resource resource) { + if (null != resource) { + List metaPropertyList = resourceManagerRef + .getMetaProperties(resource); + return metaPropertyList; + } else { + return null; + } } - private List getData() { - SimulatorResource resourceInSelection = resourceManagerRef - .getCurrentResourceInSelection(); - if (null != resourceInSelection) { + private List getData(Device dev) { + if (null != dev) { List metaPropertyList = resourceManagerRef - .getMetaProperties(resourceInSelection); + .getMetaProperties(dev); return metaPropertyList; } else { return null; @@ -137,15 +355,12 @@ public class MetaPropertiesView extends ViewPart { SWT.NONE); propName.getColumn().setWidth(columnWidth[0]); propName.getColumn().setText(columnHeaders[0]); - propName.setLabelProvider(new ColumnLabelProvider() { + propName.setLabelProvider(new StyledCellLabelProvider() { @Override - public String getText(Object element) { - MetaProperty prop = (MetaProperty) element; - if (null != prop) { - return prop.getPropName(); - } else { - return ""; - } + public void update(ViewerCell cell) { + MetaProperty prop = (MetaProperty) cell.getElement(); + cell.setText(prop.getPropName()); + super.update(cell); } }); @@ -164,11 +379,12 @@ public class MetaPropertiesView extends ViewPart { } } }); + propValue.setEditingSupport(new PropValueEditor(tableViewer)); } private void addManagerListeners() { - resourceManagerRef - .addResourceSelectionChangedUIListener(resourceSelectionChangedListener); + UiListenerHandler.getInstance().addResourceSelectionChangedUIListener( + resourceSelectionChangedListener); } class PropertycontentProvider implements IStructuredContentProvider { @@ -185,19 +401,61 @@ public class MetaPropertiesView extends ViewPart { public Object[] getElements(Object element) { return (Object[]) element; } - } @Override public void dispose() { // Unregister the listener if (null != resourceSelectionChangedListener) { - resourceManagerRef - .removeResourceSelectionChangedUIListener(resourceSelectionChangedListener); + UiListenerHandler.getInstance() + .removeResourceSelectionChangedUIListener( + resourceSelectionChangedListener); } super.dispose(); } + class PropValueEditor extends EditingSupport { + + private final TableViewer viewer; + + public PropValueEditor(TableViewer viewer) { + super(viewer); + this.viewer = viewer; + } + + @Override + protected boolean canEdit(Object element) { + return true; + } + + @Override + protected CellEditor getCellEditor(Object element) { + if (!enable_edit) { + return null; + } + // Disabling edit for resource type + String propName = ((MetaProperty) element).getPropName(); + if (null != propName && propName.equals(Constants.RESOURCE_TYPE)) { + return null; + } + CellEditor editor = new TextCellEditor(viewer.getTable()); + return editor; + } + + @Override + protected Object getValue(Object element) { + return ((MetaProperty) element).getPropValue(); + } + + @Override + protected void setValue(Object element, Object value) { + MetaProperty prop = (MetaProperty) element; + prop.setPropValue(String.valueOf(value)); + viewer.update(element, null); + } + + } + @Override public void setFocus() { } diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/MultiResourceOrchestrationView.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/MultiResourceOrchestrationView.java deleted file mode 100644 index ac26bb0..0000000 --- a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/MultiResourceOrchestrationView.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package oic.simulator.serviceprovider.view; - -import org.eclipse.swt.widgets.Composite; -import org.eclipse.ui.part.ViewPart; - -/** - * This class manages and shows the multi-resource automation view in the - * perspective. - */ -public class MultiResourceOrchestrationView extends ViewPart { - - public static final String VIEW_ID = "oic.simulator.serviceprovider.view.orchestration"; - - @Override - public void createPartControl(Composite arg0) { - // TODO: To be done - } - - @Override - public void setFocus() { - // TODO To be done - } -} \ No newline at end of file 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 index a9abf80..c102e66 100644 --- 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 @@ -18,24 +18,45 @@ package oic.simulator.serviceprovider.view; import java.util.ArrayList; import java.util.List; +import java.util.Set; import oic.simulator.serviceprovider.Activator; +import oic.simulator.serviceprovider.listener.IPropertiesChangedUIListener; import oic.simulator.serviceprovider.listener.IResourceListChangedUIListener; import oic.simulator.serviceprovider.manager.ResourceManager; -import oic.simulator.serviceprovider.resource.DeleteCategory; +import oic.simulator.serviceprovider.manager.UiListenerHandler; +import oic.simulator.serviceprovider.model.AutomationSettingHelper; +import oic.simulator.serviceprovider.model.CollectionResource; +import oic.simulator.serviceprovider.model.Device; +import oic.simulator.serviceprovider.model.Resource; +import oic.simulator.serviceprovider.model.ResourceType; +import oic.simulator.serviceprovider.model.SingleResource; import oic.simulator.serviceprovider.utils.Constants; import oic.simulator.serviceprovider.utils.Utility; +import oic.simulator.serviceprovider.view.dialogs.AddResourceToCollections; +import oic.simulator.serviceprovider.view.dialogs.AddResourceToDevices; +import oic.simulator.serviceprovider.view.dialogs.AddResources; +import oic.simulator.serviceprovider.view.dialogs.AutomationSettingDialog; import oic.simulator.serviceprovider.view.dialogs.CreateResourceWizard; import oic.simulator.serviceprovider.view.dialogs.DeleteResourceWizard; +import oic.simulator.serviceprovider.view.dialogs.RemoveResourceFromCollections; +import oic.simulator.serviceprovider.view.dialogs.RemoveResourceFromDevices; +import oic.simulator.serviceprovider.view.dialogs.RemoveResources; import oic.simulator.serviceprovider.view.dialogs.ResourceWizardDialog; import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.viewers.ISelectionChangedListener; +import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.LabelProvider; +import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.Viewer; +import org.eclipse.jface.window.Window; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.CTabFolder; +import org.eclipse.swt.custom.CTabItem; import org.eclipse.swt.events.MenuAdapter; import org.eclipse.swt.events.MenuEvent; import org.eclipse.swt.events.SelectionAdapter; @@ -56,6 +77,8 @@ import org.eclipse.ui.PlatformUI; import org.eclipse.ui.dialogs.FilteredTree; import org.eclipse.ui.dialogs.PatternFilter; import org.eclipse.ui.part.ViewPart; +import org.oic.simulator.SimulatorException; +import org.oic.simulator.server.SimulatorResource.AutoUpdateType; /** * This class manages and shows the resource manager view in the perspective. @@ -67,10 +90,19 @@ public class ResourceManagerView extends ViewPart { private Button createButton; private Button deleteButton; - private TreeViewer treeViewer; + private TreeViewer singleResTreeViewer; + private TreeViewer collectionResTreeViewer; + private TreeViewer deviceTreeViewer; + + private CTabFolder folder; + private CTabItem singleResTab; + private CTabItem collectionResTab; + private CTabItem deviceTab; private IResourceListChangedUIListener resourceListChangedListener; + private IPropertiesChangedUIListener resourcePropertiesChangedListener; + private ResourceManager resourceManager; public ResourceManagerView() { @@ -80,13 +112,23 @@ public class ResourceManagerView extends ViewPart { resourceListChangedListener = new IResourceListChangedUIListener() { @Override - public void onResourceCreation() { + public void onResourceCreation(final ResourceType type) { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { - if (null != treeViewer) { - treeViewer.refresh(); + if (type == ResourceType.SINGLE) { + if (null != singleResTreeViewer) { + singleResTreeViewer.refresh(); + } + } else if (type == ResourceType.COLLECTION) { + if (null != collectionResTreeViewer) { + collectionResTreeViewer.refresh(); + } + } else { + if (null != deviceTreeViewer) { + deviceTreeViewer.refresh(); + } } // Trigger the visibility of delete button @@ -96,34 +138,86 @@ public class ResourceManagerView extends ViewPart { } @Override - public void onResourceDeletion() { + public void onResourceDeletion(final ResourceType type) { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { - if (null != treeViewer) { - treeViewer.refresh(); + if (null != singleResTreeViewer + && null != collectionResTreeViewer + && null != deviceTreeViewer) { + switch (type) { + case SINGLE: + singleResTreeViewer.refresh(); + case COLLECTION: + collectionResTreeViewer.refresh(); + default: + deviceTreeViewer.refresh(); + } } - // Trigger the visibility of delete button changeDeleteVisibility(); } }); } + + @Override + public void onResourceListUpdate(final ResourceType type) { + Display.getDefault().asyncExec(new Runnable() { + + @Override + public void run() { + if (null != singleResTreeViewer + && null != collectionResTreeViewer + && null != deviceTreeViewer) { + switch (type) { + case SINGLE: + singleResTreeViewer.refresh(); + case COLLECTION: + collectionResTreeViewer.refresh(); + default: + deviceTreeViewer.refresh(); + } + } + } + }); + } + }; + + resourcePropertiesChangedListener = new IPropertiesChangedUIListener() { + + @Override + public void onResourcePropertyChange() { + Display.getDefault().asyncExec(new Runnable() { + @Override + public void run() { + if (null != singleResTreeViewer + && null != collectionResTreeViewer + && null != deviceTreeViewer) { + singleResTreeViewer.refresh(); + collectionResTreeViewer.refresh(); + deviceTreeViewer.refresh(); + } + } + }); + } + + @Override + public void onDevicePropertyChange() { + Display.getDefault().asyncExec(new Runnable() { + @Override + public void run() { + if (null != deviceTreeViewer) { + deviceTreeViewer.refresh(); + } + } + }); + } }; } public void changeDeleteVisibility() { - if (null == treeViewer) { - return; - } - boolean visibility; - Tree tree = treeViewer.getTree(); - if (null != tree && !tree.isDisposed() && tree.getItemCount() > 0) { - visibility = true; - } else { - visibility = false; - } + boolean visibility = resourceManager.isAnyResourceExist(); if (null != deleteButton && !deleteButton.isDisposed()) { deleteButton.setEnabled(visibility); } @@ -163,135 +257,883 @@ public class ResourceManagerView extends ViewPart { gd.widthHint = 90; deleteButton.setLayoutData(gd); - Group resourceGroup = new Group(compContent, SWT.NONE); - resourceGroup.setText("Created Resources"); + // Create a Tab Folder. + folder = new CTabFolder(compContent, SWT.BORDER); + gd = new GridData(SWT.FILL, SWT.FILL, true, true); + folder.setLayoutData(gd); + folder.setSimple(false); + folder.setUnselectedCloseVisible(false); + folder.setUnselectedImageVisible(false); + folder.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + // Tab is switched. + singleResTreeViewer.setSelection(null); + collectionResTreeViewer.setSelection(null); + deviceTreeViewer.setSelection(null); + resourceManager.resourceSelectionChanged(null); + } + }); + + createSimpleResourcesArea(); + + createCollectionResourcesArea(); + + createDeviceArea(); + + folder.setSelection(singleResTab); + + addUIListeners(); + + addManagerListeners(); + + // If there is at least one resource exist, then enable the delete + // resource button + changeDeleteVisibility(); + } + + private void createSimpleResourcesArea() { + singleResTab = new CTabItem(folder, SWT.NULL); + singleResTab.setText("Simple Resources"); + + // Create a group to show all the discovered resources. + // Adding the group to the folder. + Group resourceGroup = new Group(folder, SWT.NONE); + // resourceGroup.setText("Discovered Resources"); Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE); resourceGroup.setBackground(color); resourceGroup.setLayout(new GridLayout(1, false)); - gd = new GridData(SWT.FILL, SWT.FILL, true, true); + GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); resourceGroup.setLayoutData(gd); PatternFilter filter = new PatternFilter(); FilteredTree filteredTree = new FilteredTree(resourceGroup, SWT.H_SCROLL | SWT.V_SCROLL | SWT.SINGLE, filter, true); - treeViewer = filteredTree.getViewer(); - treeViewer.getTree().setLayoutData( + singleResTreeViewer = filteredTree.getViewer(); + singleResTreeViewer.getTree().setLayoutData( new GridData(SWT.FILL, SWT.FILL, true, true)); - treeViewer.setContentProvider(new TreeContentProvider()); - treeViewer.setLabelProvider(new TreeLabelProvider()); - treeViewer.setInput(new Object()); + singleResTreeViewer + .setContentProvider(new SingleResourceContentProvider()); + singleResTreeViewer.setLabelProvider(new TreeLabelProvider()); + singleResTreeViewer.setInput(new Object()); - addUIListeners(); + singleResTreeViewer + .addSelectionChangedListener(new ISelectionChangedListener() { + @Override + public void selectionChanged(SelectionChangedEvent e) { + IStructuredSelection selection = (IStructuredSelection) e + .getSelection(); + if (null == selection) { + return; + } - addManagerListeners(); + Resource res = null; + int size = selection.size(); + if (size == 1) { + res = (Resource) selection.getFirstElement(); + } + resourceManager.resourceSelectionChanged(res); + } + }); - // If there is at least one resource exist, then enable the delete - // resource button - changeDeleteVisibility(); + // TODO: Add menu items + addMenuToSimpleResources(); + + singleResTab.setControl(resourceGroup); } - private void addUIListeners() { + private void addMenuToSimpleResources() { + if (null != singleResTreeViewer) { + final Tree resourceTreeHead = singleResTreeViewer.getTree(); + if (null != resourceTreeHead) { + // Below code creates menu entries and shows them on right + // clicking a resource + final Menu menu = new Menu(resourceTreeHead); + resourceTreeHead.setMenu(menu); + menu.addMenuListener(new MenuAdapter() { + @Override + public void menuShown(MenuEvent e) { + // Clear existing menu items + MenuItem[] items = menu.getItems(); + for (int index = 0; index < items.length; index++) { + items[index].dispose(); + } - createButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { + IStructuredSelection selection = ((IStructuredSelection) singleResTreeViewer + .getSelection()); + final SingleResource resource = (SingleResource) selection + .getFirstElement(); + if (null == resource) { + return; + } + + addAutomationMenu(menu, resource); + // Menu to add resource to one or more collections. + MenuItem addToCollection = new MenuItem(menu, SWT.NONE); + addToCollection.setText("Add to Collection"); + addToCollection + .addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + List possibleCollections; + possibleCollections = resourceManager + .getCollectionsForAddingToSingleResource(resource); + if (null == possibleCollections + || possibleCollections + .isEmpty()) { + MessageDialog + .openError( + Display.getDefault() + .getActiveShell(), + "No possible candidates", + "There are no possible collections to which the resource can be added."); + return; + } + + AddResourceToCollections addToCollectionsDlg = new AddResourceToCollections( + Display.getDefault() + .getActiveShell(), + possibleCollections); + if (addToCollectionsDlg.open() != Window.OK) { + return; + } + + Set resultSet = addToCollectionsDlg + .getSelectedResourceList(); + + int addedCount = resourceManager + .addResourceToCollection( + resultSet, resource); + if (addedCount <= 0) { + MessageDialog + .openInformation(Display + .getDefault() + .getActiveShell(), + "Operation failed", + "Failed to add resources to the collection."); + return; + } + + collectionResTreeViewer.refresh(); + + deviceTreeViewer.refresh(); + + MessageDialog.openInformation( + Display.getDefault() + .getActiveShell(), + "Added", + "[" + + addedCount + + "/" + + resultSet.size() + + "] added to selected collections"); + } + }); + + // Menu to remove resource from one or more collections + // to which it is a member. + MenuItem removeFromCollection = new MenuItem(menu, + SWT.NONE); + removeFromCollection.setText("Remove from Collection"); + removeFromCollection + .addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + List possibleCollectionstoRemoveFrom; + possibleCollectionstoRemoveFrom = resourceManager + .getResourceReferences(resource); + if (null == possibleCollectionstoRemoveFrom + || possibleCollectionstoRemoveFrom + .isEmpty()) { + MessageDialog + .openError( + Display.getDefault() + .getActiveShell(), + "No possible candidates", + "Resource has not been added to any collections."); + return; + } + + RemoveResourceFromCollections removeFromCollectionsDlg = new RemoveResourceFromCollections( + Display.getDefault() + .getActiveShell(), + possibleCollectionstoRemoveFrom); + if (removeFromCollectionsDlg.open() != Window.OK) { + return; + } + + Set resultSet = removeFromCollectionsDlg + .getSelectedResourceList(); + + int removeCount = resourceManager + .removeResourceFromCollection( + resultSet, resource); + if (removeCount <= 0) { + MessageDialog + .openInformation(Display + .getDefault() + .getActiveShell(), + "Operation failed", + "Failed to remove resources from the collection."); + return; + } + + collectionResTreeViewer.refresh(); + + deviceTreeViewer.refresh(); + + MessageDialog.openInformation( + Display.getDefault() + .getActiveShell(), + "Removed", + "[" + + removeCount + + "/" + + resultSet.size() + + "] resource removed from selected collections"); + } + }); + + // Menu to add resource to one or more devices. + MenuItem addToDevice = new MenuItem(menu, SWT.NONE); + addToDevice.setText("Add to Device"); + addToDevice + .addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + List possibleDevices; + possibleDevices = resourceManager + .getDevicesForAddingToResource(resource); + if (null == possibleDevices + || possibleDevices.isEmpty()) { + MessageDialog + .openError( + Display.getDefault() + .getActiveShell(), + "No possible candidates", + "There are no possible devices to which the resource can be added."); + return; + } + + AddResourceToDevices addToDevicesDlg = new AddResourceToDevices( + Display.getDefault() + .getActiveShell(), + possibleDevices); + if (addToDevicesDlg.open() != Window.OK) { + return; + } + + Set resultSet = addToDevicesDlg + .getSelectedDeviceList(); + + resourceManager.addResourceToDevice( + resultSet, resource); + + deviceTreeViewer.refresh(); + + MessageDialog + .openInformation(Display + .getDefault() + .getActiveShell(), + "Added", + "Resource added to selected devices."); + } + }); + + // Menu to remove resource from one or more device to + // which it is a member. + MenuItem removeFromDevice = new MenuItem(menu, SWT.NONE); + removeFromDevice.setText("Remove from Device"); + removeFromDevice + .addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + List possibleDevices; + possibleDevices = resourceManager + .getDeviceReferences(resource); + if (null == possibleDevices + || possibleDevices.isEmpty()) { + MessageDialog + .openError( + Display.getDefault() + .getActiveShell(), + "No possible candidates", + "Resource has not been added to any devices."); + return; + } + + RemoveResourceFromDevices removeFromDevicesDlg = new RemoveResourceFromDevices( + Display.getDefault() + .getActiveShell(), + possibleDevices); + if (removeFromDevicesDlg.open() != Window.OK) { + return; + } + + Set resultSet = removeFromDevicesDlg + .getSelectedDeviceList(); + + resourceManager + .removeResourceFromDevice( + resultSet, resource); + + deviceTreeViewer.refresh(); + + MessageDialog + .openInformation(Display + .getDefault() + .getActiveShell(), + "Removed", + "Resource removed from selected devices"); + } + }); + + // Menu to remove resource from one or more device to + // which it is a member. + MenuItem deleteResource = new MenuItem(menu, SWT.NONE); + deleteResource.setText("Delete"); + deleteResource + .addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + try { + resourceManager + .removeResource(resource); + singleResTreeViewer.refresh(); + // if(refreshCollectionTree) + collectionResTreeViewer.refresh(); + // if(refreshDeviceTree) + deviceTreeViewer.refresh(); + MessageDialog.openInformation( + Display.getDefault() + .getActiveShell(), + "Deleted", + "Resource deleted."); + } catch (SimulatorException e1) { + MessageDialog + .openInformation(Display + .getDefault() + .getActiveShell(), + "Deletion Failed", + "Failed to delete the resource."); + } + changeDeleteVisibility(); + } + }); + } + }); + } + } + } + + private void createCollectionResourcesArea() { + collectionResTab = new CTabItem(folder, SWT.NULL); + collectionResTab.setText("Collection Resources"); + + // Create a group to show all the discovered resources. + // Adding the group to the folder. + Group resourceGroup = new Group(folder, SWT.NONE); + // resourceGroup.setText("Discovered Resources"); + + Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE); + resourceGroup.setBackground(color); + + resourceGroup.setLayout(new GridLayout(1, false)); + GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); + resourceGroup.setLayoutData(gd); + + PatternFilter filter = new PatternFilter(); + FilteredTree filteredTree = new FilteredTree(resourceGroup, + SWT.H_SCROLL | SWT.V_SCROLL | SWT.SINGLE, filter, true); + collectionResTreeViewer = filteredTree.getViewer(); + collectionResTreeViewer.getTree().setLayoutData( + new GridData(SWT.FILL, SWT.FILL, true, true)); + collectionResTreeViewer + .setContentProvider(new CollectionResourceContentProvider()); + collectionResTreeViewer.setLabelProvider(new TreeLabelProvider()); + collectionResTreeViewer.setInput(new Object()); + + collectionResTreeViewer + .addSelectionChangedListener(new ISelectionChangedListener() { @Override - public void run() { - CreateResourceWizard createWizard = new CreateResourceWizard(); - ResourceWizardDialog wizardDialog = new ResourceWizardDialog( - PlatformUI.getWorkbench().getDisplay() - .getActiveShell(), createWizard); - int open = wizardDialog.open(); - if (open == WizardDialog.OK) { - String configFilePath; - int count; - configFilePath = createWizard.getConfigFilePath(); - System.out.println("Resultant config file path is " - + configFilePath); - count = createWizard.getResourceCount(); - if (count > 0) { - if (count == 1) { - // Single resource creation - resourceManager - .createResource(configFilePath); - } else { - // Multi-resource creation - resourceManager.createResource( - configFilePath, count); - } + public void selectionChanged(SelectionChangedEvent e) { + IStructuredSelection selection = (IStructuredSelection) e + .getSelection(); + if (null == selection) { + return; + } + + Resource res = null; + int size = selection.size(); + if (size == 1) { + res = (Resource) selection.getFirstElement(); + } + resourceManager.resourceSelectionChanged(res); + } + }); + + // TODO: Add menu items + addMenuToCollectionResources(); + + collectionResTab.setControl(resourceGroup); + } + + private void addMenuToCollectionResources() { + if (null != collectionResTreeViewer) { + final Tree resourceTreeHead = collectionResTreeViewer.getTree(); + if (null != resourceTreeHead) { + // Below code creates menu entries and shows them on right + // clicking a resource + final Menu menu = new Menu(resourceTreeHead); + resourceTreeHead.setMenu(menu); + menu.addMenuListener(new MenuAdapter() { + @Override + public void menuShown(MenuEvent e) { + // Clear existing menu items + MenuItem[] items = menu.getItems(); + for (int index = 0; index < items.length; index++) { + items[index].dispose(); + } + + IStructuredSelection selection = ((IStructuredSelection) collectionResTreeViewer + .getSelection()); + final Resource resource = (Resource) selection + .getFirstElement(); + TreeItem[] treeItems = resourceTreeHead.getSelection(); + if (null == resource || null == treeItems) { + return; + } + + final TreeItem parent = treeItems[0].getParentItem(); + if (null == parent) { + System.out.println("No parent exist"); + // Selected item is a top-level collection + addMenuToTopLevelCollectionResources(menu, + (CollectionResource) resource); + } else { + if (resource instanceof SingleResource) + addAutomationMenu(menu, + (SingleResource) resource); + + MenuItem remFromParent = new MenuItem(menu, + SWT.NONE); + remFromParent.setText("Remove from Parent"); + remFromParent + .addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected( + SelectionEvent e) { + CollectionResource parentCollection = (CollectionResource) parent + .getData(); + String status; + try { + resourceManager + .removeResourceFromCollection( + parentCollection, + resource); + collectionResTreeViewer + .refresh(); + deviceTreeViewer.refresh(); + + status = "Resource removed from its parent"; + } catch (SimulatorException e1) { + status = "Failed to remove the resource from its parent"; + } + MessageDialog.openInformation( + Display.getDefault() + .getActiveShell(), + "Status", status); + } + }); + + if (resource instanceof SingleResource) { + // Menu Items for single resource will be added + // here. } } } }); } + } + } + + private void addMenuToTopLevelCollectionResources(final Menu menu, + final CollectionResource colRes) { + // Menu to add one or more resources to the collection. + MenuItem addResources = new MenuItem(menu, SWT.CASCADE); + addResources.setText("Add Resources"); + + Menu addSubMenu = new Menu(menu); + addResources.setMenu(addSubMenu); + + MenuItem simpleResources = new MenuItem(addSubMenu, SWT.NONE); + simpleResources.setText("Simple"); + simpleResources.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + List possibleResources; + possibleResources = resourceManager + .getSingleTypeResourcesForAddingToCollectionResource(colRes); + if (null == possibleResources || possibleResources.isEmpty()) { + MessageDialog + .openError(Display.getDefault().getActiveShell(), + "No possible candidates", + "There are no possible simple resources that can be added."); + return; + } + + List resources = Utility + .convertSingleTypeResourceListToBaseType(possibleResources); + + AddResources addToCollectionsDlg = new AddResources(Display + .getDefault().getActiveShell(), resources); + if (addToCollectionsDlg.open() != Window.OK) { + return; + } + + Set resultSet = addToCollectionsDlg + .getSelectedResourceList(); + + int addedCount = resourceManager.addResourceToCollection( + colRes, resultSet); + if (addedCount <= 0) { + MessageDialog.openInformation(Display.getDefault() + .getActiveShell(), "Operation failed", + "Failed to add resources to the collection."); + return; + } + + collectionResTreeViewer.refresh(); + + deviceTreeViewer.refresh(); + + MessageDialog.openInformation(Display.getDefault() + .getActiveShell(), "Added", "[" + addedCount + "/" + + resultSet.size() + + "] resources added to the collection"); + } }); - deleteButton.addSelectionListener(new SelectionAdapter() { + MenuItem collectionResources = new MenuItem(addSubMenu, SWT.NONE); + collectionResources.setText("Collection"); + collectionResources.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { - PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { + List possibleResources; + possibleResources = resourceManager + .getCollectionTypeResourcesForAddingToCollectionResource(colRes); + if (null == possibleResources || possibleResources.isEmpty()) { + MessageDialog + .openError(Display.getDefault().getActiveShell(), + "No possible candidates", + "There are no possible collections that can be added."); + return; + } + + List resources = Utility + .convertCollectionTypeResourceListToBaseType(possibleResources); + + AddResources addToCollectionsDlg = new AddResources(Display + .getDefault().getActiveShell(), resources); + if (addToCollectionsDlg.open() != Window.OK) { + return; + } + + Set resultSet = addToCollectionsDlg + .getSelectedResourceList(); + + int addedCount = resourceManager.addResourceToCollection( + colRes, resultSet); + if (addedCount <= 0) { + MessageDialog.openInformation(Display.getDefault() + .getActiveShell(), "Operation failed", + "Failed to add resources to the collection."); + return; + } + + collectionResTreeViewer.refresh(); + + deviceTreeViewer.refresh(); + + MessageDialog.openInformation(Display.getDefault() + .getActiveShell(), "Added", "[" + addedCount + "/" + + resultSet.size() + + "] resources added to the collection"); + } + }); + + // Menu to remove one or more resources from the collection. + MenuItem removeResources = new MenuItem(menu, SWT.CASCADE); + removeResources.setText("Remove Resources"); + + Menu removeSubMenu = new Menu(menu); + removeResources.setMenu(removeSubMenu); + + simpleResources = new MenuItem(removeSubMenu, SWT.NONE); + simpleResources.setText("Simple"); + simpleResources.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + List possibleResources; + possibleResources = resourceManager.getSingleTypeChilds(colRes); + if (null == possibleResources || possibleResources.isEmpty()) { + MessageDialog + .openError(Display.getDefault().getActiveShell(), + "No possible candidates", + "There are no possible simple resources which can be removed."); + return; + } + + List resources = Utility + .convertSingleTypeResourceListToBaseType(possibleResources); + RemoveResources removeFromCollectionsDlg = new RemoveResources( + Display.getDefault().getActiveShell(), resources); + if (removeFromCollectionsDlg.open() != Window.OK) { + return; + } + + Set resultSet = removeFromCollectionsDlg + .getSelectedResourceList(); + + int removeCount = resourceManager + .removeResourcesFromCollection(colRes, resultSet); + if (removeCount <= 0) { + MessageDialog.openInformation(Display.getDefault() + .getActiveShell(), "Operation failed", + "Failed to remove resources from the collection."); + return; + } + + collectionResTreeViewer.refresh(); + + deviceTreeViewer.refresh(); + + MessageDialog.openInformation(Display.getDefault() + .getActiveShell(), "Removed", "[" + removeCount + "/" + + resultSet.size() + + "] resources removed from the collection"); + } + }); + + collectionResources = new MenuItem(removeSubMenu, SWT.NONE); + collectionResources.setText("Collection"); + collectionResources.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + List possibleResources; + possibleResources = resourceManager + .getCollectionTypeChilds(colRes); + if (null == possibleResources || possibleResources.isEmpty()) { + MessageDialog + .openError(Display.getDefault().getActiveShell(), + "No possible candidates", + "There are no possible collections which can be removed."); + return; + } + + List resources = Utility + .convertCollectionTypeResourceListToBaseType(possibleResources); + + RemoveResources removeFromCollectionsDlg = new RemoveResources( + Display.getDefault().getActiveShell(), resources); + if (removeFromCollectionsDlg.open() != Window.OK) { + return; + } + + Set resultSet = removeFromCollectionsDlg + .getSelectedResourceList(); + + int removeCount = resourceManager + .removeResourcesFromCollection(colRes, resultSet); + if (removeCount <= 0) { + MessageDialog.openInformation(Display.getDefault() + .getActiveShell(), "Operation failed", + "Failed to remove resources from the collection."); + return; + } + + collectionResTreeViewer.refresh(); + + deviceTreeViewer.refresh(); + + MessageDialog.openInformation(Display.getDefault() + .getActiveShell(), "Removed", "[" + removeCount + "/" + + resultSet.size() + + "] resources removed from the collection"); + } + }); + + // Menu to add resource to one or more devices. + MenuItem addToDevice = new MenuItem(menu, SWT.NONE); + addToDevice.setText("Add to Device"); + addToDevice.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + List possibleDevices; + possibleDevices = resourceManager + .getDevicesForAddingToResource(colRes); + if (null == possibleDevices || possibleDevices.isEmpty()) { + MessageDialog + .openError(Display.getDefault().getActiveShell(), + "No possible candidates", + "There are no possible devices to which the resource can be added."); + return; + } + + AddResourceToDevices addToDevicesDlg = new AddResourceToDevices( + Display.getDefault().getActiveShell(), possibleDevices); + if (addToDevicesDlg.open() != Window.OK) { + return; + } + + Set resultSet = addToDevicesDlg.getSelectedDeviceList(); + + resourceManager.addResourceToDevice(resultSet, colRes); + + deviceTreeViewer.refresh(); + + MessageDialog.openInformation(Display.getDefault() + .getActiveShell(), "Added", + "Resource added to selected devices."); + } + }); + + // Menu to remove resource from one or more device to which it is a + // member. + MenuItem removeFromDevice = new MenuItem(menu, SWT.NONE); + removeFromDevice.setText("Remove from Device"); + removeFromDevice.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + List possibleDevices; + possibleDevices = resourceManager.getDeviceReferences(colRes); + if (null == possibleDevices || possibleDevices.isEmpty()) { + MessageDialog.openError(Display.getDefault() + .getActiveShell(), "No possible candidates", + "Resource has not been added to any devices."); + return; + } + + RemoveResourceFromDevices removeFromDevicesDlg = new RemoveResourceFromDevices( + Display.getDefault().getActiveShell(), possibleDevices); + if (removeFromDevicesDlg.open() != Window.OK) { + return; + } + + Set resultSet = removeFromDevicesDlg + .getSelectedDeviceList(); + + resourceManager.removeResourceFromDevice(resultSet, colRes); + + deviceTreeViewer.refresh(); + + MessageDialog.openInformation(Display.getDefault() + .getActiveShell(), "Removed", + "Resource removed from selected devices"); + } + }); + + // Menu to remove resource from one or more device to which it is a + // member. + MenuItem deleteResource = new MenuItem(menu, SWT.NONE); + deleteResource.setText("Delete"); + deleteResource.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + /* + * boolean refreshCollectionTree = false; boolean + * refreshDeviceTree = false; + * if(resource.isMemberOfAnyCollection()) { + * refreshCollectionTree = true; } + * if(resource.isMemberOfAnyDevice()) { refreshDeviceTree = + * true; } + */ + try { + resourceManager.removeResource(colRes); + // if(refreshCollectionTree) + collectionResTreeViewer.refresh(); + // if(refreshDeviceTree) + deviceTreeViewer.refresh(); + MessageDialog.openInformation(Display.getDefault() + .getActiveShell(), "Deleted", "Resource deleted."); + } catch (SimulatorException e1) { + MessageDialog.openInformation(Display.getDefault() + .getActiveShell(), "Deletion Failed", + "Failed to delete the resource."); + } + + changeDeleteVisibility(); + } + }); + + } + + private void createDeviceArea() { + deviceTab = new CTabItem(folder, SWT.NULL); + deviceTab.setText("Devices"); + + // Create a group to show all the discovered resources. + // Adding the group to the folder. + Group resourceGroup = new Group(folder, SWT.NONE); + // resourceGroup.setText("Discovered Resources"); + + Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE); + resourceGroup.setBackground(color); + + resourceGroup.setLayout(new GridLayout(1, false)); + GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); + resourceGroup.setLayoutData(gd); + + PatternFilter filter = new PatternFilter(); + FilteredTree filteredTree = new FilteredTree(resourceGroup, + SWT.H_SCROLL | SWT.V_SCROLL | SWT.SINGLE, filter, true); + deviceTreeViewer = filteredTree.getViewer(); + deviceTreeViewer.getTree().setLayoutData( + new GridData(SWT.FILL, SWT.FILL, true, true)); + deviceTreeViewer.setContentProvider(new DeviceContentProvider()); + deviceTreeViewer.setLabelProvider(new TreeLabelProvider()); + deviceTreeViewer.setInput(new Object()); + + deviceTreeViewer + .addSelectionChangedListener(new ISelectionChangedListener() { @Override - public void run() { - DeleteResourceWizard deleteWizard = new DeleteResourceWizard(); - ResourceWizardDialog wizardDialog = new ResourceWizardDialog( - PlatformUI.getWorkbench().getDisplay() - .getActiveShell(), deleteWizard); - int open = wizardDialog.open(); - if (open == WizardDialog.OK) { - DeleteCategory deleteCategory = deleteWizard - .getDeleteCategory(); - if (deleteCategory == DeleteCategory.BY_URI) { - String uri = deleteWizard.getDeleteCandidate(); - if (null != uri) { - boolean dispName = Activator.getDefault() - .getResourceManager() - .isDisplayName(uri); - if (dispName) { - uri = Activator - .getDefault() - .getResourceManager() - .getCompleteUriFromDisplayName( - uri); - } - resourceManager.deleteResourceByURI(uri); - } - } else if (deleteCategory == DeleteCategory.BY_TYPE) { + public void selectionChanged(SelectionChangedEvent e) { + IStructuredSelection selection = (IStructuredSelection) e + .getSelection(); + if (null == selection) { + return; + } + + int size = selection.size(); + if (size == 1) { + Object obj = selection.getFirstElement(); + if (obj instanceof Device) { + resourceManager + .deviceSelectionChanged((Device) obj); + } else { resourceManager - .deleteResourceByType(deleteWizard - .getDeleteCandidate()); - } else if (deleteCategory == DeleteCategory.ALL) { - resourceManager.deleteAllResources(); + .resourceSelectionChanged((Resource) obj); } + } else { + resourceManager.deviceSelectionChanged(null); } } }); - } - }); - if (null != treeViewer) { - final Tree resourceTreeHead = treeViewer.getTree(); + // TODO: Add menu items + addMenuToDevices(); + + deviceTab.setControl(resourceGroup); + } + + private void addMenuToDevices() { + if (null != deviceTreeViewer) { + final Tree resourceTreeHead = deviceTreeViewer.getTree(); if (null != resourceTreeHead) { - // Below code adds a listener to the tree for selection changes - // and notifies the resource manager - resourceTreeHead.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - TreeItem selectedItem = (TreeItem) e.item; - if (null != selectedItem) { - String selectedItemText = selectedItem.getText(); - selectedItemText = resourceManager - .getCompleteUriFromDisplayName(selectedItemText); - // Propagate this selection change event to manager - resourceManager - .resourceSelectionChanged(selectedItemText); - } - } - }); // Below code creates menu entries and shows them on right // clicking a resource final Menu menu = new Menu(resourceTreeHead); @@ -304,71 +1146,394 @@ public class ResourceManagerView extends ViewPart { for (int index = 0; index < items.length; index++) { items[index].dispose(); } - final String selectedItem = resourceTreeHead - .getSelection()[0].getText(); - MenuItem startItem = new MenuItem(menu, SWT.NONE); - startItem.setText(Constants.START_RESOURCE_AUTOMATION); - startItem.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - // Block starting resource level - // automation if any attribute level - // automation is in progress for the - // selected resource - boolean started = resourceManager - .isAttributeAutomationStarted(resourceManager - .getCompleteUriFromDisplayName(selectedItem)); - if (started) { - MessageDialog - .openInformation( + + IStructuredSelection selection = ((IStructuredSelection) deviceTreeViewer + .getSelection()); + final Object element = selection.getFirstElement(); + if (element instanceof Device) { + addMenuToDevices(menu, (Device) element); + } else { + final Resource resource = (Resource) element; + TreeItem[] treeItems = resourceTreeHead + .getSelection(); + if (null == resource || null == treeItems) { + return; + } + + if (resource instanceof SingleResource) + addAutomationMenu(menu, + (SingleResource) resource); + + final TreeItem parent = treeItems[0] + .getParentItem(); + MenuItem remFromParent = new MenuItem(menu, + SWT.NONE); + remFromParent.setText("Remove from Parent"); + remFromParent + .addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected( + SelectionEvent e) { + String status = "Resource removed from its parent."; + Object obj = parent.getData(); + if (obj instanceof Device) { + resourceManager + .removeResourceFromDevice( + (Device) obj, + resource); + } else { + try { + resourceManager + .removeResourceFromCollection( + (CollectionResource) obj, + resource); + collectionResTreeViewer + .refresh(); + status = "Resource removed from its parent"; + } catch (SimulatorException e1) { + status = "Failed to remove the resource from its parent"; + } + } + + deviceTreeViewer.refresh(); + + MessageDialog.openInformation( Display.getDefault() .getActiveShell(), - "Attribute automation is in progress", - "Attribute level automation for this resource is already in progress!!!\nPlease stop all " - + "running attribute level automations to start resource level automation."); - } else { - boolean status = resourceManager - .startResourceAutomationUIRequest(resourceManager - .getCompleteUriFromDisplayName(selectedItem)); - String statusMsg = status ? "Automation started successfully!!!" - : "Automation request failed!!!"; - MessageDialog.openInformation(Display - .getDefault().getActiveShell(), - "Automation Status", statusMsg); - } - } - }); - - MenuItem stopItem = new MenuItem(menu, SWT.NONE); - stopItem.setText(Constants.STOP_RESOURCE_AUTOMATION); - stopItem.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - boolean status = resourceManager - .stopResourceAutomationUIRequest(resourceManager - .getCompleteUriFromDisplayName(selectedItem)); - String statusMsg = status ? "Automation stop requested!!!" - : "Automation stop failed."; - MessageDialog.openInformation(Display - .getDefault().getActiveShell(), - "Automation Status", statusMsg); - } - }); + "Status", status); + } + }); - // Set the initial visibility of menu items - boolean status = resourceManager.isResourceAutomationStarted(resourceManager - .getCompleteUriFromDisplayName(selectedItem)); - startItem.setEnabled(!status); - stopItem.setEnabled(status); + if (resource instanceof SingleResource) { + // Menu Items for single resource will be added + // here. + } + } } }); } } } + private void addMenuToDevices(Menu menu, final Device dev) { + // Menu to add one or more resources to the collection. + MenuItem addResources = new MenuItem(menu, SWT.CASCADE); + addResources.setText("Add Resources"); + + Menu addSubMenu = new Menu(menu); + addResources.setMenu(addSubMenu); + + MenuItem simpleResources = new MenuItem(addSubMenu, SWT.NONE); + simpleResources.setText("Simple"); + simpleResources.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + List possibleResources; + possibleResources = resourceManager + .getSingleTypeResourcesForAddingToDevice(dev); + if (null == possibleResources || possibleResources.isEmpty()) { + MessageDialog + .openError(Display.getDefault().getActiveShell(), + "No possible candidates", + "There are no possible simple resources that can be added."); + return; + } + + List resources = Utility + .convertSingleTypeResourceListToBaseType(possibleResources); + + AddResources addDlg = new AddResources(Display.getDefault() + .getActiveShell(), resources); + if (addDlg.open() != Window.OK) { + return; + } + + Set resultSet = addDlg.getSelectedResourceList(); + + resourceManager.addResourceToDevice(dev, resultSet); + + deviceTreeViewer.refresh(); + + MessageDialog.openInformation(Display.getDefault() + .getActiveShell(), "Added", + "Single Resources added to the device"); + } + }); + + MenuItem collectionResources = new MenuItem(addSubMenu, SWT.NONE); + collectionResources.setText("Collection"); + collectionResources.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + List possibleResources; + possibleResources = resourceManager + .getCollectionTypeResourcesForAddingToDevice(dev); + if (null == possibleResources || possibleResources.isEmpty()) { + MessageDialog + .openError(Display.getDefault().getActiveShell(), + "No possible candidates", + "There are no possible collections that can be added."); + return; + } + + List resources = Utility + .convertCollectionTypeResourceListToBaseType(possibleResources); + + AddResources addDlg = new AddResources(Display.getDefault() + .getActiveShell(), resources); + if (addDlg.open() != Window.OK) { + return; + } + + Set resultSet = addDlg.getSelectedResourceList(); + + resourceManager.addResourceToDevice(dev, resultSet); + + deviceTreeViewer.refresh(); + + MessageDialog.openInformation(Display.getDefault() + .getActiveShell(), "Added", + "Collection Resources added to the device"); + } + }); + + // Menu to remove one or more resources from the collection. + MenuItem removeResources = new MenuItem(menu, SWT.CASCADE); + removeResources.setText("Remove Resources"); + + Menu removeSubMenu = new Menu(menu); + removeResources.setMenu(removeSubMenu); + + simpleResources = new MenuItem(removeSubMenu, SWT.NONE); + simpleResources.setText("Simple"); + simpleResources.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + List possibleResources; + possibleResources = resourceManager.getSingleTypeChilds(dev); + if (null == possibleResources || possibleResources.isEmpty()) { + MessageDialog + .openError(Display.getDefault().getActiveShell(), + "No possible candidates", + "There are no possible simple resources which can be removed."); + return; + } + + List resources = Utility + .convertSingleTypeResourceListToBaseType(possibleResources); + + RemoveResources removeDlg = new RemoveResources(Display + .getDefault().getActiveShell(), resources); + if (removeDlg.open() != Window.OK) { + return; + } + + Set resultSet = removeDlg.getSelectedResourceList(); + + resourceManager.removeResourcesFromDevice(dev, resultSet); + + collectionResTreeViewer.refresh(); + + deviceTreeViewer.refresh(); + + MessageDialog.openInformation(Display.getDefault() + .getActiveShell(), "Removed", + "Single Resources removed from the device"); + } + }); + + collectionResources = new MenuItem(removeSubMenu, SWT.NONE); + collectionResources.setText("Collection"); + collectionResources.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + List possibleResources; + possibleResources = resourceManager + .getCollectionTypeChilds(dev); + if (null == possibleResources || possibleResources.isEmpty()) { + MessageDialog + .openError(Display.getDefault().getActiveShell(), + "No possible candidates", + "There are no possible collections which can be removed."); + return; + } + + List resources = Utility + .convertCollectionTypeResourceListToBaseType(possibleResources); + + RemoveResources removeDlg = new RemoveResources(Display + .getDefault().getActiveShell(), resources); + if (removeDlg.open() != Window.OK) { + return; + } + + Set resultSet = removeDlg.getSelectedResourceList(); + + resourceManager.removeResourcesFromDevice(dev, resultSet); + + collectionResTreeViewer.refresh(); + + deviceTreeViewer.refresh(); + + MessageDialog.openInformation(Display.getDefault() + .getActiveShell(), "Removed", + "Collection Resources removed from the device"); + } + }); + + // Menu to remove the device. + MenuItem deleteDevice = new MenuItem(menu, SWT.NONE); + deleteDevice.setText("Delete"); + deleteDevice.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + resourceManager.removeDevice(dev); + deviceTreeViewer.refresh(); + } + }); + } + + private void addAutomationMenu(final Menu menu, + final SingleResource selectedResource) { + MenuItem startItem = new MenuItem(menu, SWT.NONE); + startItem.setText(Constants.START_RESOURCE_AUTOMATION); + startItem.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + // Block starting resource level + // automation if any attribute level + // automation is in progress for the + // selected resource + boolean started = resourceManager + .isAttributeAutomationStarted(selectedResource); + if (started) { + MessageDialog + .openInformation( + Display.getDefault().getActiveShell(), + "Attribute automation is in progress", + "Attribute level automation for this resource is already in progress!!!\nPlease stop all " + + "running attribute level automations to start resource level automation."); + } else { + + // Start the automation + // Fetch the settings data + List automationSettings; + automationSettings = AutomationSettingHelper + .getAutomationSettings(null); + + // Open the settings dialog + AutomationSettingDialog dialog = new AutomationSettingDialog( + Activator.getDefault().getWorkbench() + .getActiveWorkbenchWindow().getShell(), + automationSettings); + dialog.create(); + if (dialog.open() == Window.OK) { + String automationType = dialog.getAutomationType(); + String updateFreq = dialog.getUpdateFrequency(); + + AutoUpdateType autoType = AutoUpdateType + .valueOf(automationType); + int updFreq = Utility + .getUpdateIntervalFromString(updateFreq); + boolean status = resourceManager + .startResourceAutomationUIRequest(autoType, + updFreq, selectedResource); + String statusMsg = status ? "Automation started successfully!!!" + : "Automation request failed!!!"; + MessageDialog.openInformation(Display.getDefault() + .getActiveShell(), "Automation Status", + statusMsg); + } + } + } + }); + + MenuItem stopItem = new MenuItem(menu, SWT.NONE); + stopItem.setText(Constants.STOP_RESOURCE_AUTOMATION); + stopItem.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + boolean status = resourceManager + .stopResourceAutomationUIRequest(selectedResource); + String statusMsg = status ? "Automation stopped!!!" + : "Automation stop failed."; + MessageDialog.openInformation(Display.getDefault() + .getActiveShell(), "Automation Status", statusMsg); + } + }); + + // Set the initial visibility of menu items + boolean status = resourceManager + .isResourceAutomationStarted(selectedResource); + startItem.setEnabled(!status); + stopItem.setEnabled(status); + } + + private void addUIListeners() { + + createButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { + + @Override + public void run() { + CreateResourceWizard createWizard = new CreateResourceWizard(); + ResourceWizardDialog wizardDialog = new ResourceWizardDialog( + PlatformUI.getWorkbench().getDisplay() + .getActiveShell(), createWizard); + createWizard.setWizardDialog(wizardDialog); + int open = wizardDialog.open(); + if (open == WizardDialog.OK + || createWizard.isDlgForceClosed()) { + MessageDialog.openInformation(Display.getDefault() + .getActiveShell(), + "Resource Creation Status", createWizard + .getStatus()); + } + } + }); + } + }); + + deleteButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { + + @Override + public void run() { + boolean exist = resourceManager.isAnyResourceExist(); + if (!exist) { + return; + } + DeleteResourceWizard deleteWizard = new DeleteResourceWizard(); + ResourceWizardDialog wizardDialog = new ResourceWizardDialog( + PlatformUI.getWorkbench().getDisplay() + .getActiveShell(), deleteWizard); + int open = wizardDialog.open(); + if (open == Window.OK) { + singleResTreeViewer.refresh(); + collectionResTreeViewer.refresh(); + deviceTreeViewer.refresh(); + MessageDialog.openInformation(Display.getDefault() + .getActiveShell(), + "Resource Deletion Status", deleteWizard + .getStatus()); + + changeDeleteVisibility(); + } + } + }); + } + }); + } + public void addManagerListeners() { - resourceManager - .addResourceListChangedUIListener(resourceListChangedListener); + UiListenerHandler.getInstance().addResourceListChangedUIListener( + resourceListChangedListener); + UiListenerHandler.getInstance().addResourcePropertiesChangedUIListener( + resourcePropertiesChangedListener); } @Override @@ -379,15 +1544,110 @@ public class ResourceManagerView extends ViewPart { public void dispose() { // Unregister the listener if (null != resourceListChangedListener) { - resourceManager - .removeResourceListChangedUIListener(resourceListChangedListener); + UiListenerHandler.getInstance() + .removeResourceListChangedUIListener( + resourceListChangedListener); resourceManager.resourceSelectionChanged(null); } + if (null != resourcePropertiesChangedListener) { + UiListenerHandler.getInstance() + .removeResourcePropertiesChangedUIListener( + resourcePropertiesChangedListener); + } super.dispose(); } } -class TreeContentProvider implements ITreeContentProvider { +class SingleResourceContentProvider implements ITreeContentProvider { + + @Override + public void dispose() { + } + + @Override + public void inputChanged(Viewer arg0, Object arg1, Object arg2) { + } + + @Override + public Object[] getChildren(Object parent) { + return null; + } + + @Override + public Object[] getElements(Object parent) { + List resList; + resList = Activator.getDefault().getResourceManager() + .getSingleResourceList(); + if (null == resList) { + resList = new ArrayList(); + } + return resList.toArray(); + } + + @Override + public Object getParent(Object child) { + return null; + } + + @Override + public boolean hasChildren(Object parent) { + return false; + } +} + +class CollectionResourceContentProvider implements ITreeContentProvider { + + @Override + public void dispose() { + } + + @Override + public void inputChanged(Viewer arg0, Object arg1, Object arg2) { + } + + @Override + public Object[] getChildren(Object parent) { + if (parent instanceof CollectionResource) { + CollectionResource cRes = (CollectionResource) parent; + Set childs = cRes.getChildResources(); + if (null == childs) { + return null; + } + return childs.toArray(); + } + return null; + } + + @Override + public Object[] getElements(Object parent) { + List resList; + resList = Activator.getDefault().getResourceManager() + .getCollectionResourceList(); + if (null == resList) { + resList = new ArrayList(); + } + return resList.toArray(); + } + + @Override + public Object getParent(Object child) { + return null; + } + + @Override + public boolean hasChildren(Object parent) { + if (parent instanceof CollectionResource) { + CollectionResource cRes = (CollectionResource) parent; + Set children = cRes.getChildResources(); + if (null != children && children.size() > 0) { + return true; + } + } + return false; + } +} + +class DeviceContentProvider implements ITreeContentProvider { @Override public void dispose() { @@ -399,17 +1659,31 @@ class TreeContentProvider implements ITreeContentProvider { @Override public Object[] getChildren(Object parent) { + if (parent instanceof Device) { + Device dev = (Device) parent; + Set children = dev.getChildResources(); + if (null != children && children.size() > 0) { + return children.toArray(); + } + } else if (parent instanceof CollectionResource) { + CollectionResource res = (CollectionResource) parent; + Set children = res.getChildResources(); + if (null != children && children.size() > 0) { + return children.toArray(); + } + } return null; } @Override public Object[] getElements(Object parent) { - List uriList; - uriList = Activator.getDefault().getResourceManager().getURIList(); - if (null == uriList) { - uriList = new ArrayList(); + List deviceList; + deviceList = Activator.getDefault().getResourceManager() + .getDeviceList(); + if (null == deviceList) { + deviceList = new ArrayList(); } - return uriList.toArray(); + return deviceList.toArray(); } @Override @@ -419,6 +1693,19 @@ class TreeContentProvider implements ITreeContentProvider { @Override public boolean hasChildren(Object parent) { + if (parent instanceof Device) { + Device dev = (Device) parent; + Set children = dev.getChildResources(); + if (null != children && children.size() > 0) { + return true; + } + } else if (parent instanceof CollectionResource) { + CollectionResource res = (CollectionResource) parent; + Set children = res.getChildResources(); + if (null != children && children.size() > 0) { + return true; + } + } return false; } } @@ -426,15 +1713,26 @@ class TreeContentProvider implements ITreeContentProvider { class TreeLabelProvider extends LabelProvider { @Override public String getText(Object element) { - String value = (String) element; - value = Utility.uriToDisplayName(value); - return value; + if (element instanceof Resource) { + Resource res = (Resource) element; + return res.getResourceName(); + } else { + Device dev = (Device) element; + return dev.getDeviceName(); + } } @Override public Image getImage(Object element) { - ResourceManager resourceManager = Activator.getDefault() - .getResourceManager(); - return resourceManager.getImage((String) element); + if (element instanceof SingleResource) { + return Activator.getDefault().getImageRegistry() + .get(Constants.SINGLE_RESOURCE); + } else if (element instanceof CollectionResource) { + return Activator.getDefault().getImageRegistry() + .get(Constants.COLLECTION_RESOURCE); + } else { + return Activator.getDefault().getImageRegistry() + .get(Constants.DEVICE); + } } } \ No newline at end of file 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 index 5e9361f..14fd2b2 100644 --- 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 @@ -22,10 +22,12 @@ import java.util.Set; import oic.simulator.serviceprovider.Activator; import oic.simulator.serviceprovider.listener.IObserverListChangedUIListener; -import oic.simulator.serviceprovider.listener.IResourceSelectionChangedUIListener; +import oic.simulator.serviceprovider.listener.ISelectionChangedUIListener; import oic.simulator.serviceprovider.manager.ResourceManager; -import oic.simulator.serviceprovider.resource.ObserverDetail; -import oic.simulator.serviceprovider.resource.SimulatorResource; +import oic.simulator.serviceprovider.manager.UiListenerHandler; +import oic.simulator.serviceprovider.model.Device; +import oic.simulator.serviceprovider.model.ObserverDetail; +import oic.simulator.serviceprovider.model.Resource; import oic.simulator.serviceprovider.utils.Constants; import org.eclipse.jface.viewers.CellEditor; @@ -51,60 +53,65 @@ import org.eclipse.ui.part.ViewPart; * This class manages and shows the resource observer view in the perspective. */ public class ResourceObserverView extends ViewPart { - public static final String VIEW_ID = "oic.simulator.serviceprovider.view.observer"; + public static final String VIEW_ID = "oic.simulator.serviceprovider.view.observer"; - private TableViewer tblViewer; + private TableViewer tblViewer; - private final String[] columnHeaders = { - "Client Address", "Port", "Notify" }; + private final String[] columnHeaders = { "Client Address", + "Port", "Notify" }; - private final Integer[] columnWidth = { 150, 75, 50 }; + private final Integer[] columnWidth = { 150, 75, 50 }; - private IResourceSelectionChangedUIListener resourceSelectionChangedListener; + private ISelectionChangedUIListener resourceSelectionChangedListener; - private IObserverListChangedUIListener resourceObserverListChangedListener; + private IObserverListChangedUIListener resourceObserverListChangedListener; - private ResourceManager resourceManagerRef; + private ResourceManager resourceManagerRef; public ResourceObserverView() { resourceManagerRef = Activator.getDefault().getResourceManager(); - resourceSelectionChangedListener = new IResourceSelectionChangedUIListener() { + resourceSelectionChangedListener = new ISelectionChangedUIListener() { @Override - public void onResourceSelectionChange() { + public void onResourceSelectionChange(final Resource resource) { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { if (null != tblViewer) { changeButtonStatus(); - updateViewer(getData(resourceManagerRef - .getCurrentResourceInSelection())); + updateViewer(getData(resource)); } } }); } + + @Override + public void onDeviceSelectionChange(Device dev) { + // TODO Auto-generated method stub + + } }; resourceObserverListChangedListener = new IObserverListChangedUIListener() { @Override - public void onObserverListChanged(final String resourceURI) { + public void onObserverListChanged(final Resource resource) { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { - if (null == resourceURI) { + if (null == resource) { return; } - SimulatorResource resource = resourceManagerRef + Resource resourceInSelection = resourceManagerRef .getCurrentResourceInSelection(); - if (null == resource) { + if (null == resourceInSelection) { return; } - if (resource.getResourceURI().equals(resourceURI)) { + if (resource == resourceInSelection) { if (null != tblViewer) { updateViewer(getData(resource)); } @@ -116,7 +123,7 @@ public class ResourceObserverView extends ViewPart { }; } - private Map getData(SimulatorResource resource) { + private Map getData(Resource resource) { if (null == resource) { return null; } @@ -229,10 +236,10 @@ public class ResourceObserverView extends ViewPart { } private void addManagerListeners() { - resourceManagerRef - .addResourceSelectionChangedUIListener(resourceSelectionChangedListener); - resourceManagerRef - .addObserverListChangedUIListener(resourceObserverListChangedListener); + UiListenerHandler.getInstance().addResourceSelectionChangedUIListener( + resourceSelectionChangedListener); + UiListenerHandler.getInstance().addObserverListChangedUIListener( + resourceObserverListChangedListener); } class ObserverContentProvider implements IStructuredContentProvider { @@ -273,7 +280,6 @@ public class ResourceObserverView extends ViewPart { @Override protected Object getValue(Object element) { - System.out.println("getValue()"); @SuppressWarnings("unchecked") Map.Entry observer = (Map.Entry) element; return observer.getValue().isClicked(); @@ -281,7 +287,6 @@ public class ResourceObserverView extends ViewPart { @Override protected void setValue(Object element, Object value) { - System.out.println("setValue()"); // Change the button status of all the resources changeButtonStatus(); @@ -298,8 +303,7 @@ public class ResourceObserverView extends ViewPart { } private void changeButtonStatus() { - SimulatorResource resource = resourceManagerRef - .getCurrentResourceInSelection(); + Resource resource = resourceManagerRef.getCurrentResourceInSelection(); if (null == resource) { return; } @@ -318,13 +322,15 @@ public class ResourceObserverView extends ViewPart { public void dispose() { // Unregister the listener if (null != resourceSelectionChangedListener) { - resourceManagerRef - .removeResourceSelectionChangedUIListener(resourceSelectionChangedListener); + UiListenerHandler.getInstance() + .removeResourceSelectionChangedUIListener( + resourceSelectionChangedListener); } if (null != resourceObserverListChangedListener) { - resourceManagerRef - .removeObserverListChangedUIListener(resourceObserverListChangedListener); + UiListenerHandler.getInstance() + .removeObserverListChangedUIListener( + resourceObserverListChangedListener); } super.dispose(); } diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/AddAttributeDialog.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/AddAttributeDialog.java new file mode 100644 index 0000000..6fc69fa --- /dev/null +++ b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/AddAttributeDialog.java @@ -0,0 +1,731 @@ +package oic.simulator.serviceprovider.view.dialogs; + +import java.util.Iterator; +import java.util.Set; + +import oic.simulator.serviceprovider.model.AttributeHelper; +import oic.simulator.serviceprovider.utils.Constants; + +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.dialogs.TitleAreaDialog; +import org.eclipse.jface.window.Window; +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.CCombo; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.graphics.Rectangle; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Event; +import org.eclipse.swt.widgets.Group; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.List; +import org.eclipse.swt.widgets.Listener; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Text; +import org.oic.simulator.AttributeProperty.Type; + +public class AddAttributeDialog extends TitleAreaDialog { + + private Text attNameTxt; + private Text minRangeTxt; + private Text maxRangeTxt; + private CCombo attTypeCmb; + private Text dflValueTxt; + private Button rangeBtn; + private Button cusValuesBtn; + private Button noneBtn; + private Button addBtn; + private Button remBtn; + private Label minLbl; + private Label maxLbl; + private List customValuesList; + private Text detail; + + private AttributeHelper attHelper; + + private AttributeHelper attClone; + + private Set attributes; + + private final String defaultMessage = "Name, Type, and Default Value fields " + + "are mandatory.\n\nRange and custom fields allow to set the valid " + + "values of the attribute.\n\n"; + private final String msgForBoolType = "Possible attribute values of Bool are " + + "true and false.\nSo range and custom options are disabled."; + private final String msgForIntType = "Valid values for Int type can either be " + + "of range type (Ex: 1 - 10) or custom values (Ex: 10, 20, 50, and 100).\n"; + private final String msgForDoubleType = "Valid values for Double type can either be " + + "of range type (Ex: 18.0 - 22.0) or custom values (Ex: 1.5, 2.5, 3.9, 4.8, etc).\n"; + private final String msgForStringType = "For String type, range option is not" + + "applicable. Hence it is disabled.\n\n" + + "Custom option is available to provide the valid values.\n\n" + + "Ex: low, mid, high, etc."; + + private Set attValueTypes; + + private boolean editOperation; + + public AddAttributeDialog(Shell parentShell, AttributeHelper att, + Set attValueTypes, Set attributes) { + super(parentShell); + if (null == att) { + att = new AttributeHelper(); + } else { + attClone = att.clone(); + System.out.println("Cloned attribute's data:" + attClone); + editOperation = true; + } + attHelper = att; + this.attValueTypes = attValueTypes; + this.attributes = attributes; + } + + @Override + public void create() { + super.create(); + setTitle("Add Attribute"); + setMessage("Fill the details for creating an attribute"); + } + + @Override + protected Control createDialogArea(Composite parent) { + Composite compLayout = (Composite) super.createDialogArea(parent); + Composite container = new Composite(compLayout, SWT.NONE); + container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + GridLayout layout = new GridLayout(5, false); + /* + * layout.verticalSpacing = 10; layout.marginTop = 10; + */ + container.setLayout(layout); + + Label attNameLbl = new Label(container, SWT.NULL); + attNameLbl.setText("Attribute Name:"); + + attNameTxt = new Text(container, SWT.BORDER); + GridData gd = new GridData(); + gd.horizontalAlignment = SWT.FILL; + gd.horizontalSpan = 4; + gd.grabExcessHorizontalSpace = true; + attNameTxt.setLayoutData(gd); + + Label attTypeLbl = new Label(container, SWT.NULL); + attTypeLbl.setText("Attribute Type:"); + + attTypeCmb = new CCombo(container, SWT.READ_ONLY | SWT.BORDER); + gd = new GridData(); + gd.grabExcessHorizontalSpace = true; + gd.horizontalSpan = 4; + gd.horizontalAlignment = SWT.FILL; + attTypeCmb.setLayoutData(gd); + initTypes(); + + Group valuesGrp = new Group(container, SWT.NULL); + valuesGrp.setText("Attribute Values"); + gd = new GridData(); + gd.verticalIndent = 10; + gd.horizontalSpan = 3; + gd.grabExcessHorizontalSpace = true; + gd.horizontalAlignment = SWT.FILL; + gd.grabExcessVerticalSpace = true; + gd.verticalAlignment = SWT.FILL; + valuesGrp.setLayoutData(gd); + layout = new GridLayout(4, false); + valuesGrp.setLayout(layout); + + rangeBtn = new Button(valuesGrp, SWT.RADIO); + rangeBtn.setText("Range"); + gd = new GridData(); + gd.horizontalSpan = 4; + rangeBtn.setLayoutData(gd); + + minLbl = new Label(valuesGrp, SWT.NONE); + minLbl.setText("Min:"); + gd = new GridData(); + gd.horizontalIndent = 25; + minLbl.setLayoutData(gd); + + minRangeTxt = new Text(valuesGrp, SWT.BORDER); + gd = new GridData(); + gd.widthHint = 70; + minRangeTxt.setLayoutData(gd); + + maxLbl = new Label(valuesGrp, SWT.NONE); + maxLbl.setText("Max:"); + gd = new GridData(); + gd.horizontalIndent = 25; + maxLbl.setLayoutData(gd); + + maxRangeTxt = new Text(valuesGrp, SWT.BORDER); + gd = new GridData(); + gd.widthHint = 70; + maxRangeTxt.setLayoutData(gd); + + cusValuesBtn = new Button(valuesGrp, SWT.RADIO); + cusValuesBtn.setText("Custom"); + gd = new GridData(); + gd.horizontalSpan = 4; + cusValuesBtn.setLayoutData(gd); + + Composite cusValuesComp = new Composite(valuesGrp, SWT.NONE); + gd = new GridData(SWT.FILL, SWT.FILL, true, true); + gd.horizontalSpan = 4; + cusValuesComp.setLayoutData(gd); + layout = new GridLayout(2, false); + cusValuesComp.setLayout(layout); + + customValuesList = new List(cusValuesComp, SWT.BORDER | SWT.MULTI + | SWT.V_SCROLL); + gd = new GridData(SWT.FILL, SWT.FILL, true, true); + gd.heightHint = 75; + gd.horizontalIndent = 25; + customValuesList.setLayoutData(gd); + + Composite cusValuesActionsComp = new Composite(cusValuesComp, SWT.NONE); + layout = new GridLayout(); + cusValuesActionsComp.setLayout(layout); + gd = new GridData(); + gd.verticalAlignment = SWT.TOP; + cusValuesActionsComp.setLayoutData(gd); + + addBtn = new Button(cusValuesActionsComp, SWT.PUSH); + addBtn.setText("Add"); + gd = new GridData(); + gd.widthHint = 70; + addBtn.setLayoutData(gd); + + remBtn = new Button(cusValuesActionsComp, SWT.PUSH); + remBtn.setText("Remove"); + gd = new GridData(); + gd.widthHint = 70; + remBtn.setLayoutData(gd); + remBtn.setEnabled(false); + + noneBtn = new Button(valuesGrp, SWT.RADIO); + noneBtn.setText("None"); + gd = new GridData(); + gd.horizontalSpan = 4; + noneBtn.setLayoutData(gd); + + Composite detailsComp = new Composite(container, SWT.NULL); + detailsComp.setLayout(new GridLayout()); + gd = new GridData(SWT.FILL, SWT.FILL, true, true); + gd.horizontalSpan = 2; + gd.widthHint = 100; + detailsComp.setLayoutData(gd); + + Label lbl = new Label(detailsComp, SWT.NULL); + lbl.setText("Details"); + + Group detailsGrp = new Group(detailsComp, SWT.NULL); + detailsGrp.setLayout(new GridLayout()); + gd = new GridData(SWT.FILL, SWT.FILL, true, true); + detailsGrp.setLayoutData(gd); + + detail = new Text(detailsGrp, SWT.MULTI | SWT.READ_ONLY | SWT.BORDER + | SWT.WRAP | SWT.V_SCROLL); + detail.setBackground(detailsGrp.getBackground()); + detail.setText(defaultMessage); + gd = new GridData(SWT.FILL, SWT.FILL, true, true); + detail.setLayoutData(gd); + + Label dflValueLbl = new Label(container, SWT.NULL); + dflValueLbl.setText("Default value"); + + dflValueTxt = new Text(container, SWT.BORDER); + gd = new GridData(); + gd.horizontalSpan = 4; + gd.grabExcessHorizontalSpace = true; + gd.horizontalAlignment = SWT.FILL; + dflValueTxt.setLayoutData(gd); + + setUiListeners(); + + if (editOperation) { + initData(); + attNameTxt.setFocus(); + } else { + setInitialSelection(); + } + + return compLayout; + } + + private void initTypes() { + if (null != attValueTypes && attValueTypes.size() > 0) { + Iterator itr = attValueTypes.iterator(); + while (itr.hasNext()) { + attTypeCmb.add(itr.next()); + } + } + } + + private void setInitialSelection() { + enable(false); + rangeOptionSelected(false); + customOptionSelected(false); + } + + private void initData() { + if (editOperation) { + // Populate the UI controls with the data. + attNameTxt.setText(attHelper.getAttributeName()); + attTypeCmb.select(attTypeCmb.indexOf(attHelper.getAttributeType())); + updateControls(); + dflValueTxt.setText(attHelper.getAttributeDflValue()); + Type valuesType = attHelper.getValidValuesType(); + /* + * if (valuesType == Type.UNKNOWN) { noneBtn.setSelection(true); } + * else + */if (valuesType == Type.RANGE) { + rangeBtn.setSelection(true); + noneBtn.setSelection(false); + rangeOptionSelected(true); + minRangeTxt.setText(attHelper.getMin()); + maxRangeTxt.setText(attHelper.getMax()); + } else if (valuesType == Type.VALUESET) { + cusValuesBtn.setSelection(true); + noneBtn.setSelection(false); + customOptionSelected(true); + Set allowedValues = attHelper.getAllowedValues(); + customValuesList.setItems(allowedValues.toArray(new String[1])); + } + } + } + + private void setUiListeners() { + + /* + * attNameTxt.addModifyListener(new ModifyListener() { + * + * @Override public void modifyText(ModifyEvent e) { String value = + * attNameTxt.getText(); if(null != value) { value = value.trim(); } + * attHelper.setAttributeName(value); } }); + * + * dflValueTxt.addModifyListener(new ModifyListener() { + * + * @Override public void modifyText(ModifyEvent arg0) { String value = + * dflValueTxt.getText(); if(null != value) { value = value.trim(); } + * attHelper.setAttributeDflValue(value); } }); + */ + rangeBtn.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + rangeOptionSelected(true); + customOptionSelected(false); + minRangeTxt.setFocus(); + } + }); + + cusValuesBtn.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + addBtn.setFocus(); + rangeOptionSelected(false); + customOptionSelected(true); + } + }); + + noneBtn.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + rangeOptionSelected(false); + customOptionSelected(false); + } + }); + + attTypeCmb.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + updateControls(); + } + }); + + minRangeTxt.addListener(SWT.Verify, new Listener() { + @Override + public void handleEvent(Event e) { + String string = e.text; + System.out.println(string); + char[] chars = new char[string.length()]; + string.getChars(0, chars.length, chars, 0); + for (int i = 0; i < chars.length; i++) { + if (!('0' <= chars[i] && chars[i] <= '9')) { + if (attTypeCmb.getText().equals(Constants.INT)) { + e.doit = false; + return; + } else if (attTypeCmb.getText() + .equals(Constants.DOUBLE)) { + if (!(chars[i] == '.')) { + e.doit = false; + return; + } + } + } + } + // attHelper.setMin(minRangeTxt.getText() + string); + } + }); + + maxRangeTxt.addListener(SWT.Verify, new Listener() { + @Override + public void handleEvent(Event e) { + String string = e.text; + char[] chars = new char[string.length()]; + string.getChars(0, chars.length, chars, 0); + for (int i = 0; i < chars.length; i++) { + if (!('0' <= chars[i] && chars[i] <= '9')) { + if (attTypeCmb.getText().equals(Constants.INT)) { + e.doit = false; + return; + } else if (attTypeCmb.getText() + .equals(Constants.DOUBLE)) { + if (!(chars[i] == '.')) { + e.doit = false; + return; + } + } + } + } + // attHelper.setMax(maxRangeTxt.getText() + string); + } + }); + + addBtn.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + SingleTextInputDialog dialog = new SingleTextInputDialog( + getShell(), "Add Attribute Value", "Attribute Value"); + if (dialog.open() == Window.OK) { + System.out.println(dialog.getValue()); + String value = dialog.getValue(); + String type = attTypeCmb.getText(); + if (!attHelper.isValueValid(value, type)) { + MessageDialog.openError(getParentShell(), + "Invalid value", "Attribute value is invalid."); + } else if (attHelper.isAllowedValueExist( + customValuesList.getItems(), value)) { + MessageDialog.openError(getParentShell(), + "Duplicate value", + "Attribute value already exists."); + } else { + customValuesList.add(value); + customValuesList.deselectAll(); + customValuesList.select(customValuesList.getItemCount() - 1); + customValuesList.showSelection(); + remBtn.setEnabled(true); + // attHelper.addValueToAllowedValues(value); + } + } + } + }); + + remBtn.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + int[] selection = customValuesList.getSelectionIndices(); + // String[] selectionStr = customValuesList.getSelection(); + if (null != selection && selection.length > 0) { + customValuesList.remove(selection); + /* + * for (String selected : selectionStr) { + * attHelper.removeValueFromAllowedValues(selected); } + */ + } + + changeRemBtnVisibility(); + } + }); + + customValuesList.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + changeRemBtnVisibility(); + } + }); + } + + private void updateControls() { + rangeBtn.setSelection(false); + cusValuesBtn.setSelection(false); + noneBtn.setSelection(true); + + cleanRangeAndCustomValues(); + dflValueTxt.setText(""); + + String selected = attTypeCmb.getText(); + // attHelper.setAttributeType(selected); + + if (selected.equals(Constants.INT)) { + enable(true); + rangeOptionSelected(false); + customOptionSelected(false); + detail.setText(defaultMessage + msgForIntType); + } else if (selected.equals(Constants.DOUBLE)) { + enable(true); + rangeOptionSelected(false); + customOptionSelected(false); + detail.setText(defaultMessage + msgForDoubleType); + } else if (selected.equals(Constants.BOOL)) { + // noneBtn.setSelection(true); + enable(false); + rangeOptionSelected(false); + customOptionSelected(false); + detail.setText(defaultMessage + msgForBoolType); + } else if (selected.equals(Constants.STRING)) { + rangeBtn.setEnabled(false); + rangeOptionSelected(false); + cusValuesBtn.setEnabled(true); + noneBtn.setEnabled(true); + // cusValuesBtn.setSelection(true); + detail.setText(defaultMessage + msgForStringType); + } else { + // noneBtn.setSelection(true); + enable(false); + rangeOptionSelected(false); + customOptionSelected(false); + detail.setText(defaultMessage); + } + } + + private void changeRemBtnVisibility() { + if (cusValuesBtn.isEnabled() && cusValuesBtn.getSelection()) { + int[] selection = customValuesList.getSelectionIndices(); + if (null != selection && selection.length > 0) { + remBtn.setEnabled(true); + } else { + remBtn.setEnabled(false); + } + } else { + remBtn.setEnabled(false); + } + } + + private void enable(boolean enable) { + rangeBtn.setEnabled(enable); + cusValuesBtn.setEnabled(enable); + noneBtn.setEnabled(enable); + } + + private void rangeOptionSelected(boolean enable) { + minRangeTxt.setEnabled(enable); + maxRangeTxt.setEnabled(enable); + minLbl.setEnabled(enable); + maxLbl.setEnabled(enable); + } + + private void customOptionSelected(boolean enable) { + customValuesList.setEnabled(enable); + addBtn.setEnabled(enable); + changeRemBtnVisibility(); + } + + private void cleanRangeAndCustomValues() { + cleanRangeValues(); + cleanCustomValues(); + } + + private void cleanRangeValues() { + minRangeTxt.setText(""); + maxRangeTxt.setText(""); + } + + private void cleanCustomValues() { + customValuesList.removeAll(); + } + + public AttributeHelper getAttHelper() { + return attHelper; + } + + public AttributeHelper getAttClone() { + return attClone; + } + + @Override + protected void okPressed() { + // Attribute Name + String attName = attNameTxt.getText(); + if (null == attName || attName.isEmpty()) { + MessageDialog.openError(getParentShell(), + "Mandatory field is empty", + "Please fill the attribute name."); + attNameTxt.setFocus(); + return; + } + attName = attName.trim(); + if (attName.length() < 1) { + MessageDialog.openError(getParentShell(), + "Mandatory field is empty", "Attribute name is invalid."); + attNameTxt.setFocus(); + return; + } + attHelper.setAttributeName(attName); + + // Duplicate check for attribute name if this is not editing operation + if (!editOperation) { + if (!attributes.isEmpty()) { + Iterator itr = attributes.iterator(); + AttributeHelper att; + while (itr.hasNext()) { + att = itr.next(); + if (att.getAttributeName().equals(attName)) { + MessageDialog + .openError( + getParentShell(), + "Duplicate Attribute", + "Another attribute with the same attribute name exist. Please enter a new attribute name."); + attNameTxt.setFocus(); + return; + } + } + } + } + + // Attribute Type + String attType = attTypeCmb.getText(); + if (null == attType || attType.isEmpty()) { + MessageDialog.openError(getParentShell(), + "Mandatory field is empty", + "Please select an attribute type."); + return; + } + attHelper.setAttributeType(attType); + + // Attribute values + if (rangeBtn.isEnabled() && rangeBtn.getSelection()) { // Range option + String min = minRangeTxt.getText(); + String max = maxRangeTxt.getText(); + if (null == min && null == max) { + MessageDialog + .openError(getParentShell(), "Range is empty", + "Please enter the minimum and maximum value of the range."); + minRangeTxt.setFocus(); + return; + } + if (null == min || null == max) { + String msg; + msg = "Please enter the " + + ((null == min) ? "minimum value" : "maximum value") + + "of the range."; + MessageDialog + .openError(getParentShell(), "Range is empty", msg); + ((null == min) ? minRangeTxt : maxRangeTxt).setFocus(); + return; + } + if (min.isEmpty() && max.isEmpty()) { + MessageDialog + .openError(getParentShell(), "Range is empty", + "Please enter the minimum and maximum value of the range."); + minRangeTxt.setFocus(); + return; + } + if (min.isEmpty()) { + MessageDialog.openError(getParentShell(), "Range is empty", + "Please enter the minimum value for the range."); + minRangeTxt.setFocus(); + return; + } + if (max.isEmpty()) { + MessageDialog.openError(getParentShell(), "Range is empty", + "Please enter the maximum value for the range."); + maxRangeTxt.setFocus(); + return; + } + + if (!min.isEmpty() && !max.isEmpty() + && !attHelper.isRangeValid(min, max, attType)) { + MessageDialog.openError(getParentShell(), "Invalid range", + "Range is invalid."); + maxRangeTxt.setFocus(); + return; + } + attHelper.setValidValuesType(Type.RANGE); + attHelper.setMin(min); + attHelper.setMax(max); + + if (editOperation) { + // Remove all existing custom values + attHelper.setAllowedValues(null); + } + } else if (cusValuesBtn.isEnabled() && cusValuesBtn.getSelection()) { + String[] cusItems = customValuesList.getItems(); + if (null == cusItems || cusItems.length < 1) { + MessageDialog.openError(getParentShell(), + "Custom list is empty.", + "No values are added to the custom list."); + maxRangeTxt.setFocus(); + return; + } + attHelper.setValidValuesType(Type.VALUESET); + attHelper.setAllowedValuesByArray(cusItems); + + if (editOperation) { + // Remove min and max values + attHelper.setMin(null); + attHelper.setMax(null); + } + } else if (noneBtn.isEnabled() && noneBtn.getSelection()) { + attHelper.setValidValuesType(Type.UNKNOWN); + if (editOperation) { + // Remove min, max and custom values + attHelper.setAllowedValues(null); + attHelper.setMin(null); + attHelper.setMax(null); + } + } + + // Attribute Default Value + String attDflValue = dflValueTxt.getText(); + if (null == attDflValue || attDflValue.isEmpty()) { + MessageDialog.openError(getParentShell(), + "Mandatory field is empty", + "Please enter a default value for the attribute."); + dflValueTxt.setFocus(); + return; + } + attDflValue = attDflValue.trim(); + if (attDflValue.length() < 1 + || !attHelper.isValueValid(attDflValue, attType)) { + MessageDialog.openError(getParentShell(), "Invalid value", + "Default value is invalid."); + dflValueTxt.setFocus(); + return; + } + if (!attHelper.isDefaultValueValid(attDflValue)) { + MessageDialog.openError(getParentShell(), "Invalid value", + "Default value is not in the valid values."); + dflValueTxt.setFocus(); + return; + } + + attHelper.setAttributeDflValue(attDflValue.toLowerCase()); + + close(); + } + + @Override + public boolean isHelpAvailable() { + return false; + } + + /* + * @Override protected Point getInitialSize() { Point curSize = + * super.getInitialSize(); return new Point(curSize.x, curSize.y + 200); } + */ + + @Override + protected Point getInitialLocation(Point initialSize) { + Rectangle shellBounds = Display.getDefault().getActiveShell() + .getBounds(); + Point dialogSize = getInitialSize(); + + return new Point( + shellBounds.x + (shellBounds.width - dialogSize.x) / 2, + shellBounds.y + (shellBounds.height - dialogSize.y) / 2); + } +} \ No newline at end of file diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/AddResourceToCollections.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/AddResourceToCollections.java new file mode 100644 index 0000000..914e515 --- /dev/null +++ b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/AddResourceToCollections.java @@ -0,0 +1,206 @@ +/* + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package oic.simulator.serviceprovider.view.dialogs; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import oic.simulator.serviceprovider.Activator; +import oic.simulator.serviceprovider.model.CollectionResource; +import oic.simulator.serviceprovider.utils.Constants; + +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.dialogs.TitleAreaDialog; +import org.eclipse.jface.viewers.CheckStateChangedEvent; +import org.eclipse.jface.viewers.CheckboxTreeViewer; +import org.eclipse.jface.viewers.ICheckStateListener; +import org.eclipse.jface.viewers.ITreeContentProvider; +import org.eclipse.jface.viewers.LabelProvider; +import org.eclipse.jface.viewers.Viewer; +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Group; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Shell; + +/** + * This dialog is used for loading the RAML file. + */ +public class AddResourceToCollections extends TitleAreaDialog { + + private CheckboxTreeViewer treeViewer; + + List sourceList; + + Set selectedResourceList; + + public AddResourceToCollections(Shell parentShell, + List sourceList) { + super(parentShell); + this.sourceList = sourceList; + selectedResourceList = new HashSet(); + } + + @Override + public void create() { + super.create(); + setTitle("Add To Collections"); + setMessage("Select one or more collection resources to which the single resource will be added."); + } + + @Override + protected Control createDialogArea(Composite parent) { + Composite compLayout = (Composite) super.createDialogArea(parent); + Composite container = new Composite(compLayout, SWT.NONE); + container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + GridLayout layout = new GridLayout(); + layout.verticalSpacing = 10; + layout.marginTop = 10; + container.setLayout(layout); + + Label lbl = new Label(container, SWT.NONE); + lbl.setText("Select Resources from:"); + GridData gd; + gd = new GridData(); + gd.grabExcessHorizontalSpace = true; + gd.horizontalAlignment = SWT.FILL; + lbl.setLayoutData(gd); + + Group resourceGroup = new Group(container, SWT.NONE); + + Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE); + + resourceGroup.setLayout(new GridLayout()); + gd = new GridData(); + gd.grabExcessHorizontalSpace = true; + gd.horizontalAlignment = SWT.FILL; + gd.heightHint = 300; + gd.horizontalSpan = 2; + resourceGroup.setLayoutData(gd); + + treeViewer = new CheckboxTreeViewer(resourceGroup); + treeViewer.getTree().setBackground(color); + gd = new GridData(); + gd.grabExcessHorizontalSpace = true; + gd.horizontalAlignment = SWT.FILL; + gd.grabExcessVerticalSpace = true; + gd.verticalAlignment = SWT.FILL; + // gd.heightHint = 300; + treeViewer.getTree().setLayoutData(gd); + treeViewer.setContentProvider(new TreeContentProvider()); + treeViewer.setLabelProvider(new TreeLabelProvider()); + treeViewer.setInput(new Object()); + treeViewer.addCheckStateListener(new ICheckStateListener() { + + @Override + public void checkStateChanged(CheckStateChangedEvent e) { + CollectionResource res = (CollectionResource) e.getElement(); + if (null != res) { + if (e.getChecked()) { + selectedResourceList.add(res); + System.out.println("Checked" + res.getResourceName()); + } else { + selectedResourceList.remove(res); + System.out.println("Unchecked:" + res.getResourceName()); + } + } + } + }); + + return compLayout; + } + + public Set getSelectedResourceList() { + return selectedResourceList; + } + + class TreeContentProvider implements ITreeContentProvider { + + @Override + public void dispose() { + } + + @Override + public void inputChanged(Viewer arg0, Object arg1, Object arg2) { + } + + @Override + public Object[] getChildren(Object parent) { + return null; + } + + @Override + public Object[] getElements(Object parent) { + if (null == sourceList) { + sourceList = new ArrayList(); + } + return sourceList.toArray(); + } + + @Override + public Object getParent(Object child) { + return null; + } + + @Override + public boolean hasChildren(Object parent) { + return false; + } + } + + class TreeLabelProvider extends LabelProvider { + @Override + public String getText(Object element) { + CollectionResource res = (CollectionResource) element; + return res.getResourceName(); + } + + @Override + public Image getImage(Object element) { + if (element instanceof CollectionResource) { + return Activator.getDefault().getImageRegistry() + .get(Constants.COLLECTION_RESOURCE); + } else { + return null; + } + } + } + + @Override + protected void okPressed() { + if (selectedResourceList.isEmpty()) { + MessageDialog.openInformation( + Display.getDefault().getActiveShell(), + "No selection done.", "No resources are selected."); + return; + } + close(); + } + + @Override + public boolean isHelpAvailable() { + return false; + } +} diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/AddResourceToDevices.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/AddResourceToDevices.java new file mode 100644 index 0000000..8eaaa5f --- /dev/null +++ b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/AddResourceToDevices.java @@ -0,0 +1,205 @@ +/* + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package oic.simulator.serviceprovider.view.dialogs; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import oic.simulator.serviceprovider.Activator; +import oic.simulator.serviceprovider.model.Device; +import oic.simulator.serviceprovider.utils.Constants; + +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.dialogs.TitleAreaDialog; +import org.eclipse.jface.viewers.CheckStateChangedEvent; +import org.eclipse.jface.viewers.CheckboxTreeViewer; +import org.eclipse.jface.viewers.ICheckStateListener; +import org.eclipse.jface.viewers.ITreeContentProvider; +import org.eclipse.jface.viewers.LabelProvider; +import org.eclipse.jface.viewers.Viewer; +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Group; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Shell; + +/** + * This dialog is used for loading the RAML file. + */ +public class AddResourceToDevices extends TitleAreaDialog { + + private CheckboxTreeViewer treeViewer; + + List sourceList; + + Set selectedDeviceList; + + public AddResourceToDevices(Shell parentShell, List sourceList) { + super(parentShell); + this.sourceList = sourceList; + selectedDeviceList = new HashSet(); + } + + @Override + public void create() { + super.create(); + setTitle("Add To Devices"); + setMessage("Select one or more devices to which the single resource will be added."); + } + + @Override + protected Control createDialogArea(Composite parent) { + Composite compLayout = (Composite) super.createDialogArea(parent); + Composite container = new Composite(compLayout, SWT.NONE); + container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + GridLayout layout = new GridLayout(); + layout.verticalSpacing = 10; + layout.marginTop = 10; + container.setLayout(layout); + + Label lbl = new Label(container, SWT.NONE); + lbl.setText("Select Resources from:"); + GridData gd; + gd = new GridData(); + gd.grabExcessHorizontalSpace = true; + gd.horizontalAlignment = SWT.FILL; + lbl.setLayoutData(gd); + + Group resourceGroup = new Group(container, SWT.NONE); + + Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE); + + resourceGroup.setLayout(new GridLayout()); + gd = new GridData(); + gd.grabExcessHorizontalSpace = true; + gd.horizontalAlignment = SWT.FILL; + gd.heightHint = 300; + gd.horizontalSpan = 2; + resourceGroup.setLayoutData(gd); + + treeViewer = new CheckboxTreeViewer(resourceGroup); + treeViewer.getTree().setBackground(color); + gd = new GridData(); + gd.grabExcessHorizontalSpace = true; + gd.horizontalAlignment = SWT.FILL; + gd.grabExcessVerticalSpace = true; + gd.verticalAlignment = SWT.FILL; + // gd.heightHint = 300; + treeViewer.getTree().setLayoutData(gd); + treeViewer.setContentProvider(new TreeContentProvider()); + treeViewer.setLabelProvider(new TreeLabelProvider()); + treeViewer.setInput(new Object()); + treeViewer.addCheckStateListener(new ICheckStateListener() { + + @Override + public void checkStateChanged(CheckStateChangedEvent e) { + Device dev = (Device) e.getElement(); + if (null != dev) { + if (e.getChecked()) { + selectedDeviceList.add(dev); + System.out.println("Checked" + dev.getDeviceName()); + } else { + selectedDeviceList.remove(dev); + System.out.println("Unchecked:" + dev.getDeviceName()); + } + } + } + }); + + return compLayout; + } + + public Set getSelectedDeviceList() { + return selectedDeviceList; + } + + class TreeContentProvider implements ITreeContentProvider { + + @Override + public void dispose() { + } + + @Override + public void inputChanged(Viewer arg0, Object arg1, Object arg2) { + } + + @Override + public Object[] getChildren(Object parent) { + return null; + } + + @Override + public Object[] getElements(Object parent) { + if (null == sourceList) { + sourceList = new ArrayList(); + } + return sourceList.toArray(); + } + + @Override + public Object getParent(Object child) { + return null; + } + + @Override + public boolean hasChildren(Object parent) { + return false; + } + } + + class TreeLabelProvider extends LabelProvider { + @Override + public String getText(Object element) { + Device dev = (Device) element; + return dev.getDeviceName(); + } + + @Override + public Image getImage(Object element) { + if (element instanceof Device) { + return Activator.getDefault().getImageRegistry() + .get(Constants.DEVICE); + } else { + return null; + } + } + } + + @Override + protected void okPressed() { + if (selectedDeviceList.isEmpty()) { + MessageDialog.openInformation( + Display.getDefault().getActiveShell(), + "No selection done.", "No devices are selected."); + return; + } + close(); + } + + @Override + public boolean isHelpAvailable() { + return false; + } +} diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/AddResources.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/AddResources.java new file mode 100644 index 0000000..6e13f6c --- /dev/null +++ b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/AddResources.java @@ -0,0 +1,207 @@ +/* + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package oic.simulator.serviceprovider.view.dialogs; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import oic.simulator.serviceprovider.Activator; +import oic.simulator.serviceprovider.model.CollectionResource; +import oic.simulator.serviceprovider.model.Resource; +import oic.simulator.serviceprovider.utils.Constants; + +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.dialogs.TitleAreaDialog; +import org.eclipse.jface.viewers.CheckStateChangedEvent; +import org.eclipse.jface.viewers.CheckboxTreeViewer; +import org.eclipse.jface.viewers.ICheckStateListener; +import org.eclipse.jface.viewers.ITreeContentProvider; +import org.eclipse.jface.viewers.LabelProvider; +import org.eclipse.jface.viewers.Viewer; +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Group; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Shell; + +/** + * This dialog is used for loading the RAML file. + */ +public class AddResources extends TitleAreaDialog { + + private CheckboxTreeViewer treeViewer; + + List sourceList; + + Set selectedResourceList; + + public AddResources(Shell parentShell, List sourceList) { + super(parentShell); + this.sourceList = sourceList; + selectedResourceList = new HashSet(); + } + + @Override + public void create() { + super.create(); + setTitle("Add Resources"); + setMessage("Select one or more resources to be added."); + } + + @Override + protected Control createDialogArea(Composite parent) { + Composite compLayout = (Composite) super.createDialogArea(parent); + Composite container = new Composite(compLayout, SWT.NONE); + container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + GridLayout layout = new GridLayout(); + layout.verticalSpacing = 10; + layout.marginTop = 10; + container.setLayout(layout); + + Label lbl = new Label(container, SWT.NONE); + lbl.setText("Select Resources from:"); + GridData gd; + gd = new GridData(); + gd.grabExcessHorizontalSpace = true; + gd.horizontalAlignment = SWT.FILL; + lbl.setLayoutData(gd); + + Group resourceGroup = new Group(container, SWT.NONE); + + Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE); + + resourceGroup.setLayout(new GridLayout()); + gd = new GridData(); + gd.grabExcessHorizontalSpace = true; + gd.horizontalAlignment = SWT.FILL; + gd.heightHint = 300; + gd.horizontalSpan = 2; + resourceGroup.setLayoutData(gd); + + treeViewer = new CheckboxTreeViewer(resourceGroup); + treeViewer.getTree().setBackground(color); + gd = new GridData(); + gd.grabExcessHorizontalSpace = true; + gd.horizontalAlignment = SWT.FILL; + gd.grabExcessVerticalSpace = true; + gd.verticalAlignment = SWT.FILL; + // gd.heightHint = 300; + treeViewer.getTree().setLayoutData(gd); + treeViewer.setContentProvider(new TreeContentProvider()); + treeViewer.setLabelProvider(new TreeLabelProvider()); + treeViewer.setInput(new Object()); + treeViewer.addCheckStateListener(new ICheckStateListener() { + + @Override + public void checkStateChanged(CheckStateChangedEvent e) { + Resource res = (Resource) e.getElement(); + if (null != res) { + if (e.getChecked()) { + selectedResourceList.add(res); + System.out.println("Checked" + res.getResourceName()); + } else { + selectedResourceList.remove(res); + System.out.println("Unchecked:" + res.getResourceName()); + } + } + } + }); + + return compLayout; + } + + public Set getSelectedResourceList() { + return selectedResourceList; + } + + class TreeContentProvider implements ITreeContentProvider { + + @Override + public void dispose() { + } + + @Override + public void inputChanged(Viewer arg0, Object arg1, Object arg2) { + } + + @Override + public Object[] getChildren(Object parent) { + return null; + } + + @Override + public Object[] getElements(Object parent) { + if (null == sourceList) { + sourceList = new ArrayList(); + } + return sourceList.toArray(); + } + + @Override + public Object getParent(Object child) { + return null; + } + + @Override + public boolean hasChildren(Object parent) { + return false; + } + } + + class TreeLabelProvider extends LabelProvider { + @Override + public String getText(Object element) { + Resource res = (Resource) element; + return res.getResourceName(); + } + + @Override + public Image getImage(Object element) { + if (element instanceof CollectionResource) { + return Activator.getDefault().getImageRegistry() + .get(Constants.COLLECTION_RESOURCE); + } else { + return Activator.getDefault().getImageRegistry() + .get(Constants.SINGLE_RESOURCE); + } + } + } + + @Override + protected void okPressed() { + if (selectedResourceList.isEmpty()) { + MessageDialog.openInformation( + Display.getDefault().getActiveShell(), + "No selection done.", "No resources are selected."); + return; + } + close(); + } + + @Override + public boolean isHelpAvailable() { + return false; + } +} diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/AddResourcesToCollectionPage.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/AddResourcesToCollectionPage.java new file mode 100644 index 0000000..d745c38 --- /dev/null +++ b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/AddResourcesToCollectionPage.java @@ -0,0 +1,169 @@ +package oic.simulator.serviceprovider.view.dialogs; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import oic.simulator.serviceprovider.Activator; +import oic.simulator.serviceprovider.model.CollectionResource; +import oic.simulator.serviceprovider.model.Resource; +import oic.simulator.serviceprovider.model.SingleResource; +import oic.simulator.serviceprovider.utils.Constants; + +import org.eclipse.jface.viewers.CheckStateChangedEvent; +import org.eclipse.jface.viewers.CheckboxTreeViewer; +import org.eclipse.jface.viewers.ICheckStateListener; +import org.eclipse.jface.viewers.ITreeContentProvider; +import org.eclipse.jface.viewers.LabelProvider; +import org.eclipse.jface.viewers.Viewer; +import org.eclipse.jface.wizard.IWizardPage; +import org.eclipse.jface.wizard.WizardPage; +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Group; + +public class AddResourcesToCollectionPage extends WizardPage { + + private CheckboxTreeViewer treeViewer; + + Set selectedResourceList; + + protected AddResourcesToCollectionPage() { + super("Add Resources To Collection"); + selectedResourceList = new HashSet(); + } + + @Override + public void createControl(Composite parent) { + setPageComplete(false); + setTitle(Constants.COLLECTION_RESOURCE_ADD_OTHER_RESOURCES_PAGE_TITLE); + setMessage(Constants.COLLECTION_RESOURCE_ADD_OTHER_RESOURCES_PAGE_MESSAGE); + + Composite container = new Composite(parent, SWT.NONE); + GridLayout gridLayout = new GridLayout(); + container.setLayout(gridLayout); + GridData gd = new GridData(); + gd.grabExcessHorizontalSpace = true; + gd.horizontalAlignment = SWT.FILL; + gd.heightHint = 300; + container.setLayoutData(gd); + + Group resourceGroup = new Group(container, SWT.NONE); + + Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE); + + resourceGroup.setLayout(new GridLayout()); + gd = new GridData(); + gd.grabExcessHorizontalSpace = true; + gd.horizontalAlignment = SWT.FILL; + gd.heightHint = 300; + resourceGroup.setLayoutData(gd); + + treeViewer = new CheckboxTreeViewer(resourceGroup); + treeViewer.getTree().setBackground(color); + gd = new GridData(); + gd.grabExcessHorizontalSpace = true; + gd.horizontalAlignment = SWT.FILL; + gd.grabExcessVerticalSpace = true; + gd.verticalAlignment = SWT.FILL; + // gd.heightHint = 300; + treeViewer.getTree().setLayoutData(gd); + treeViewer.setContentProvider(new TreeContentProvider()); + treeViewer.setLabelProvider(new TreeLabelProvider()); + treeViewer.setInput(new Object()); + treeViewer.addCheckStateListener(new ICheckStateListener() { + + @Override + public void checkStateChanged(CheckStateChangedEvent e) { + Resource res = (Resource) e.getElement(); + if (null != res) { + if (e.getChecked()) { + selectedResourceList.add(res); + System.out.println("Checked" + res.getResourceName()); + } else { + selectedResourceList.remove(res); + System.out.println("Unchecked:" + res.getResourceName()); + } + } + } + }); + + setControl(container); + } + + @Override + public IWizardPage getNextPage() { + return null; + } + + public Set getSelectedResourceList() { + return selectedResourceList; + } + + class TreeContentProvider implements ITreeContentProvider { + + @Override + public void dispose() { + } + + @Override + public void inputChanged(Viewer arg0, Object arg1, Object arg2) { + } + + @Override + public Object[] getChildren(Object parent) { + System.out.println("getChildren()"); + + return null; + } + + @Override + public Object[] getElements(Object parent) { + List resList; + resList = Activator.getDefault().getResourceManager() + .getResourceList(); + if (null == resList) { + resList = new ArrayList(); + } + return resList.toArray(); + } + + @Override + public Object getParent(Object child) { + return null; + } + + @Override + public boolean hasChildren(Object parent) { + return false; + } + } + + class TreeLabelProvider extends LabelProvider { + @Override + public String getText(Object element) { + Resource res = (Resource) element; + return res.getResourceName(); + } + + @Override + public Image getImage(Object element) { + if (element instanceof SingleResource) { + return Activator.getDefault().getImageRegistry() + .get(Constants.SINGLE_RESOURCE); + } else if (element instanceof CollectionResource) { + return Activator.getDefault().getImageRegistry() + .get(Constants.COLLECTION_RESOURCE); + } else { + return Activator.getDefault().getImageRegistry() + .get(Constants.DEVICE); + } + } + } +} 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 index e2bb48f..f6ab64b 100644 --- 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 @@ -19,7 +19,7 @@ package oic.simulator.serviceprovider.view.dialogs; import java.util.Iterator; import java.util.List; -import oic.simulator.serviceprovider.resource.AutomationSettingHelper; +import oic.simulator.serviceprovider.model.AutomationSettingHelper; import oic.simulator.serviceprovider.utils.Constants; import org.eclipse.jface.dialogs.TitleAreaDialog; diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/CollectionResourceBasicDetailsPage.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/CollectionResourceBasicDetailsPage.java new file mode 100644 index 0000000..5024c6d --- /dev/null +++ b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/CollectionResourceBasicDetailsPage.java @@ -0,0 +1,337 @@ +package oic.simulator.serviceprovider.view.dialogs; + +import java.util.HashSet; +import java.util.Set; + +import oic.simulator.serviceprovider.Activator; +import oic.simulator.serviceprovider.utils.Constants; + +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.window.Window; +import org.eclipse.jface.wizard.IWizardPage; +import org.eclipse.jface.wizard.WizardPage; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.ModifyEvent; +import org.eclipse.swt.events.ModifyListener; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Group; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.List; +import org.eclipse.swt.widgets.Text; + +public class CollectionResourceBasicDetailsPage extends WizardPage { + + private Text resNameTxt; + private Text resUriTxt; + private List resTypeslist; + private Button addToListBtn; + private Button remFromListBtn; + private Button observeBtn; + // private Button startBtn; + + private String resName; + private String resURI; + private Set resTypes; + // private boolean start; + private boolean observable; + private boolean anyResourceExist; + + protected CollectionResourceBasicDetailsPage() { + super("Basic Details"); + resTypes = new HashSet(); + anyResourceExist = Activator.getDefault().getResourceManager() + .isAnyResourceExist(); + } + + @Override + public void createControl(Composite parent) { + setPageComplete(false); + if (anyResourceExist) + setTitle(Constants.COLLECTION_RESOURCE_BASIC_DETAILS_PAGE_TITLE2); + else + setTitle(Constants.COLLECTION_RESOURCE_BASIC_DETAILS_PAGE_TITLE1); + setMessage(Constants.COLLECTION_RESOURCE_BASIC_DETAILS_PAGE_MESSAGE); + + Composite container = new Composite(parent, SWT.NONE); + GridLayout gridLayout = new GridLayout(); + container.setLayout(gridLayout); + GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); + container.setLayoutData(gd); + + Group resDetGrp = new Group(container, SWT.NONE); + resDetGrp.setText("Resource Details"); + gridLayout = new GridLayout(4, false); + resDetGrp.setLayout(gridLayout); + gd = new GridData(); + gd.grabExcessHorizontalSpace = true; + gd.horizontalAlignment = SWT.FILL; + resDetGrp.setLayoutData(gd); + + Label resNameLbl = new Label(resDetGrp, SWT.NULL); + resNameLbl.setText(Constants.RESOURCE_NAME); + gd = new GridData(); + resNameLbl.setLayoutData(gd); + + resNameTxt = new Text(resDetGrp, SWT.BORDER); + gd = new GridData(); + // gd.widthHint = 300; + gd.horizontalAlignment = SWT.FILL; + gd.grabExcessHorizontalSpace = true; + gd.horizontalSpan = 3; + resNameTxt.setLayoutData(gd); + resNameTxt.setFocus(); + + Label resUriLbl = new Label(resDetGrp, SWT.NULL); + resUriLbl.setText(Constants.RESOURCE_URI); + + resUriTxt = new Text(resDetGrp, SWT.BORDER); + gd = new GridData(); + // gd.widthHint = 300; + gd.horizontalSpan = 3; + gd.horizontalAlignment = SWT.FILL; + gd.grabExcessHorizontalSpace = true; + resUriTxt.setLayoutData(gd); + /* + * Composite resTypesComp = new Composite(compContent, SWT.NONE); + * gridLayout = new GridLayout(3, false); + * resTypesComp.setLayout(gridLayout); gd = new GridData(); + * gd.grabExcessHorizontalSpace = true; gd.horizontalAlignment = + * SWT.FILL; resTypesComp.setLayoutData(gd); + */ + + Label resTypesLbl = new Label(resDetGrp, SWT.NULL); + resTypesLbl.setText(Constants.RESOURCE_TYPES); + + resTypeslist = new List(resDetGrp, SWT.BORDER | SWT.MULTI + | SWT.V_SCROLL); + gd = new GridData(); + gd.grabExcessHorizontalSpace = true; + gd.horizontalAlignment = SWT.FILL; + gd.horizontalSpan = 2; + gd.heightHint = 100; + /* gd.widthHint = 200; */ + resTypeslist.setLayoutData(gd); + // resTypeslist.setBackground(new Color()); + + Composite resTypesActionsComp = new Composite(resDetGrp, SWT.NONE); + gridLayout = new GridLayout(); + resTypesActionsComp.setLayout(gridLayout); + gd = new GridData(); + gd.verticalAlignment = SWT.TOP; + /* + * gd.grabExcessHorizontalSpace = true; gd.horizontalAlignment = + * SWT.FILL; + */ + resTypesActionsComp.setLayoutData(gd); + + addToListBtn = new Button(resTypesActionsComp, SWT.PUSH); + addToListBtn.setText("Add"); + gd = new GridData(); + gd.widthHint = 70; + addToListBtn.setLayoutData(gd); + + remFromListBtn = new Button(resTypesActionsComp, SWT.PUSH); + remFromListBtn.setText("Remove"); + gd = new GridData(); + gd.widthHint = 70; + remFromListBtn.setLayoutData(gd); + remFromListBtn.setEnabled(false); + + Group otherOptionsGrp = new Group(container, SWT.NONE); + otherOptionsGrp.setText("Other options"); + gridLayout = new GridLayout(); + otherOptionsGrp.setLayout(gridLayout); + gd = new GridData(SWT.FILL, SWT.FILL, true, true); + otherOptionsGrp.setLayoutData(gd); + + observeBtn = new Button(otherOptionsGrp, SWT.CHECK); + observeBtn.setText("Observable"); + observeBtn.setSelection(true); + observable = true; + + /* + * startBtn = new Button(otherOptionsGrp, SWT.CHECK); + * startBtn.setText("Start the resource immediately after creation"); + * startBtn.setSelection(true); + */ + + addUiListeners(); + + setControl(container); + } + + private void addUiListeners() { + + resUriTxt.addModifyListener(new ModifyListener() { + @Override + public void modifyText(ModifyEvent arg0) { + resURI = resUriTxt.getText(); + if (null == resURI) { + return; + } + if (anyResourceExist) + getWizard().getContainer().updateButtons(); + else + setPageComplete(isSelectionDone()); + } + }); + + resNameTxt.addModifyListener(new ModifyListener() { + @Override + public void modifyText(ModifyEvent arg0) { + resName = resNameTxt.getText(); + if (null == resName) { + return; + } + if (anyResourceExist) + getWizard().getContainer().updateButtons(); + else + setPageComplete(isSelectionDone()); + } + }); + + addToListBtn.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + SingleTextInputDialog dialog = new SingleTextInputDialog( + getShell(), "Add Resource Type", "Resource Type"); + if (dialog.open() == Window.OK) { + System.out.println(dialog.getValue()); + String resType = dialog.getValue(); + // Duplicate check. + if (resTypes.contains(resType)) { + MessageDialog.openError(Display.getDefault() + .getActiveShell(), "Duplicate value", + "value already exist."); + return; + } + resTypeslist.add(resType); + resTypeslist.deselectAll(); + resTypeslist.select(resTypeslist.getItemCount() - 1); + resTypeslist.showSelection(); + remFromListBtn.setEnabled(true); + resTypes.add(resType); + if (anyResourceExist) + getWizard().getContainer().updateButtons(); + else + setPageComplete(isSelectionDone()); + } + } + }); + + remFromListBtn.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + int[] selection = resTypeslist.getSelectionIndices(); + String[] selectionStr = resTypeslist.getSelection(); + if (null != selection && selection.length > 0) { + resTypeslist.remove(selection); + for (String selected : selectionStr) { + resTypes.remove(selected); + } + } + changeVisibility(); + if (anyResourceExist) + getWizard().getContainer().updateButtons(); + else + setPageComplete(isSelectionDone()); + } + }); + + resTypeslist.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + changeVisibility(); + } + }); + + observeBtn.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + observable = observeBtn.getSelection(); + } + }); + + /* + * startBtn.addSelectionListener(new SelectionAdapter() { + * + * @Override public void widgetSelected(SelectionEvent e) { start = + * startBtn.getSelection(); } }); + */ + } + + private void changeVisibility() { + int[] selection = resTypeslist.getSelectionIndices(); + if (null != selection && selection.length > 0) { + remFromListBtn.setEnabled(true); + } else { + remFromListBtn.setEnabled(false); + } + } + + @Override + public boolean canFlipToNextPage() { + System.out.println("canFlipToNextPage()"); + if (!anyResourceExist) { + return false; + } + return isSelectionDone(); + } + + public boolean isSelectionDone() { + if (null == resName || resName.trim().length() < 1 || null == resURI + || resURI.trim().length() < 1 || null == resTypes + || resTypes.size() < 1) { + return false; + } + return true; + } + + @Override + public IWizardPage getNextPage() { + // Checking whether the uri is used by any other resource. + if (Activator.getDefault().getResourceManager().isResourceExist(resURI)) { + MessageDialog + .openError(getShell(), "Resource URI in use", + "Entered resource URI is in use. Please try a different one."); + // TODO: Instead of MessageDialog, errors may be shown on wizard + // itself. + return null; + } + if (anyResourceExist) { + return ((CreateResourceWizard) getWizard()) + .getAddResourcesToCollectionPage(); + } + return null; + } + + public String getResName() { + return resName; + } + + public String getResURI() { + return resURI; + } + + public Set getResTypes() { + return resTypes; + } + + /* + * public boolean isStart() { return start; } + */ + + public boolean isObservable() { + return observable; + } + + public boolean isAnyResourceExist() { + return anyResourceExist; + } +} diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/CreateResourceWizard.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/CreateResourceWizard.java index 5a11cc0..9098bcf 100644 --- 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 @@ -16,22 +16,59 @@ package oic.simulator.serviceprovider.view.dialogs; +import java.lang.reflect.InvocationTargetException; import java.net.URL; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; import oic.simulator.serviceprovider.Activator; +import oic.simulator.serviceprovider.manager.UiListenerHandler; +import oic.simulator.serviceprovider.model.AttributeHelper; +import oic.simulator.serviceprovider.model.CollectionResource; +import oic.simulator.serviceprovider.model.LocalResourceAttribute; +import oic.simulator.serviceprovider.model.Resource; +import oic.simulator.serviceprovider.model.ResourceType; +import oic.simulator.serviceprovider.model.SingleResource; +import oic.simulator.serviceprovider.utils.Utility; +import oic.simulator.serviceprovider.view.dialogs.MainPage.ResourceOption; import org.eclipse.core.runtime.FileLocator; import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Path; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.jface.wizard.IWizardPage; import org.eclipse.jface.wizard.Wizard; +import org.eclipse.jface.wizard.WizardDialog; +import org.oic.simulator.ILogger.Level; +import org.oic.simulator.SimulatorException; /** * This class creates a UI wizard for create resource operation. */ public class CreateResourceWizard extends Wizard { - private CreateResourcePage page; + private MainPage mainPage; + private SimpleResourceBasicDetailsPage simpleResourceBasicDetailsPage; + private SimpleResourceAddAttributePage simpleResourceAddAttributePage; + private SimpleResourceOtherDetailsPage simpleResourceOtherDetailsPage; + private CollectionResourceBasicDetailsPage collectionResourceBasicDetailsPage; + private AddResourcesToCollectionPage addResourcesToCollectionPage; + private LoadRamlPage loadRamlPage; + private UpdatePropertiesPage updatePropPage; + private DevicePage devicePage; + private StartStopResourcePage startStopPage; + + // private SingleResource simResource; + private String status; + + private WizardDialog wizDialog; + private boolean dlgForceClosed; public CreateResourceWizard() { setWindowTitle("Create resources"); @@ -39,30 +76,544 @@ public class CreateResourceWizard extends Wizard { URL find = FileLocator.find(Activator.getDefault().getBundle(), path, null); setDefaultPageImageDescriptor(ImageDescriptor.createFromURL(find)); + + setNeedsProgressMonitor(true); } @Override public void addPages() { - page = new CreateResourcePage(); - addPage(page); + mainPage = new MainPage(); + simpleResourceBasicDetailsPage = new SimpleResourceBasicDetailsPage(); + simpleResourceAddAttributePage = new SimpleResourceAddAttributePage(); + simpleResourceOtherDetailsPage = new SimpleResourceOtherDetailsPage(); + collectionResourceBasicDetailsPage = new CollectionResourceBasicDetailsPage(); + addResourcesToCollectionPage = new AddResourcesToCollectionPage(); + loadRamlPage = new LoadRamlPage(); + updatePropPage = new UpdatePropertiesPage(); + devicePage = new DevicePage(); + startStopPage = new StartStopResourcePage(); + + addPage(mainPage); + addPage(simpleResourceBasicDetailsPage); + addPage(simpleResourceAddAttributePage); + addPage(simpleResourceOtherDetailsPage); + addPage(collectionResourceBasicDetailsPage); + if (Activator.getDefault().getResourceManager().isAnyResourceExist()) + addPage(addResourcesToCollectionPage); + addPage(loadRamlPage); + addPage(updatePropPage); + addPage(devicePage); + addPage(startStopPage); + } + + public void setWizardDialog(WizardDialog dlg) { + wizDialog = dlg; + } + + public WizardDialog getWizardDialog() { + return wizDialog; + } + + public boolean isDlgForceClosed() { + return dlgForceClosed; + } + + public void setDlgForceClosed(boolean dlgForceClosed) { + this.dlgForceClosed = dlgForceClosed; } public String getConfigFilePath() { - if (null == page) { + if (null == loadRamlPage) { return null; } - return page.getConfigFilePath(); + return loadRamlPage.getConfigFilePath(); } public int getResourceCount() { - if (null == page) { + if (null == loadRamlPage) { return 0; } - return page.getResourceCount(); + return loadRamlPage.getResourceCount(); + } + + @Override + public boolean canFinish() { + System.out.println("canFinish()"); + IWizardPage curPage = this.getContainer().getCurrentPage(); + System.out.println(curPage.getName()); + if ((curPage == updatePropPage && ((mainPage.getResourceOption() == ResourceOption.SIMPLE_FROM_RAML) || !Activator + .getDefault().getResourceManager().isAnyResourceExist())) + || (curPage == collectionResourceBasicDetailsPage + && !Activator.getDefault().getResourceManager() + .isAnyResourceExist() && collectionResourceBasicDetailsPage + .isSelectionDone()) + || curPage == addResourcesToCollectionPage + || curPage == simpleResourceAddAttributePage + || (curPage == loadRamlPage && loadRamlPage.isSelectionDone() && loadRamlPage + .isMultiResourceCreation()) || curPage == devicePage) { + return true; + } + return false; } @Override public boolean performFinish() { + System.out.println("performFinish()"); + final IWizardPage curPage = this.getContainer().getCurrentPage(); + System.out.println(curPage.getClass().getSimpleName()); + if (curPage == simpleResourceAddAttributePage) { // Handling Simple + // Resource Creation + // without RAML + try { + getContainer().run(true, true, new IRunnableWithProgress() { + + @Override + public void run(IProgressMonitor monitor) + throws InvocationTargetException, + InterruptedException { + try { + monitor.beginTask( + "Single Resource Creation Without RAML", 2); + monitor.worked(1); + createSingleResourceWithoutRAML(); + monitor.worked(1); + } finally { + monitor.done(); + } + } + }); + } catch (InvocationTargetException e) { + Activator.getDefault().getLogManager() + .log(Level.ERROR.ordinal(), new Date(), e.getMessage()); + e.printStackTrace(); + } catch (InterruptedException e) { + Activator.getDefault().getLogManager() + .log(Level.ERROR.ordinal(), new Date(), e.getMessage()); + e.printStackTrace(); + } + } else if (curPage == loadRamlPage) { // Handling multi-instance + // creation of simple resource + // with RAML + try { + getContainer().run(true, true, new IRunnableWithProgress() { + + @Override + public void run(IProgressMonitor monitor) + throws InvocationTargetException, + InterruptedException { + try { + monitor.beginTask( + "Single Resource Creation(multi-instance) With RAML", + 3); + monitor.worked(1); + createMultiInstanceSingleResourceWithoutRAML(); + monitor.worked(2); + } finally { + monitor.done(); + } + } + }); + } catch (InvocationTargetException e) { + Activator.getDefault().getLogManager() + .log(Level.ERROR.ordinal(), new Date(), e.getMessage()); + e.printStackTrace(); + } catch (InterruptedException e) { + Activator.getDefault().getLogManager() + .log(Level.ERROR.ordinal(), new Date(), e.getMessage()); + e.printStackTrace(); + } + } else if (curPage == updatePropPage) { // Handling the single instance + // creation of simple resource + // with RAML + // String resURI = updatePropPage.getResURI(); + // Checking whether the uri is used by any other resource. + if (Activator.getDefault().getResourceManager() + .isResourceExist(updatePropPage.getResURI())) { + MessageDialog + .openError(getShell(), "Resource URI in use", + "Entered resource URI is in use. Please try a different one."); + // TODO: Instead of MessageDialog, errors may be shown on wizard + // itself. + return false; + } + // Resource resource = loadRamlPage.getResource(); + // resource.setResourceName(updatePropPage.getResName()); + try { + getContainer().run(true, true, new IRunnableWithProgress() { + + @Override + public void run(IProgressMonitor monitor) + throws InvocationTargetException, + InterruptedException { + try { + monitor.beginTask("Completing Resource Creation", 2); + monitor.worked(1); + completeResourceCreationWithRAML(); + monitor.worked(1); + } finally { + monitor.done(); + } + } + }); + } catch (InvocationTargetException e) { + Activator.getDefault().getLogManager() + .log(Level.ERROR.ordinal(), new Date(), e.getMessage()); + e.printStackTrace(); + } catch (InterruptedException e) { + Activator.getDefault().getLogManager() + .log(Level.ERROR.ordinal(), new Date(), e.getMessage()); + e.printStackTrace(); + } + } else if (curPage == collectionResourceBasicDetailsPage + || curPage == addResourcesToCollectionPage) { // Handling + // Collection + // Resource + // Creation + // without RAML + if (mainPage.getResourceOption() == ResourceOption.COLLECTION_FROM_RAML) { + Resource res = loadRamlPage.getResource(); + if (null != res && res instanceof CollectionResource) { + Set selectedResources = addResourcesToCollectionPage + .getSelectedResourceList(); + if (!selectedResources.isEmpty()) { + int addedCount = Activator + .getDefault() + .getResourceManager() + .addResourceToCollection( + (CollectionResource) res, + selectedResources); + if (addedCount > 0) { + + status = "[" + addedCount + "/" + + selectedResources.size() + + "] resources added to the collection"; + + UiListenerHandler.getInstance() + .resourceListUpdateUINotification( + ResourceType.COLLECTION); + } else { + status = "Failed to add resources to the collection"; + } + } + } + } else { + // Checking whether the uri is used by any other resource. + if (Activator + .getDefault() + .getResourceManager() + .isResourceExist( + collectionResourceBasicDetailsPage.getResURI())) { + MessageDialog + .openError(getShell(), "Resource URI in use", + "Entered resource URI is in use. Please try a different one."); + // TODO: Instead of MessageDialog, errors may be shown on + // wizard + // itself. + return false; + } + try { + getContainer().run(true, true, new IRunnableWithProgress() { + + @Override + public void run(IProgressMonitor monitor) + throws InvocationTargetException, + InterruptedException { + try { + monitor.beginTask( + "Collection Resource Creation Without RAML", + 3); + monitor.worked(1); + createCollectionResourceWithoutRAML((curPage == addResourcesToCollectionPage) ? true + : false); + monitor.worked(1); + if (curPage == addResourcesToCollectionPage) { + UiListenerHandler.getInstance() + .resourceListUpdateUINotification( + ResourceType.COLLECTION); + } + monitor.worked(1); + } finally { + monitor.done(); + } + } + }); + } catch (InvocationTargetException e) { + Activator + .getDefault() + .getLogManager() + .log(Level.ERROR.ordinal(), new Date(), + e.getMessage()); + e.printStackTrace(); + } catch (InterruptedException e) { + Activator + .getDefault() + .getLogManager() + .log(Level.ERROR.ordinal(), new Date(), + e.getMessage()); + e.printStackTrace(); + } + } + } else if (curPage == devicePage) { + final String devName = devicePage.getDeviceName(); + final Set resourceList = devicePage + .getSelectedResourceList(); + try { + getContainer().run(true, true, new IRunnableWithProgress() { + + @Override + public void run(IProgressMonitor monitor) + throws InvocationTargetException, + InterruptedException { + try { + monitor.beginTask("Device Creation", 3); + monitor.worked(1); + createDevice(devName, resourceList); + monitor.worked(1); + UiListenerHandler.getInstance() + .resourceListUpdateUINotification( + ResourceType.DEVICE); + status = "Device Created."; + monitor.worked(1); + } finally { + monitor.done(); + } + } + }); + } catch (InvocationTargetException e) { + Activator.getDefault().getLogManager() + .log(Level.ERROR.ordinal(), new Date(), e.getMessage()); + e.printStackTrace(); + } catch (InterruptedException e) { + Activator.getDefault().getLogManager() + .log(Level.ERROR.ordinal(), new Date(), e.getMessage()); + e.printStackTrace(); + } + } return true; } + + public MainPage getMainPage() { + return mainPage; + } + + public SimpleResourceBasicDetailsPage getSimpleResourceBasicDetailsPage() { + return simpleResourceBasicDetailsPage; + } + + public SimpleResourceAddAttributePage getSimpleResourceAddAttributePage() { + return simpleResourceAddAttributePage; + } + + public CollectionResourceBasicDetailsPage getCollectionResourceBasicDetailsPage() { + return collectionResourceBasicDetailsPage; + } + + public SimpleResourceOtherDetailsPage getSimpleResourceOtherDetailsPage() { + return simpleResourceOtherDetailsPage; + } + + public AddResourcesToCollectionPage getAddResourcesToCollectionPage() { + return addResourcesToCollectionPage; + } + + public LoadRamlPage getLoadRamlPage() { + return loadRamlPage; + } + + public UpdatePropertiesPage getUpdatePropPage() { + return updatePropPage; + } + + public DevicePage getDevicePage() { + return devicePage; + } + + public StartStopResourcePage getStartStopPage() { + return startStopPage; + } + + /* + * public SingleResource getSimResource() { return simResource; } + * + * public void setSimResource(SingleResource simResource) { this.simResource + * = simResource; } + */ + + public void setStatus(String status) { + this.status = status; + } + + public String getStatus() { + return status; + } + + /* + * public SingleResource getCreatedResource() { return simResource; } + */ + + private void createSingleResourceWithoutRAML() { + SingleResource resource = new SingleResource(); + // Basic resource details + resource.setResourceURI(simpleResourceBasicDetailsPage.getResURI()); + resource.setResourceName(simpleResourceBasicDetailsPage.getResName()); + resource.setResourceTypes(simpleResourceBasicDetailsPage.getResTypes()); + resource.setObservable(simpleResourceBasicDetailsPage.isObservable()); + // resource.setStarted(simpleResourceBasicDetailsPage.isStart()); + + // Resource Attributes + Map attributes = new HashMap(); + Set attributeSet = simpleResourceAddAttributePage + .getAttributes(); + if (null != attributeSet && !attributeSet.isEmpty()) { + Iterator itr = attributeSet.iterator(); + AttributeHelper attHelper; + LocalResourceAttribute localResAtt; + // List attValues; + while (itr.hasNext()) { + attHelper = itr.next(); + if (null != attHelper) { + localResAtt = attHelper.convertToLocalResourceAttribute(); + + // Set the attribute value list. + /* + * attValues = + * Activator.getDefault().getResourceManager().getValueList + * (localResAtt); localResAtt.setAttValues(attValues); + */ + attributes.put( + localResAtt.getResourceAttributeRef().name(), + localResAtt); + } + } + resource.setResourceAttributes(attributes); + } + + // Request types + resource.setGetAllowed(simpleResourceOtherDetailsPage.isGetChecked()); + resource.setPutAllowed(simpleResourceOtherDetailsPage.isPutChecked()); + resource.setPostAllowed(simpleResourceOtherDetailsPage.isPostChecked()); + + // Call method of ResourceManager and update the response in the status + // string. + try { + boolean result = Activator.getDefault().getResourceManager() + .createSingleResource(resource); + if (result) { + status = "Resource created."; + resource.printResourceInfo(); + } else { + status = "Failed to create resource."; + } + } catch (SimulatorException e) { + status = "Failed to create resource.\n" + + Utility.getSimulatorErrorString(e, null); + } + } + + private void completeResourceCreationWithRAML() { + try { + boolean result; + Resource res = loadRamlPage.getResource(); + if (res instanceof SingleResource) { + result = Activator + .getDefault() + .getResourceManager() + .completeSingleResourceCreationByRAML(res, + updatePropPage.getResURI(), + updatePropPage.getResName(), false); + } else { + result = Activator + .getDefault() + .getResourceManager() + .completeCollectionResourceCreationByRAML(res, + updatePropPage.getResURI(), + updatePropPage.getResName()); + } + + if (result) { + status = "Resource created."; + loadRamlPage.getResource().printResourceInfo(); + } else { + status = "Failed to create resource."; + } + } catch (SimulatorException e) { + status = "Failed to create resource.\n" + + Utility.getSimulatorErrorString(e, null); + } + } + + private void createMultiInstanceSingleResourceWithoutRAML() { + try { + int toCreateCount = loadRamlPage.getResourceCount(); + int resCreatedCount = Activator + .getDefault() + .getResourceManager() + .createSingleResourceMultiInstances( + loadRamlPage.getConfigFilePath(), toCreateCount); + if (resCreatedCount > 0) { + status = "[" + resCreatedCount + " out of " + toCreateCount + + "]"; + status += ((resCreatedCount == 1) ? "resource" : "resources") + + " created successfully."; + } else { + status = "Failed to create resources."; + } + } catch (SimulatorException e) { + status = "Failed to create resource.\n" + + Utility.getSimulatorErrorString(e, null); + } + } + + private void createCollectionResourceWithoutRAML(boolean childResExist) { + CollectionResource resource = new CollectionResource(); + // Basic resource details + resource.setResourceURI(collectionResourceBasicDetailsPage.getResURI()); + resource.setResourceName(collectionResourceBasicDetailsPage + .getResName()); + resource.setResourceTypes(collectionResourceBasicDetailsPage + .getResTypes()); + resource.setObservable(collectionResourceBasicDetailsPage + .isObservable()); + // resource.setStarted(simpleResourceBasicDetailsPage.isStart()); + + // Call method of ResourceManager and update the response in the status + // string. + try { + boolean result = Activator.getDefault().getResourceManager() + .createCollectionResource(resource); + if (result) { + status = "Resource created."; + // Adding child resources. + if (childResExist) { + Set selectedResources = addResourcesToCollectionPage + .getSelectedResourceList(); + if (!selectedResources.isEmpty()) { + int addedCount = Activator + .getDefault() + .getResourceManager() + .addResourceToCollection(resource, + selectedResources); + if (addedCount > 0) { + status = "[" + addedCount + "/" + + selectedResources.size() + + "] resources added to the collection"; + } else { + status = "Failed to add resources to the collection."; + } + } + } + } else { + status = "Failed to create resource."; + } + } catch (SimulatorException e) { + status = "Failed to create resource.\n" + + Utility.getSimulatorErrorString(e, null); + } + } + + private void createDevice(String deviceName, Set childs) { + Activator.getDefault().getResourceManager() + .createDevice(deviceName, childs); + } + } \ 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 index be7dae8..d27ebf6 100644 --- 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 @@ -16,219 +16,414 @@ package oic.simulator.serviceprovider.view.dialogs; -import java.util.Iterator; +import java.util.ArrayList; +import java.util.HashSet; import java.util.List; +import java.util.Set; import oic.simulator.serviceprovider.Activator; -import oic.simulator.serviceprovider.resource.DeleteCategory; +import oic.simulator.serviceprovider.model.CollectionResource; +import oic.simulator.serviceprovider.model.Resource; +import oic.simulator.serviceprovider.model.SingleResource; import oic.simulator.serviceprovider.utils.Constants; +import org.eclipse.jface.viewers.CheckStateChangedEvent; +import org.eclipse.jface.viewers.CheckboxTreeViewer; +import org.eclipse.jface.viewers.ICheckStateListener; +import org.eclipse.jface.viewers.ITreeContentProvider; +import org.eclipse.jface.viewers.LabelProvider; +import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.CCombo; -import org.eclipse.swt.events.ModifyEvent; -import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; -import org.eclipse.swt.widgets.Text; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Tree; +import org.eclipse.swt.widgets.TreeItem; /** * This class shows UI for deleting resources. */ public class DeleteResourcePage extends WizardPage { - private Button allRbtn; - private Button byTypeRbtn; - private Button byUriRbtn; + private CheckboxTreeViewer collectionTreeViewer; + private CheckboxTreeViewer singleTreeViewer; - private CCombo resourceTypeCmb; - private Text resourceUriTxt; + private Button selectAllSingle; + private Button selectAllCollection; + private Button deselectAllSingle; + private Button deselectAllCollection; - private DeleteCategory deleteCategory; + private List collectionSourceList; + private List singleSourceList; - // It will hold either the resource type or resource uri - private String deleteCandidate; + private Set selectedCollections; + private Set selectedSingles; protected DeleteResourcePage() { - super("Delete Resource"); + super("Delete Resources"); + + singleSourceList = Activator.getDefault().getResourceManager() + .getSingleResourceList(); + collectionSourceList = Activator.getDefault().getResourceManager() + .getCollectionResourceList(); + + selectedCollections = new HashSet(); + selectedSingles = new HashSet(); } @Override public void createControl(Composite parent) { setPageComplete(false); - setTitle(Constants.DELETE_PAGE_TITLE); - setMessage(Constants.DELETE_PAGE_MESSAGE); + setTitle("Delete Resources"); + setMessage("Select one or more single and/or collection resources for deletion."); - Composite compContent = new Composite(parent, SWT.NONE); - compContent.setLayout(new GridLayout(1, false)); - GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); - compContent.setLayoutData(gd); - - Group group = new Group(compContent, SWT.NONE); - group.setText("Select Category"); - GridLayout gridLayout = new GridLayout(2, false); - gridLayout.verticalSpacing = 15; - gridLayout.marginTop = 10; - gridLayout.marginLeft = 10; - group.setLayout(gridLayout); - gd = new GridData(SWT.FILL, SWT.FILL, true, true); - group.setLayoutData(gd); + Composite container = new Composite(parent, SWT.NONE); + container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + GridLayout layout = new GridLayout(5, true); + container.setLayout(layout); - allRbtn = new Button(group, SWT.RADIO); - allRbtn.setText("All resources"); - gd = new GridData(); + createSingleResourcesArea(container); + + createCollectionResourcesArea(container); + + createSelectionControls(container); + + setControl(container); + } + + private void createSingleResourcesArea(Composite container) { + Composite singleContainer = new Composite(container, SWT.NONE); + GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); gd.horizontalSpan = 2; - gd.widthHint = 200; - allRbtn.setLayoutData(gd); + singleContainer.setLayoutData(gd); + GridLayout layout = new GridLayout(); + singleContainer.setLayout(layout); - byTypeRbtn = new Button(group, SWT.RADIO); - byTypeRbtn.setText("All (By resource type)"); - gd = new GridData(); - gd.widthHint = 200; - byTypeRbtn.setLayoutData(gd); + Label lbl = new Label(singleContainer, SWT.NONE); + lbl.setText("Simple Resources:"); + gd = new GridData(SWT.FILL, SWT.FILL, true, true); + // gd.grabExcessHorizontalSpace = true; + // gd.horizontalAlignment = SWT.FILL; + lbl.setLayoutData(gd); - resourceTypeCmb = new CCombo(group, SWT.READ_ONLY | SWT.BORDER); - gd = new GridData(); - gd.widthHint = 200; - resourceTypeCmb.setLayoutData(gd); + Group resourceGroup = new Group(singleContainer, SWT.NONE); + + Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE); - byUriRbtn = new Button(group, SWT.RADIO); - byUriRbtn.setText("By Resource URI"); + resourceGroup.setLayout(new GridLayout()); gd = new GridData(); - gd.widthHint = 200; - byUriRbtn.setLayoutData(gd); + gd.grabExcessHorizontalSpace = true; + gd.horizontalAlignment = SWT.FILL; + gd.heightHint = 300; + gd.horizontalSpan = 2; + resourceGroup.setLayoutData(gd); - resourceUriTxt = new Text(group, SWT.BORDER); + singleTreeViewer = new CheckboxTreeViewer(resourceGroup); + singleTreeViewer.getTree().setBackground(color); gd = new GridData(); - gd.widthHint = 300; - resourceUriTxt.setLayoutData(gd); + gd.grabExcessHorizontalSpace = true; + gd.horizontalAlignment = SWT.FILL; + gd.grabExcessVerticalSpace = true; + gd.verticalAlignment = SWT.FILL; + // gd.heightHint = 300; + singleTreeViewer.getTree().setLayoutData(gd); + singleTreeViewer + .setContentProvider(new SingleResourceContentProvider()); + singleTreeViewer.setLabelProvider(new TreeLabelProvider()); + singleTreeViewer.setInput(new Object()); + singleTreeViewer.addCheckStateListener(new ICheckStateListener() { - // Setting the initial visibility of controls - allRbtn.setSelection(false); - byTypeRbtn.setSelection(false); - byUriRbtn.setSelection(false); + @Override + public void checkStateChanged(CheckStateChangedEvent e) { + SingleResource res = (SingleResource) e.getElement(); + if (null != res) { + if (e.getChecked()) { + selectedSingles.add(res); + System.out.println("Checked" + res.getResourceName()); + } else { + selectedSingles.remove(res); + System.out.println("Unchecked:" + res.getResourceName()); + } + setPageComplete(isSelectionDone()); + } + } + }); + } - resourceTypeCmb.setEnabled(false); - resourceUriTxt.setEnabled(false); + private void createCollectionResourcesArea(Composite container) { + Composite collectionContainer = new Composite(container, SWT.NONE); + GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); + gd.horizontalSpan = 2; + collectionContainer.setLayoutData(gd); + GridLayout layout = new GridLayout(); + collectionContainer.setLayout(layout); - deleteCategory = DeleteCategory.NONE; + Label lbl = new Label(collectionContainer, SWT.NONE); + lbl.setText("Collection Resources:"); + gd = new GridData(SWT.FILL, SWT.FILL, true, true); + // gd.grabExcessHorizontalSpace = true; + // gd.horizontalAlignment = SWT.FILL; + lbl.setLayoutData(gd); - populateDataInUI(); + Group resourceGroup = new Group(collectionContainer, SWT.NONE); - addUIListeners(); + Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE); - setControl(compContent); - } + resourceGroup.setLayout(new GridLayout()); + gd = new GridData(); + gd.grabExcessHorizontalSpace = true; + gd.horizontalAlignment = SWT.FILL; + gd.heightHint = 300; + gd.horizontalSpan = 2; + resourceGroup.setLayoutData(gd); - private void populateDataInUI() { - // Populate Resourcetype in Combo - populateResourceTypeCombo(); - } + collectionTreeViewer = new CheckboxTreeViewer(resourceGroup); + collectionTreeViewer.getTree().setBackground(color); + gd = new GridData(); + gd.grabExcessHorizontalSpace = true; + gd.horizontalAlignment = SWT.FILL; + gd.grabExcessVerticalSpace = true; + gd.verticalAlignment = SWT.FILL; + // gd.heightHint = 300; + collectionTreeViewer.getTree().setLayoutData(gd); + collectionTreeViewer + .setContentProvider(new CollectionResourceContentProvider()); + collectionTreeViewer.setLabelProvider(new TreeLabelProvider()); + collectionTreeViewer.setInput(new Object()); + collectionTreeViewer.addCheckStateListener(new ICheckStateListener() { - private void populateResourceTypeCombo() { - List resourceTypeList; - resourceTypeList = Activator.getDefault().getResourceManager() - .getResourceTypeList(); - if (null != resourceTypeList) { - Iterator itr = resourceTypeList.iterator(); - while (itr.hasNext()) { - resourceTypeCmb.add(itr.next()); + @Override + public void checkStateChanged(CheckStateChangedEvent e) { + CollectionResource res = (CollectionResource) e.getElement(); + if (null != res) { + if (e.getChecked()) { + selectedCollections.add(res); + System.out.println("Checked" + res.getResourceName()); + } else { + selectedCollections.remove(res); + System.out.println("Unchecked:" + res.getResourceName()); + } + setPageComplete(isSelectionDone()); + } } - } - - // By default, select the first item in the combo - if (resourceTypeCmb.getItemCount() > 0) { - resourceTypeCmb.select(0); - deleteCandidate = resourceTypeCmb.getText(); - } + }); } - public void addUIListeners() { - allRbtn.addSelectionListener(new SelectionAdapter() { + private void createSelectionControls(Composite container) { + Composite innerComp = new Composite(container, SWT.NULL); + GridLayout layout = new GridLayout(); + // layout.verticalSpacing = 10; + layout.marginTop = 15; + innerComp.setLayout(layout); + GridData gd = new GridData(); + gd.verticalAlignment = SWT.TOP; + innerComp.setLayoutData(gd); + + selectAllSingle = new Button(innerComp, SWT.PUSH); + selectAllSingle.setText("Select All Simple"); + gd = new GridData(); + gd.grabExcessHorizontalSpace = true; + gd.horizontalAlignment = SWT.FILL; + // gd.widthHint = 70; + selectAllSingle.setLayoutData(gd); + selectAllSingle.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { - // Update the visibility of controls - resourceTypeCmb.setEnabled(false); - resourceUriTxt.setEnabled(false); - - deleteCategory = DeleteCategory.ALL; - deleteCandidate = null; - setPageComplete(isSelectionDone()); + check(singleTreeViewer, true); } }); - byTypeRbtn.addSelectionListener(new SelectionAdapter() { + selectAllCollection = new Button(innerComp, SWT.PUSH); + selectAllCollection.setText("Select All Collection"); + gd = new GridData(); + gd.grabExcessHorizontalSpace = true; + gd.horizontalAlignment = SWT.FILL; + // gd.widthHint = 70; + selectAllCollection.setLayoutData(gd); + selectAllCollection.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { - // Update the visibility of controls - resourceTypeCmb.setEnabled(true); - resourceUriTxt.setEnabled(false); - - deleteCategory = DeleteCategory.BY_TYPE; - setPageComplete(isSelectionDone()); + check(collectionTreeViewer, true); } }); - byUriRbtn.addSelectionListener(new SelectionAdapter() { + deselectAllSingle = new Button(innerComp, SWT.PUSH); + deselectAllSingle.setText("Deselect All Simple"); + gd = new GridData(); + gd.grabExcessHorizontalSpace = true; + gd.horizontalAlignment = SWT.FILL; + // gd.widthHint = 70; + deselectAllSingle.setLayoutData(gd); + deselectAllSingle.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { - // Update the visibility of controls - resourceUriTxt.setEnabled(true); - resourceUriTxt.setFocus(); - resourceTypeCmb.setEnabled(false); - - deleteCategory = DeleteCategory.BY_URI; - setPageComplete(isSelectionDone()); + check(singleTreeViewer, false); } }); - resourceTypeCmb.addModifyListener(new ModifyListener() { + deselectAllCollection = new Button(innerComp, SWT.PUSH); + deselectAllCollection.setText("Deselect All Collection"); + gd = new GridData(); + gd.grabExcessHorizontalSpace = true; + gd.horizontalAlignment = SWT.FILL; + // gd.widthHint = 70; + deselectAllCollection.setLayoutData(gd); + + deselectAllCollection.addSelectionListener(new SelectionAdapter() { @Override - public void modifyText(ModifyEvent arg0) { - setPageComplete(isSelectionDone()); + public void widgetSelected(SelectionEvent e) { + check(collectionTreeViewer, false); } }); + } - resourceUriTxt.addModifyListener(new ModifyListener() { - @Override - public void modifyText(ModifyEvent arg0) { + private void check(CheckboxTreeViewer viewer, boolean toCheck) { + Tree tree = viewer.getTree(); + if (null != tree) { + TreeItem[] items = tree.getItems(); + if (null != items && items.length > 0) { + Object obj; + for (TreeItem item : items) { + obj = item.getData(); + if (null != obj) { + viewer.setChecked(obj, toCheck); + updateSelectionList((Resource) obj, toCheck); + } + } setPageComplete(isSelectionDone()); } - }); + } } - public boolean isSelectionDone() { - boolean done = false; - if (deleteCategory == DeleteCategory.ALL) { - done = true; - } else if (deleteCategory == DeleteCategory.BY_TYPE) { - deleteCandidate = resourceTypeCmb.getText(); - if (null != deleteCandidate && deleteCandidate.length() > 0) { - done = true; + private void updateSelectionList(Resource res, boolean isChecked) { + if (res instanceof SingleResource) { + if (isChecked) { + selectedSingles.add((SingleResource) res); + } else { + selectedSingles.remove((SingleResource) res); } - } else if (deleteCategory == DeleteCategory.BY_URI) { - deleteCandidate = resourceUriTxt.getText(); - if (null != deleteCandidate && deleteCandidate.length() > 0) { - done = true; + } else { + if (isChecked) { + selectedCollections.add((CollectionResource) res); + } else { + selectedCollections.remove((CollectionResource) res); } } - return done; } - public DeleteCategory getDeleteCategory() { - return deleteCategory; + public Set getSelectedSingleResourcesList() { + return selectedSingles; + } + + public Set getSelectedCollectionResourcesList() { + return selectedCollections; + } + + class SingleResourceContentProvider implements ITreeContentProvider { + + @Override + public void dispose() { + } + + @Override + public void inputChanged(Viewer arg0, Object arg1, Object arg2) { + } + + @Override + public Object[] getChildren(Object parent) { + return null; + } + + @Override + public Object[] getElements(Object parent) { + if (null == singleSourceList) { + singleSourceList = new ArrayList(); + } + return singleSourceList.toArray(); + } + + @Override + public Object getParent(Object child) { + return null; + } + + @Override + public boolean hasChildren(Object parent) { + return false; + } + } + + class CollectionResourceContentProvider implements ITreeContentProvider { + + @Override + public void dispose() { + } + + @Override + public void inputChanged(Viewer arg0, Object arg1, Object arg2) { + } + + @Override + public Object[] getChildren(Object parent) { + return null; + } + + @Override + public Object[] getElements(Object parent) { + if (null == collectionSourceList) { + collectionSourceList = new ArrayList(); + } + return collectionSourceList.toArray(); + } + + @Override + public Object getParent(Object child) { + return null; + } + + @Override + public boolean hasChildren(Object parent) { + return false; + } } - public String getDeleteCandidate() { - return deleteCandidate; + class TreeLabelProvider extends LabelProvider { + @Override + public String getText(Object element) { + Resource res = (Resource) element; + return res.getResourceName(); + } + + @Override + public Image getImage(Object element) { + if (element instanceof CollectionResource) { + return Activator.getDefault().getImageRegistry() + .get(Constants.COLLECTION_RESOURCE); + } else { + return Activator.getDefault().getImageRegistry() + .get(Constants.SINGLE_RESOURCE); + } + } } - public void setFocusToTextBox() { - resourceUriTxt.setFocus(); + public boolean isSelectionDone() { + boolean done = true; + Object obj[] = singleTreeViewer.getCheckedElements(); + if (null == obj || obj.length < 1) { + obj = collectionTreeViewer.getCheckedElements(); + if (null == obj || obj.length < 1) { + done = false; + } + } + return done; } } \ No newline at end of file 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 index 4d079eb..4a2cc9e 100644 --- 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 @@ -16,19 +16,24 @@ package oic.simulator.serviceprovider.view.dialogs; +import java.lang.reflect.InvocationTargetException; import java.net.URL; +import java.util.Date; +import java.util.Set; import oic.simulator.serviceprovider.Activator; -import oic.simulator.serviceprovider.resource.DeleteCategory; +import oic.simulator.serviceprovider.model.CollectionResource; +import oic.simulator.serviceprovider.model.SingleResource; import org.eclipse.core.runtime.FileLocator; import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Path; -import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.wizard.Wizard; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.PlatformUI; +import org.oic.simulator.ILogger.Level; +import org.oic.simulator.SimulatorException; /** * This class creates a UI wizard for delete resource operation. @@ -37,6 +42,8 @@ public class DeleteResourceWizard extends Wizard { private DeleteResourcePage page; + private String status; + public DeleteResourceWizard() { setWindowTitle("Delete resources"); IPath path = new Path("/icons/oic_logo_64x64.png"); @@ -56,45 +63,52 @@ public class DeleteResourceWizard extends Wizard { if (null == page) { return false; } - // Check the existence of the resource if the user has entered the uri - if (page.getDeleteCategory() == DeleteCategory.BY_URI) { - // Check whether the uri is in full form or short form - // If it is in short form, expand it to its full form. - String uri = page.getDeleteCandidate(); - boolean dispName = Activator.getDefault().getResourceManager() - .isDisplayName(uri); - if (dispName) { - uri = Activator.getDefault().getResourceManager() - .getCompleteUriFromDisplayName(uri); - } - boolean exist = Activator.getDefault().getResourceManager() - .isResourceExist(uri); - if (!exist) { - Shell activeShell = PlatformUI.getWorkbench().getDisplay() - .getActiveShell(); - MessageDialog dialog = new MessageDialog(activeShell, - "Resource Not Found", null, - "No resource exist with the given URI.", - MessageDialog.INFORMATION, new String[] { "OK" }, 0); - dialog.open(); - page.setFocusToTextBox(); - return false; - } - } - return true; - } + try { + getContainer().run(true, true, new IRunnableWithProgress() { - public DeleteCategory getDeleteCategory() { - if (null == page) { - return DeleteCategory.NONE; + @Override + public void run(IProgressMonitor monitor) + throws InvocationTargetException, InterruptedException { + try { + monitor.beginTask("Resource Deletion", 2); + Set collectionResources = page + .getSelectedCollectionResourcesList(); + if (null != collectionResources + && collectionResources.size() > 0) { + Activator + .getDefault() + .getResourceManager() + .removeCollectionResources( + collectionResources); + } + monitor.worked(1); + Set singleResources = page + .getSelectedSingleResourcesList(); + if (null != singleResources + && singleResources.size() > 0) { + Activator.getDefault().getResourceManager() + .removeSingleResources(singleResources); + } + monitor.worked(1); + status = "Resources deleted."; + } catch (SimulatorException e) { + status = "Failed to delete some of the resources. Please try again."; + } finally { + monitor.done(); + } + } + }); + } catch (InvocationTargetException e) { + Activator.getDefault().getLogManager() + .log(Level.ERROR.ordinal(), new Date(), e.getMessage()); + } catch (InterruptedException e) { + Activator.getDefault().getLogManager() + .log(Level.ERROR.ordinal(), new Date(), e.getMessage()); } - return page.getDeleteCategory(); + return true; } - public String getDeleteCandidate() { - if (null == page) { - return null; - } - return page.getDeleteCandidate(); + public String getStatus() { + return status; } } \ No newline at end of file diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/DevicePage.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/DevicePage.java new file mode 100644 index 0000000..b6a194f --- /dev/null +++ b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/DevicePage.java @@ -0,0 +1,207 @@ +package oic.simulator.serviceprovider.view.dialogs; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import oic.simulator.serviceprovider.Activator; +import oic.simulator.serviceprovider.model.Resource; +import oic.simulator.serviceprovider.model.SingleResource; +import oic.simulator.serviceprovider.utils.Constants; + +import org.eclipse.jface.viewers.CheckStateChangedEvent; +import org.eclipse.jface.viewers.CheckboxTreeViewer; +import org.eclipse.jface.viewers.ICheckStateListener; +import org.eclipse.jface.viewers.ITreeContentProvider; +import org.eclipse.jface.viewers.LabelProvider; +import org.eclipse.jface.viewers.Viewer; +import org.eclipse.jface.wizard.IWizardPage; +import org.eclipse.jface.wizard.WizardPage; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.ModifyEvent; +import org.eclipse.swt.events.ModifyListener; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Group; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Text; + +public class DevicePage extends WizardPage { + + private CheckboxTreeViewer treeViewer; + + private Text deviceNameTxt; + + private String deviceName; + + Set selectedResourceList; + + protected DevicePage() { + super("Devices"); + selectedResourceList = new HashSet(); + } + + @Override + public void createControl(Composite parent) { + setPageComplete(false); + setTitle(Constants.CREATE_DEVICE_PAGE_TITLE); + setMessage(Constants.CREATE_DEVICE_PAGE_MESSAGE); + + Composite container = new Composite(parent, SWT.NONE); + GridLayout gridLayout = new GridLayout(2, false); + container.setLayout(gridLayout); + GridData gd = new GridData(); + gd.grabExcessHorizontalSpace = true; + gd.horizontalAlignment = SWT.FILL; + gd.heightHint = 300; + container.setLayoutData(gd); + + Label deviceNameLbl = new Label(container, SWT.NULL); + deviceNameLbl.setText("Device Name"); + + deviceNameTxt = new Text(container, SWT.BORDER); + gd = new GridData(); + gd.grabExcessHorizontalSpace = true; + gd.horizontalAlignment = SWT.FILL; + deviceNameTxt.setLayoutData(gd); + + Group resourceGroup = new Group(container, SWT.NONE); + + Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE); + + resourceGroup.setLayout(new GridLayout()); + gd = new GridData(); + gd.grabExcessHorizontalSpace = true; + gd.horizontalAlignment = SWT.FILL; + gd.heightHint = 300; + gd.horizontalSpan = 2; + resourceGroup.setLayoutData(gd); + + treeViewer = new CheckboxTreeViewer(resourceGroup); + treeViewer.getTree().setBackground(color); + gd = new GridData(); + gd.grabExcessHorizontalSpace = true; + gd.horizontalAlignment = SWT.FILL; + gd.grabExcessVerticalSpace = true; + gd.verticalAlignment = SWT.FILL; + // gd.heightHint = 300; + treeViewer.getTree().setLayoutData(gd); + treeViewer.setContentProvider(new TreeContentProvider()); + treeViewer.setLabelProvider(new TreeLabelProvider()); + treeViewer.setInput(new Object()); + treeViewer.addCheckStateListener(new ICheckStateListener() { + + @Override + public void checkStateChanged(CheckStateChangedEvent e) { + Resource res = (Resource) e.getElement(); + if (null != res) { + if (e.getChecked()) { + selectedResourceList.add(res); + System.out.println("Checked" + res.getResourceName()); + } else { + selectedResourceList.remove(res); + System.out.println("Unchecked:" + res.getResourceName()); + } + } + } + }); + + setUiListeners(); + + setControl(container); + } + + private void setUiListeners() { + deviceNameTxt.addModifyListener(new ModifyListener() { + @Override + public void modifyText(ModifyEvent e) { + deviceName = deviceNameTxt.getText(); + setPageComplete(isSelectionDone()); + } + }); + } + + private boolean isSelectionDone() { + if (null != deviceName) { + deviceName = deviceName.trim(); + } + if (deviceName.isEmpty()) { + return false; + } + return true; + } + + @Override + public IWizardPage getNextPage() { + return null; + } + + public String getDeviceName() { + return deviceName; + } + + public Set getSelectedResourceList() { + return selectedResourceList; + } + +} + +class TreeContentProvider implements ITreeContentProvider { + + @Override + public void dispose() { + } + + @Override + public void inputChanged(Viewer arg0, Object arg1, Object arg2) { + } + + @Override + public Object[] getChildren(Object parent) { + return null; + } + + @Override + public Object[] getElements(Object parent) { + List resList; + resList = Activator.getDefault().getResourceManager().getResourceList(); + if (null == resList) { + resList = new ArrayList(); + } + return resList.toArray(); + } + + @Override + public Object getParent(Object child) { + return null; + } + + @Override + public boolean hasChildren(Object parent) { + return false; + } +} + +class TreeLabelProvider extends LabelProvider { + @Override + public String getText(Object element) { + Resource res = (Resource) element; + return res.getResourceName(); + } + + @Override + public Image getImage(Object element) { + if (element instanceof SingleResource) { + return Activator.getDefault().getImageRegistry() + .get(Constants.SINGLE_RESOURCE); + } else { + return Activator.getDefault().getImageRegistry() + .get(Constants.COLLECTION_RESOURCE); + } + } +} \ No newline at end of file diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/CreateResourcePage.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/LoadRamlPage.java similarity index 53% rename from service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/CreateResourcePage.java rename to service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/LoadRamlPage.java index dc44ad6..8cc4928 100644 --- 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/LoadRamlPage.java @@ -16,16 +16,21 @@ package oic.simulator.serviceprovider.view.dialogs; -import java.util.Iterator; -import java.util.Map; +import java.io.FileInputStream; +import java.lang.reflect.InvocationTargetException; +import java.util.Date; import oic.simulator.serviceprovider.Activator; +import oic.simulator.serviceprovider.model.Resource; import oic.simulator.serviceprovider.utils.Constants; import oic.simulator.serviceprovider.utils.Utility; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.operation.IRunnableWithProgress; +import org.eclipse.jface.wizard.IWizardPage; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.ModifyEvent; @@ -43,37 +48,51 @@ import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.PlatformUI; +import org.oic.simulator.ILogger.Level; +import org.oic.simulator.SimulatorException; +import org.oic.simulator.server.SimulatorResource; +import org.oic.simulator.server.SimulatorResource.Type; /** * This class shows UI for creating resources. */ -public class 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() { +public class LoadRamlPage extends WizardPage { + + private Text locationTxt; + private Button btnBrowse; + private Text noOfInstancesText; + private Label noOfInstancesLbl; + private Label locationLbl; + + private String configFilePath = null; + private int resourceCount; + + private Resource resource; + + private SimulatorResource.Type typeOfResource; + + protected LoadRamlPage() { super("Create Resource"); resourceCount = -1; } + public void initialSetup(SimulatorResource.Type type) { + this.typeOfResource = type; + if (!noOfInstancesLbl.isDisposed()) { + noOfInstancesLbl.setVisible(type == Type.SINGLE); + } + if (!noOfInstancesText.isDisposed()) { + noOfInstancesText.setVisible(type == Type.SINGLE); + } + } + @Override public void createControl(Composite parent) { setPageComplete(false); setTitle(Constants.CREATE_PAGE_TITLE); setMessage(Constants.CREATE_PAGE_MESSAGE); Composite compContent = new Composite(parent, SWT.NONE); - GridLayout gridLayout = new GridLayout(1, false); + GridLayout gridLayout = new GridLayout(); compContent.setLayout(gridLayout); GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); compContent.setLayoutData(gd); @@ -87,30 +106,7 @@ public class CreateResourcePage extends WizardPage { 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"); + configGroup.setText("Load RAML File"); Composite cusConfigComp = new Composite(configGroup, SWT.NONE); cusConfigComp.setLayout(new GridLayout(3, false)); @@ -121,7 +117,6 @@ public class CreateResourcePage extends WizardPage { locationLbl = new Label(cusConfigComp, SWT.NONE); locationLbl.setText("Location:"); - locationLbl.setEnabled(false); locationTxt = new Text(cusConfigComp, SWT.BORDER); gd = new GridData(); @@ -129,7 +124,6 @@ public class CreateResourcePage extends WizardPage { gd.horizontalAlignment = SWT.FILL; gd.grabExcessHorizontalSpace = true; locationTxt.setLayoutData(gd); - locationTxt.setEnabled(false); btnBrowse = new Button(cusConfigComp, SWT.NONE); btnBrowse.setText("Browse"); @@ -137,7 +131,7 @@ public class CreateResourcePage extends WizardPage { gd.widthHint = 80; gd.horizontalAlignment = SWT.FILL; btnBrowse.setLayoutData(gd); - btnBrowse.setEnabled(false); + btnBrowse.setFocus(); Composite instanceComp = new Composite(compContent, SWT.NONE); instanceComp.setLayout(new GridLayout(2, false)); @@ -158,75 +152,12 @@ public class CreateResourcePage extends WizardPage { // 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 configMap; - configMap = Activator.getDefault().getResourceManager() - .getResourceConfigurationList(); - if (null != configMap) { - Iterator 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) { @@ -235,30 +166,8 @@ public class CreateResourcePage extends WizardPage { 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()); - } - } + if (null != configFileAbsolutePath) + locationTxt.setText(configFileAbsolutePath); } }); @@ -266,7 +175,7 @@ public class CreateResourcePage extends WizardPage { @Override public void modifyText(ModifyEvent e) { configFilePath = locationTxt.getText(); - setPageComplete(isSelectionDone()); + getWizard().getContainer().updateButtons(); } }); @@ -288,37 +197,109 @@ public class CreateResourcePage extends WizardPage { noOfInstancesText.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { - setPageComplete(isSelectionDone()); + getWizard().getContainer().updateButtons(); } }); } - private void selectInitialItem() { - if (resourceTypeCmb.getItemCount() > 0) { - resourceTypeCmb.select(0); - String fileName = Utility.displayToFileName(resourceTypeCmb - .getText()); - configFilePath = Activator.getDefault().getResourceManager() - .getConfigFilePath(fileName); + @Override + public boolean canFlipToNextPage() { + boolean done = false; + try { + resourceCount = Integer.parseInt(noOfInstancesText.getText()); + } catch (Exception e) { + resourceCount = -1; } + if (null != configFilePath && configFilePath.trim().length() > 0) { + if (typeOfResource == Type.COLLECTION) { + done = true; + } else { + if (resourceCount == 1) { + done = true; + } + } + } + return done; } - private boolean isSelectionDone() { + public 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.trim().length() > 0) { + if (typeOfResource == Type.COLLECTION) { + done = true; + } else { + if (resourceCount >= 1) { + done = true; + } + } + } + return done; + } + + public boolean isMultiResourceCreation() { + if (typeOfResource != Type.COLLECTION && resourceCount > 1) { + return true; } + return false; + } - if (null != configFilePath && configFilePath.length() > 0 - && resourceCount >= 1) { - done = true; + @Override + public IWizardPage getNextPage() { + // Validate the file path. + try { + new FileInputStream(configFilePath); + } catch (Exception e) { + MessageDialog + .openError(getShell(), "Invalid File", + "File doesn't exist. Either the file path or file name is invalid."); + // TODO: Instead of MessageDialog, errors may be shown on wizard + // itself. + return null; } - return done; + final CreateResourceWizard wizard = ((CreateResourceWizard) getWizard()); + + try { + getContainer().run(true, true, new IRunnableWithProgress() { + @Override + public void run(IProgressMonitor monitor) + throws InvocationTargetException, InterruptedException { + try { + monitor.beginTask("Resource Creation With RAML", 2); + monitor.worked(1); + resource = Activator.getDefault().getResourceManager() + .createResourceByRAML(configFilePath); + monitor.worked(1); + } catch (SimulatorException e) { + wizard.setStatus("Failed to create resource.\n" + + Utility.getSimulatorErrorString(e, null)); + } finally { + monitor.done(); + } + } + }); + } catch (InvocationTargetException e) { + Activator.getDefault().getLogManager() + .log(Level.ERROR.ordinal(), new Date(), e.getMessage()); + e.printStackTrace(); + } catch (InterruptedException e) { + Activator.getDefault().getLogManager() + .log(Level.ERROR.ordinal(), new Date(), e.getMessage()); + e.printStackTrace(); + } + if (null == resource) { + wizard.setStatus("Failed to create Resource."); + wizard.getWizardDialog().close(); + return null; + } + UpdatePropertiesPage updatePageRef = wizard.getUpdatePropPage(); + updatePageRef.setResName(resource.getResourceName()); + updatePageRef.setResURI(resource.getResourceURI()); + return updatePageRef; } public String getConfigFilePath() { @@ -328,4 +309,12 @@ public class CreateResourcePage extends WizardPage { public int getResourceCount() { return resourceCount; } + + public Resource getResource() { + return resource; + } + + public void setResource(Resource resource) { + this.resource = resource; + } } \ No newline at end of file diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/MainPage.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/MainPage.java new file mode 100644 index 0000000..f546f64 --- /dev/null +++ b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/MainPage.java @@ -0,0 +1,191 @@ +package oic.simulator.serviceprovider.view.dialogs; + +import oic.simulator.serviceprovider.utils.Constants; + +import org.eclipse.jface.wizard.IWizardPage; +import org.eclipse.jface.wizard.WizardPage; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Text; +import org.oic.simulator.server.SimulatorResource.Type; + +public class MainPage extends WizardPage { + + private Button simpleBtn; + private Button collectionBtn; + private Button simpleFromRamlBtn; + private Button collectionFromRamlBtn; + private Button deviceBtn; + private Text description; + + public enum ResourceOption { + SIMPLE, SIMPLE_FROM_RAML, COLLECTION, COLLECTION_FROM_RAML, DEVICE, NONE + } + + private ResourceOption resOption; + + protected MainPage() { + super("Main Page"); + } + + @Override + public void createControl(Composite parent) { + setPageComplete(false); + setTitle(Constants.MAIN_PAGE_TITLE); + setMessage(Constants.MAIN_PAGE_MESSAGE); + Composite compContent = new Composite(parent, SWT.NONE); + GridLayout gridLayout = new GridLayout(); + compContent.setLayout(gridLayout); + GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); + compContent.setLayoutData(gd); + + simpleBtn = new Button(compContent, SWT.RADIO); + simpleBtn.setText("Simple resource"); + + simpleFromRamlBtn = new Button(compContent, SWT.RADIO); + simpleFromRamlBtn.setText("Simple resource(From RAML)"); + + collectionBtn = new Button(compContent, SWT.RADIO); + collectionBtn.setText("Collection resource"); + + collectionFromRamlBtn = new Button(compContent, SWT.RADIO); + collectionFromRamlBtn.setText("Collection resource(From RAML)"); + + deviceBtn = new Button(compContent, SWT.RADIO); + deviceBtn.setText("Device"); + + Label lbl = new Label(compContent, SWT.NULL); + lbl.setText("Details:"); + gd = new GridData(); + gd.verticalIndent = 20; + lbl.setLayoutData(gd); + + description = new Text(compContent, SWT.MULTI | SWT.READ_ONLY + | SWT.BORDER | SWT.WRAP | SWT.V_SCROLL); + description.setBackground(compContent.getBackground()); + description.setText("[Select an option to view more details]"); + gd = new GridData(SWT.FILL, SWT.FILL, true, true); + description.setLayoutData(gd); + + addUIListeners(); + + setControl(compContent); + } + + private void addUIListeners() { + simpleBtn.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + description + .setText("Create a simple resource by manually entering all the details given below.\n" + + "\t1. Basic resource details: URI, Name, Resource Types, etc.\n" + + "\t2. Options such as Observable, allowed request types, start/stop resource etc.\n" + + "\t3. Adding attributes."); + resOption = ResourceOption.SIMPLE; + getWizard().getContainer().updateButtons(); + } + }); + + simpleFromRamlBtn.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + description + .setText("Create a simple resource from RAML configuration file.\n" + + "\t1. Resource details, attributes, and other properties will be read from RAML.\n" + + "\t2. Supports multi-instance creation.\n" + + "\t3. For single instance creation, allows editing the URI and Name of the resource.\n" + + "\t4. Allows to start or stop the resource(s)."); + resOption = ResourceOption.SIMPLE_FROM_RAML; + getWizard().getContainer().updateButtons(); + } + }); + + collectionBtn.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + description + .setText("Create a collection resource by manually entering all the details given below.\n" + + "\t1. Basic resource details: URI, Name, Resource Types, etc.\n" + + "\t2. Start/stop the resource.\n" + + "\t3. Adding existing simple resources to this collection."); + resOption = ResourceOption.COLLECTION; + getWizard().getContainer().updateButtons(); + } + }); + + collectionFromRamlBtn.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + description + .setText("Create a collection resource from RAML configuration file.\n" + + "\t1. Resource details, attributes, and other properties will be read from RAML.\n" + + "\t2. Supports multi-instance creation.\n" + + "\t3. For single instance creation, allows editing the URI and Name of the resource.\n" + + "\t4. Allows to start or stop the resource(s)."); + resOption = ResourceOption.COLLECTION_FROM_RAML; + getWizard().getContainer().updateButtons(); + } + }); + + deviceBtn.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + description + .setText("Create a logical device that acts as a top-level logical classification.\n" + + "\t1. Takes a device name for identication.\n" + + "\t2. One or more simple and collection resources can be added to it."); + resOption = ResourceOption.DEVICE; + getWizard().getContainer().updateButtons(); + } + }); + } + + @Override + public boolean canFlipToNextPage() { + if (resOption != ResourceOption.NONE) { + return true; + } + return false; + } + + @Override + public IWizardPage getPreviousPage() { + return null; + } + + @Override + public IWizardPage getNextPage() { + CreateResourceWizard createWizard = (CreateResourceWizard) getWizard(); + if (simpleBtn.getSelection()) { + return createWizard.getSimpleResourceBasicDetailsPage(); + } + if (simpleFromRamlBtn.getSelection()) { + LoadRamlPage page = createWizard.getLoadRamlPage(); + page.initialSetup(Type.SINGLE); + return page; + } + if (collectionBtn.getSelection()) { + return createWizard.getCollectionResourceBasicDetailsPage(); + } + if (collectionFromRamlBtn.getSelection()) { + LoadRamlPage page = createWizard.getLoadRamlPage(); + page.initialSetup(Type.COLLECTION); + return page; + } + if (deviceBtn.getSelection()) { + DevicePage page = createWizard.getDevicePage(); + return page; + } + return null; + } + + public ResourceOption getResourceOption() { + return resOption; + } +} diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/RemoveResourceFromCollections.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/RemoveResourceFromCollections.java new file mode 100644 index 0000000..627a76f --- /dev/null +++ b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/RemoveResourceFromCollections.java @@ -0,0 +1,206 @@ +/* + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package oic.simulator.serviceprovider.view.dialogs; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import oic.simulator.serviceprovider.Activator; +import oic.simulator.serviceprovider.model.CollectionResource; +import oic.simulator.serviceprovider.utils.Constants; + +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.dialogs.TitleAreaDialog; +import org.eclipse.jface.viewers.CheckStateChangedEvent; +import org.eclipse.jface.viewers.CheckboxTreeViewer; +import org.eclipse.jface.viewers.ICheckStateListener; +import org.eclipse.jface.viewers.ITreeContentProvider; +import org.eclipse.jface.viewers.LabelProvider; +import org.eclipse.jface.viewers.Viewer; +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Group; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Shell; + +/** + * This dialog is used for loading the RAML file. + */ +public class RemoveResourceFromCollections extends TitleAreaDialog { + + private CheckboxTreeViewer treeViewer; + + List sourceList; + + Set selectedResourceList; + + public RemoveResourceFromCollections(Shell parentShell, + List sourceList) { + super(parentShell); + this.sourceList = sourceList; + selectedResourceList = new HashSet(); + } + + @Override + public void create() { + super.create(); + setTitle("Remove from Collections"); + setMessage("Select one or more collection resources from which the simple resource will be removed."); + } + + @Override + protected Control createDialogArea(Composite parent) { + Composite compLayout = (Composite) super.createDialogArea(parent); + Composite container = new Composite(compLayout, SWT.NONE); + container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + GridLayout layout = new GridLayout(); + layout.verticalSpacing = 10; + layout.marginTop = 10; + container.setLayout(layout); + + Label lbl = new Label(container, SWT.NONE); + lbl.setText("Select Resources from:"); + GridData gd; + gd = new GridData(); + gd.grabExcessHorizontalSpace = true; + gd.horizontalAlignment = SWT.FILL; + lbl.setLayoutData(gd); + + Group resourceGroup = new Group(container, SWT.NONE); + + Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE); + + resourceGroup.setLayout(new GridLayout()); + gd = new GridData(); + gd.grabExcessHorizontalSpace = true; + gd.horizontalAlignment = SWT.FILL; + gd.heightHint = 300; + gd.horizontalSpan = 2; + resourceGroup.setLayoutData(gd); + + treeViewer = new CheckboxTreeViewer(resourceGroup); + treeViewer.getTree().setBackground(color); + gd = new GridData(); + gd.grabExcessHorizontalSpace = true; + gd.horizontalAlignment = SWT.FILL; + gd.grabExcessVerticalSpace = true; + gd.verticalAlignment = SWT.FILL; + // gd.heightHint = 300; + treeViewer.getTree().setLayoutData(gd); + treeViewer.setContentProvider(new TreeContentProvider()); + treeViewer.setLabelProvider(new TreeLabelProvider()); + treeViewer.setInput(new Object()); + treeViewer.addCheckStateListener(new ICheckStateListener() { + + @Override + public void checkStateChanged(CheckStateChangedEvent e) { + CollectionResource res = (CollectionResource) e.getElement(); + if (null != res) { + if (e.getChecked()) { + selectedResourceList.add(res); + System.out.println("Checked" + res.getResourceName()); + } else { + selectedResourceList.remove(res); + System.out.println("Unchecked:" + res.getResourceName()); + } + } + } + }); + + return compLayout; + } + + public Set getSelectedResourceList() { + return selectedResourceList; + } + + class TreeContentProvider implements ITreeContentProvider { + + @Override + public void dispose() { + } + + @Override + public void inputChanged(Viewer arg0, Object arg1, Object arg2) { + } + + @Override + public Object[] getChildren(Object parent) { + return null; + } + + @Override + public Object[] getElements(Object parent) { + if (null == sourceList) { + sourceList = new ArrayList(); + } + return sourceList.toArray(); + } + + @Override + public Object getParent(Object child) { + return null; + } + + @Override + public boolean hasChildren(Object parent) { + return false; + } + } + + class TreeLabelProvider extends LabelProvider { + @Override + public String getText(Object element) { + CollectionResource res = (CollectionResource) element; + return res.getResourceName(); + } + + @Override + public Image getImage(Object element) { + if (element instanceof CollectionResource) { + return Activator.getDefault().getImageRegistry() + .get(Constants.COLLECTION_RESOURCE); + } else { + return null; + } + } + } + + @Override + protected void okPressed() { + if (selectedResourceList.isEmpty()) { + MessageDialog.openInformation( + Display.getDefault().getActiveShell(), + "No selection done.", "No resources are selected."); + return; + } + close(); + } + + @Override + public boolean isHelpAvailable() { + return false; + } +} diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/RemoveResourceFromDevices.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/RemoveResourceFromDevices.java new file mode 100644 index 0000000..01bedd9 --- /dev/null +++ b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/RemoveResourceFromDevices.java @@ -0,0 +1,205 @@ +/* + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package oic.simulator.serviceprovider.view.dialogs; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import oic.simulator.serviceprovider.Activator; +import oic.simulator.serviceprovider.model.Device; +import oic.simulator.serviceprovider.utils.Constants; + +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.dialogs.TitleAreaDialog; +import org.eclipse.jface.viewers.CheckStateChangedEvent; +import org.eclipse.jface.viewers.CheckboxTreeViewer; +import org.eclipse.jface.viewers.ICheckStateListener; +import org.eclipse.jface.viewers.ITreeContentProvider; +import org.eclipse.jface.viewers.LabelProvider; +import org.eclipse.jface.viewers.Viewer; +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Group; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Shell; + +/** + * This dialog is used for loading the RAML file. + */ +public class RemoveResourceFromDevices extends TitleAreaDialog { + + private CheckboxTreeViewer treeViewer; + + List sourceList; + + Set selectedDeviceList; + + public RemoveResourceFromDevices(Shell parentShell, List sourceList) { + super(parentShell); + this.sourceList = sourceList; + selectedDeviceList = new HashSet(); + } + + @Override + public void create() { + super.create(); + setTitle("Remove from Device"); + setMessage("Select one or more devices from which the simple resource will be removed."); + } + + @Override + protected Control createDialogArea(Composite parent) { + Composite compLayout = (Composite) super.createDialogArea(parent); + Composite container = new Composite(compLayout, SWT.NONE); + container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + GridLayout layout = new GridLayout(); + layout.verticalSpacing = 10; + layout.marginTop = 10; + container.setLayout(layout); + + Label lbl = new Label(container, SWT.NONE); + lbl.setText("Select Resources from:"); + GridData gd; + gd = new GridData(); + gd.grabExcessHorizontalSpace = true; + gd.horizontalAlignment = SWT.FILL; + lbl.setLayoutData(gd); + + Group resourceGroup = new Group(container, SWT.NONE); + + Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE); + + resourceGroup.setLayout(new GridLayout()); + gd = new GridData(); + gd.grabExcessHorizontalSpace = true; + gd.horizontalAlignment = SWT.FILL; + gd.heightHint = 300; + gd.horizontalSpan = 2; + resourceGroup.setLayoutData(gd); + + treeViewer = new CheckboxTreeViewer(resourceGroup); + treeViewer.getTree().setBackground(color); + gd = new GridData(); + gd.grabExcessHorizontalSpace = true; + gd.horizontalAlignment = SWT.FILL; + gd.grabExcessVerticalSpace = true; + gd.verticalAlignment = SWT.FILL; + // gd.heightHint = 300; + treeViewer.getTree().setLayoutData(gd); + treeViewer.setContentProvider(new TreeContentProvider()); + treeViewer.setLabelProvider(new TreeLabelProvider()); + treeViewer.setInput(new Object()); + treeViewer.addCheckStateListener(new ICheckStateListener() { + + @Override + public void checkStateChanged(CheckStateChangedEvent e) { + Device res = (Device) e.getElement(); + if (null != res) { + if (e.getChecked()) { + selectedDeviceList.add(res); + System.out.println("Checked" + res.getDeviceName()); + } else { + selectedDeviceList.remove(res); + System.out.println("Unchecked:" + res.getDeviceName()); + } + } + } + }); + + return compLayout; + } + + public Set getSelectedDeviceList() { + return selectedDeviceList; + } + + class TreeContentProvider implements ITreeContentProvider { + + @Override + public void dispose() { + } + + @Override + public void inputChanged(Viewer arg0, Object arg1, Object arg2) { + } + + @Override + public Object[] getChildren(Object parent) { + return null; + } + + @Override + public Object[] getElements(Object parent) { + if (null == sourceList) { + sourceList = new ArrayList(); + } + return sourceList.toArray(); + } + + @Override + public Object getParent(Object child) { + return null; + } + + @Override + public boolean hasChildren(Object parent) { + return false; + } + } + + class TreeLabelProvider extends LabelProvider { + @Override + public String getText(Object element) { + Device res = (Device) element; + return res.getDeviceName(); + } + + @Override + public Image getImage(Object element) { + if (element instanceof Device) { + return Activator.getDefault().getImageRegistry() + .get(Constants.DEVICE); + } else { + return null; + } + } + } + + @Override + protected void okPressed() { + if (selectedDeviceList.isEmpty()) { + MessageDialog.openInformation( + Display.getDefault().getActiveShell(), + "No selection done.", "No devices are selected."); + return; + } + close(); + } + + @Override + public boolean isHelpAvailable() { + return false; + } +} diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/RemoveResources.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/RemoveResources.java new file mode 100644 index 0000000..f76f8f9 --- /dev/null +++ b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/RemoveResources.java @@ -0,0 +1,207 @@ +/* + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package oic.simulator.serviceprovider.view.dialogs; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import oic.simulator.serviceprovider.Activator; +import oic.simulator.serviceprovider.model.CollectionResource; +import oic.simulator.serviceprovider.model.Resource; +import oic.simulator.serviceprovider.utils.Constants; + +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.dialogs.TitleAreaDialog; +import org.eclipse.jface.viewers.CheckStateChangedEvent; +import org.eclipse.jface.viewers.CheckboxTreeViewer; +import org.eclipse.jface.viewers.ICheckStateListener; +import org.eclipse.jface.viewers.ITreeContentProvider; +import org.eclipse.jface.viewers.LabelProvider; +import org.eclipse.jface.viewers.Viewer; +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Group; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Shell; + +/** + * This dialog is used for loading the RAML file. + */ +public class RemoveResources extends TitleAreaDialog { + + private CheckboxTreeViewer treeViewer; + + List sourceList; + + Set selectedResourceList; + + public RemoveResources(Shell parentShell, List sourceList) { + super(parentShell); + this.sourceList = sourceList; + selectedResourceList = new HashSet(); + } + + @Override + public void create() { + super.create(); + setTitle("Remove Resources"); + setMessage("Select one or more resources to be removed."); + } + + @Override + protected Control createDialogArea(Composite parent) { + Composite compLayout = (Composite) super.createDialogArea(parent); + Composite container = new Composite(compLayout, SWT.NONE); + container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + GridLayout layout = new GridLayout(); + layout.verticalSpacing = 10; + layout.marginTop = 10; + container.setLayout(layout); + + Label lbl = new Label(container, SWT.NONE); + lbl.setText("Select Resources from:"); + GridData gd; + gd = new GridData(); + gd.grabExcessHorizontalSpace = true; + gd.horizontalAlignment = SWT.FILL; + lbl.setLayoutData(gd); + + Group resourceGroup = new Group(container, SWT.NONE); + + Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE); + + resourceGroup.setLayout(new GridLayout()); + gd = new GridData(); + gd.grabExcessHorizontalSpace = true; + gd.horizontalAlignment = SWT.FILL; + gd.heightHint = 300; + gd.horizontalSpan = 2; + resourceGroup.setLayoutData(gd); + + treeViewer = new CheckboxTreeViewer(resourceGroup); + treeViewer.getTree().setBackground(color); + gd = new GridData(); + gd.grabExcessHorizontalSpace = true; + gd.horizontalAlignment = SWT.FILL; + gd.grabExcessVerticalSpace = true; + gd.verticalAlignment = SWT.FILL; + // gd.heightHint = 300; + treeViewer.getTree().setLayoutData(gd); + treeViewer.setContentProvider(new TreeContentProvider()); + treeViewer.setLabelProvider(new TreeLabelProvider()); + treeViewer.setInput(new Object()); + treeViewer.addCheckStateListener(new ICheckStateListener() { + + @Override + public void checkStateChanged(CheckStateChangedEvent e) { + Resource res = (Resource) e.getElement(); + if (null != res) { + if (e.getChecked()) { + selectedResourceList.add(res); + System.out.println("Checked" + res.getResourceName()); + } else { + selectedResourceList.remove(res); + System.out.println("Unchecked:" + res.getResourceName()); + } + } + } + }); + + return compLayout; + } + + public Set getSelectedResourceList() { + return selectedResourceList; + } + + class TreeContentProvider implements ITreeContentProvider { + + @Override + public void dispose() { + } + + @Override + public void inputChanged(Viewer arg0, Object arg1, Object arg2) { + } + + @Override + public Object[] getChildren(Object parent) { + return null; + } + + @Override + public Object[] getElements(Object parent) { + if (null == sourceList) { + sourceList = new ArrayList(); + } + return sourceList.toArray(); + } + + @Override + public Object getParent(Object child) { + return null; + } + + @Override + public boolean hasChildren(Object parent) { + return false; + } + } + + class TreeLabelProvider extends LabelProvider { + @Override + public String getText(Object element) { + Resource res = (Resource) element; + return res.getResourceName(); + } + + @Override + public Image getImage(Object element) { + if (element instanceof CollectionResource) { + return Activator.getDefault().getImageRegistry() + .get(Constants.COLLECTION_RESOURCE); + } else { + return Activator.getDefault().getImageRegistry() + .get(Constants.SINGLE_RESOURCE); + } + } + } + + @Override + protected void okPressed() { + if (selectedResourceList.isEmpty()) { + MessageDialog.openInformation( + Display.getDefault().getActiveShell(), + "No selection done.", "No resources are selected."); + return; + } + close(); + } + + @Override + public boolean isHelpAvailable() { + return false; + } +} diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/ResourceWizardDialog.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/ResourceWizardDialog.java index 09f95fe..5113712 100644 --- 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 @@ -16,11 +16,9 @@ package oic.simulator.serviceprovider.view.dialogs; -import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.wizard.IWizard; +import org.eclipse.jface.wizard.IWizardPage; import org.eclipse.jface.wizard.WizardDialog; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Shell; /** @@ -28,8 +26,11 @@ import org.eclipse.swt.widgets.Shell; */ public class ResourceWizardDialog extends WizardDialog { + private IWizard wizard; + public ResourceWizardDialog(Shell parentShell, IWizard newWizard) { super(parentShell, newWizard); + wizard = newWizard; } @Override @@ -43,11 +44,46 @@ public class ResourceWizardDialog extends WizardDialog { } @Override - protected void createButtonsForButtonBar(Composite parent) { - super.createButtonsForButtonBar(parent); - Button finishButton = getButton(IDialogConstants.FINISH_ID); - if (finishButton != null) { - finishButton.setText(IDialogConstants.OK_LABEL); + protected void backPressed() { + if (wizard.getClass() == CreateResourceWizard.class) { + CreateResourceWizard createWizard = (CreateResourceWizard) wizard; + + MainPage mainPage = createWizard.getMainPage(); + SimpleResourceBasicDetailsPage simpleResourceBasicDetailsPage = createWizard + .getSimpleResourceBasicDetailsPage(); + SimpleResourceOtherDetailsPage simpleResourceOtherDetailsPage = createWizard + .getSimpleResourceOtherDetailsPage(); + SimpleResourceAddAttributePage simpleResourceAddAttributesPage = createWizard + .getSimpleResourceAddAttributePage(); + CollectionResourceBasicDetailsPage collectionResourceBasicDetailsPage = createWizard + .getCollectionResourceBasicDetailsPage(); + AddResourcesToCollectionPage addResourcesToCollectionPage = createWizard + .getAddResourcesToCollectionPage(); + LoadRamlPage loadRamlPage = createWizard.getLoadRamlPage(); + UpdatePropertiesPage updatePropPage = createWizard + .getUpdatePropPage(); + DevicePage devPage = createWizard.getDevicePage(); + + IWizardPage curPage = wizard.getContainer().getCurrentPage(); + IWizardPage prevPage = null; + + if (curPage == loadRamlPage + || curPage == simpleResourceBasicDetailsPage + || curPage == collectionResourceBasicDetailsPage + || curPage == devPage) { + prevPage = mainPage; + } else if (curPage == updatePropPage) { + loadRamlPage.setResource(null); + prevPage = loadRamlPage; + } else if (curPage == addResourcesToCollectionPage) { + prevPage = collectionResourceBasicDetailsPage; + } else if (curPage == simpleResourceAddAttributesPage) { + prevPage = simpleResourceBasicDetailsPage; + } else if (curPage == simpleResourceOtherDetailsPage) { + prevPage = simpleResourceAddAttributesPage; + } + if (null != prevPage) + showPage(prevPage); } } } \ No newline at end of file diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/SimpleResourceAddAttributePage.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/SimpleResourceAddAttributePage.java new file mode 100644 index 0000000..0e664ca --- /dev/null +++ b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/SimpleResourceAddAttributePage.java @@ -0,0 +1,379 @@ +package oic.simulator.serviceprovider.view.dialogs; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import oic.simulator.serviceprovider.model.AttributeHelper; +import oic.simulator.serviceprovider.utils.Constants; +import oic.simulator.serviceprovider.utils.Utility; + +import org.eclipse.jface.viewers.ISelectionChangedListener; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.viewers.ITreeContentProvider; +import org.eclipse.jface.viewers.SelectionChangedEvent; +import org.eclipse.jface.viewers.StyledCellLabelProvider; +import org.eclipse.jface.viewers.TableViewer; +import org.eclipse.jface.viewers.TableViewerColumn; +import org.eclipse.jface.viewers.Viewer; +import org.eclipse.jface.viewers.ViewerCell; +import org.eclipse.jface.window.Window; +import org.eclipse.jface.wizard.IWizardPage; +import org.eclipse.jface.wizard.WizardPage; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Table; +import org.oic.simulator.AttributeProperty.Type; + +public class SimpleResourceAddAttributePage extends WizardPage { + + private TableViewer attTblViewer; + private Button addBtn; + private Button remBtn; + private Button editBtn; + + private final String[] attTblHeaders = { "Name", "Type", "Range", + "Allowed Values", "Default Value" }; + private final Integer[] attTblColWidth = { 90, 75, 75, 150, 75 }; + + private Set attributes; + + protected SimpleResourceAddAttributePage() { + super("Add Attributes"); + attributes = new HashSet(); + } + + @Override + public void createControl(Composite parent) { + setPageComplete(false); + setTitle(Constants.SIMPLE_RESOURCE_ADD_ATTRIBUTE_PAGE_TITLE); + setMessage(Constants.SIMPLE_RESOURCE_ADD_ATTRIBUTE_PAGE_MESSAGE); + Composite compContent = new Composite(parent, SWT.NONE); + GridLayout gridLayout = new GridLayout(2, false); + compContent.setLayout(gridLayout); + GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); + compContent.setLayoutData(gd); + + Label lbl = new Label(compContent, SWT.NULL); + lbl.setText("Attributes:"); + gd = new GridData(); + gd.horizontalSpan = 2; + lbl.setLayoutData(gd); + + setupAttributeTable(compContent); + + setupAttributeControls(compContent); + + setUiListeners(compContent); + + setControl(compContent); + } + + private void setupAttributeTable(Composite attComp) { + attTblViewer = new TableViewer(attComp, SWT.MULTI | SWT.H_SCROLL + | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER); + + createAttributeColumns(attTblViewer); + + // make lines and header visible + Table table = attTblViewer.getTable(); + table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + table.setHeaderVisible(true); + table.setLinesVisible(true); + + attTblViewer.setContentProvider(new AttributeContentProvider()); + } + + public void createAttributeColumns(TableViewer tableViewer) { + + TableViewerColumn attName = new TableViewerColumn(tableViewer, SWT.NONE); + attName.getColumn().setWidth(attTblColWidth[0]); + attName.getColumn().setText(attTblHeaders[0]); + attName.setLabelProvider(new StyledCellLabelProvider() { + @Override + public void update(ViewerCell cell) { + Object e = cell.getElement(); + if (null == e) { + return; + } + AttributeHelper att = (AttributeHelper) e; + cell.setText(att.getAttributeName()); + + } + }); + + TableViewerColumn attType = new TableViewerColumn(tableViewer, SWT.NONE); + attType.getColumn().setWidth(attTblColWidth[1]); + attType.getColumn().setText(attTblHeaders[1]); + attType.setLabelProvider(new StyledCellLabelProvider() { + @Override + public void update(ViewerCell cell) { + Object e = cell.getElement(); + if (null == e) { + return; + } + AttributeHelper att = (AttributeHelper) e; + cell.setText(att.getAttributeType()); + } + }); + + TableViewerColumn attRange = new TableViewerColumn(tableViewer, + SWT.NONE); + attRange.getColumn().setWidth(attTblColWidth[2]); + attRange.getColumn().setText(attTblHeaders[2]); + attRange.setLabelProvider(new StyledCellLabelProvider() { + @Override + public void update(ViewerCell cell) { + Object e = cell.getElement(); + if (null == e) { + return; + } + AttributeHelper att = (AttributeHelper) e; + if (att.getValidValuesType() != Type.RANGE) { + cell.setText("Nil"); + } else { + String min = att.getMin(); + String max = att.getMax(); + if (null != min && null != max) { + cell.setText("[" + att.getMin() + " to " + att.getMax() + + "]"); + } else { + cell.setText("Nil"); + } + } + } + }); + + TableViewerColumn attAllwdValues = new TableViewerColumn(tableViewer, + SWT.NONE); + attAllwdValues.getColumn().setWidth(attTblColWidth[3]); + attAllwdValues.getColumn().setText(attTblHeaders[3]); + attAllwdValues.setLabelProvider(new StyledCellLabelProvider() { + @Override + public void update(ViewerCell cell) { + Object e = cell.getElement(); + if (null == e) { + return; + } + AttributeHelper att = (AttributeHelper) e; + if (att.getValidValuesType() != Type.VALUESET) { + cell.setText("Nil"); + } else { + cell.setText(att.getAllowedValues().toString()); + } + } + }); + + TableViewerColumn attDflValue = new TableViewerColumn(tableViewer, + SWT.NONE); + attDflValue.getColumn().setWidth(attTblColWidth[4]); + attDflValue.getColumn().setText(attTblHeaders[4]); + attDflValue.setLabelProvider(new StyledCellLabelProvider() { + @Override + public void update(ViewerCell cell) { + Object e = cell.getElement(); + if (null == e) { + return; + } + AttributeHelper att = (AttributeHelper) e; + cell.setText(att.getAttributeDflValue()); + } + }); + } + + private void setupAttributeControls(Composite compContent) { + + Composite innerComp = new Composite(compContent, SWT.NULL); + innerComp.setLayout(new GridLayout()); + GridData gd = new GridData(); + gd.verticalAlignment = SWT.TOP; + innerComp.setLayoutData(gd); + + addBtn = new Button(innerComp, SWT.PUSH); + addBtn.setText("Add"); + gd = new GridData(); + gd.widthHint = 70; + addBtn.setLayoutData(gd); + + editBtn = new Button(innerComp, SWT.PUSH); + editBtn.setText("Edit"); + editBtn.setEnabled(false); + gd = new GridData(); + gd.widthHint = 70; + editBtn.setLayoutData(gd); + + remBtn = new Button(innerComp, SWT.PUSH); + remBtn.setText("Remove"); + remBtn.setEnabled(false); + gd = new GridData(); + gd.widthHint = 70; + remBtn.setLayoutData(gd); + } + + private void setUiListeners(Composite compContent) { + addBtn.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + Set rTypes = Utility.getAttributeTypes(); + AddAttributeDialog dialog = new AddAttributeDialog(Display + .getDefault().getActiveShell(), null, rTypes, + attributes); + if (dialog.open() == Window.OK) { + AttributeHelper att = dialog.getAttHelper(); + attributes.add(att); + remBtn.setEnabled(true); + AttributeContentProvider provider = (AttributeContentProvider) attTblViewer + .getContentProvider(); + provider.addAttribute(att); + attTblViewer.add(att); + attTblViewer.getTable().deselectAll(); + attTblViewer.getTable().select( + attTblViewer.getTable().getItemCount() - 1); + editBtn.setEnabled(true); + } + } + }); + + editBtn.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + IStructuredSelection selection = (IStructuredSelection) attTblViewer + .getSelection(); + if (null == selection) { + editBtn.setEnabled(false); + return; + } + AttributeHelper att = (AttributeHelper) selection + .getFirstElement(); + if (null == att) { + editBtn.setEnabled(false); + return; + } + // Opening the dialog for edit operation. + // Passing the attribute to pre-fill the UI controls. + Set rTypes = Utility.getAttributeTypes(); + AddAttributeDialog dialog = new AddAttributeDialog(Display + .getDefault().getActiveShell(), att, rTypes, attributes); + if (dialog.open() != Window.OK) { + AttributeHelper newAtt = dialog.getAttClone(); + att.setAttributeName(newAtt.getAttributeName()); + att.setAttributeType(newAtt.getAttributeType()); + att.setAttributeDflValue(newAtt.getAttributeDflValue()); + att.setValidValuesType(newAtt.getValidValuesType()); + att.setMin(newAtt.getMin()); + att.setMax(newAtt.getMax()); + att.setAllowedValues(newAtt.getAllowedValues()); + } + attTblViewer.update(att, null); + System.out.println("Attribute data after closing edit dialog: " + + att); + } + }); + + remBtn.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + IStructuredSelection selection = (IStructuredSelection) attTblViewer + .getSelection(); + if (null != selection) { + System.out.println(selection.size()); + Iterator itr = selection.iterator(); + while (itr.hasNext()) { + AttributeHelper att = (AttributeHelper) itr.next(); + System.out.println(att.getAttributeName()); + attTblViewer.remove(att); + attributes.remove(att); + AttributeContentProvider provider = (AttributeContentProvider) attTblViewer + .getContentProvider(); + provider.removeAttribute(att); + } + if (attributes.size() < 1) { + remBtn.setEnabled(false); + } + editBtn.setEnabled(false); + } + } + }); + + attTblViewer + .addSelectionChangedListener(new ISelectionChangedListener() { + + @Override + public void selectionChanged(SelectionChangedEvent event) { + System.out.println("table selection changed"); + remBtn.setEnabled(true); + IStructuredSelection selection = (IStructuredSelection) event + .getSelection(); + if (null == selection) { + return; + } + if (selection.size() > 1) { + editBtn.setEnabled(false); + } else { + editBtn.setEnabled(true); + } + } + }); + } + + class AttributeContentProvider implements ITreeContentProvider { + + List attList = new ArrayList(); + + @SuppressWarnings("unchecked") + @Override + public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { + attList = (List) newInput; + } + + @Override + public Object[] getChildren(Object element) { + return new Object[0]; + } + + @Override + public Object[] getElements(Object input) { + return attList.toArray(); + } + + @Override + public Object getParent(Object element) { + return null; + } + + @Override + public boolean hasChildren(Object element) { + return false; + } + + @Override + public void dispose() { + } + + public synchronized void addAttribute(AttributeHelper newElement) { + attList.add(newElement); + } + + public synchronized void removeAttribute(AttributeHelper element) { + attList.remove(element); + } + } + + @Override + public boolean canFlipToNextPage() { + return false; + } + + public Set getAttributes() { + return attributes; + } +} diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/SimpleResourceBasicDetailsPage.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/SimpleResourceBasicDetailsPage.java new file mode 100644 index 0000000..f01939b --- /dev/null +++ b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/SimpleResourceBasicDetailsPage.java @@ -0,0 +1,303 @@ +package oic.simulator.serviceprovider.view.dialogs; + +import java.util.HashSet; +import java.util.Set; + +import oic.simulator.serviceprovider.Activator; +import oic.simulator.serviceprovider.utils.Constants; + +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.window.Window; +import org.eclipse.jface.wizard.IWizardPage; +import org.eclipse.jface.wizard.WizardPage; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.ModifyEvent; +import org.eclipse.swt.events.ModifyListener; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Group; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.List; +import org.eclipse.swt.widgets.Text; + +public class SimpleResourceBasicDetailsPage extends WizardPage { + + private Text resNameTxt; + private Text resUriTxt; + private List resTypeslist; + private Button addToListBtn; + private Button remFromListBtn; + private Button observeBtn; + // private Button startBtn; + + private String resName; + private String resURI; + private Set resTypes; + private boolean observable; + + // private boolean start; + + protected SimpleResourceBasicDetailsPage() { + super("Basic Details"); + resTypes = new HashSet(); + } + + @Override + public void createControl(Composite parent) { + setPageComplete(false); + setTitle(Constants.SIMPLE_RESOURCE_BASIC_DETAILS_PAGE_TITLE); + setMessage(Constants.SIMPLE_RESOURCE_BASIC_DETAILS_PAGE_MESSAGE); + + Composite container = new Composite(parent, SWT.NONE); + GridLayout gridLayout = new GridLayout(); + container.setLayout(gridLayout); + GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); + container.setLayoutData(gd); + + Group resDetGrp = new Group(container, SWT.NONE); + resDetGrp.setText("Resource Details"); + gridLayout = new GridLayout(4, false); + resDetGrp.setLayout(gridLayout); + gd = new GridData(SWT.FILL, SWT.FILL, true, true); + resDetGrp.setLayoutData(gd); + + Label resNameLbl = new Label(resDetGrp, SWT.NULL); + resNameLbl.setText(Constants.RESOURCE_NAME); + gd = new GridData(); + resNameLbl.setLayoutData(gd); + + resNameTxt = new Text(resDetGrp, SWT.BORDER); + gd = new GridData(); + // gd.widthHint = 300; + gd.horizontalAlignment = SWT.FILL; + gd.grabExcessHorizontalSpace = true; + gd.horizontalSpan = 3; + resNameTxt.setLayoutData(gd); + resNameTxt.setFocus(); + + Label resUriLbl = new Label(resDetGrp, SWT.NULL); + resUriLbl.setText(Constants.RESOURCE_URI); + + resUriTxt = new Text(resDetGrp, SWT.BORDER); + gd = new GridData(); + // gd.widthHint = 300; + gd.horizontalSpan = 3; + gd.horizontalAlignment = SWT.FILL; + gd.grabExcessHorizontalSpace = true; + resUriTxt.setLayoutData(gd); + /* + * Composite resTypesComp = new Composite(compContent, SWT.NONE); + * gridLayout = new GridLayout(3, false); + * resTypesComp.setLayout(gridLayout); gd = new GridData(); + * gd.grabExcessHorizontalSpace = true; gd.horizontalAlignment = + * SWT.FILL; resTypesComp.setLayoutData(gd); + */ + + Label resTypesLbl = new Label(resDetGrp, SWT.NULL); + resTypesLbl.setText(Constants.RESOURCE_TYPES); + + resTypeslist = new List(resDetGrp, SWT.BORDER | SWT.MULTI + | SWT.V_SCROLL); + gd = new GridData(); + gd.grabExcessHorizontalSpace = true; + gd.horizontalAlignment = SWT.FILL; + gd.horizontalSpan = 2; + gd.heightHint = 100; + /* gd.widthHint = 200; */ + resTypeslist.setLayoutData(gd); + // resTypeslist.setBackground(new Color()); + + Composite resTypesActionsComp = new Composite(resDetGrp, SWT.NONE); + gridLayout = new GridLayout(); + resTypesActionsComp.setLayout(gridLayout); + gd = new GridData(); + gd.verticalAlignment = SWT.TOP; + /* + * gd.grabExcessHorizontalSpace = true; gd.horizontalAlignment = + * SWT.FILL; + */ + resTypesActionsComp.setLayoutData(gd); + + addToListBtn = new Button(resTypesActionsComp, SWT.PUSH); + addToListBtn.setText("Add"); + gd = new GridData(); + gd.widthHint = 70; + addToListBtn.setLayoutData(gd); + + remFromListBtn = new Button(resTypesActionsComp, SWT.PUSH); + remFromListBtn.setText("Remove"); + gd = new GridData(); + gd.widthHint = 70; + remFromListBtn.setLayoutData(gd); + remFromListBtn.setEnabled(false); + + Group otherOptionsGrp = new Group(container, SWT.NONE); + otherOptionsGrp.setText("Other options"); + gridLayout = new GridLayout(); + otherOptionsGrp.setLayout(gridLayout); + gd = new GridData(SWT.FILL, SWT.FILL, true, true); + otherOptionsGrp.setLayoutData(gd); + + observeBtn = new Button(otherOptionsGrp, SWT.CHECK); + observeBtn.setText("Observable"); + observeBtn.setSelection(true); + observable = true; + + /* + * startBtn = new Button(otherOptionsGrp, SWT.CHECK); + * startBtn.setText("Start the resource immediately after creation"); + * startBtn.setSelection(true); + */ + addUiListeners(); + + setControl(container); + } + + private void addUiListeners() { + + resUriTxt.addModifyListener(new ModifyListener() { + @Override + public void modifyText(ModifyEvent arg0) { + resURI = resUriTxt.getText(); + getWizard().getContainer().updateButtons(); + } + }); + + resNameTxt.addModifyListener(new ModifyListener() { + @Override + public void modifyText(ModifyEvent arg0) { + resName = resNameTxt.getText(); + getWizard().getContainer().updateButtons(); + } + }); + + addToListBtn.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + SingleTextInputDialog dialog = new SingleTextInputDialog( + getShell(), "Add Resource Type", "Resource Type"); + if (dialog.open() == Window.OK) { + System.out.println(dialog.getValue()); + String resType = dialog.getValue(); + // Duplicate check. + if (resTypes.contains(resType)) { + MessageDialog.openError(Display.getDefault() + .getActiveShell(), "Duplicate value", + "value already exist."); + return; + } + resTypeslist.add(resType); + resTypeslist.deselectAll(); + resTypeslist.select(resTypeslist.getItemCount() - 1); + resTypeslist.showSelection(); + remFromListBtn.setEnabled(true); + + resTypes.add(resType); + + getWizard().getContainer().updateButtons(); + } + } + }); + + remFromListBtn.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + int[] selection = resTypeslist.getSelectionIndices(); + String[] selectionStr = resTypeslist.getSelection(); + if (null != selection && selection.length > 0) { + resTypeslist.remove(selection); + for (String selected : selectionStr) { + resTypes.remove(selected); + } + } + + changeVisibility(); + getWizard().getContainer().updateButtons(); + } + }); + + resTypeslist.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + changeVisibility(); + } + }); + + observeBtn.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + observable = observeBtn.getSelection(); + } + }); + + /* + * startBtn.addSelectionListener(new SelectionAdapter() { + * + * @Override public void widgetSelected(SelectionEvent e) { start = + * startBtn.getSelection(); } }); + */ + } + + private void changeVisibility() { + int[] selection = resTypeslist.getSelectionIndices(); + if (null != selection && selection.length > 0) { + remFromListBtn.setEnabled(true); + } else { + remFromListBtn.setEnabled(false); + } + } + + @Override + public boolean canFlipToNextPage() { + if (null == resName || null == resURI || resTypes.size() < 1) { + return false; + } + resName = resName.trim(); + resURI = resURI.trim(); + if (resName.length() < 1 || resURI.length() < 1) { + return false; + } + return true; + } + + @Override + public IWizardPage getNextPage() { + // Checking whether the uri is used by any other resource. + if (Activator.getDefault().getResourceManager().isResourceExist(resURI)) { + MessageDialog + .openError(getShell(), "Resource URI in use", + "Entered resource URI is in use. Please try a different one."); + // TODO: Instead of MessageDialog, errors may be shown on wizard + // itself. + return null; + } + return ((CreateResourceWizard) getWizard()) + .getSimpleResourceAddAttributePage(); + } + + public String getResName() { + return resName; + } + + public String getResURI() { + return resURI; + } + + public Set getResTypes() { + return resTypes; + } + + public boolean isObservable() { + return observable; + } + + /* + * public boolean isStart() { return start; } + */ + +} diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/SimpleResourceOtherDetailsPage.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/SimpleResourceOtherDetailsPage.java new file mode 100644 index 0000000..41cd07b --- /dev/null +++ b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/SimpleResourceOtherDetailsPage.java @@ -0,0 +1,119 @@ +package oic.simulator.serviceprovider.view.dialogs; + +import oic.simulator.serviceprovider.utils.Constants; + +import org.eclipse.jface.wizard.IWizardPage; +import org.eclipse.jface.wizard.WizardPage; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Group; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Text; + +public class SimpleResourceOtherDetailsPage extends WizardPage { + + private Button getBtn; + private Button putBtn; + private Button postBtn; + + public boolean getChecked; + public boolean putChecked; + public boolean postChecked; + + protected SimpleResourceOtherDetailsPage() { + super("Allowed Request Types"); + } + + @Override + public void createControl(Composite parent) { + setPageComplete(false); + setTitle(Constants.SIMPLE_RESOURCE_OTHER_DETAILS_PAGE_TITLE); + setMessage(Constants.SIMPLE_RESOURCE_OTHER_DETAILS_PAGE_MESSAGE); + + Composite container = new Composite(parent, SWT.NONE); + GridLayout gridLayout = new GridLayout(); + container.setLayout(gridLayout); + GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); + container.setLayoutData(gd); + + Group resDetGrp = new Group(container, SWT.NONE); + resDetGrp.setText("Allowed Request Types"); + gridLayout = new GridLayout(); + resDetGrp.setLayout(gridLayout); + gd = new GridData(SWT.FILL, SWT.FILL, true, true); + resDetGrp.setLayoutData(gd); + + getBtn = new Button(resDetGrp, SWT.CHECK); + getBtn.setText("GET Request"); + + putBtn = new Button(resDetGrp, SWT.CHECK); + putBtn.setText("PUT Request"); + + postBtn = new Button(resDetGrp, SWT.CHECK); + postBtn.setText("POST Request"); + + Label lbl = new Label(container, SWT.NULL); + lbl.setText("Details:"); + gd = new GridData(); + gd.verticalIndent = 20; + lbl.setLayoutData(gd); + + Text desc = new Text(container, SWT.MULTI | SWT.READ_ONLY | SWT.BORDER + | SWT.WRAP | SWT.V_SCROLL); + desc.setBackground(container.getBackground()); + desc.setText("Shows the different types of request that can be used by the clients on the resource.\n" + + "Resource will handle only the request types which are selected here."); + gd = new GridData(SWT.FILL, SWT.FILL, true, true); + desc.setLayoutData(gd); + + addUiListeners(); + + setControl(container); + } + + private void addUiListeners() { + getBtn.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + getChecked = getBtn.getSelection(); + } + }); + + putBtn.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + putChecked = putBtn.getSelection(); + } + }); + + postBtn.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + postChecked = postBtn.getSelection(); + } + }); + } + + @Override + public IWizardPage getNextPage() { + return null; + } + + public boolean isGetChecked() { + return getChecked; + } + + public boolean isPutChecked() { + return putChecked; + } + + public boolean isPostChecked() { + return postChecked; + } + +} diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/SimpleResourcePage.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/SimpleResourcePage.java new file mode 100644 index 0000000..e743332 --- /dev/null +++ b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/SimpleResourcePage.java @@ -0,0 +1,96 @@ +package oic.simulator.serviceprovider.view.dialogs; + +import oic.simulator.serviceprovider.utils.Constants; + +import org.eclipse.jface.wizard.IWizardPage; +import org.eclipse.jface.wizard.WizardPage; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Text; + +public class SimpleResourcePage extends WizardPage { + + Button manualBtn; + Button ramlBtn; + + protected SimpleResourcePage() { + super("Simle Page"); + } + + @Override + public void createControl(Composite parent) { + setPageComplete(false); + setTitle(Constants.SIMPLE_PAGE_TITLE); + setMessage(Constants.SIMPLE_PAGE_MESSAGE); + Composite compContent = new Composite(parent, SWT.NONE); + GridLayout gridLayout = new GridLayout(); + compContent.setLayout(gridLayout); + GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); + compContent.setLayoutData(gd); + + manualBtn = new Button(compContent, SWT.RADIO); + manualBtn.setText("Manually"); + + ramlBtn = new Button(compContent, SWT.RADIO); + ramlBtn.setText("From RAML file"); + + Label lbl = new Label(compContent, SWT.NULL); + lbl.setText("Details:"); + gd = new GridData(); + gd.verticalIndent = 20; + lbl.setLayoutData(gd); + + Text desc = new Text(compContent, SWT.MULTI | SWT.READ_ONLY + | SWT.BORDER | SWT.WRAP | SWT.V_SCROLL); + desc.setBackground(compContent.getBackground()); + desc.setText("[Select an option to view more details]"); + gd = new GridData(SWT.FILL, SWT.FILL, true, true); + desc.setLayoutData(gd); + + addUIListeners(); + + setControl(compContent); + } + + private void addUIListeners() { + manualBtn.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + getWizard().getContainer().updateButtons(); + } + }); + + ramlBtn.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + getWizard().getContainer().updateButtons(); + } + }); + } + + @Override + public boolean canFlipToNextPage() { + if (manualBtn.getSelection() || ramlBtn.getSelection()) { + return true; + } + return false; + } + + @Override + public IWizardPage getNextPage() { + CreateResourceWizard createWizard = (CreateResourceWizard) getWizard(); + if (manualBtn.getSelection()) { + return createWizard.getSimpleResourceBasicDetailsPage(); + } + if (ramlBtn.getSelection()) { + return createWizard.getLoadRamlPage(); + } + return null; + } +} diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/SingleTextInputDialog.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/SingleTextInputDialog.java new file mode 100644 index 0000000..860d31d --- /dev/null +++ b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/SingleTextInputDialog.java @@ -0,0 +1,100 @@ +/* + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package oic.simulator.serviceprovider.view.dialogs; + +import org.eclipse.jface.dialogs.TrayDialog; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.ModifyEvent; +import org.eclipse.swt.events.ModifyListener; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Text; + +/** + * This class shows a dialog for filtering logs based on severity levels. + */ +public class SingleTextInputDialog extends TrayDialog { + + private Text txt; + private String value; + private String lblTxt; + private String shellTitle; + + public SingleTextInputDialog(Shell shell, String title, String lblTxt) { + super(shell); + shellTitle = title; + this.lblTxt = lblTxt; + } + + @Override + protected void configureShell(Shell shell) { + super.configureShell(shell); + } + + @Override + protected Control createDialogArea(Composite parent) { + Composite composite = (Composite) super.createDialogArea(parent); + getShell().setText(shellTitle); + + Composite content = new Composite(parent, SWT.NULL); + GridLayout gridLayout = new GridLayout(); + content.setLayout(gridLayout); + GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); + content.setLayoutData(gd); + + Label lbl = new Label(content, SWT.NONE); + lbl.setText(lblTxt); + + txt = new Text(content, SWT.BORDER); + gd = new GridData(SWT.FILL, SWT.FILL, true, true); + txt.setLayoutData(gd); + txt.addModifyListener(new ModifyListener() { + + @Override + public void modifyText(ModifyEvent e) { + value = txt.getText(); + } + }); + + return composite; + } + + @Override + protected void okPressed() { + if (null != value) { + value = value.trim(); + if (value.length() > 0) { + close(); + return; + } + } + txt.setFocus(); + } + + @Override + public boolean isHelpAvailable() { + return false; + } + + public String getValue() { + return value; + } +} \ No newline at end of file diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/StartStopResourcePage.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/StartStopResourcePage.java new file mode 100644 index 0000000..4f2a3c8 --- /dev/null +++ b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/StartStopResourcePage.java @@ -0,0 +1,90 @@ +package oic.simulator.serviceprovider.view.dialogs; + +import oic.simulator.serviceprovider.utils.Constants; + +import org.eclipse.jface.wizard.IWizardPage; +import org.eclipse.jface.wizard.WizardPage; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Text; + +public class StartStopResourcePage extends WizardPage { + + private Button startButton; + + private boolean start; + + protected StartStopResourcePage() { + super("Start/Stop Resource"); + setStart(true); + } + + @Override + public void createControl(Composite parent) { + setPageComplete(false); + setTitle(Constants.START_STOP_PAGE_TITLE); + setMessage(Constants.START_STOP_PAGE_MESSAGE); + Composite compContent = new Composite(parent, SWT.NONE); + GridLayout gridLayout = new GridLayout(); + compContent.setLayout(gridLayout); + GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); + compContent.setLayoutData(gd); + + startButton = new Button(compContent, SWT.CHECK); + startButton.setText("Start Resource(s)"); + startButton.setSelection(true); + gd = new GridData(); + gd.verticalIndent = 10; + startButton.setLayoutData(gd); + + Label descLbl = new Label(compContent, SWT.NONE); + descLbl.setText("Description:"); + gd = new GridData(); + gd.verticalIndent = 50; + descLbl.setLayoutData(gd); + + final Text text = new Text(compContent, SWT.MULTI | SWT.READ_ONLY + | SWT.BORDER | SWT.WRAP | SWT.V_SCROLL); + text.setText("Starting the resource will register it with the platform and makes it visible on the network.\n" + + "Resources can be started or stopped later from 'Resource Manager' view."); + gd = new GridData(); + gd.horizontalAlignment = SWT.FILL; + gd.grabExcessHorizontalSpace = true; + gd.heightHint = 100; + gd.verticalAlignment = SWT.BOTTOM; + text.setLayoutData(gd); + + addUIListeners(); + + setControl(compContent); + } + + private void addUIListeners() { + startButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + setStart(startButton.getSelection()); + } + }); + } + + public boolean isStart() { + return start; + } + + public void setStart(boolean start) { + this.start = start; + } + + @Override + public IWizardPage getNextPage() { + System.out.println(this.getClass().getName() + ": getNextPage"); + return null; + } +} diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/UpdatePropertiesPage.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/UpdatePropertiesPage.java new file mode 100644 index 0000000..e2faddb --- /dev/null +++ b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/UpdatePropertiesPage.java @@ -0,0 +1,255 @@ +/* + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package oic.simulator.serviceprovider.view.dialogs; + +import java.lang.reflect.InvocationTargetException; +import java.util.Date; + +import oic.simulator.serviceprovider.Activator; +import oic.simulator.serviceprovider.utils.Constants; +import oic.simulator.serviceprovider.utils.Utility; +import oic.simulator.serviceprovider.view.dialogs.MainPage.ResourceOption; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.operation.IRunnableWithProgress; +import org.eclipse.jface.wizard.IWizardPage; +import org.eclipse.jface.wizard.WizardPage; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.ModifyEvent; +import org.eclipse.swt.events.ModifyListener; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Group; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Text; +import org.oic.simulator.ILogger.Level; +import org.oic.simulator.SimulatorException; + +public class UpdatePropertiesPage extends WizardPage { + + private Text resNameTxt; + private Text resUriTxt; + + private String resName; + private String resURI; + + protected UpdatePropertiesPage() { + super("Update Properties"); + } + + @Override + public void createControl(Composite parent) { + setPageComplete(true); + setTitle(Constants.UPDATE_PROP_PAGE_TITLE); + setMessage(Constants.UPDATE_PROP_PAGE_MESSAGE); + + Composite comp = new Composite(parent, SWT.NONE); + GridLayout gridLayout = new GridLayout(); + comp.setLayout(gridLayout); + GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); + comp.setLayoutData(gd); + + Group grp = new Group(comp, SWT.NONE); + gridLayout = new GridLayout(2, false); + grp.setLayout(gridLayout); + gd = new GridData(SWT.FILL, SWT.FILL, true, true); + grp.setLayoutData(gd); + + Label resNameLbl = new Label(grp, SWT.NULL); + resNameLbl.setText("Resource Name"); + gd = new GridData(); + gd.verticalIndent = 20; + resNameLbl.setLayoutData(gd); + + resNameTxt = new Text(grp, SWT.BORDER); + resNameTxt.setFocus(); + gd = new GridData(); + gd.widthHint = 300; + gd.verticalIndent = 20; + resNameTxt.setLayoutData(gd); + + Label resUriLbl = new Label(grp, SWT.NULL); + resUriLbl.setText("Resource URI"); + gd = new GridData(); + gd.verticalIndent = 10; + resUriLbl.setLayoutData(gd); + + resUriTxt = new Text(grp, SWT.BORDER); + gd = new GridData(); + gd.widthHint = 300; + gd.verticalIndent = 10; + resUriTxt.setLayoutData(gd); + + Label descLbl = new Label(comp, SWT.NONE); + descLbl.setText("Description:"); + gd = new GridData(); + descLbl.setLayoutData(gd); + + final Text text = new Text(comp, SWT.MULTI | SWT.READ_ONLY | SWT.BORDER + | SWT.WRAP | SWT.V_SCROLL); + text.setText("These properties can be changed later from properties view."); + gd = new GridData(SWT.FILL, SWT.FILL, true, true); + text.setLayoutData(gd); + + addUIListeners(); + + // Initialize data + if (resUriTxt.getText().length() < 1 && null != resURI) { + resUriTxt.setText(resURI); + } + if (resNameTxt.getText().length() < 1 && null != resName) { + resNameTxt.setText(resName); + } + + setControl(comp); + } + + private void addUIListeners() { + resNameTxt.addModifyListener(new ModifyListener() { + @Override + public void modifyText(ModifyEvent e) { + resName = resNameTxt.getText(); + setPageComplete(isSelectionDone()); + // getWizard().getContainer().updateButtons(); + } + }); + + resUriTxt.addModifyListener(new ModifyListener() { + @Override + public void modifyText(ModifyEvent e) { + resURI = resUriTxt.getText(); + setPageComplete(isSelectionDone()); + // getWizard().getContainer().updateButtons(); + } + }); + } + + @Override + public boolean canFlipToNextPage() { + CreateResourceWizard createWizard = (CreateResourceWizard) getWizard(); + if (isSelectionDone() + && (createWizard.getMainPage().getResourceOption() == ResourceOption.COLLECTION_FROM_RAML) + && Activator.getDefault().getResourceManager() + .isAnyResourceExist()) { + return true; + } + return false; + } + + public boolean isSelectionDone() { + boolean done = false; + if (null != resName && resName.trim().length() > 0 && null != resURI + && resURI.trim().length() > 0) { + done = true; + } + return done; + } + + @Override + public IWizardPage getNextPage() { + final boolean done[] = new boolean[1]; + CreateResourceWizard createWizard = (CreateResourceWizard) getWizard(); + // Checking whether the uri is used by any other resource. + if (Activator.getDefault().getResourceManager().isResourceExist(resURI)) { + MessageDialog + .openError(getShell(), "Resource URI in use", + "Entered resource URI is in use. Please try a different one."); + // TODO: Instead of MessageDialog, errors may be shown on wizard + // itself. + return null; + } + try { + getContainer().run(true, true, new IRunnableWithProgress() { + + @Override + public void run(IProgressMonitor monitor) + throws InvocationTargetException, InterruptedException { + try { + monitor.beginTask( + "Completing Collection Resource Creation With RAML", + 2); + monitor.worked(1); + done[0] = completeCollectionResourceCreationWithRAML(); + monitor.worked(1); + } finally { + monitor.done(); + } + } + }); + } catch (InvocationTargetException e) { + Activator.getDefault().getLogManager() + .log(Level.ERROR.ordinal(), new Date(), e.getMessage()); + e.printStackTrace(); + return null; + } catch (InterruptedException e) { + Activator.getDefault().getLogManager() + .log(Level.ERROR.ordinal(), new Date(), e.getMessage()); + e.printStackTrace(); + return null; + } + if (!done[0]) { + return null; + } + return createWizard.getAddResourcesToCollectionPage(); + } + + public void setResName(String resName) { + this.resName = resName; + if (!resNameTxt.isDisposed()) + resNameTxt.setText(resName); + } + + public void setResURI(String resURI) { + this.resURI = resURI; + if (!resUriTxt.isDisposed()) + resUriTxt.setText(resURI); + } + + public String getResName() { + return resName; + } + + public String getResURI() { + return resURI; + } + + private boolean completeCollectionResourceCreationWithRAML() { + boolean result = false; + String status; + CreateResourceWizard createWizard = (CreateResourceWizard) getWizard(); + try { + result = Activator + .getDefault() + .getResourceManager() + .completeCollectionResourceCreationByRAML( + createWizard.getLoadRamlPage().getResource(), + resURI, resName); + if (result) + status = "Resource created."; + else { + status = "Failed to create resource."; + } + } catch (SimulatorException e) { + status = "Failed to create resource.\n" + + Utility.getSimulatorErrorString(e, null); + } + createWizard.setStatus(status); + return result; + } +} diff --git a/service/simulator/java/jni/jni_listener_holder.h b/service/simulator/java/jni/jni_listener_holder.h new file mode 100644 index 0000000..254aa68 --- /dev/null +++ b/service/simulator/java/jni/jni_listener_holder.h @@ -0,0 +1,54 @@ +/****************************************************************** + * + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +#ifndef JNI_LISTENER_HOLDER_H_ +#define JNI_LISTENER_HOLDER_H_ + +class JniListenerHolder +{ + public: + ~JniListenerHolder() + { + JNIEnv *env = getEnv(); + if (!env) + return; + env->DeleteGlobalRef(m_listener); + releaseEnv(); + } + + jobject get() + { + return m_listener; + } + + static std::shared_ptr create(JNIEnv *env, jobject &listener) + { + return std::shared_ptr(new JniListenerHolder(env, listener)); + } + + private: + JniListenerHolder(JNIEnv *env, jobject &listener) + : m_listener(env->NewGlobalRef(listener)) {} + + jobject m_listener; +}; + +#endif + diff --git a/service/simulator/java/jni/jni_queryparam.cpp b/service/simulator/java/jni/jni_queryparam.cpp new file mode 100644 index 0000000..fd59abf --- /dev/null +++ b/service/simulator/java/jni/jni_queryparam.cpp @@ -0,0 +1,68 @@ +/****************************************************************** + * + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +#include "jni_queryparam.h" +#include "jni_string.h" +#include "simulator_utils_jni.h" + +JniQueryParameter::JniQueryParameter(JNIEnv *env) : m_env(env) {} + +std::map JniQueryParameter::toCpp(jobject jQueryParams) +{ + std::map result; + if (!jQueryParams) + return result; + + static jmethodID entrySetMethodID = m_env->GetMethodID(gSimulatorClassRefs.mapCls, "entrySet", + "()Ljava/util/Set;"); + static jmethodID iteratorMethodID = m_env->GetMethodID(gSimulatorClassRefs.setCls, "iterator", + "()Ljava/util/Iterator;"); + static jmethodID hasNextMethodID = m_env->GetMethodID(gSimulatorClassRefs.iteratorCls, "hasNext", + "()Z"); + static jmethodID nextMethodID = m_env->GetMethodID(gSimulatorClassRefs.iteratorCls, "next", + "()Ljava/lang/Object;"); + static jmethodID getKeyMethodID = m_env->GetMethodID(gSimulatorClassRefs.mapEntryCls, "getKey", + "()Ljava/lang/Object;"); + static jmethodID getValueMethodID = m_env->GetMethodID(gSimulatorClassRefs.mapEntryCls, "getValue", + "()Ljava/lang/Object;"); + + jobject entrySet = m_env->CallObjectMethod(jQueryParams, entrySetMethodID); + jobject iterator = m_env->CallObjectMethod(entrySet, iteratorMethodID); + if (!entrySet || !iterator || m_env->ExceptionCheck()) + return result; + + while (m_env->CallBooleanMethod(iterator, hasNextMethodID)) + { + jobject entry = m_env->CallObjectMethod(iterator, nextMethodID); + jstring key = (jstring) m_env->CallObjectMethod(entry, getKeyMethodID); + jstring value = (jstring) m_env->CallObjectMethod(entry, getValueMethodID); + + JniString jniKey(m_env, key); + JniString jniValue(m_env, key); + + result[jniKey.get()] = jniValue.get(); + + m_env->DeleteLocalRef(entry); + m_env->DeleteLocalRef(key); + m_env->DeleteLocalRef(value); + } + + return result; +} diff --git a/service/simulator/java/jni/jni_queryparam.h b/service/simulator/java/jni/jni_queryparam.h new file mode 100644 index 0000000..7b63171 --- /dev/null +++ b/service/simulator/java/jni/jni_queryparam.h @@ -0,0 +1,38 @@ +/****************************************************************** + * + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +#ifndef JNI_QUERY_PARAM_H_ +#define JNI_QUERY_PARAM_H_ + +#include +#include +#include + +class JniQueryParameter +{ + public: + JniQueryParameter(JNIEnv *env); + std::map toCpp(jobject queryParams); + + private: + JNIEnv *m_env; +}; + +#endif \ No newline at end of file diff --git a/service/simulator/java/jni/jni_sharedobject_holder.h b/service/simulator/java/jni/jni_sharedobject_holder.h new file mode 100644 index 0000000..46756fd --- /dev/null +++ b/service/simulator/java/jni/jni_sharedobject_holder.h @@ -0,0 +1,49 @@ +/****************************************************************** + * + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +#ifndef JNI_SHARED_OBJECT_HOLDER_H_ +#define JNI_SHARED_OBJECT_HOLDER_H_ + +#include + +template +class JniSharedObjectHolder +{ + public: + std::shared_ptr get() + { + return m_sharedObject; + } + + static JniSharedObjectHolder *create(std::shared_ptr &sharedObject) + { + return new JniSharedObjectHolder(sharedObject); + } + + private: + JniSharedObjectHolder(std::shared_ptr &sharedObject) + { + m_sharedObject = sharedObject; + } + + std::shared_ptr m_sharedObject; +}; + +#endif diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/serviceprovider/test/AutomationObject.java b/service/simulator/java/jni/jni_string.cpp similarity index 53% rename from service/simulator/unittests/SimulatorTest/src/org/oic/simulator/serviceprovider/test/AutomationObject.java rename to service/simulator/java/jni/jni_string.cpp index 9ada5d8..95e77de 100644 --- a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/serviceprovider/test/AutomationObject.java +++ b/service/simulator/java/jni/jni_string.cpp @@ -1,6 +1,9 @@ -/* +/****************************************************************** + * * Copyright 2015 Samsung Electronics All Rights Reserved. * + * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,37 +15,32 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - */ + * + ******************************************************************/ -package org.oic.simulator.serviceprovider.test; +#include "jni_string.h" -/** - * This class implements methods for setting/getting URI - * and automation ID. - */ -public class AutomationObject +JniString::JniString(JNIEnv *env, jstring &string) + : m_env(nullptr), m_string(nullptr), m_cStr("") { - - private String resourceURI; - private int automationId; - - public void setResourceURI(String resourceURI) - { - this.resourceURI = resourceURI; - } - - public String getResourceURI() + m_env = env; + m_string = string; + if (m_string) { - return resourceURI; + m_cStr = env->GetStringUTFChars(m_string, nullptr); } +} - public void setAutomationId(int automationId) +JniString::~JniString() +{ + if (m_string && m_cStr) { - this.automationId = automationId; + m_env->ReleaseStringUTFChars(m_string, m_cStr); } +} - public int getAutomationId() - { - return automationId; - } +std::string JniString::get() +{ + return std::string(m_cStr); } + diff --git a/service/simulator/src/service-provider/simulator_resource_creator.h b/service/simulator/java/jni/jni_string.h similarity index 71% rename from service/simulator/src/service-provider/simulator_resource_creator.h rename to service/simulator/java/jni/jni_string.h index 7a9a87d..ba14d43 100644 --- a/service/simulator/src/service-provider/simulator_resource_creator.h +++ b/service/simulator/java/jni/jni_string.h @@ -18,19 +18,23 @@ * ******************************************************************/ -#ifndef SIMULATOR_RESOURCE_CREATOR_H_ -#define SIMULATOR_RESOURCE_CREATOR_H_ +#ifndef JNI_STRING_H_ +#define JNI_STRING_H_ -#include "simulator_resource_server_impl.h" +#include +#include -class SimulatorResourceCreator +class JniString { public: - SimulatorResourceServerImplSP createResource(const std::string &configPath); + JniString(JNIEnv *env, jstring &string); + ~JniString(); + std::string get(); private: - std::string constructURI(const std::string &uri); - static unsigned int s_id; + JNIEnv *m_env; + jstring m_string; + const char *m_cStr; }; #endif diff --git a/service/simulator/java/jni/jni_vector.cpp b/service/simulator/java/jni/jni_vector.cpp new file mode 100644 index 0000000..5f2135f --- /dev/null +++ b/service/simulator/java/jni/jni_vector.cpp @@ -0,0 +1,92 @@ +/****************************************************************** + * + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +#include "jni_vector.h" +#include "jni_string.h" +#include "simulator_utils_jni.h" + +JniVector::JniVector(JNIEnv *env) : m_env(env) +{ + m_vectorCls = gSimulatorClassRefs.vectorCls; +} + +jobject JniVector::toJava() +{ + static jmethodID vectorCtor = m_env->GetMethodID(m_vectorCls, "", "()V"); + return m_env->NewObject(m_vectorCls, vectorCtor); +} + +jobject JniVector::toJava(std::vector &cppVector) +{ + static jmethodID addMethod = m_env->GetMethodID(m_vectorCls, "add", "(Ljava/lang/Object;)Z"); + + jobject vectorObject = toJava(); + if (!vectorObject) + return nullptr; + + for (size_t index = 0; index < cppVector.size(); index++) + { + jstring element = m_env->NewStringUTF(cppVector[index].c_str()); + m_env->CallBooleanMethod(vectorObject, addMethod, element); + m_env->DeleteLocalRef(element); + } + + return vectorObject; +} + +void JniVector::addElementsCpp(jobject vector, int size, std::vector &result) +{ + static jmethodID getMethod = m_env->GetMethodID(m_vectorCls, "get", "(I)Ljava/lang/Object;"); + static jmethodID intValueMethod = m_env->GetMethodID(gSimulatorClassRefs.integerCls, "intValue", + "()I"); + + for (int index = 0; index < size; index++) + { + jobject intObject = m_env->CallObjectMethod(vector, getMethod, index); + int value = m_env->CallIntMethod(intObject, intValueMethod); + result.push_back(value); + } +} + +void JniVector::addElementsCpp(jobject vector, int size, std::vector &result) +{ + static jmethodID getMethod = m_env->GetMethodID(m_vectorCls, "get", "(I)Ljava/lang/Object;"); + static jmethodID doubleValueMethod = m_env->GetMethodID(gSimulatorClassRefs.doubleCls, + "doubleValue", "()D"); + + for (int index = 0; index < size; index++) + { + jobject doubleObject = m_env->CallObjectMethod(vector, getMethod, index); + double value = m_env->CallDoubleMethod(doubleObject, doubleValueMethod); + result.push_back(value); + } +} + +void JniVector::addElementsCpp(jobject vector, int size, std::vector &result) +{ + static jmethodID getMethodID = m_env->GetMethodID(m_vectorCls, "get", "(I)Ljava/lang/Object;"); + + for (int index = 0; index < size; index++) + { + jstring stringObject = (jstring) m_env->CallObjectMethod(vector, getMethodID, index); + JniString value(m_env, stringObject); + result.push_back(value.get()); + } +} \ No newline at end of file diff --git a/service/simulator/java/jni/jni_vector.h b/service/simulator/java/jni/jni_vector.h new file mode 100644 index 0000000..860c082 --- /dev/null +++ b/service/simulator/java/jni/jni_vector.h @@ -0,0 +1,56 @@ +/****************************************************************** + * + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +#ifndef JNI_VECTOR_H_ +#define JNI_VECTOR_H_ + +#include +#include +#include + +class JniVector +{ + public: + JniVector(JNIEnv *env); + + template + std::vector toCpp(jobject vector) + { + std::vector result; + jmethodID sizeMethodID = m_env->GetMethodID(m_vectorCls, "size", "()I"); + + int size = m_env->CallIntMethod(vector, sizeMethodID); + addElementsCpp(vector, size, result); + return result; + } + + jobject toJava(std::vector &cppVector); + jobject toJava(); + + private: + void addElementsCpp(jobject vector, int size, std::vector &result); + void addElementsCpp(jobject vector, int size, std::vector &result); + void addElementsCpp(jobject vector, int size, std::vector &result); + + JNIEnv *m_env; + jclass m_vectorCls; +}; + +#endif diff --git a/service/simulator/java/jni/resource_attributes_jni.cpp b/service/simulator/java/jni/resource_attributes_jni.cpp deleted file mode 100644 index 5732eff..0000000 --- a/service/simulator/java/jni/resource_attributes_jni.cpp +++ /dev/null @@ -1,246 +0,0 @@ -/****************************************************************** - * - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************/ - -#include "resource_attributes_jni.h" -#include "simulator_resource_model.h" -#include "simulator_common_jni.h" -#include "simulator_error_codes.h" -#include - -extern SimulatorClassRefs gSimulatorClassRefs; - -class attribute_value_visitor : public boost::static_visitor -{ - 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(str); - } - - // Boolean type value conversion - jobject operator ()(const bool &value) const - { - jobject result = m_Env->NewObject(gSimulatorClassRefs.classBoolean, - gSimulatorClassRefs.classBooleanCtor, value); - return result; - } -#if 0 - // SimulatorResourceModel::Attribute type value conversion - jobject operator ()(const SimulatorResourceModel::Attribute &value) const - { - JResourceAttributeConverter converter(value); - return converter.toJava(); - } -#endif - - private: - JNIEnv *m_Env; -}; - -jobject JResourceAttributeConverter::toJava(JNIEnv *env) -{ - // Create an object of ResourceAttribute java class - jobject jattributeObj = (jobject) env->NewObject(gSimulatorClassRefs.classResourceAttribute, - gSimulatorClassRefs.classResourceAttributeCtor); - if (env->ExceptionCheck() || !jattributeObj) - { - return nullptr; - } - - // Set attribute name - if (!setName(env, jattributeObj)) - { - return nullptr; - } - - // Set types - if (!setType(env, jattributeObj)) - { - return nullptr; - } - - // Set value - if (!setValue(env, jattributeObj)) - { - return nullptr; - } - - // Set Range - if (!setRange(env, jattributeObj)) - { - return nullptr; - } - - // Set Allowed values - if (!setAllowedValues(env, jattributeObj)) - { - return nullptr; - } - - return jattributeObj; -} - -bool JResourceAttributeConverter::setName(JNIEnv *env, jobject &jattributeObj) -{ - // Get field reference to "ResourceAttribute::m_name" - static jfieldID fidName = env->GetFieldID(gSimulatorClassRefs.classResourceAttribute, "m_name", - "Ljava/lang/String;"); - if (!fidName) - { - return false; - } - - // Set the attribute name - std::string name = m_attribute.getName(); - jstring jname = env->NewStringUTF(name.c_str()); - env->SetObjectField(jattributeObj, fidName, jname); - if (env->ExceptionCheck()) - { - return false; - } - - return true; -} - -bool JResourceAttributeConverter::setType(JNIEnv *env, jobject &jattributeObj) -{ - // Get class refs to ResourceAttribute::Type class - static jclass clsType = env->FindClass("org/oic/simulator/ResourceAttribute$Type"); - if (!clsType) - { - return false; - } - - // Get method ref to static method to ResourceAttribute::Type::getType - static jmethodID midGetType = env->GetStaticMethodID(clsType, "getType", - "(I)Lorg/oic/simulator/ResourceAttribute$Type;"); - if (!midGetType) - { - return false; - } - - // Get field reference to "ResourceAttribute::m_type" - static jfieldID fidType = env->GetFieldID(gSimulatorClassRefs.classResourceAttribute, - "m_type", "Lorg/oic/simulator/ResourceAttribute$Type;"); - if (!fidType) - { - return false; - } - - int type = static_cast(m_attribute.getValueType()); - jobject jtype = env->CallStaticObjectMethod(clsType, midGetType, type); - if (env->ExceptionCheck()) - { - return false; - } - - env->SetObjectField(jattributeObj, fidType, jtype); - if (env->ExceptionCheck()) - { - return false; - } - - return true; -} - -bool JResourceAttributeConverter::setValue(JNIEnv *env, jobject &jattributeObj) -{ - // Get field reference to "ResourceAttribute::m_value" - static jfieldID fidValue = env->GetFieldID(gSimulatorClassRefs.classResourceAttribute, - "m_value", "Ljava/lang/Object;"); - if (!fidValue) - { - return false; - } - jobject jvalue = boost::apply_visitor(attribute_value_visitor(env), m_attribute.getValue()); - env->SetObjectField(jattributeObj, fidValue, jvalue); - return true; -} - -bool JResourceAttributeConverter::setRange(JNIEnv *env, jobject &jattributeObj) -{ - int min = INT_MIN; - int max = INT_MAX; - m_attribute.getRange(min, max); - if (INT_MIN == min || INT_MAX == max) - { - return true; - } - env->CallVoidMethod(jattributeObj, gSimulatorClassRefs.classResourceAttributeSetRange, min, max); - if (env->ExceptionCheck()) - { - return false; - } - - return true; -} - -bool JResourceAttributeConverter::setAllowedValues(JNIEnv *env, jobject &jattributeObj) -{ - // Get field reference to "ResourceAttribute::m_AllowedValues" - static jfieldID fidAllowedValues = env->GetFieldID(gSimulatorClassRefs.classResourceAttribute, - "m_AllowedValues", "Ljava/lang/Object;"); - if (!fidAllowedValues) - { - return false; - } - - jobjectArray jallowedValues = env->NewObjectArray(m_attribute.getAllowedValuesSize(), - gSimulatorClassRefs.classObject, NULL); - if (!jallowedValues) - { - return false; - } - - int index = 0; - for (auto & value : m_attribute.getAllowedValues()) - { - jobject jvalue = boost::apply_visitor(attribute_value_visitor(env), value); - env->SetObjectArrayElement(jallowedValues, index++, jvalue); - } - - env->SetObjectField(jattributeObj, fidAllowedValues, jallowedValues); - if (env->ExceptionCheck()) - { - return false; - } - - return true; -} \ No newline at end of file diff --git a/service/simulator/java/jni/resource_attributes_jni.h b/service/simulator/java/jni/resource_attributes_jni.h deleted file mode 100644 index 3c34cf1..0000000 --- a/service/simulator/java/jni/resource_attributes_jni.h +++ /dev/null @@ -1,47 +0,0 @@ -/****************************************************************** - * - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************/ - -#ifndef RESOURCE_ATTRIBUTE_JNI_H_ -#define RESOURCE_ATTRIBUTE_JNI_H_ - -#include -#include "simulator_resource_model.h" - -class JResourceAttributeConverter -{ - public: - JResourceAttributeConverter(SimulatorResourceModel::Attribute &attribute) {m_attribute = attribute;} - JResourceAttributeConverter(const JResourceAttributeConverter &) = delete; - JResourceAttributeConverter &operator=(const JResourceAttributeConverter &) = delete; - JResourceAttributeConverter(const JResourceAttributeConverter &&) = delete; - JResourceAttributeConverter &operator=(const JResourceAttributeConverter && ) = delete; - jobject toJava(JNIEnv *env); - - private: - bool setName(JNIEnv *env, jobject &jaAttributeObj); - bool setType(JNIEnv *env, jobject &jaAttributeObj); - bool setValue(JNIEnv *env, jobject &jaAttributeObj); - bool setRange(JNIEnv *env, jobject &jaAttributeObj); - bool setAllowedValues(JNIEnv *env, jobject &jaAttributeObj); - - SimulatorResourceModel::Attribute m_attribute; -}; - -#endif //SIMULATOR_RESOURCE_ATTRIBUTE_JNI_H_ diff --git a/service/simulator/java/jni/simulator_collection_resource_jni.cpp b/service/simulator/java/jni/simulator_collection_resource_jni.cpp new file mode 100644 index 0000000..1b9c2dc --- /dev/null +++ b/service/simulator/java/jni/simulator_collection_resource_jni.cpp @@ -0,0 +1,154 @@ +/****************************************************************** + * + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +#include "simulator_exceptions_jni.h" +#include "simulator_resource_utils_jni.h" +#include "simulator_utils_jni.h" +#include "jni_sharedobject_holder.h" +#include "jni_string.h" +#include "jni_vector.h" + +#include "simulator_collection_resource.h" + +#define VALIDATE_OBJECT(ENV, OBJECT) if (!OBJECT){throwBadObjectException(ENV, "No corresponsing native object!"); return;} +#define VALIDATE_OBJECT_RET(ENV, OBJECT, RET) if (!OBJECT){throwBadObjectException(ENV, "No corresponsing native object!"); return RET;} + +extern SimulatorResourceSP SimulatorResourceToCpp(JNIEnv *env, jobject object); + +SimulatorCollectionResourceSP SimulatorCollectionResourceToCpp(JNIEnv *env, jobject object) +{ + JniSharedObjectHolder *jniResource = + GetHandle>(env, object); + if (jniResource) + return jniResource->get(); + return nullptr; +} + +#ifdef __cplusplus +extern "C" { +#endif + +JNIEXPORT jobject JNICALL +Java_org_oic_simulator_server_SimulatorCollectionResource_getSupportedResources +(JNIEnv *env, jobject object) +{ + SimulatorCollectionResourceSP collectionResource = SimulatorCollectionResourceToCpp(env, object); + VALIDATE_OBJECT_RET(env, collectionResource, nullptr) + + std::vector supportedTypes = collectionResource->getSupportedResources(); + return JniVector(env).toJava(supportedTypes); +} + +JNIEXPORT void JNICALL +Java_org_oic_simulator_server_SimulatorCollectionResource_addChildResource +(JNIEnv *env, jobject object, jobject resource) +{ + VALIDATE_INPUT(env, !resource, "Child resource is null!") + + SimulatorResourceSP childResource = SimulatorResourceToCpp(env, resource); + VALIDATE_INPUT(env, !childResource, "No corresponding native object of child resource!") + + SimulatorCollectionResourceSP collectionResource = SimulatorCollectionResourceToCpp(env, object); + VALIDATE_OBJECT(env, collectionResource) + + try + { + collectionResource->addChildResource(childResource); + } + catch (InvalidArgsException &e) + { + throwInvalidArgsException(env, e.code(), e.what()); + } + catch (SimulatorException &e) + { + throwSimulatorException(env, e.code(), e.what()); + } +} + +JNIEXPORT void JNICALL +Java_org_oic_simulator_server_SimulatorCollectionResource_removeChildResource +(JNIEnv *env, jobject object, jobject resource) +{ + VALIDATE_INPUT(env, !resource, "Child resource is null!") + + SimulatorResourceSP childResource = SimulatorResourceToCpp(env, resource); + VALIDATE_INPUT(env, !childResource, "No corresponding native object of child resource!") + + SimulatorCollectionResourceSP collectionResource = SimulatorCollectionResourceToCpp(env, object); + VALIDATE_OBJECT(env, collectionResource) + + try + { + collectionResource->removeChildResource(childResource); + } + catch (InvalidArgsException &e) + { + throwInvalidArgsException(env, e.code(), e.what()); + } + catch (SimulatorException &e) + { + throwSimulatorException(env, e.code(), e.what()); + } +} + +JNIEXPORT void JNICALL +Java_org_oic_simulator_server_SimulatorCollectionResource_removeChildResourceByUri +(JNIEnv *env, jobject object, jstring uri) +{ + SimulatorCollectionResourceSP collectionResource = SimulatorCollectionResourceToCpp(env, object); + VALIDATE_OBJECT(env, collectionResource) + + try + { + JniString jniUri(env, uri); + collectionResource->removeChildResource(jniUri.get()); + } + catch (InvalidArgsException &e) + { + throwInvalidArgsException(env, e.code(), e.what()); + } + catch (SimulatorException &e) + { + throwSimulatorException(env, e.code(), e.what()); + } +} + +JNIEXPORT jobject JNICALL +Java_org_oic_simulator_server_SimulatorCollectionResource_getChildResource +(JNIEnv *env, jobject object) +{ + SimulatorCollectionResourceSP collectionResource = SimulatorCollectionResourceToCpp(env, object); + VALIDATE_OBJECT_RET(env, collectionResource, nullptr) + + std::vector childResources = collectionResource->getChildResources(); + return createSimulatorResourceVector(env, childResources); +} + +JNIEXPORT void JNICALL Java_org_oic_simulator_server_SimulatorCollectionResource_dispose +(JNIEnv *env, jobject object) +{ + JniSharedObjectHolder *resource = + GetHandle>(env, object); + delete resource; +} + +#ifdef __cplusplus +} +#endif diff --git a/service/simulator/java/jni/simulator_common_jni.h b/service/simulator/java/jni/simulator_common_jni.h deleted file mode 100644 index b0fd74b..0000000 --- a/service/simulator/java/jni/simulator_common_jni.h +++ /dev/null @@ -1,107 +0,0 @@ -/****************************************************************** - * - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************/ - -#ifndef SIMULATOR_COMMON_JNI_H_ -#define SIMULATOR_COMMON_JNI_H_ - -#include - -typedef struct -{ - jclass classObject; - jclass classInteger; - jclass classDouble; - jclass classBoolean; - jclass classString; - jclass classHashMap; - jclass classVector; - jclass classMap; - jclass classMapEntry; - jclass classSet; - jclass classIterator; - jclass classLinkedList; - - jclass classSimulatorResource; - jclass classSimulatorResourceModel; - jclass classResourceAttribute; - jclass classSimulatorRemoteResource; - jclass classSimulatorCallback; - jclass classObserverInfo; - jclass classDeviceInfo; - jclass classPlatformInfo; - jclass classSimulatorException; - jclass classInvalidArgsException; - jclass classNoSupportException; - jclass classOperationInProgressException; - - jmethodID classIntegerCtor; - jmethodID classDoubleCtor; - jmethodID classBooleanCtor; - jmethodID classHashMapCtor; - jmethodID classHashMapPut; - jmethodID classVectorCtor; - jmethodID classVectorAddElement; - jmethodID classMapEntrySet; - jmethodID classMapGetKey; - jmethodID classMapGetValue; - jmethodID classIteratorId; - jmethodID classHasNextId; - jmethodID classNextId; - jmethodID classLinkedListCtor; - jmethodID classLinkedListAddObject; - - jmethodID classSimulatorResourceCtor; - jmethodID classSimulatorResourceModelCtor; - jmethodID classResourceAttributeCtor; - jmethodID classResourceAttributeSetRange; - jmethodID classSimulatorResourceModelId; - jmethodID classObserverInfoCtor; - jmethodID classSimulatorExceptionCtor; - jmethodID classInvalidArgsExceptionCtor; - jmethodID classNoSupportExceptionCtor; - jmethodID classOperationInProgressExceptionCtor; - -} SimulatorClassRefs; - -static jfieldID GetHandleField(JNIEnv *env, jobject jobj) -{ - jclass cls = env->GetObjectClass(jobj); - return env->GetFieldID(cls, "nativeHandle", "J"); -} - -template -static T *GetHandle(JNIEnv *env, jobject jobj) -{ - jlong handle = env->GetLongField(jobj, GetHandleField(env, jobj)); - return reinterpret_cast(handle); -} - -template -static void SetHandle(JNIEnv *env, jobject jobj, T *type) -{ - jlong handle = reinterpret_cast(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 index c954a97..a2f17ed 100644 --- a/service/simulator/java/jni/simulator_device_info_jni.cpp +++ b/service/simulator/java/jni/simulator_device_info_jni.cpp @@ -19,22 +19,18 @@ ******************************************************************/ #include "simulator_device_info_jni.h" -#include "simulator_common_jni.h" +#include "simulator_utils_jni.h" extern SimulatorClassRefs gSimulatorClassRefs; -jobject JDeviceInfo::toJava(DeviceInfo &deviceInfo) + +jobject JniDeviceInfo::toJava(DeviceInfo &deviceInfo) { if (!m_env) return nullptr; - jmethodID deviceInfoMId = m_env->GetMethodID(gSimulatorClassRefs.classDeviceInfo, "", "(V)V"); - if (!deviceInfoMId) - return nullptr; - - jobject jDeviceInfo = (jobject) m_env->NewObject(gSimulatorClassRefs.classDeviceInfo, deviceInfoMId); - if (!jDeviceInfo) - return nullptr; - + static jmethodID deviceInfoCtor = m_env->GetMethodID(gSimulatorClassRefs.deviceInfoCls, "", + "()V"); + jobject jDeviceInfo = m_env->NewObject(gSimulatorClassRefs.deviceInfoCls, deviceInfoCtor); setFieldValue(jDeviceInfo, "mName", deviceInfo.getName()); setFieldValue(jDeviceInfo, "mID", deviceInfo.getID()); setFieldValue(jDeviceInfo, "mSpecVersion", deviceInfo.getSpecVersion()); @@ -43,54 +39,33 @@ jobject JDeviceInfo::toJava(DeviceInfo &deviceInfo) return jDeviceInfo; } -void JDeviceInfo::setFieldValue(jobject jDeviceInfo, const std::string &fieldName, - const std::string &value) +void JniDeviceInfo::setFieldValue(jobject jDeviceInfo, const std::string &fieldName, + const std::string &value) { - jfieldID fieldID = m_env->GetFieldID(gSimulatorClassRefs.classDeviceInfo, fieldName.c_str(), + jfieldID fieldID = m_env->GetFieldID(m_env->GetObjectClass(jDeviceInfo), fieldName.c_str(), "Ljava/lang/String;"); jstring valueStr = m_env->NewStringUTF(value.c_str()); m_env->SetObjectField(jDeviceInfo, fieldID, valueStr); } -void JniDeviceInfoListener::onDeviceInfoReceived(DeviceInfo &deviceInfo) +void onDeviceInfoReceived(jobject listener, DeviceInfo &deviceInfo) { - // Get the environment JNIEnv *env = getEnv(); if (!env) return; - jobject listener = env->NewLocalRef(m_listener); - if (!listener) - { - releaseEnv(); - return; - } - jclass listenerCls = env->GetObjectClass(listener); - if (!listenerCls) - { - releaseEnv(); - return; - } - - jmethodID listenerMId = env->GetMethodID(listenerCls, "onDeviceFound", - "(Lorg/oic/simulator/DeviceInfo;)V"); - if (!listenerMId) - { - releaseEnv(); - return; - } + jmethodID listenerMethodId = env->GetMethodID(listenerCls, "onDeviceFound", + "(Lorg/oic/simulator/DeviceInfo;)V"); - // Convert CPP to Java DeviceInfo object - jobject jDeviceInfo = JDeviceInfo(env).toJava(deviceInfo); + jobject jDeviceInfo = JniDeviceInfo(env).toJava(deviceInfo); if (!jDeviceInfo) { releaseEnv(); return; } - // Invoke java listener with DeviceInfo - env->CallVoidMethod(listener, listenerMId, jDeviceInfo); + env->CallVoidMethod(listener, listenerMethodId, jDeviceInfo); if (env->ExceptionCheck()) { releaseEnv(); diff --git a/service/simulator/java/jni/simulator_device_info_jni.h b/service/simulator/java/jni/simulator_device_info_jni.h index ac53867..27e845d 100644 --- a/service/simulator/java/jni/simulator_device_info_jni.h +++ b/service/simulator/java/jni/simulator_device_info_jni.h @@ -24,14 +24,14 @@ #include "simulator_device_info.h" #include -class JDeviceInfo +class JniDeviceInfo { public: - JDeviceInfo(JNIEnv *env) : m_env(env) {} - JDeviceInfo(const JDeviceInfo &) = delete; - JDeviceInfo &operator=(const JDeviceInfo &) = delete; - JDeviceInfo(const JDeviceInfo &&) = delete; - JDeviceInfo &operator=(const JDeviceInfo && ) = delete; + JniDeviceInfo(JNIEnv *env) : m_env(env) {} + JniDeviceInfo(const JniDeviceInfo &) = delete; + JniDeviceInfo &operator=(const JniDeviceInfo &) = delete; + JniDeviceInfo(const JniDeviceInfo &&) = delete; + JniDeviceInfo &operator=(const JniDeviceInfo && ) = delete; jobject toJava(DeviceInfo &deviceInfo); private: @@ -41,18 +41,6 @@ class JDeviceInfo JNIEnv *m_env; }; -class JniDeviceInfoListener -{ - public: - JniDeviceInfoListener(JNIEnv *env, jobject listener) - { - m_listener = env->NewWeakGlobalRef(listener); - } - - void onDeviceInfoReceived(DeviceInfo &deviceInfo); - - private: - jweak m_listener; -}; +void onDeviceInfoReceived(jobject listener, DeviceInfo &deviceInfo); #endif diff --git a/service/simulator/java/jni/simulator_exceptions_jni.cpp b/service/simulator/java/jni/simulator_exceptions_jni.cpp new file mode 100644 index 0000000..041b844 --- /dev/null +++ b/service/simulator/java/jni/simulator_exceptions_jni.cpp @@ -0,0 +1,89 @@ +/****************************************************************** + * + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +#include "simulator_exceptions_jni.h" +#include "simulator_utils_jni.h" + +extern SimulatorClassRefs gSimulatorClassRefs; + +void throwSimulatorException(JNIEnv *env, SimulatorResult code, const char *message) +{ + static jmethodID simulatorExceptionCtor = env->GetMethodID( + gSimulatorClassRefs.simulatorExceptionCls, "", "(ILjava/lang/String;)V"); + + jobject exceptionObject = env->NewObject(gSimulatorClassRefs.simulatorExceptionCls, + simulatorExceptionCtor, code, env->NewStringUTF(message)); + if (exceptionObject) + { + env->Throw((jthrowable) exceptionObject); + } +} + +void throwInvalidArgsException(JNIEnv *env, SimulatorResult code, const char *message) +{ + static jmethodID invalidArgsExceptionCtor = env->GetMethodID( + gSimulatorClassRefs.invalidArgsExceptionCls, "", "(ILjava/lang/String;)V"); + + jobject exceptionObject = env->NewObject(gSimulatorClassRefs.invalidArgsExceptionCls, + invalidArgsExceptionCtor, code, env->NewStringUTF(message)); + if (exceptionObject) + { + env->Throw((jthrowable) exceptionObject); + } +} + +void throwNoSupportException(JNIEnv *env, const char *message) +{ + static jmethodID noSupportExceptionCtor = env->GetMethodID( + gSimulatorClassRefs.noSupportExceptionCls, "", "(Ljava/lang/String;)V"); + + jobject exceptionObject = env->NewObject(gSimulatorClassRefs.noSupportExceptionCls, + noSupportExceptionCtor, env->NewStringUTF(message)); + if (exceptionObject) + { + env->Throw((jthrowable) exceptionObject); + } +} + +void throwOperationInProgressException(JNIEnv *env, const char *message) +{ + static jmethodID operationInProgressExceptionCtor = env->GetMethodID( + gSimulatorClassRefs.operationInProgressExceptionCls, "", "(Ljava/lang/String;)V"); + + jobject exceptionObject = env->NewObject(gSimulatorClassRefs.operationInProgressExceptionCls, + operationInProgressExceptionCtor, env->NewStringUTF(message)); + if (exceptionObject) + { + env->Throw((jthrowable) exceptionObject); + } +} + +void throwBadObjectException(JNIEnv *env, const char *message) +{ + static jmethodID simulatorExceptionCtor = env->GetMethodID( + gSimulatorClassRefs.simulatorExceptionCls, "", "(ILjava/lang/String;)V"); + + jobject exceptionObject = env->NewObject(gSimulatorClassRefs.simulatorExceptionCls, + simulatorExceptionCtor, SIMULATOR_BAD_OBJECT, env->NewStringUTF(message)); + if (exceptionObject) + { + env->Throw((jthrowable) exceptionObject); + } +} \ No newline at end of file diff --git a/service/simulator/java/jni/simulator_jni_utils.h b/service/simulator/java/jni/simulator_exceptions_jni.h similarity index 65% rename from service/simulator/java/jni/simulator_jni_utils.h rename to service/simulator/java/jni/simulator_exceptions_jni.h index 4815a04..f7cc9d9 100644 --- a/service/simulator/java/jni/simulator_jni_utils.h +++ b/service/simulator/java/jni/simulator_exceptions_jni.h @@ -25,19 +25,20 @@ * and viceversa */ -#ifndef __SIMULATOR_JNI_UTILS_H_ -#define __SIMULATOR_JNI_UTILS_H_ +#ifndef SIMULATOR_EXCEPTIONS_JNI_H_ +#define SIMULATOR_EXCEPTIONS_JNI_H_ #include #include "simulator_error_codes.h" -void throwSimulatorException(JNIEnv *env, SimulatorResult errCode, const char *errMessage); +void throwSimulatorException(JNIEnv *env, SimulatorResult code, const char *message); -void throwInvalidArgsException(JNIEnv *env, SimulatorResult errCode, const char *errMessage); +void throwInvalidArgsException(JNIEnv *env, SimulatorResult code, const char *message); -void throwNoSupportException(JNIEnv *env, SimulatorResult errCode, const char *errMessage); +void throwNoSupportException(JNIEnv *env, const char *message); -void throwOperationInProgressException(JNIEnv *env, SimulatorResult errCode, - const char *errMessage); +void throwOperationInProgressException(JNIEnv *env, const char *message); -#endif //__SIMULATOR_JNI_UTILS_H_ +void throwBadObjectException(JNIEnv *env, const char *message); + +#endif diff --git a/service/simulator/java/jni/simulator_init_jni.cpp b/service/simulator/java/jni/simulator_init_jni.cpp new file mode 100644 index 0000000..63178ae --- /dev/null +++ b/service/simulator/java/jni/simulator_init_jni.cpp @@ -0,0 +1,234 @@ +/****************************************************************** + * + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +#include "simulator_utils_jni.h" +#include + +#define OBJECT_CLS "java/lang/Object" +#define INTEGER_CLS "java/lang/Integer" +#define DOUBLE_CLS "java/lang/Double" +#define BOOLEAN_CLS "java/lang/Boolean" +#define STRING_CLS "java/lang/String" +#define VECTOR_CLS "java/util/Vector" +#define HASHMAP_CLS "java/util/HashMap" +#define MAP_CLS "java/util/Map" +#define MAP_ENTRY_CLS "java/util/Map$Entry" +#define SET_CLS "java/util/Set" +#define ITERATOR_CLS "java/util/Iterator" + +#define SIMULATOR_RESOURCE_CLS "org/oic/simulator/server/SimulatorResource" +#define SIMULATOR_RESOURCE_TYPE_CLS "org/oic/simulator/server/SimulatorResource$Type" +#define SIMULATOR_SINGLE_RESOURCE_CLS "org/oic/simulator/server/SimulatorSingleResource" +#define SIMULATOR_COLLECTION_RESOURCE_CLS "org/oic/simulator/server/SimulatorCollectionResource" +#define SIMULATOR_RESOURCE_MODEL_CLS "org/oic/simulator/SimulatorResourceModel" +#define SIMULATOR_RESOURCE_ATTRIBUTE_CLS "org/oic/simulator/SimulatorResourceAttribute" +#define ATTRIBUTE_VALUE_CLS "org/oic/simulator/AttributeValue" +#define ATTRIBUTE_VALUE_TYPE_CLS "org/oic/simulator/AttributeValue$ValueType" +#define ATTRIBUTE_TYPE_INFO_CLS "org/oic/simulator/AttributeValue$TypeInfo" +#define ATTRIBUTE_PROPERTY_CLS "org/oic/simulator/AttributeProperty" +#define ATTRIBUTE_PROPERTY_TYPE_CLS "org/oic/simulator/AttributeProperty$Type" +#define AUTOMATION_TYPE_CLS "org/oic/simulator/server/SimulatorResource$AutoUpdateType" + +#define SIMULATOR_REMOTE_RESOURCE_CLS "org/oic/simulator/client/SimulatorRemoteResource" +#define OBSERVER_CLS "org/oic/simulator/server/Observer" +#define DEVICE_INFO_CLS "org/oic/simulator/DeviceInfo" +#define PLATFORM_INFO_CLS "org/oic/simulator/PlatformInfo" +#define SIMULATOR_EXCEPTION_CLS "org/oic/simulator/SimulatorException" +#define INVALID_ARGS_EXCEPTION_CLS "org/oic/simulator/InvalidArgsException" +#define NO_SUPPORT_EXCEPTION_CLS "org/oic/simulator/NoSupportException" +#define OPERATION_IN_PROGRESS_EXCEPTION_CLS "org/oic/simulator/OperationInProgressException" +#define SIMULATOR_RESULT_CLS "org/oic/simulator/SimulatorResult" + +#define INTEGER_1D_ARRAY "[Ljava/lang/Integer;" +#define INTEGER_2D_ARRAY "[[Ljava/lang/Integer;" +#define INTEGER_3D_ARRAY "[[Ljava/lang/Integer;" +#define DOUBLE_1D_ARRAY "[Ljava/lang/Double;" +#define DOUBLE_2D_ARRAY "[[Ljava/lang/Double;" +#define DOUBLE_3D_ARRAY "[[Ljava/lang/Double;" +#define BOOLEAN_1D_ARRAY "[Ljava/lang/Boolean;" +#define BOOLEAN_2D_ARRAY "[[Ljava/lang/Boolean;" +#define BOOLEAN_3D_ARRAY "[[Ljava/lang/Boolean;" +#define STRING_1D_ARRAY "[Ljava/lang/String;" +#define STRING_2D_ARRAY "[[Ljava/lang/String;" +#define STRING_3D_ARRAY "[[Ljava/lang/String;" +#define SIMULATOR_RESOURCE_MODEL_1D_ARRAY "[Lorg/oic/simulator/SimulatorResourceModel;" +#define SIMULATOR_RESOURCE_MODEL_2D_ARRAY "[[Lorg/oic/simulator/SimulatorResourceModel;" +#define SIMULATOR_RESOURCE_MODEL_3D_ARRAY "[[Lorg/oic/simulator/SimulatorResourceModel;" + +SimulatorClassRefs gSimulatorClassRefs; +static std::mutex gJvmMutex; +static JavaVM *gJavaVM; + +JNIEnv *getEnv() +{ + std::unique_lock lock(gJvmMutex); + if (!gJavaVM) + return nullptr; + + JNIEnv *env = nullptr; + jint ret = gJavaVM->GetEnv((void **)&env, JNI_VERSION_1_6); + switch (ret) + { + case JNI_OK: + return env; + case JNI_EDETACHED: + if (!gJavaVM->AttachCurrentThread((void **)&env, NULL)) + return env; + } + + return nullptr; +} + +void releaseEnv() +{ + std::unique_lock lock(gJvmMutex); + if (!gJavaVM) + return; + gJavaVM->DetachCurrentThread(); +} + +static void getClassRef(JNIEnv *env, const char *className, jclass &classRef) +{ + jclass localRef = env->FindClass(className); + if (localRef) + { + classRef = (jclass) env->NewGlobalRef(localRef); + env->DeleteLocalRef(localRef); + } +} + +#ifdef __cplusplus +extern "C" { +#endif + +JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) +{ + if (!vm) + return JNI_ERR; + + JNIEnv *env = nullptr; + if (JNI_OK != vm->GetEnv((void **) &env, JNI_VERSION_1_6)) + return JNI_ERR; + + // Get the class references + getClassRef(env, OBJECT_CLS, gSimulatorClassRefs.objectCls); + getClassRef(env, INTEGER_CLS, gSimulatorClassRefs.integerCls); + getClassRef(env, DOUBLE_CLS, gSimulatorClassRefs.doubleCls); + getClassRef(env, BOOLEAN_CLS, gSimulatorClassRefs.booleanCls); + getClassRef(env, STRING_CLS, gSimulatorClassRefs.stringCls); + getClassRef(env, VECTOR_CLS, gSimulatorClassRefs.vectorCls); + getClassRef(env, HASHMAP_CLS, gSimulatorClassRefs.hashMapCls); + getClassRef(env, MAP_CLS, gSimulatorClassRefs.mapCls); + getClassRef(env, MAP_ENTRY_CLS, gSimulatorClassRefs.mapEntryCls); + getClassRef(env, SET_CLS, gSimulatorClassRefs.setCls); + getClassRef(env, ITERATOR_CLS, gSimulatorClassRefs.iteratorCls); + getClassRef(env, SIMULATOR_RESOURCE_CLS, gSimulatorClassRefs.simulatorResourceCls); + getClassRef(env, SIMULATOR_RESOURCE_TYPE_CLS, gSimulatorClassRefs.simulatorResourceTypeCls); + getClassRef(env, SIMULATOR_SINGLE_RESOURCE_CLS, gSimulatorClassRefs.simulatorSingleResourceCls); + getClassRef(env, SIMULATOR_COLLECTION_RESOURCE_CLS, + gSimulatorClassRefs.simulatorCollectionResourceCls); + getClassRef(env, SIMULATOR_REMOTE_RESOURCE_CLS, gSimulatorClassRefs.simulatorRemoteResourceCls); + getClassRef(env, SIMULATOR_RESOURCE_MODEL_CLS, gSimulatorClassRefs.simulatorResourceModelCls); + getClassRef(env, SIMULATOR_RESOURCE_ATTRIBUTE_CLS, + gSimulatorClassRefs.simulatorResourceAttributeCls); + getClassRef(env, ATTRIBUTE_VALUE_CLS, gSimulatorClassRefs.attributeValueCls); + getClassRef(env, ATTRIBUTE_VALUE_TYPE_CLS, gSimulatorClassRefs.attributeValueTypeCls); + getClassRef(env, ATTRIBUTE_TYPE_INFO_CLS, gSimulatorClassRefs.attributeTypeInfoCls); + getClassRef(env, ATTRIBUTE_PROPERTY_CLS, gSimulatorClassRefs.attributePropertyCls); + getClassRef(env, ATTRIBUTE_PROPERTY_TYPE_CLS, gSimulatorClassRefs.attributePropertyTypeCls); + getClassRef(env, AUTOMATION_TYPE_CLS, gSimulatorClassRefs.automationTypeCls); + getClassRef(env, OBSERVER_CLS, gSimulatorClassRefs.observerCls); + getClassRef(env, DEVICE_INFO_CLS, gSimulatorClassRefs.deviceInfoCls); + getClassRef(env, PLATFORM_INFO_CLS, gSimulatorClassRefs.platformInfoCls); + getClassRef(env, SIMULATOR_EXCEPTION_CLS, gSimulatorClassRefs.simulatorExceptionCls); + getClassRef(env, INVALID_ARGS_EXCEPTION_CLS, gSimulatorClassRefs.invalidArgsExceptionCls); + getClassRef(env, NO_SUPPORT_EXCEPTION_CLS, gSimulatorClassRefs.noSupportExceptionCls); + getClassRef(env, OPERATION_IN_PROGRESS_EXCEPTION_CLS, + gSimulatorClassRefs.operationInProgressExceptionCls); + getClassRef(env, SIMULATOR_RESULT_CLS, gSimulatorClassRefs.simulatorResultCls); + getClassRef(env, INTEGER_1D_ARRAY, gSimulatorClassRefs.integer1DArrayCls); + getClassRef(env, INTEGER_2D_ARRAY, gSimulatorClassRefs.integer2DArrayCls); + getClassRef(env, INTEGER_3D_ARRAY, gSimulatorClassRefs.integer3DArrayCls); + getClassRef(env, DOUBLE_1D_ARRAY, gSimulatorClassRefs.double1DArrayCls); + getClassRef(env, DOUBLE_2D_ARRAY, gSimulatorClassRefs.double2DArrayCls); + getClassRef(env, DOUBLE_3D_ARRAY, gSimulatorClassRefs.double3DArrayCls); + getClassRef(env, BOOLEAN_1D_ARRAY, gSimulatorClassRefs.boolean1DArrayCls); + getClassRef(env, BOOLEAN_2D_ARRAY, gSimulatorClassRefs.boolean2DArrayCls); + getClassRef(env, BOOLEAN_3D_ARRAY, gSimulatorClassRefs.boolean3DArrayCls); + getClassRef(env, STRING_1D_ARRAY, gSimulatorClassRefs.string1DArrayCls); + getClassRef(env, STRING_2D_ARRAY, gSimulatorClassRefs.string2DArrayCls); + getClassRef(env, STRING_3D_ARRAY, gSimulatorClassRefs.string3DArrayCls); + getClassRef(env, SIMULATOR_RESOURCE_MODEL_1D_ARRAY, + gSimulatorClassRefs.simulatorResModel1DArrayCls); + getClassRef(env, SIMULATOR_RESOURCE_MODEL_2D_ARRAY, + gSimulatorClassRefs.simulatorResModel2DArrayCls); + getClassRef(env, SIMULATOR_RESOURCE_MODEL_3D_ARRAY, + gSimulatorClassRefs.simulatorResModel3DArrayCls); + + gJavaVM = vm; + return JNI_VERSION_1_6; +} + +JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *vm, void *reserved) +{ + if (!vm) + return; + + JNIEnv *env = nullptr; + if (JNI_OK != vm->GetEnv((void **) &env, JNI_VERSION_1_6)) + return; + + // Release the class global references + env->DeleteGlobalRef(gSimulatorClassRefs.objectCls); + env->DeleteGlobalRef(gSimulatorClassRefs.integerCls); + env->DeleteGlobalRef(gSimulatorClassRefs.doubleCls); + env->DeleteGlobalRef(gSimulatorClassRefs.booleanCls); + env->DeleteGlobalRef(gSimulatorClassRefs.stringCls); + env->DeleteGlobalRef(gSimulatorClassRefs.hashMapCls); + env->DeleteGlobalRef(gSimulatorClassRefs.vectorCls); + env->DeleteGlobalRef(gSimulatorClassRefs.mapCls); + env->DeleteGlobalRef(gSimulatorClassRefs.mapEntryCls); + env->DeleteGlobalRef(gSimulatorClassRefs.setCls); + env->DeleteGlobalRef(gSimulatorClassRefs.iteratorCls); + env->DeleteGlobalRef(gSimulatorClassRefs.simulatorResourceCls); + env->DeleteGlobalRef(gSimulatorClassRefs.simulatorSingleResourceCls); + env->DeleteGlobalRef(gSimulatorClassRefs.simulatorCollectionResourceCls); + env->DeleteGlobalRef(gSimulatorClassRefs.simulatorResourceModelCls); + env->DeleteGlobalRef(gSimulatorClassRefs.simulatorResourceAttributeCls); + env->DeleteGlobalRef(gSimulatorClassRefs.attributeValueCls); + env->DeleteGlobalRef(gSimulatorClassRefs.attributeValueTypeCls); + env->DeleteGlobalRef(gSimulatorClassRefs.attributeTypeInfoCls); + env->DeleteGlobalRef(gSimulatorClassRefs.attributePropertyCls); + env->DeleteGlobalRef(gSimulatorClassRefs.attributePropertyTypeCls); + env->DeleteGlobalRef(gSimulatorClassRefs.automationTypeCls); + env->DeleteGlobalRef(gSimulatorClassRefs.simulatorRemoteResourceCls); + env->DeleteGlobalRef(gSimulatorClassRefs.observerCls); + env->DeleteGlobalRef(gSimulatorClassRefs.deviceInfoCls); + env->DeleteGlobalRef(gSimulatorClassRefs.platformInfoCls); + env->DeleteGlobalRef(gSimulatorClassRefs.simulatorExceptionCls); + env->DeleteGlobalRef(gSimulatorClassRefs.invalidArgsExceptionCls); + env->DeleteGlobalRef(gSimulatorClassRefs.noSupportExceptionCls); + env->DeleteGlobalRef(gSimulatorClassRefs.operationInProgressExceptionCls); +} + +#ifdef __cplusplus +} +#endif + diff --git a/service/simulator/java/jni/simulator_jni_utils.cpp b/service/simulator/java/jni/simulator_jni_utils.cpp deleted file mode 100644 index 0274d63..0000000 --- a/service/simulator/java/jni/simulator_jni_utils.cpp +++ /dev/null @@ -1,71 +0,0 @@ -/****************************************************************** - * - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************/ -#include "simulator_jni_utils.h" -#include "simulator_common_jni.h" - -extern SimulatorClassRefs gSimulatorClassRefs; - -void throwSimulatorException(JNIEnv *env, SimulatorResult errCode, const char *errMessage) -{ - jobject ex = env->NewObject(gSimulatorClassRefs.classSimulatorException, - gSimulatorClassRefs.classSimulatorExceptionCtor, errCode, - env->NewStringUTF(errMessage)); - if (!ex) - { - return; - } - env->Throw((jthrowable)ex); -} - -void throwInvalidArgsException(JNIEnv *env, SimulatorResult errCode, const char *errMessage) -{ - jobject ex = env->NewObject(gSimulatorClassRefs.classInvalidArgsException, - gSimulatorClassRefs.classInvalidArgsExceptionCtor, errCode, - env->NewStringUTF(errMessage)); - if (!ex) - { - return; - } - env->Throw((jthrowable)ex); -} - -void throwNoSupportException(JNIEnv *env, SimulatorResult errCode, const char *errMessage) -{ - jobject ex = env->NewObject(gSimulatorClassRefs.classNoSupportException, - gSimulatorClassRefs.classNoSupportExceptionCtor, errCode, - env->NewStringUTF(errMessage)); - if (!ex) - { - return; - } - env->Throw((jthrowable)ex); -} - -void throwOperationInProgressException(JNIEnv *env, SimulatorResult errCode, const char *errMessage) -{ - jobject ex = env->NewObject(gSimulatorClassRefs.classOperationInProgressException, - gSimulatorClassRefs.classOperationInProgressExceptionCtor, errCode, - env->NewStringUTF(errMessage)); - if (!ex) - { - return; - } - env->Throw((jthrowable)ex); -} diff --git a/service/simulator/java/jni/simulator_manager_jni.cpp b/service/simulator/java/jni/simulator_manager_jni.cpp index 0fc5796..3391685 100644 --- a/service/simulator/java/jni/simulator_manager_jni.cpp +++ b/service/simulator/java/jni/simulator_manager_jni.cpp @@ -18,48 +18,17 @@ * ******************************************************************/ -#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 lock(gEnvMutex); - if (nullptr == gvm) - return NULL; - - JNIEnv *env = NULL; - jint ret = gvm->GetEnv((void **)&env, JNI_VERSION_1_6); - switch (ret) - { - case JNI_OK: - return env; - case JNI_EDETACHED: - if (0 == gvm->AttachCurrentThread((void **)&env, NULL)) - return env; - } - - return NULL; -} +#include "simulator_exceptions_jni.h" +#include "simulator_resource_utils_jni.h" +#include "simulator_utils_jni.h" +#include "jni_sharedobject_holder.h" +#include "jni_listener_holder.h" +#include "jni_string.h" -void releaseEnv() -{ - std::unique_lock lock(gEnvMutex); - if (nullptr == gvm) - return; - gvm->DetachCurrentThread(); -} +#include "simulator_manager.h" class JNILogger : public ILogger { @@ -109,448 +78,185 @@ class JNILogger : public ILogger jweak m_logger; }; - -jobject SimulatorRemoteResourceToJava(JNIEnv *env, jlong resource) -{ - jmethodID constructor = env->GetMethodID(gSimulatorClassRefs.classSimulatorRemoteResource, "", - "(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 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(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 resourceTypes = resource->getResourceTypes(); - jobject jResTypes = convertStringVectorToJavaList(env, resourceTypes); - env->SetObjectField(simulatorResource, fieldID, jResTypes); - - fieldID = env->GetFieldID(gSimulatorClassRefs.classSimulatorRemoteResource, "mResInterfaces", - "Ljava/util/LinkedList;"); - std::vector interfaceTypes = resource->getResourceInterfaces(); - jobject jResInterfaces = convertStringVectorToJavaList(env, interfaceTypes); - env->SetObjectField(simulatorResource, fieldID, jResInterfaces); - - fieldID = env->GetFieldID(gSimulatorClassRefs.classSimulatorRemoteResource, "mIsObservable", "Z"); - env->SetBooleanField(simulatorResource, fieldID, resource->isObservable()); - - env->CallVoidMethod(foundResourceListener, foundResourceMId, simulatorResource); - if ((env)->ExceptionCheck()) - { - delete jniSimulatorResource; - releaseEnv(); - return; - } - - releaseEnv(); - } - - private: - jweak m_listener; - -}; - -void onResourceModelChange(jweak jlistenerRef, const std::string &uri, - const SimulatorResourceModel &resModel) +void onResourceFound(jobject listener, std::shared_ptr remoteResource) { JNIEnv *env = getEnv(); - if (nullptr == env) - return; - - jobject modelChangeListener = env->NewLocalRef(jlistenerRef); - if (!modelChangeListener) - { - releaseEnv(); - return; - } - - jclass modelChangeCls = env->GetObjectClass(modelChangeListener); - if (!modelChangeCls) - { - releaseEnv(); + if (!env) return; - } - jmethodID foundModelChangeMId = env->GetMethodID(modelChangeCls, "onResourceModelChanged", - "(Ljava/lang/String;Lorg/oic/simulator/SimulatorResourceModel;)V"); - if (!foundModelChangeMId) - { - releaseEnv(); - return; - } - - JSimulatorResourceModel *jniModel = new JSimulatorResourceModel(resModel); - if (!jniModel) - { - releaseEnv(); - return; - } + jclass listenerCls = env->GetObjectClass(listener); + jmethodID callbackMethod = env->GetMethodID(listenerCls, "onResourceFound", + "(Lorg/oic/simulator/client/SimulatorRemoteResource;)V"); - jobject jModel = JSimulatorResourceModel::toJava(env, reinterpret_cast(jniModel)); - jstring jUri = env->NewStringUTF(uri.c_str()); - env->CallVoidMethod(modelChangeListener, foundModelChangeMId, jUri, jModel); - if ((env)->ExceptionCheck()) - { - delete jniModel; - releaseEnv(); + jobject resource = createSimulatorRemoteResource(env, remoteResource); + if (!resource) return; - } - - env->DeleteLocalRef(jUri); + env->CallVoidMethod(listener, callbackMethod, resource); releaseEnv(); } +#ifdef __cplusplus +extern "C" { +#endif JNIEXPORT jobject JNICALL -Java_org_oic_simulator_SimulatorManagerNativeInterface_createResource -(JNIEnv *env, jclass object, jstring configPath, jobject listener) +Java_org_oic_simulator_SimulatorManager_createResource +(JNIEnv *env, jclass object, jstring configPath) { - if (!configPath) - { - throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, - "Configuration file path is empty!"); - return nullptr; - } - - if (!listener) - { - throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, - "Resource model change callback not set!"); - return nullptr; - } + VALIDATE_INPUT_RET(env, !configPath, "Path is null!", nullptr) - jweak jlistenerRef = env->NewWeakGlobalRef(listener); - SimulatorResourceServer::ResourceModelChangedCB callback = [jlistenerRef](const std::string & uri, - const SimulatorResourceModel & resModel) - { - onResourceModelChange(jlistenerRef, uri, resModel); - }; - - const char *configPathCStr = env->GetStringUTFChars(configPath, NULL); - SimulatorResourceServerSP resource = NULL; try { - resource = SimulatorManager::getInstance()->createResource( - configPathCStr, callback); - if (nullptr == resource) - { - if (configPathCStr) - env->ReleaseStringUTFChars(configPath, configPathCStr); - return NULL; - } + JniString jniPath(env, configPath); + SimulatorResourceSP resource = SimulatorManager::getInstance()->createResource( + jniPath.get()); + return createSimulatorResource(env, resource); } catch (InvalidArgsException &e) { throwInvalidArgsException(env, e.code(), e.what()); - return nullptr; } catch (SimulatorException &e) { throwSimulatorException(env, e.code(), e.what()); - return nullptr; } - catch (...) - { - throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception"); - return nullptr; - } - - JniSimulatorResource *jniSimResource = new JniSimulatorResource(resource); - jobject jSimulatorResource = JniSimulatorResource::toJava(env, - reinterpret_cast(jniSimResource)); - - jniSimResource->setResourceInfo(env, jSimulatorResource); - if (configPathCStr) - env->ReleaseStringUTFChars(configPath, configPathCStr); - return jSimulatorResource; + return nullptr; } -JNIEXPORT jobjectArray JNICALL -Java_org_oic_simulator_SimulatorManagerNativeInterface_createResources -(JNIEnv *env, jclass object, jstring configPath, jint count, jobject listener) +JNIEXPORT jobject JNICALL +Java_org_oic_simulator_SimulatorManager_createResources +(JNIEnv *env, jclass object, jstring configPath, jint count) { - if (!configPath) - { - throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, - "Configuration file path is empty!"); - return nullptr; - } + VALIDATE_INPUT_RET(env, !configPath, "Path is null!", nullptr) + VALIDATE_INPUT_RET(env, !count || count < 0, "Invalid count value!", nullptr) - if (!listener) - { - throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, - "Resource model change callback not set!"); - return nullptr; - } - - jweak jlistenerRef = env->NewWeakGlobalRef(listener); - SimulatorResourceServer::ResourceModelChangedCB callback = [jlistenerRef](const std::string & uri, - const SimulatorResourceModel & resModel) - { - onResourceModelChange(jlistenerRef, uri, resModel); - }; - - const char *configPathCStr = env->GetStringUTFChars(configPath, NULL); - std::vector resources; try { - resources = SimulatorManager::getInstance()->createResource(configPathCStr, count, callback); + JniString jniPath(env, configPath); + std::vector resources = + SimulatorManager::getInstance()->createResource(jniPath.get(), count); + return createSimulatorResourceVector(env, resources); } catch (InvalidArgsException &e) { throwInvalidArgsException(env, e.code(), e.what()); - return nullptr; } catch (SimulatorException &e) { throwSimulatorException(env, e.code(), e.what()); - return nullptr; - } - catch (...) - { - throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception"); - return nullptr; } - // Construct the object array and send it java layer - jobjectArray resourceArray = env->NewObjectArray(resources.size(), - gSimulatorClassRefs.classSimulatorResource, NULL); - if (resourceArray) - { - for (size_t i = 0; i < resources.size(); i++) - { - JniSimulatorResource *jniSimResource = new JniSimulatorResource(resources[i]); - jobject jSimulatorResource = JniSimulatorResource::toJava(env, - reinterpret_cast(jniSimResource)); - jniSimResource->setResourceInfo(env, jSimulatorResource); - env->SetObjectArrayElement(resourceArray, i, jSimulatorResource); - } - } - - if (configPathCStr) - env->ReleaseStringUTFChars(configPath, configPathCStr); - return resourceArray; + return nullptr; } -JNIEXPORT void JNICALL -Java_org_oic_simulator_SimulatorManagerNativeInterface_deleteResource -(JNIEnv *env, jclass object, jobject jResource) +JNIEXPORT jobject JNICALL +Java_org_oic_simulator_SimulatorManager_createSingleResource +(JNIEnv *env, jclass object, jstring name, jstring uri, jstring resourceType) { - if (!jResource) - { - throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, - "No resource has been passed!"); - return; - } - - SimulatorResourceServerSP resource = - JniSimulatorResource::getJniSimulatorResourceSP(env, jResource); - if (!resource) - { - throwSimulatorException(env, SIMULATOR_BAD_OBJECT, - "Simulator resource not found!"); - return; - } + VALIDATE_INPUT_RET(env, !name, "Name is null!", nullptr) + VALIDATE_INPUT_RET(env, !uri, "URI is null!", nullptr) + VALIDATE_INPUT_RET(env, !resourceType, "Resource type is null!", nullptr) try { - SimulatorManager::getInstance()->deleteResource(resource); + JniString jniName(env, name); + JniString jniUri(env, uri); + JniString jniResourceType(env, resourceType); + + SimulatorSingleResourceSP resource = SimulatorManager::getInstance()->createSingleResource( + jniName.get(), jniUri.get(), jniResourceType.get()); + return createSimulatorResource(env, std::dynamic_pointer_cast(resource)); } catch (InvalidArgsException &e) { throwInvalidArgsException(env, e.code(), e.what()); } - catch (...) + catch (SimulatorException &e) { - throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception"); + throwSimulatorException(env, e.code(), e.what()); } + + return nullptr; } -JNIEXPORT void JNICALL -Java_org_oic_simulator_SimulatorManagerNativeInterface_deleteResources -(JNIEnv *env, jclass object, jstring resourceType) +JNIEXPORT jobject JNICALL +Java_org_oic_simulator_SimulatorManager_createCollectionResource +(JNIEnv *env, jclass object, jstring name, jstring uri, jstring resourceType) { - std::string type; - const char *typeCStr = NULL; - if (resourceType) - { - typeCStr = env->GetStringUTFChars(resourceType, NULL); - type = typeCStr; - } + VALIDATE_INPUT_RET(env, !name, "Name is null!", nullptr) + VALIDATE_INPUT_RET(env, !uri, "URI is null!", nullptr) + VALIDATE_INPUT_RET(env, !resourceType, "Resource type is null!", nullptr) try { - SimulatorManager::getInstance()->deleteResource(type); + JniString jniName(env, name); + JniString jniUri(env, uri); + JniString jniResourceType(env, resourceType); + + SimulatorCollectionResourceSP resource = SimulatorManager::getInstance()->createCollectionResource( + jniName.get(), jniUri.get(), jniResourceType.get()); + return createSimulatorResource(env, std::dynamic_pointer_cast(resource)); } - catch (...) + catch (InvalidArgsException &e) { - throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception"); - return; + throwInvalidArgsException(env, e.code(), e.what()); + } + catch (SimulatorException &e) + { + throwSimulatorException(env, e.code(), e.what()); } - if (typeCStr) - env->ReleaseStringUTFChars(resourceType, typeCStr); + return nullptr; } JNIEXPORT void JNICALL -Java_org_oic_simulator_SimulatorManagerNativeInterface_findResource -(JNIEnv *env, jobject object, jstring jResourceType, jobject jListener) +Java_org_oic_simulator_SimulatorManager_searchResource +(JNIEnv *env, jobject object, jstring resourceType, jobject listener) { - if (!jListener) - { - throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, "Invalid callback!"); - return; - } + VALIDATE_CALLBACK(env, listener) - const char *typeCStr = NULL; - std::string resourceType; - if (jResourceType) + ResourceFindCallback callback = std::bind([]( + std::shared_ptr resource, + const std::shared_ptr &listenerRef) { - typeCStr = env->GetStringUTFChars(jResourceType, NULL); - resourceType = typeCStr; - } - - JNIFoundResourceListener *resourceListener = new JNIFoundResourceListener(); - resourceListener->setJavaFoundResourceListener(env, jListener); + onResourceFound(listenerRef->get(), resource); + }, std::placeholders::_1, JniListenerHolder::create(env, listener)); try { - if (!jResourceType) + if (!resourceType) { - SimulatorManager::getInstance()->findResource( - std::bind(&JNIFoundResourceListener::onFoundResource, - resourceListener, std::placeholders::_1)); + SimulatorManager::getInstance()->findResource(callback); } else { - SimulatorManager::getInstance()->findResource(resourceType, - std::bind(&JNIFoundResourceListener::onFoundResource, - resourceListener, std::placeholders::_1)); + JniString type(env, resourceType); + SimulatorManager::getInstance()->findResource(type.get(), callback); } } catch (InvalidArgsException &e) { throwInvalidArgsException(env, e.code(), e.what()); - return; } catch (SimulatorException &e) { throwSimulatorException(env, e.code(), e.what()); - return; } - catch (...) - { - throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception"); - return; - } - - if (typeCStr) - env->ReleaseStringUTFChars(jResourceType, typeCStr); } - JNIEXPORT void JNICALL -Java_org_oic_simulator_SimulatorManagerNativeInterface_setLogger -(JNIEnv *env, jclass object, jobject logger) +Java_org_oic_simulator_SimulatorManager_setDeviceInfo +(JNIEnv *env, jobject object, jstring deviceName) { - static std::shared_ptr target(new JNILogger()); - target->setJavaLogger(env, logger); - SimulatorManager::getInstance()->setLogger(target); -} - -JNIEXPORT void JNICALL -Java_org_oic_simulator_SimulatorManagerNativeInterface_setDeviceInfo -(JNIEnv *env, jobject interfaceObject, jstring deviceInfo) -{ - if (!deviceInfo) - { - throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid device info!"); - return; - } - - const char *deviceName = env->GetStringUTFChars(deviceInfo, NULL); + VALIDATE_INPUT(env, !deviceName, "Device name is null!") try { - SimulatorManager::getInstance()->setDeviceInfo(deviceName); + JniString jniDeviceName(env, deviceName); + SimulatorManager::getInstance()->setDeviceInfo(jniDeviceName.get()); } catch (InvalidArgsException &e) { @@ -560,31 +266,19 @@ Java_org_oic_simulator_SimulatorManagerNativeInterface_setDeviceInfo { throwSimulatorException(env, e.code(), e.what()); } - catch (...) - { - throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception"); - return; - } - - env->ReleaseStringUTFChars(deviceInfo, deviceName); } JNIEXPORT void JNICALL -Java_org_oic_simulator_SimulatorManagerNativeInterface_getDeviceInfo -(JNIEnv *env, jobject interfaceObject, jobject jListener) +Java_org_oic_simulator_SimulatorManager_findDevices +(JNIEnv *env, jobject object, jobject listener) { - if (!jListener) - { - throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, "Invalid callback!"); - return; - } + VALIDATE_CALLBACK(env, listener) - JniDeviceInfoListener *deviceInfoListener = new JniDeviceInfoListener(env, jListener); - DeviceInfoCallback callback = std::bind([deviceInfoListener](DeviceInfo & deviceInfo) + DeviceInfoCallback callback = std::bind([](DeviceInfo & deviceInfo, + const std::shared_ptr &listenerRef) { - deviceInfoListener->onDeviceInfoReceived(deviceInfo); - delete deviceInfoListener; - }, std::placeholders::_1); + onDeviceInfoReceived(listenerRef->get(), deviceInfo); + }, std::placeholders::_1, JniListenerHolder::create(env, listener)); try { @@ -598,56 +292,37 @@ Java_org_oic_simulator_SimulatorManagerNativeInterface_getDeviceInfo { throwSimulatorException(env, e.code(), e.what()); } - catch (...) - { - throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception"); - return; - } } JNIEXPORT void JNICALL -Java_org_oic_simulator_SimulatorManagerNativeInterface_setPlatformInfo -(JNIEnv *env, jobject interfaceObject, jobject jPlatformInfo) +Java_org_oic_simulator_SimulatorManager_setPlatformInfo +(JNIEnv *env, jobject object, jobject platformInfo) { - if (!jPlatformInfo) - { - throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid platform info!"); - return; - } + VALIDATE_INPUT(env, !platformInfo, "Platform info is null!") - JPlatformInfo jniPlatformInfo(env); try { - PlatformInfo platformInfo = jniPlatformInfo.toCPP(jPlatformInfo); - SimulatorManager::getInstance()->setPlatformInfo(platformInfo); + JniPlatformInfo jniPlatformInfo(env); + PlatformInfo info = jniPlatformInfo.toCpp(platformInfo); + SimulatorManager::getInstance()->setPlatformInfo(info); } catch (SimulatorException &e) { throwSimulatorException(env, e.code(), e.what()); } - catch (...) - { - throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception"); - return; - } } JNIEXPORT void JNICALL -Java_org_oic_simulator_SimulatorManagerNativeInterface_getPlatformInfo -(JNIEnv *env, jobject interfaceObject, jobject jListener) +Java_org_oic_simulator_SimulatorManager_getPlatformInformation +(JNIEnv *env, jobject object, jobject listener) { - if (!jListener) - { - throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, "Invalid callback!"); - return; - } + VALIDATE_CALLBACK(env, listener) - JniPlatformInfoListener *platformInfoListener = new JniPlatformInfoListener(env, jListener); - PlatformInfoCallback callback = std::bind([platformInfoListener](PlatformInfo & platformInfo) + PlatformInfoCallback callback = std::bind([](PlatformInfo & platformInfo, + const std::shared_ptr &listenerRef) { - platformInfoListener->onPlatformInfoReceived(platformInfo); - delete platformInfoListener; - }, std::placeholders::_1); + onPlatformInfoReceived(listenerRef->get(), platformInfo); + }, std::placeholders::_1, JniListenerHolder::create(env, listener)); try { @@ -661,308 +336,17 @@ Java_org_oic_simulator_SimulatorManagerNativeInterface_getPlatformInfo { throwSimulatorException(env, e.code(), e.what()); } - catch (...) - { - throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception"); - return; - } } -static bool getClassRef(JNIEnv *env, const char *className, jclass &classRef) -{ - jclass localClassRef = nullptr; - localClassRef = env->FindClass(className); - if (!localClassRef) - return false; - - classRef = (jclass)env->NewGlobalRef(localClassRef); - env->DeleteLocalRef(localClassRef); - return true; -} - -#ifdef __cplusplus -extern "C" { -#endif -JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) -{ - if (!vm) - { - return JNI_ERR; - } - - JNIEnv *env = NULL; - if (JNI_OK != vm->GetEnv((void **) &env, JNI_VERSION_1_6)) - { - return JNI_ERR; - } - - // Get the class references - if (false == getClassRef(env, "java/lang/Object", gSimulatorClassRefs.classObject)) - { - return JNI_ERR; - } - - if (false == getClassRef(env, "java/lang/Integer", gSimulatorClassRefs.classInteger)) - { - return JNI_ERR; - } - - if (false == getClassRef(env, "java/lang/Double", gSimulatorClassRefs.classDouble)) - { - return JNI_ERR; - } - - if (false == getClassRef(env, "java/lang/Boolean", gSimulatorClassRefs.classBoolean)) - { - return JNI_ERR; - } - - if (false == getClassRef(env, "java/lang/String", gSimulatorClassRefs.classString)) - { - return JNI_ERR; - } - - if (false == getClassRef(env, "java/util/HashMap", gSimulatorClassRefs.classHashMap)) - { - return JNI_ERR; - } - - if (false == getClassRef(env, "java/util/Vector", gSimulatorClassRefs.classVector)) - { - return JNI_ERR; - } - - if (false == getClassRef(env, "java/util/Map", gSimulatorClassRefs.classMap)) - { - return JNI_ERR; - } - - if (false == getClassRef(env, "java/util/Map$Entry", gSimulatorClassRefs.classMapEntry)) - { - return JNI_ERR; - } - - if (false == getClassRef(env, "java/util/Set", gSimulatorClassRefs.classSet)) - { - return JNI_ERR; - } - - if (false == getClassRef(env, "java/util/Iterator", gSimulatorClassRefs.classIterator)) - { - return JNI_ERR; - } - - if (false == getClassRef(env, "java/util/LinkedList", gSimulatorClassRefs.classLinkedList)) - { - return JNI_ERR; - } - - if (false == getClassRef(env, "org/oic/simulator/serviceprovider/SimulatorResourceServer", - gSimulatorClassRefs.classSimulatorResource)) - { - return JNI_ERR; - } - - if (false == getClassRef(env, "org/oic/simulator/SimulatorResourceModel", - gSimulatorClassRefs.classSimulatorResourceModel)) - { - return JNI_ERR; - } - - if (false == getClassRef(env, "org/oic/simulator/ResourceAttribute", - gSimulatorClassRefs.classResourceAttribute)) - { - return JNI_ERR; - } - - if (false == getClassRef(env, "org/oic/simulator/clientcontroller/SimulatorRemoteResource", - gSimulatorClassRefs.classSimulatorRemoteResource)) - { - return JNI_ERR; - } - - if (false == getClassRef(env, "org/oic/simulator/serviceprovider/ObserverInfo", - gSimulatorClassRefs.classObserverInfo)) - { - return JNI_ERR; - } - - if (false == getClassRef(env, "org/oic/simulator/DeviceInfo", - gSimulatorClassRefs.classDeviceInfo)) - { - return JNI_ERR; - } - - if (false == getClassRef(env, "org/oic/simulator/PlatformInfo", - gSimulatorClassRefs.classPlatformInfo)) - { - return JNI_ERR; - } - - if (false == getClassRef(env, "org/oic/simulator/SimulatorException", - gSimulatorClassRefs.classSimulatorException)) - { - return JNI_ERR; - } - - if (false == getClassRef(env, "org/oic/simulator/InvalidArgsException", - gSimulatorClassRefs.classInvalidArgsException)) - { - return JNI_ERR; - } - - if (false == getClassRef(env, "org/oic/simulator/NoSupportException", - gSimulatorClassRefs.classNoSupportException)) - { - return JNI_ERR; - } - - if (false == getClassRef(env, "org/oic/simulator/OperationInProgressException", - gSimulatorClassRefs.classOperationInProgressException)) - { - return JNI_ERR; - } - - // Get the reference to methods - gSimulatorClassRefs.classIntegerCtor = env->GetMethodID(gSimulatorClassRefs.classInteger, "", - "(I)V"); - if (!gSimulatorClassRefs.classIntegerCtor) - return JNI_ERR; - - gSimulatorClassRefs.classDoubleCtor = env->GetMethodID(gSimulatorClassRefs.classDouble, "", - "(D)V"); - if (!gSimulatorClassRefs.classDoubleCtor) - return JNI_ERR; - - gSimulatorClassRefs.classBooleanCtor= env->GetMethodID(gSimulatorClassRefs.classBoolean, "", - "(Z)V"); - if (!gSimulatorClassRefs.classBooleanCtor) - return JNI_ERR; - - gSimulatorClassRefs.classHashMapCtor = env->GetMethodID(gSimulatorClassRefs.classHashMap, "", - "()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, "", - "()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, - "", "()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, "", "(J)V"); - if (!gSimulatorClassRefs.classSimulatorResourceCtor) - return JNI_ERR; - - gSimulatorClassRefs.classSimulatorResourceModelCtor = env->GetMethodID( - gSimulatorClassRefs.classSimulatorResourceModel, "", "(J)V"); - if (!gSimulatorClassRefs.classSimulatorResourceModelCtor) - return JNI_ERR; - - gSimulatorClassRefs.classResourceAttributeCtor = env->GetMethodID( - gSimulatorClassRefs.classResourceAttribute, "", "()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, "", "(J)V"); - if (!gSimulatorClassRefs.classSimulatorResourceModelId) - return JNI_ERR; - - gSimulatorClassRefs.classObserverInfoCtor = env->GetMethodID( - gSimulatorClassRefs.classObserverInfo, "", - "(ILjava/lang/String;I)V"); - if (!gSimulatorClassRefs.classObserverInfoCtor) - return JNI_ERR; - - gSimulatorClassRefs.classSimulatorExceptionCtor = env->GetMethodID( - gSimulatorClassRefs.classSimulatorException, "", - "(ILjava/lang/String;)V"); - if (!gSimulatorClassRefs.classSimulatorExceptionCtor) - return JNI_ERR; - - gSimulatorClassRefs.classInvalidArgsExceptionCtor = env->GetMethodID( - gSimulatorClassRefs.classInvalidArgsException, "", - "(ILjava/lang/String;)V"); - if (!gSimulatorClassRefs.classInvalidArgsExceptionCtor) - return JNI_ERR; - - gSimulatorClassRefs.classNoSupportExceptionCtor = env->GetMethodID( - gSimulatorClassRefs.classNoSupportException, "", - "(ILjava/lang/String;)V"); - if (!gSimulatorClassRefs.classNoSupportExceptionCtor) - return JNI_ERR; - - gSimulatorClassRefs.classOperationInProgressExceptionCtor = env->GetMethodID( - gSimulatorClassRefs.classOperationInProgressException, "", - "(ILjava/lang/String;)V"); - if (!gSimulatorClassRefs.classOperationInProgressExceptionCtor) - return JNI_ERR; - - gvm = vm; - return JNI_VERSION_1_6; -} - -JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *vm, void *reserved) +JNIEXPORT void JNICALL +Java_org_oic_simulator_SimulatorManager_setLogger +(JNIEnv *env, jobject object, jobject logger) { + static std::shared_ptr target(new JNILogger()); + target->setJavaLogger(env, logger); + SimulatorManager::getInstance()->setLogger(target); } #ifdef __cplusplus } -#endif +#endif \ No newline at end of file diff --git a/service/simulator/java/jni/simulator_manager_jni.h b/service/simulator/java/jni/simulator_manager_jni.h deleted file mode 100644 index 2a71031..0000000 --- a/service/simulator/java/jni/simulator_manager_jni.h +++ /dev/null @@ -1,74 +0,0 @@ -/****************************************************************** - * - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************/ - -#ifndef SIMULATOR_MANAGER_JNI_H_ -#define SIMULATOR_MANAGER_JNI_H_ - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -JNIEXPORT jobject JNICALL -Java_org_oic_simulator_SimulatorManagerNativeInterface_createResource -(JNIEnv *env, jclass object, jstring jConfigPath, jobject jListener); - -JNIEXPORT jobjectArray JNICALL -Java_org_oic_simulator_SimulatorManagerNativeInterface_createResources -(JNIEnv *env, jclass object, jstring jConfigPath, jint count, jobject jListener); - -JNIEXPORT void JNICALL -Java_org_oic_simulator_SimulatorManagerNativeInterface_deleteResource -(JNIEnv *env, jclass object, jobject jResource); - -JNIEXPORT void JNICALL -Java_org_oic_simulator_SimulatorManagerNativeInterface_deleteResources -(JNIEnv *env, jclass object, jstring resourceType); - -JNIEXPORT void JNICALL -Java_org_oic_simulator_SimulatorManagerNativeInterface_findResource -(JNIEnv *env, jobject interfaceObject, jstring jResourceType, jobject jListener); - -JNIEXPORT void JNICALL -Java_org_oic_simulator_SimulatorManagerNativeInterface_setDeviceInfo -(JNIEnv *env, jobject interfaceObject, jstring deviceInfo); - -JNIEXPORT void JNICALL -Java_org_oic_simulator_SimulatorManagerNativeInterface_getDeviceInfo -(JNIEnv *env, jobject interfaceObject, jobject jListener); - -JNIEXPORT void JNICALL -Java_org_oic_simulator_SimulatorManagerNativeInterface_setPlatformInfo -(JNIEnv *env, jobject interfaceObject, jobject platformInfo); - -JNIEXPORT void JNICALL -Java_org_oic_simulator_SimulatorManagerNativeInterface_getPlatformInfo -(JNIEnv *env, jobject interfaceObject, jobject jListener); - -JNIEXPORT void JNICALL -Java_org_oic_simulator_SimulatorManagerNativeInterface_setLogger -(JNIEnv *env, jclass object, jobject logger); - -#ifdef __cplusplus -} -#endif - -#endif //SIMULATOR_MANAGER_JNI_H_ diff --git a/service/simulator/java/jni/simulator_platform_info_jni.cpp b/service/simulator/java/jni/simulator_platform_info_jni.cpp index f3be763..4fb7702 100644 --- a/service/simulator/java/jni/simulator_platform_info_jni.cpp +++ b/service/simulator/java/jni/simulator_platform_info_jni.cpp @@ -19,117 +19,92 @@ ******************************************************************/ #include "simulator_platform_info_jni.h" -#include "simulator_common_jni.h" +#include "simulator_utils_jni.h" +#include "jni_string.h" extern SimulatorClassRefs gSimulatorClassRefs; -jobject JPlatformInfo::toJava(PlatformInfo &platformInfo) + +jobject JniPlatformInfo::toJava(PlatformInfo &platformInfo) { if (!m_env) return nullptr; - jmethodID constr = m_env->GetMethodID(gSimulatorClassRefs.classPlatformInfo, "", "(V)V"); - if (constr) - return nullptr; - - jobject jPlatformInfo = (jobject) m_env->NewObject(gSimulatorClassRefs.classPlatformInfo, constr); - if (jPlatformInfo) - return nullptr; - + static jmethodID platformInfoCtor = m_env->GetMethodID(gSimulatorClassRefs.platformInfoCls, + "", "()V"); + jobject jPlatformInfo = (jobject) m_env->NewObject(gSimulatorClassRefs.platformInfoCls, + platformInfoCtor); setFieldValue(jPlatformInfo, "mPlatformId", platformInfo.getPlatformID()); - setFieldValue(jPlatformInfo, "m_manufacturerName", platformInfo.getManufacturerName()); - setFieldValue(jPlatformInfo, "m_manufacturerUrl", platformInfo.getManufacturerUrl()); - setFieldValue(jPlatformInfo, "m_modelNumber", platformInfo.getModelNumber()); - setFieldValue(jPlatformInfo, "m_dateOfManufacture", platformInfo.getDateOfManfacture()); - setFieldValue(jPlatformInfo, "m_platformVersion", platformInfo.getPlatformVersion()); - setFieldValue(jPlatformInfo, "m_operationSystemVersion", platformInfo.getOSVersion()); - setFieldValue(jPlatformInfo, "m_hardwareVersion", platformInfo.getHardwareVersion()); - setFieldValue(jPlatformInfo, "m_firmwareVersion", platformInfo.getFirmwareVersion()); - setFieldValue(jPlatformInfo, "m_supportUrl", platformInfo.getSupportUrl()); - setFieldValue(jPlatformInfo, "m_systemTime", platformInfo.getSystemTime()); + setFieldValue(jPlatformInfo, "mManufacturerName", platformInfo.getManufacturerName()); + setFieldValue(jPlatformInfo, "mManufacturerUrl", platformInfo.getManufacturerUrl()); + setFieldValue(jPlatformInfo, "mModelNumber", platformInfo.getModelNumber()); + setFieldValue(jPlatformInfo, "mDateOfManufacture", platformInfo.getDateOfManfacture()); + setFieldValue(jPlatformInfo, "mPlatformVersion", platformInfo.getPlatformVersion()); + setFieldValue(jPlatformInfo, "mOperationSystemVersion", platformInfo.getOSVersion()); + setFieldValue(jPlatformInfo, "mHardwareVersion", platformInfo.getHardwareVersion()); + setFieldValue(jPlatformInfo, "mFirmwareVersion", platformInfo.getFirmwareVersion()); + setFieldValue(jPlatformInfo, "mSupportUrl", platformInfo.getSupportUrl()); + setFieldValue(jPlatformInfo, "mSystemTime", platformInfo.getSystemTime()); return jPlatformInfo; } -PlatformInfo JPlatformInfo::toCPP(jobject jPlatformInfo) +PlatformInfo JniPlatformInfo::toCpp(jobject jPlatformInfo) { PlatformInfo platformInfo; if (!m_env || !jPlatformInfo) return platformInfo; platformInfo.setPlatformID(getFieldValue(jPlatformInfo, "mPlatformId")); - platformInfo.setManufacturerName(getFieldValue(jPlatformInfo, "m_manufacturerName")); - platformInfo.setManufacturerUrl(getFieldValue(jPlatformInfo, "m_manufacturerUrl")); - platformInfo.setModelNumber(getFieldValue(jPlatformInfo, "m_modelNumber")); - platformInfo.setDateOfManfacture(getFieldValue(jPlatformInfo, "m_dateOfManufacture")); - platformInfo.setPlatformVersion(getFieldValue(jPlatformInfo, "m_platformVersion")); - platformInfo.setOSVersion(getFieldValue(jPlatformInfo, "m_operationSystemVersion")); - platformInfo.setHardwareVersion(getFieldValue(jPlatformInfo, "m_hardwareVersion")); - platformInfo.setFirmwareVersion(getFieldValue(jPlatformInfo, "m_firmwareVersion")); - platformInfo.setSupportUrl(getFieldValue(jPlatformInfo, "m_supportUrl")); - platformInfo.setSystemTime(getFieldValue(jPlatformInfo, "m_systemTime")); + platformInfo.setManufacturerName(getFieldValue(jPlatformInfo, "mManufacturerName")); + platformInfo.setManufacturerUrl(getFieldValue(jPlatformInfo, "mManufacturerUrl")); + platformInfo.setModelNumber(getFieldValue(jPlatformInfo, "mModelNumber")); + platformInfo.setDateOfManfacture(getFieldValue(jPlatformInfo, "mDateOfManufacture")); + platformInfo.setPlatformVersion(getFieldValue(jPlatformInfo, "mPlatformVersion")); + platformInfo.setOSVersion(getFieldValue(jPlatformInfo, "mOperationSystemVersion")); + platformInfo.setHardwareVersion(getFieldValue(jPlatformInfo, "mHardwareVersion")); + platformInfo.setFirmwareVersion(getFieldValue(jPlatformInfo, "mFirmwareVersion")); + platformInfo.setSupportUrl(getFieldValue(jPlatformInfo, "mSupportUrl")); + platformInfo.setSystemTime(getFieldValue(jPlatformInfo, "mSystemTime")); return std::move(platformInfo); } -void JPlatformInfo::setFieldValue(jobject jPlatformInfo, const std::string &fieldName, - const std::string &value) +void JniPlatformInfo::setFieldValue(jobject jPlatformInfo, const std::string &fieldName, + const std::string &value) { - jfieldID fieldID = m_env->GetFieldID(gSimulatorClassRefs.classPlatformInfo, fieldName.c_str(), + jfieldID fieldID = m_env->GetFieldID(m_env->GetObjectClass(jPlatformInfo), fieldName.c_str(), "Ljava/lang/String;"); jstring valueStr = m_env->NewStringUTF(value.c_str()); m_env->SetObjectField(jPlatformInfo, fieldID, valueStr); } -std::string JPlatformInfo::getFieldValue(jobject jPlatformInfo, const std::string &fieldName) +std::string JniPlatformInfo::getFieldValue(jobject jPlatformInfo, const std::string &fieldName) { - jfieldID fieldID = m_env->GetFieldID(gSimulatorClassRefs.classPlatformInfo, fieldName.c_str(), + jfieldID fieldID = m_env->GetFieldID(m_env->GetObjectClass(jPlatformInfo), fieldName.c_str(), "Ljava/lang/String;"); jstring jvalue = (jstring) m_env->GetObjectField(jPlatformInfo, fieldID); - const char *valueCStr = m_env->GetStringUTFChars(jvalue, NULL); - if (valueCStr) - return std::string(valueCStr); - return std::string(); + JniString value(m_env, jvalue); + return value.get(); } -void JniPlatformInfoListener::onPlatformInfoReceived(PlatformInfo &platformInfo) +void onPlatformInfoReceived(jobject listener, PlatformInfo &platformInfo) { - // Get the environment JNIEnv *env = getEnv(); if (!env) return; - jobject listener = env->NewLocalRef(m_listener); - if (!listener) - { - releaseEnv(); - return; - } - jclass listenerCls = env->GetObjectClass(listener); - if (!listenerCls) - { - releaseEnv(); - return; - } - - jmethodID listenerMId = env->GetMethodID(listenerCls, "onPlatformFound", - "(Lorg/oic/simulator/PlatformInfo;)V"); - if (!listenerMId) - { - releaseEnv(); - return; - } + jmethodID listenerMethodId = env->GetMethodID(listenerCls, "onPlatformFound", + "(Lorg/oic/simulator/PlatformInfo;)V"); - // Convert CPP to Java DeviceInfo object - jobject jPlatformInfo = JPlatformInfo(env).toJava(platformInfo); + jobject jPlatformInfo = JniPlatformInfo(env).toJava(platformInfo); if (!jPlatformInfo) { releaseEnv(); return; } - // Invoke java listener with DeviceInfo - env->CallVoidMethod(listener, listenerMId, jPlatformInfo); + env->CallVoidMethod(listener, listenerMethodId, jPlatformInfo); if (env->ExceptionCheck()) { releaseEnv(); diff --git a/service/simulator/java/jni/simulator_platform_info_jni.h b/service/simulator/java/jni/simulator_platform_info_jni.h index e623b81..ba75df7 100644 --- a/service/simulator/java/jni/simulator_platform_info_jni.h +++ b/service/simulator/java/jni/simulator_platform_info_jni.h @@ -24,16 +24,16 @@ #include "simulator_platform_info.h" #include -class JPlatformInfo +class JniPlatformInfo { public: - JPlatformInfo(JNIEnv *env) : m_env(env) {} - JPlatformInfo(const JPlatformInfo &) = delete; - JPlatformInfo &operator=(const JPlatformInfo &) = delete; - JPlatformInfo(const JPlatformInfo &&) = delete; - JPlatformInfo &operator=(const JPlatformInfo && ) = delete; + JniPlatformInfo(JNIEnv *env) : m_env(env) {} + JniPlatformInfo(const JniPlatformInfo &) = delete; + JniPlatformInfo &operator=(const JniPlatformInfo &) = delete; + JniPlatformInfo(const JniPlatformInfo &&) = delete; + JniPlatformInfo &operator=(const JniPlatformInfo && ) = delete; jobject toJava(PlatformInfo &platformInfo); - PlatformInfo toCPP(jobject jPlatformInfo); + PlatformInfo toCpp(jobject jPlatformInfo); private: void setFieldValue(jobject jPlatformInfo, const std::string &fieldName, @@ -43,18 +43,6 @@ class JPlatformInfo JNIEnv *m_env; }; -class JniPlatformInfoListener -{ - public: - JniPlatformInfoListener(JNIEnv *env, jobject listener) - { - m_listener = env->NewWeakGlobalRef(listener); - } - - void onPlatformInfoReceived(PlatformInfo &platformInfo); - - private: - jweak m_listener; -}; +void onPlatformInfoReceived(jobject listener, PlatformInfo &platformInfo); #endif diff --git a/service/simulator/java/jni/simulator_remote_resource_jni.cpp b/service/simulator/java/jni/simulator_remote_resource_jni.cpp index 63215b6..f413696 100644 --- a/service/simulator/java/jni/simulator_remote_resource_jni.cpp +++ b/service/simulator/java/jni/simulator_remote_resource_jni.cpp @@ -18,822 +18,375 @@ * ******************************************************************/ -#include "simulator_remote_resource_jni.h" -#include "simulator_common_jni.h" -#include "simulator_error_codes.h" -#include "simulator_resource_jni_util.h" #include "simulator_resource_model_jni.h" -#include "simulator_client_types.h" -#include "simulator_exceptions.h" -#include "simulator_jni_utils.h" +#include "simulator_exceptions_jni.h" +#include "simulator_utils_jni.h" +#include "jni_sharedobject_holder.h" +#include "jni_listener_holder.h" +#include "jni_queryparam.h" +#include "jni_string.h" +#include "jni_vector.h" -extern SimulatorClassRefs gSimulatorClassRefs; +#include "simulator_remote_resource.h" -SimulatorRemoteResourceSP JniSimulatorRemoteResource::getResourceHandle -(JNIEnv *env, jobject object) -{ - JniSimulatorRemoteResource *jniResource = GetHandle(env, object); - if (env->ExceptionCheck() || !jniResource) - { - return nullptr; - } +#define VALIDATE_OBJECT(ENV, OBJECT) if (!OBJECT){throwBadObjectException(ENV, "No corresponsing native object!"); return;} +#define VALIDATE_OBJECT_RET(ENV, OBJECT, RET) if (!OBJECT){throwBadObjectException(ENV, "No corresponsing native object!"); return RET;} - return jniResource->m_resource; +SimulatorRemoteResourceSP SimulatorRemoteResourceToCpp(JNIEnv *env, jobject object) +{ + JniSharedObjectHolder *jniResource = + GetHandle>(env, object); + if (jniResource) + return jniResource->get(); + return nullptr; } -class JNIOnObserveListener +void onObserveCallback(jobject listener, const std::string &uid, const int errorCode, + SimulatorResourceModelSP representation, const int seq) { - public: - void setJavaOnObserveListener(JNIEnv *env, jobject listener) - { - m_listener = env->NewWeakGlobalRef(listener); - } + JNIEnv *env = getEnv(); + if (!env) + return; - void onObserveCallback(const std::string &uId, const int errorCode, - SimulatorResourceModelSP representation, - const int seqNumber) - { - JNIEnv *env = getEnv(); - if (nullptr == env) - return; - - jobject onObserveListener = env->NewLocalRef(m_listener); - if (!onObserveListener) - { - releaseEnv(); - return; - } - - jclass onObserveCls = env->GetObjectClass(onObserveListener); - if (!onObserveCls) - { - releaseEnv(); - return; - } - - if (OC_STACK_OK != errorCode && OC_STACK_RESOURCE_CREATED != errorCode - && OC_STACK_RESOURCE_DELETED != errorCode) - { - jmethodID midL = env->GetMethodID(onObserveCls, "onObserveFailed", "(Ljava/lang/Throwable;)V"); - if (!midL) - { - releaseEnv(); - return; - } - env->CallVoidMethod(onObserveListener, midL); - } - else - { - JSimulatorResourceModel *jniModel = new JSimulatorResourceModel(representation); - if (!jniModel) - { - releaseEnv(); - return; - } - - jobject jRepresentation = JSimulatorResourceModel::toJava(env, - reinterpret_cast(jniModel)); - if (!jRepresentation) - { - delete jniModel; - releaseEnv(); - return; - } - - jmethodID midL = env->GetMethodID(onObserveCls, "onObserveCompleted", - "(Ljava/lang/String;Lorg/oic/simulator/SimulatorResourceModel;I)V"); - if (!midL) - { - delete jniModel; - releaseEnv(); - return; - } - - jstring jUid = env->NewStringUTF(uId.c_str()); - - env->CallVoidMethod(onObserveListener, midL, jUid, jRepresentation, - static_cast(seqNumber)); - if (env->ExceptionCheck()) - { - delete jniModel; - releaseEnv(); - } - } - } - - private: - jweak m_listener; -}; - -class JNIOnGetListener -{ - public: - void setJavaOnGetListener(JNIEnv *env, jobject listener) - { - m_listener = env->NewWeakGlobalRef(listener); - } + jclass listenerCls = env->GetObjectClass(listener); + jmethodID listenerMethodId = env->GetMethodID(listenerCls, "onObserveNotification", + "(Ljava/lang/String;Lorg/oic/simulator/SimulatorResourceModel;I)V"); - void onGetCallback(const std::string &uId, int errorCode, - SimulatorResourceModelSP representation) - { - JNIEnv *env = getEnv(); - if (nullptr == env) - return; - - jobject onGetListener = env->NewLocalRef(m_listener); - if (!onGetListener) - { - releaseEnv(); - return; - } - - jclass onGetCls = env->GetObjectClass(onGetListener); - if (!onGetCls) - { - releaseEnv(); - return; - } - - // TODO: Revisit is it required? - if (OC_STACK_OK != errorCode && OC_STACK_RESOURCE_CREATED != errorCode - && OC_STACK_RESOURCE_DELETED != errorCode) - { - jmethodID midL = env->GetMethodID(onGetCls, "onGetFailed", "(Ljava/lang/Throwable;)V"); - if (!midL) - { - releaseEnv(); - return; - } - env->CallVoidMethod(onGetListener, midL); - } - else - { - JSimulatorResourceModel *jniModel = new JSimulatorResourceModel(representation); - if (!jniModel) - { - releaseEnv(); - return; - } - - jobject jRepresentation = JSimulatorResourceModel::toJava(env, reinterpret_cast(jniModel)); - if (!jRepresentation) - { - delete jniModel; - releaseEnv(); - return; - } - - jmethodID midL = env->GetMethodID(onGetCls, "onGetCompleted", - "(Ljava/lang/String;Lorg/oic/simulator/SimulatorResourceModel;)V"); - if (!midL) - { - delete jniModel; - releaseEnv(); - return; - } - - jstring jUid = env->NewStringUTF(uId.c_str()); - env->CallVoidMethod(onGetListener, midL, jUid, jRepresentation); - if (env->ExceptionCheck()) - { - delete jniModel; - releaseEnv(); - } - } - } - - private: - jweak m_listener; -}; - -class JNIOnPutListener -{ - public: - void setJavaOnPutListener(JNIEnv *env, jobject listener) - { - m_listener = env->NewWeakGlobalRef(listener); - } + SimulatorResourceModel *resModel = representation.get(); + jobject jResModel = simulatorResourceModelToJava(env, *resModel); + jstring jUid = env->NewStringUTF(uid.c_str()); + env->CallVoidMethod(listener, listenerMethodId, jUid, jResModel, seq); + releaseEnv(); +} - void onPutCallback(const std::string &uId, int errorCode, - SimulatorResourceModelSP representation) - { - JNIEnv *env = getEnv(); - if (nullptr == env) - return; - - jobject onPutListener = env->NewLocalRef(m_listener); - if (!onPutListener) - { - releaseEnv(); - return; - } - - jclass onGetCls = env->GetObjectClass(onPutListener); - if (!onGetCls) - { - releaseEnv(); - return; - } - - // TODO: Revisit is it required? - if (OC_STACK_OK != errorCode && OC_STACK_RESOURCE_CREATED != errorCode - && OC_STACK_RESOURCE_DELETED != errorCode) - { - jmethodID midL = env->GetMethodID(onGetCls, "onPutFailed", "(Ljava/lang/Throwable;)V"); - if (!midL) - { - releaseEnv(); - return; - } - env->CallVoidMethod(onPutListener, midL); - } - else - { - JSimulatorResourceModel *jniModel = new JSimulatorResourceModel(representation); - if (!jniModel) - { - releaseEnv(); - return; - } - - jobject jRepresentation = JSimulatorResourceModel::toJava(env, - reinterpret_cast(jniModel)); - if (!jRepresentation) - { - delete jniModel; - releaseEnv(); - return; - } - - jmethodID midL = env->GetMethodID(onGetCls, "onPutCompleted", - "(Ljava/lang/String;Lorg/oic/simulator/SimulatorResourceModel;)V"); - if (!midL) - { - delete jniModel; - releaseEnv(); - return; - } - - jstring jUid = env->NewStringUTF(uId.c_str()); - env->CallVoidMethod(onPutListener, midL, jUid, jRepresentation); - if (env->ExceptionCheck()) - { - delete jniModel; - releaseEnv(); - } - } - } - - private: - jweak m_listener; -}; - -class JNIOnPostListener +void onGetCallback(jobject listener, const std::string &uid, int errorCode, + SimulatorResourceModelSP representation) { - public: - void setJavaOnPostListener(JNIEnv *env, jobject listener) - { - m_listener = env->NewWeakGlobalRef(listener); - } + JNIEnv *env = getEnv(); + if (!env) + return; - void onPostCallback(const std::string &uId, int errorCode, - SimulatorResourceModelSP representation) - { - JNIEnv *env = getEnv(); - if (nullptr == env) - return; - - jobject onPostListener = env->NewLocalRef(m_listener); - if (!onPostListener) - { - releaseEnv(); - return; - } - - jclass onGetCls = env->GetObjectClass(onPostListener); - if (!onGetCls) - { - releaseEnv(); - return; - } - - // TODO: Revisit is it required? - if (OC_STACK_OK != errorCode && OC_STACK_RESOURCE_CREATED != errorCode - && OC_STACK_RESOURCE_DELETED != errorCode) - { - jmethodID midL = env->GetMethodID(onGetCls, "onPostFailed", "(Ljava/lang/Throwable;)V"); - if (!midL) - { - releaseEnv(); - return; - } - env->CallVoidMethod(onPostListener, midL); - } - else - { - JSimulatorResourceModel *jniModel = new JSimulatorResourceModel(representation); - if (!jniModel) - { - releaseEnv(); - return; - } - - jobject jRepresentation = JSimulatorResourceModel::toJava(env, - reinterpret_cast(jniModel)); - if (!jRepresentation) - { - delete jniModel; - releaseEnv(); - return; - } - - jmethodID midL = env->GetMethodID(onGetCls, "onPostCompleted", - "(Ljava/lang/String;Lorg/oic/simulator/SimulatorResourceModel;)V"); - if (!midL) - { - delete jniModel; - releaseEnv(); - return; - } - - jstring jUid = env->NewStringUTF(uId.c_str()); - - env->CallVoidMethod(onPostListener, midL, jUid, jRepresentation); - if (env->ExceptionCheck()) - { - delete jniModel; - releaseEnv(); - } - } - } - - private: - jweak m_listener; - -}; - -class JNIOnVerificationListener -{ - public: - void setJavaOnVerificationListener(JNIEnv *env, jobject listener) - { - m_listener = env->NewWeakGlobalRef(listener); - } + jclass listenerCls = env->GetObjectClass(listener); + jmethodID listenerMethodId = env->GetMethodID(listenerCls, "onGetResponse", + "(Ljava/lang/String;Lorg/oic/simulator/SimulatorResult;Lorg/oic/simulator/SimulatorResourceModel;)V"); - void onVerificationCallback(const std::string &uId, int id, OperationState opState) - { - JNIEnv *env = getEnv(); - if (nullptr == env) - return; - - jobject onVerificationListener = env->NewLocalRef(m_listener); - if (!onVerificationListener) - { - releaseEnv(); - return; - } - - jclass onVerificationCls = env->GetObjectClass(onVerificationListener); - if (!onVerificationCls) - { - releaseEnv(); - return; - } - - jmethodID midL; - - if (OP_START == opState) - { - midL = env->GetMethodID(onVerificationCls, "onVerificationStarted", "(Ljava/lang/String;I)V"); - } - else if (OP_COMPLETE == opState) - { - midL = env->GetMethodID(onVerificationCls, "onVerificationCompleted", "(Ljava/lang/String;I)V"); - } - else - { - midL = env->GetMethodID(onVerificationCls, "onVerificationAborted", "(Ljava/lang/String;I)V"); - } - - if (!midL) - { - releaseEnv(); - return; - } - - jstring jUid = env->NewStringUTF(uId.c_str()); - - env->CallVoidMethod(onVerificationListener, midL, jUid, (jint)id); - - if (env->ExceptionCheck()) - { - releaseEnv(); - } - } - - private: - jweak m_listener; - -}; + SimulatorResourceModel *resModel = representation.get(); + jobject jResModel = simulatorResourceModelToJava(env, *resModel); + jstring jUid = env->NewStringUTF(uid.c_str()); + env->CallVoidMethod(listener, listenerMethodId, jUid, + simulatorResultToJava(env, static_cast(errorCode)), jResModel); + releaseEnv(); +} -JNIEXPORT void JNICALL -Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_startObserve -(JNIEnv *env, jobject thiz, jint observeType, jobject jQueryParamsMap, jobject jListener) +void onPutCallback(jobject listener, const std::string &uid, int errorCode, + SimulatorResourceModelSP representation) { - if (!jListener) - { - throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, "Invalid callback!"); + JNIEnv *env = getEnv(); + if (!env) return; - } - SimulatorRemoteResourceSP resource = JniSimulatorRemoteResource::getResourceHandle(env, - thiz); - if (!resource) - { - throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!"); - return; - } + jclass listenerCls = env->GetObjectClass(listener); + jmethodID listenerMethodId = env->GetMethodID(listenerCls, "onPutResponse", + "(Ljava/lang/String;Lorg/oic/simulator/SimulatorResult;Lorg/oic/simulator/SimulatorResourceModel;)V"); - std::map queryParams; - if (jQueryParamsMap) - convertJavaMapToQueryParamsMap(env, jQueryParamsMap, queryParams); + SimulatorResourceModel *resModel = representation.get(); + jobject jResModel = simulatorResourceModelToJava(env, *resModel); + jstring jUid = env->NewStringUTF(uid.c_str()); + env->CallVoidMethod(listener, listenerMethodId, jUid, + simulatorResultToJava(env, static_cast(errorCode)), jResModel); - ObserveType type = ObserveType::OBSERVE; - if (1 == observeType) - type = ObserveType::OBSERVE_ALL; + releaseEnv(); +} - JNIOnObserveListener *onObserveListener = new JNIOnObserveListener(); - onObserveListener->setJavaOnObserveListener(env, jListener); +void onPostCallback(jobject listener, const std::string &uid, int errorCode, + SimulatorResourceModelSP representation) +{ + JNIEnv *env = getEnv(); + if (!env) + return; - try - { - resource->observe(type, - std::bind(&JNIOnObserveListener::onObserveCallback, - onObserveListener, std::placeholders::_1, - std::placeholders::_2, std::placeholders::_3, - std::placeholders::_4)); - } - catch (InvalidArgsException &e) - { - throwInvalidArgsException(env, e.code(), e.what()); - } - catch (SimulatorException &e) - { - throwSimulatorException(env, e.code(), e.what()); - } - catch (...) - { - throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception"); - } + jclass listenerCls = env->GetObjectClass(listener); + jmethodID listenerMethodId = env->GetMethodID(listenerCls, "onPostResponse", + "(Ljava/lang/String;Lorg/oic/simulator/SimulatorResult;Lorg/oic/simulator/SimulatorResourceModel;)V"); + + SimulatorResourceModel *resModel = representation.get(); + jobject jResModel = simulatorResourceModelToJava(env, *resModel); + jstring jUid = env->NewStringUTF(uid.c_str()); + env->CallVoidMethod(listener, listenerMethodId, jUid, + simulatorResultToJava(env, static_cast(errorCode)), jResModel); + + releaseEnv(); } -JNIEXPORT void JNICALL -Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_stopObserve -(JNIEnv *env, jobject thiz) +void onVerificationCallback(jobject listener, const std::string &uid, int id, + OperationState opState) { - SimulatorRemoteResourceSP resource = JniSimulatorRemoteResource::getResourceHandle(env, - thiz); - if (!resource) - { - throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!"); + JNIEnv *env = getEnv(); + if (!env) return; - } - try + jclass listenerCls = env->GetObjectClass(listener); + jmethodID listenerMethodId; + if (OP_START == opState) { - resource->cancelObserve(); + listenerMethodId = env->GetMethodID(listenerCls, "onVerificationStarted", "(Ljava/lang/String;I)V"); } - catch (SimulatorException &e) + else if (OP_COMPLETE == opState) { - throwSimulatorException(env, e.code(), e.what()); + listenerMethodId = env->GetMethodID(listenerCls, "onVerificationCompleted", + "(Ljava/lang/String;I)V"); } - catch (...) + else if (OP_ABORT == opState) { - throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception"); + listenerMethodId = env->GetMethodID(listenerCls, "onVerificationAborted", "(Ljava/lang/String;I)V"); } + + jstring jUid = env->NewStringUTF(uid.c_str()); + env->CallVoidMethod(listener, listenerMethodId, jUid, id); + + if (OP_COMPLETE == opState || OP_ABORT == opState) + env->DeleteGlobalRef(listener); + releaseEnv(); } +#ifdef __cplusplus +extern "C" { +#endif + JNIEXPORT void JNICALL -Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_nativeGet -(JNIEnv *env, jobject thiz, jstring jResourceInterface, - jobject jQueryParamsMap, jobject jListener) +Java_org_oic_simulator_client_SimulatorRemoteResource_nativeGet +(JNIEnv *env, jobject object, jstring resInterface, jobject queryParamsMap, jobject listener) { - if (!jListener) - { - throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, "Invalid callback!"); - return; - } + VALIDATE_CALLBACK(env, listener) - SimulatorRemoteResourceSP resource = JniSimulatorRemoteResource::getResourceHandle(env, - thiz); - if (!resource) - { - throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!"); - return; - } + SimulatorRemoteResourceSP resource = SimulatorRemoteResourceToCpp(env, object); + VALIDATE_OBJECT(env, resource) - // Interface type - const char *interfaceCStr = NULL; - std::string interfaceType; - if (jResourceInterface) + try { - interfaceCStr = env->GetStringUTFChars(jResourceInterface, NULL); - interfaceType = interfaceCStr; - } - - // Query parameters - std::map queryParams; - if (jQueryParamsMap) - convertJavaMapToQueryParamsMap(env, jQueryParamsMap, queryParams); + JniString jniInterface(env, resInterface); + std::map queryParams = + JniQueryParameter(env).toCpp(queryParamsMap); - // Create listener - JNIOnGetListener *onGetListener = new JNIOnGetListener(); - onGetListener->setJavaOnGetListener(env, jListener); + SimulatorRemoteResource::ResponseCallback callback = std::bind([]( + const std::string & uid, int errorCode, SimulatorResourceModelSP representation, + const std::shared_ptr &listenerRef) + { + onGetCallback(listenerRef->get(), uid, errorCode, representation); + }, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, + JniListenerHolder::create(env, listener)); - try - { - resource->get(interfaceType, - queryParams, - std::bind(&JNIOnGetListener::onGetCallback, - onGetListener, std::placeholders::_1, - std::placeholders::_2, std::placeholders::_3)); + resource->get(jniInterface.get(), queryParams, callback); } catch (InvalidArgsException &e) { throwInvalidArgsException(env, e.code(), e.what()); - return; } catch (NoSupportException &e) { - throwNoSupportException(env, e.code(), e.what()); - return; + throwNoSupportException(env, e.what()); } catch (SimulatorException &e) { throwSimulatorException(env, e.code(), e.what()); - return; } - catch (...) - { - throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception"); - return; - } - - if (interfaceCStr) - env->ReleaseStringUTFChars(jResourceInterface, interfaceCStr); } JNIEXPORT void JNICALL -Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_nativePut -(JNIEnv *env, jobject thiz, jstring jResourceInterface, - jobject jRepresentation, jobject jQueryParamsMap, jobject jListener) +Java_org_oic_simulator_client_SimulatorRemoteResource_nativePut +(JNIEnv *env, jobject object, jstring resInterface, jobject queryParamsMap, + jobject representation, jobject listener) { - if (!jListener) - { - throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, "Invalid callback!"); - return; - } + VALIDATE_CALLBACK(env, listener) - SimulatorRemoteResourceSP resource = JniSimulatorRemoteResource::getResourceHandle(env, - thiz); - if (!resource) - { - throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!"); - return; - } + SimulatorRemoteResourceSP resource = SimulatorRemoteResourceToCpp(env, object); + VALIDATE_OBJECT(env, resource) - // Interface type - const char *interfaceCStr = NULL; - std::string interfaceType; - if (jResourceInterface) + try { - interfaceCStr = env->GetStringUTFChars(jResourceInterface, NULL); - interfaceType = interfaceCStr; - } - - // Query parameters - std::map queryParams; - if (jQueryParamsMap) - convertJavaMapToQueryParamsMap(env, jQueryParamsMap, queryParams); + JniString jniInterface(env, resInterface); + std::map queryParams = + JniQueryParameter(env).toCpp(queryParamsMap); - SimulatorResourceModelSP resourceModel = - JSimulatorResourceModel::getResourceModelPtr(env, jRepresentation); + SimulatorResourceModel resModel; + simulatorResourceModelToCpp(env, representation, resModel); + SimulatorResourceModelSP resModelSP(new SimulatorResourceModel(resModel)); - // Create listener - JNIOnPutListener *onPutListener = new JNIOnPutListener(); - onPutListener->setJavaOnPutListener(env, jListener); + SimulatorRemoteResource::ResponseCallback callback = std::bind([]( + const std::string & uid, int errorCode, SimulatorResourceModelSP representation, + const std::shared_ptr &listenerRef) + { + onPutCallback(listenerRef->get(), uid, errorCode, representation); + }, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, + JniListenerHolder::create(env, listener)); - try - { - resource->put(interfaceType, - queryParams, - resourceModel, - std::bind(&JNIOnPutListener::onPutCallback, - onPutListener, std::placeholders::_1, - std::placeholders::_2, std::placeholders::_3)); + resource->put(jniInterface.get(), queryParams, resModelSP, callback); } catch (InvalidArgsException &e) { throwInvalidArgsException(env, e.code(), e.what()); - return; } catch (NoSupportException &e) { - throwNoSupportException(env, e.code(), e.what()); - return; + throwNoSupportException(env, e.what()); } catch (SimulatorException &e) { throwSimulatorException(env, e.code(), e.what()); - return; } - catch (...) - { - throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception"); - return; - } - - if (interfaceCStr) - env->ReleaseStringUTFChars(jResourceInterface, interfaceCStr); } JNIEXPORT void JNICALL -Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_nativePost -(JNIEnv *env, jobject thiz, jstring jResourceInterface, - jobject jRepresentation, jobject jQueryParamsMap, jobject jListener) +Java_org_oic_simulator_client_SimulatorRemoteResource_nativePost +(JNIEnv *env, jobject object, jstring resInterface, jobject queryParamsMap, + jobject representation, jobject listener) { - if (!jListener) - { - throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, "Invalid callback!"); - return; - } + VALIDATE_CALLBACK(env, listener) - SimulatorRemoteResourceSP resource = JniSimulatorRemoteResource::getResourceHandle(env, - thiz); - if (!resource) - { - throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!"); - return; - } + SimulatorRemoteResourceSP resource = SimulatorRemoteResourceToCpp(env, object); + VALIDATE_OBJECT(env, resource) - // Interface type - const char *interfaceCStr = NULL; - std::string interfaceType; - if (jResourceInterface) + try { - interfaceCStr = env->GetStringUTFChars(jResourceInterface, NULL); - interfaceType = interfaceCStr; - } - - // Query parameters - std::map queryParams; - if (jQueryParamsMap) - convertJavaMapToQueryParamsMap(env, jQueryParamsMap, queryParams); + JniString jniInterface(env, resInterface); + std::map queryParams = + JniQueryParameter(env).toCpp(queryParamsMap); - SimulatorResourceModelSP resourceModel = - JSimulatorResourceModel::getResourceModelPtr(env, jRepresentation); + SimulatorResourceModel resModel; + simulatorResourceModelToCpp(env, representation, resModel); + SimulatorResourceModelSP resModelSP(new SimulatorResourceModel(resModel)); - // Create listener - JNIOnPostListener *onPostListener = new JNIOnPostListener(); - onPostListener->setJavaOnPostListener(env, jListener); + SimulatorRemoteResource::ResponseCallback callback = std::bind([]( + const std::string & uid, int errorCode, SimulatorResourceModelSP representation, + const std::shared_ptr &listenerRef) + { + onPostCallback(listenerRef->get(), uid, errorCode, representation); + }, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, + JniListenerHolder::create(env, listener)); - try - { - resource->post(interfaceType, - queryParams, - resourceModel, - std::bind(&JNIOnPostListener::onPostCallback, - onPostListener, std::placeholders::_1, - std::placeholders::_2, std::placeholders::_3)); + resource->post(jniInterface.get(), queryParams, resModelSP, callback); } catch (InvalidArgsException &e) { throwInvalidArgsException(env, e.code(), e.what()); - return; } catch (NoSupportException &e) { - throwNoSupportException(env, e.code(), e.what()); - return; + throwNoSupportException(env, e.what()); } catch (SimulatorException &e) { throwSimulatorException(env, e.code(), e.what()); - return; - } - catch (...) - { - throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception"); - return; } - - if (interfaceCStr) - env->ReleaseStringUTFChars(jResourceInterface, interfaceCStr); } -JNIEXPORT void JNICALL -Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_setConfigInfo -(JNIEnv *env, jobject thiz, jstring jConfigPath) +JNIEXPORT jobject JNICALL +Java_org_oic_simulator_client_SimulatorRemoteResource_setConfigInfo +(JNIEnv *env, jobject object, jstring configPath) { - if (!jConfigPath) - { - throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, - "Configuration file path is null!"); - return; - } + VALIDATE_INPUT_RET(env, !configPath, "Path is null!", nullptr) - SimulatorRemoteResourceSP resource = JniSimulatorRemoteResource::getResourceHandle(env, - thiz); - if (!resource) + SimulatorRemoteResourceSP resource = SimulatorRemoteResourceToCpp(env, object); + VALIDATE_OBJECT_RET(env, resource, nullptr) + + try { - throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!"); - return; + JniString jniConfigPath(env, configPath); + SimulatorResourceModelSP repSchema = resource->configure(jniConfigPath.get()); + return simulatorResourceModelToJava(env, *(repSchema.get())); } - - // Interface type - const char *configCStr = NULL; - std::string configPath; - if (jConfigPath) + catch (InvalidArgsException &e) { - configCStr = env->GetStringUTFChars(jConfigPath, NULL); - configPath = configCStr; + throwInvalidArgsException(env, e.code(), e.what()); } + return nullptr; +} + +JNIEXPORT void JNICALL +Java_org_oic_simulator_client_SimulatorRemoteResource_startObserve +(JNIEnv *env, jobject object, jobject queryParamsMap, jobject listener) +{ + VALIDATE_CALLBACK(env, listener) + + SimulatorRemoteResourceSP resource = SimulatorRemoteResourceToCpp(env, object); + VALIDATE_OBJECT(env, resource) + try { - resource->configure(configPath); + std::map queryParams = + JniQueryParameter(env).toCpp(queryParamsMap); + + SimulatorRemoteResource::ObserveNotificationCallback callback = std::bind([]( + const std::string & uid, const int errorCode, + SimulatorResourceModelSP representation, const int seq, + const std::shared_ptr &listenerRef) + { + onObserveCallback(listenerRef->get(), uid, errorCode, representation, seq); + }, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, + std::placeholders::_4, JniListenerHolder::create(env, listener)); + + resource->observe(ObserveType::OBSERVE, callback); } catch (InvalidArgsException &e) { throwInvalidArgsException(env, e.code(), e.what()); - return; } - catch (...) + catch (SimulatorException &e) { - throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception"); - return; + throwSimulatorException(env, e.code(), e.what()); } - - if (configCStr) - env->ReleaseStringUTFChars(jConfigPath, configCStr); } -JNIEXPORT jint JNICALL -Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_startVerification -(JNIEnv *env, jobject thiz, jint jReqType, jobject jListener) +JNIEXPORT void JNICALL +Java_org_oic_simulator_client_SimulatorRemoteResource_stopObserve +(JNIEnv *env, jobject object) { - if (!jListener) - { - throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, "Invalid callback!"); - return SIMULATOR_INVALID_CALLBACK; - } + SimulatorRemoteResourceSP resource = SimulatorRemoteResourceToCpp(env, object); + VALIDATE_OBJECT(env, resource) - SimulatorRemoteResourceSP resource = JniSimulatorRemoteResource::getResourceHandle(env, - thiz); - if (!resource) + try { - throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!"); - return SIMULATOR_BAD_OBJECT; + resource->cancelObserve(); } - - // Convert RequestType - RequestType reqType; - - switch (jReqType) + catch (SimulatorException &e) { - case 0: - reqType = RequestType::RQ_TYPE_GET; - break; - - case 1: - reqType = RequestType::RQ_TYPE_PUT; - break; + throwSimulatorException(env, e.code(), e.what()); + } +} - case 2: - reqType = RequestType::RQ_TYPE_POST; - break; +JNIEXPORT jint JNICALL +Java_org_oic_simulator_client_SimulatorRemoteResource_startVerification +(JNIEnv *env, jobject object, jint reqType, jobject listener) +{ + VALIDATE_CALLBACK_RET(env, listener, -1) - case 3: - reqType = RequestType::RQ_TYPE_DELETE; - break; + SimulatorRemoteResourceSP resource = SimulatorRemoteResourceToCpp(env, object); + VALIDATE_OBJECT_RET(env, resource, -1) - default: - return -1; + // Convert RequestType + RequestType type; + switch (reqType) + { + case 0: type = RequestType::RQ_TYPE_GET; break; + case 1: type = RequestType::RQ_TYPE_PUT; break; + case 2: type = RequestType::RQ_TYPE_POST; break; + case 3: type = RequestType::RQ_TYPE_DELETE; break; + default: return -1; } - // Create listener - JNIOnVerificationListener *onVerificationListener = new JNIOnVerificationListener(); - onVerificationListener->setJavaOnVerificationListener(env, jListener); - - int automationId = -1; - try { - automationId = resource->startVerification(reqType, - std::bind(&JNIOnVerificationListener::onVerificationCallback, - onVerificationListener, std::placeholders::_1, - std::placeholders::_2, std::placeholders::_3)); + SimulatorRemoteResource::StateCallback callback = std::bind([]( + const std::string & uid, int id, OperationState opState, + const std::shared_ptr &listenerRef) + { + onVerificationCallback(listenerRef->get(), uid, id, opState); + }, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, + JniListenerHolder::create(env, listener)); + + return resource->startVerification(type, callback); } catch (InvalidArgsException &e) { @@ -841,39 +394,30 @@ Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_startVerificatio } catch (NoSupportException &e) { - throwNoSupportException(env, e.code(), e.what()); + throwNoSupportException(env, e.what()); } catch (OperationInProgressException &e) { - throwOperationInProgressException(env, e.code(), e.what()); + throwOperationInProgressException(env, e.what()); } catch (SimulatorException &e) { throwSimulatorException(env, e.code(), e.what()); } - catch (...) - { - throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception"); - } - return automationId; + return -1; } JNIEXPORT void JNICALL -Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_stopVerification -(JNIEnv *env, jobject thiz, jint jId) +Java_org_oic_simulator_client_SimulatorRemoteResource_stopVerification +(JNIEnv *env, jobject object, jint id) { - SimulatorRemoteResourceSP resource = JniSimulatorRemoteResource::getResourceHandle(env, - thiz); - if (!resource) - { - throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!"); - return; - } + SimulatorRemoteResourceSP resource = SimulatorRemoteResourceToCpp(env, object); + VALIDATE_OBJECT(env, resource) try { - resource->stopVerification((int)jId); + resource->stopVerification(id); } catch (InvalidArgsException &e) { @@ -881,17 +425,19 @@ Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_stopVerification } catch (NoSupportException &e) { - throwNoSupportException(env, e.code(), e.what()); - } - catch (...) - { - throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception"); + throwNoSupportException(env, e.what()); } } -JNIEXPORT void JNICALL Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_dispose -(JNIEnv *env, jobject thiz) +JNIEXPORT void JNICALL +Java_org_oic_simulator_client_SimulatorRemoteResource_dispose +(JNIEnv *env, jobject object) { - JniSimulatorRemoteResource *resource = GetHandle(env, thiz); + JniSharedObjectHolder *resource = + GetHandle>(env, object); delete resource; -} \ No newline at end of file +} + +#ifdef __cplusplus +} +#endif diff --git a/service/simulator/java/jni/simulator_remote_resource_jni.h b/service/simulator/java/jni/simulator_remote_resource_jni.h deleted file mode 100644 index b1fbecd..0000000 --- a/service/simulator/java/jni/simulator_remote_resource_jni.h +++ /dev/null @@ -1,85 +0,0 @@ -/****************************************************************** - * - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************/ - -#ifndef SIMULATOR_REMOTE_RESOURCE_JNI_H_ -#define SIMULATOR_REMOTE_RESOURCE_JNI_H_ - -#include -#include "simulator_remote_resource.h" - -class JniSimulatorRemoteResource -{ - public: - JniSimulatorRemoteResource(SimulatorRemoteResourceSP &resource) - : m_resource(resource) {}; - static SimulatorRemoteResourceSP getResourceHandle(JNIEnv *env, jobject object); - private: - SimulatorRemoteResourceSP m_resource; -}; - -#ifdef __cplusplus -extern "C" { -#endif - -JNIEXPORT void JNICALL -Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_startObserve -(JNIEnv *env, jobject thiz, jint observeType, jobject jQueryParamsMap, jobject jListener); - -JNIEXPORT void JNICALL -Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_stopObserve -(JNIEnv *env, jobject thiz); - -JNIEXPORT void JNICALL -Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_nativeGet -(JNIEnv *env, jobject thiz, jstring jResourceInterface, - jobject jQueryParamsMap, jobject jListener); - -JNIEXPORT void JNICALL -Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_nativePut -(JNIEnv *env, jobject thiz, jstring jResourceInterface, - jobject jRepresentation, jobject jQueryParamsMap, jobject jListener); - -JNIEXPORT void JNICALL -Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_nativePost -(JNIEnv *env, jobject thiz, jstring jResourceInterface, - jobject jRepresentation, jobject jQueryParamsMap, jobject jListener); - -JNIEXPORT void JNICALL -Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_setConfigInfo -(JNIEnv *env, jobject thiz, jstring jConfigPath); - -JNIEXPORT jint JNICALL -Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_startVerification -(JNIEnv *env, jobject thiz, jint jReqType, jobject jListener); - -JNIEXPORT void JNICALL -Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_stopVerification -(JNIEnv *env, jobject thiz, jint jId); - -JNIEXPORT void JNICALL -Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_dispose -(JNIEnv *, jobject); - -#ifdef __cplusplus -} -#endif - -#endif - diff --git a/service/simulator/java/jni/simulator_resource_jni.cpp b/service/simulator/java/jni/simulator_resource_jni.cpp new file mode 100644 index 0000000..334b5b5 --- /dev/null +++ b/service/simulator/java/jni/simulator_resource_jni.cpp @@ -0,0 +1,470 @@ +/****************************************************************** + * + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +#include "simulator_resource_model_jni.h" +#include "simulator_exceptions_jni.h" +#include "simulator_utils_jni.h" +#include "jni_sharedobject_holder.h" +#include "jni_listener_holder.h" +#include "jni_string.h" +#include "jni_vector.h" + +#include "simulator_resource.h" + +#define VALIDATE_OBJECT(ENV, OBJECT) if (!OBJECT){throwBadObjectException(ENV, "No corresponsing native object!"); return;} +#define VALIDATE_OBJECT_RET(ENV, OBJECT, RET) if (!OBJECT){throwBadObjectException(ENV, "No corresponsing native object!"); return RET;} + +SimulatorResourceSP SimulatorResourceToCpp(JNIEnv *env, jobject object) +{ + JniSharedObjectHolder *jniResource = + GetHandle>(env, object); + if (jniResource) + return jniResource->get(); + return nullptr; +} + +static jobject resourceTypeToJava(JNIEnv *env, SimulatorResource::Type type) +{ + static jfieldID single = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResourceTypeCls, + "SINGLE", "Lorg/oic/simulator/server/SimulatorResource$Type;"); + static jfieldID collection = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResourceTypeCls, + "COLLECTION", "Lorg/oic/simulator/server/SimulatorResource$Type;"); + + switch (type) + { + case SimulatorResource::Type::SINGLE_RESOURCE: + return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResourceTypeCls, single); + case SimulatorResource::Type::COLLECTION_RESOURCE: + return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResourceTypeCls, collection); + } + + return nullptr; +} + +static jobject createObserverInfo(JNIEnv *env, const ObserverInfo &observerInfo) +{ + static jmethodID observerInfoCtor = env->GetMethodID(gSimulatorClassRefs.observerCls, + "", "(ILjava/lang/String;I)V"); + + jstring address = env->NewStringUTF(observerInfo.address.c_str()); + jobject observer = (jobject) env->NewObject(gSimulatorClassRefs.observerCls, + observerInfoCtor, observerInfo.id, address, observerInfo.port); + env->DeleteLocalRef(address); + + return observer; +} + +static jobject createObserverInfoVector(JNIEnv *env, + const std::vector observersList) +{ + jobject vectorObject = JniVector(env).toJava(); + if (!vectorObject) + return nullptr; + + static jmethodID addMethod = env->GetMethodID(gSimulatorClassRefs.vectorCls, + "add", "(Ljava/lang/Object;)Z"); + + for (auto &observer : observersList) + env->CallBooleanMethod(vectorObject, addMethod, createObserverInfo(env, observer)); + + return vectorObject; +} + +static void onObserverChange(jobject listener, const std::string &uri, + ObservationStatus state, const ObserverInfo &observerInfo) +{ + JNIEnv *env = getEnv(); + if (!env) + return; + + jclass listenerCls = env->GetObjectClass(listener); + jmethodID listenerMethod = nullptr; + if (ObservationStatus::REGISTER == state) + { + listenerMethod = env->GetMethodID(listenerCls, "onObserverAdded", + "(Ljava/lang/String;Lorg/oic/simulator/server/Observer;)V"); + } + else + { + listenerMethod = env->GetMethodID(listenerCls, "onObserverRemoved", + "(Ljava/lang/String;Lorg/oic/simulator/server/Observer;)V"); + } + + jstring jUri = env->NewStringUTF(uri.c_str()); + jobject jobserver = createObserverInfo(env, observerInfo); + + env->CallVoidMethod(listener, listenerMethod, jUri, jobserver); + releaseEnv(); +} + +static void onResourceModelChange(jobject listener, const std::string &uri, + SimulatorResourceModel &resModel) +{ + JNIEnv *env = getEnv(); + if (!env) + return; + + jclass listenerCls = env->GetObjectClass(listener); + jmethodID listenerMethod = env->GetMethodID(listenerCls, "onResourceModelChanged", + "(Ljava/lang/String;Lorg/oic/simulator/SimulatorResourceModel;)V"); + + jobject jResModel = simulatorResourceModelToJava(env, resModel); + jstring jUri = env->NewStringUTF(uri.c_str()); + env->CallVoidMethod(listener, listenerMethod, jUri, jResModel); + releaseEnv(); +} + +#ifdef __cplusplus +extern "C" { +#endif + +JNIEXPORT jstring JNICALL +Java_org_oic_simulator_server_SimulatorResource_getName +(JNIEnv *env, jobject object) +{ + SimulatorResourceSP resource = SimulatorResourceToCpp(env, object); + VALIDATE_OBJECT_RET(env, resource, nullptr) + + return env->NewStringUTF(resource->getName().c_str()); +} + +JNIEXPORT jobject JNICALL +Java_org_oic_simulator_server_SimulatorResource_getType +(JNIEnv *env, jobject object) +{ + SimulatorResourceSP resource = SimulatorResourceToCpp(env, object); + VALIDATE_OBJECT_RET(env, resource, nullptr) + + return resourceTypeToJava(env, resource->getType()); +} + +JNIEXPORT jstring JNICALL +Java_org_oic_simulator_server_SimulatorResource_getURI +(JNIEnv *env, jobject object) +{ + SimulatorResourceSP resource = SimulatorResourceToCpp(env, object); + VALIDATE_OBJECT_RET(env, resource, nullptr) + + return env->NewStringUTF(resource->getURI().c_str()); +} + +JNIEXPORT jstring JNICALL +Java_org_oic_simulator_server_SimulatorResource_getResourceType +(JNIEnv *env, jobject object) +{ + SimulatorResourceSP resource = SimulatorResourceToCpp(env, object); + VALIDATE_OBJECT_RET(env, resource, nullptr) + + return env->NewStringUTF(resource->getResourceType().c_str()); +} + +JNIEXPORT jobject JNICALL +Java_org_oic_simulator_server_SimulatorResource_getInterface +(JNIEnv *env, jobject object) +{ + SimulatorResourceSP resource = SimulatorResourceToCpp(env, object); + VALIDATE_OBJECT_RET(env, resource, nullptr) + + std::vector interfaces = resource->getInterface(); + return JniVector(env).toJava(interfaces); +} + +JNIEXPORT jboolean JNICALL +Java_org_oic_simulator_server_SimulatorResource_isObservable +(JNIEnv *env, jobject object) +{ + SimulatorResourceSP resource = SimulatorResourceToCpp(env, object); + VALIDATE_OBJECT_RET(env, resource, false) + + return resource->isObservable(); +} + +JNIEXPORT jboolean JNICALL +Java_org_oic_simulator_server_SimulatorResource_isStarted +(JNIEnv *env, jobject object) +{ + SimulatorResourceSP resource = SimulatorResourceToCpp(env, object); + VALIDATE_OBJECT_RET(env, resource, false) + + return resource->isStarted(); +} + +JNIEXPORT jobject JNICALL +Java_org_oic_simulator_server_SimulatorResource_getResourceModel +(JNIEnv *env, jobject object) +{ + SimulatorResourceSP resource = SimulatorResourceToCpp(env, object); + VALIDATE_OBJECT_RET(env, resource, nullptr) + + SimulatorResourceModel resModel = resource->getResourceModel(); + return simulatorResourceModelToJava(env, resModel); +} + +JNIEXPORT void JNICALL +Java_org_oic_simulator_server_SimulatorResource_setName +(JNIEnv *env, jobject object, jstring name) +{ + VALIDATE_INPUT(env, !name, "Name is null!") + + SimulatorResourceSP resource = SimulatorResourceToCpp(env, object); + VALIDATE_OBJECT(env, resource) + + try + { + JniString jniName(env, name); + resource->setName(jniName.get()); + } + catch (InvalidArgsException &e) + { + throwInvalidArgsException(env, e.code(), e.what()); + } + catch (SimulatorException &e) + { + throwInvalidArgsException(env, e.code(), e.what()); + } +} + +JNIEXPORT void JNICALL +Java_org_oic_simulator_server_SimulatorResource_setURI +(JNIEnv *env, jobject object, jstring uri) +{ + VALIDATE_INPUT(env, !uri, "Uri is null!") + + SimulatorResourceSP resource = SimulatorResourceToCpp(env, object); + VALIDATE_OBJECT(env, resource) + + try + { + JniString jniUri(env, uri); + resource->setURI(jniUri.get()); + } + catch (InvalidArgsException &e) + { + throwInvalidArgsException(env, e.code(), e.what()); + } + catch (SimulatorException &e) + { + throwInvalidArgsException(env, e.code(), e.what()); + } +} + +JNIEXPORT void JNICALL +Java_org_oic_simulator_server_SimulatorResource_setResourceType +(JNIEnv *env, jobject object, jstring resourceType) +{ + VALIDATE_INPUT(env, !resourceType, "Resource type is null!") + + SimulatorResourceSP resource = SimulatorResourceToCpp(env, object); + VALIDATE_OBJECT(env, resource) + + try + { + JniString jniType(env, resourceType); + resource->setResourceType(jniType.get()); + } + catch (InvalidArgsException &e) + { + throwInvalidArgsException(env, e.code(), e.what()); + } + catch (SimulatorException &e) + { + throwInvalidArgsException(env, e.code(), e.what()); + } +} + +JNIEXPORT void JNICALL +Java_org_oic_simulator_server_SimulatorResource_addInterface +(JNIEnv *env, jobject object, jstring interfaceType) +{ + VALIDATE_INPUT(env, !interfaceType, "Interface type is null!") + + SimulatorResourceSP resource = SimulatorResourceToCpp(env, object); + VALIDATE_OBJECT(env, resource) + + try + { + JniString jniInterfaceType(env, interfaceType); + resource->addInterface(jniInterfaceType.get()); + } + catch (InvalidArgsException &e) + { + throwInvalidArgsException(env, e.code(), e.what()); + } + catch (NoSupportException &e) + { + throwNoSupportException(env, e.what()); + } + catch (SimulatorException &e) + { + throwInvalidArgsException(env, e.code(), e.what()); + } +} + +JNIEXPORT void JNICALL +Java_org_oic_simulator_server_SimulatorResource_setObservable +(JNIEnv *env, jobject object, jboolean state) +{ + SimulatorResourceSP resource = SimulatorResourceToCpp(env, object); + VALIDATE_OBJECT(env, resource) + + try + { + resource->setObservable(static_cast(state)); + } + catch (SimulatorException &e) + { + throwInvalidArgsException(env, e.code(), e.what()); + } +} + +JNIEXPORT void JNICALL +Java_org_oic_simulator_server_SimulatorResource_setObserverListener +(JNIEnv *env, jobject object, jobject listener) +{ + VALIDATE_CALLBACK(env, listener) + + SimulatorResourceSP resource = SimulatorResourceToCpp(env, object); + VALIDATE_OBJECT(env, resource) + + SimulatorResource::ObserverCallback callback = std::bind([](const std::string & uri, + ObservationStatus state, const ObserverInfo & observerInfo, + const std::shared_ptr &listenerRef) + { + onObserverChange(listenerRef->get(), uri, state, observerInfo); + }, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, + JniListenerHolder::create(env, listener)); + + try + { + resource->setObserverCallback(callback); + } + catch (InvalidArgsException &e) + { + throwInvalidArgsException(env, e.code(), e.what()); + } +} + +JNIEXPORT void JNICALL +Java_org_oic_simulator_server_SimulatorResource_setResourceModelChangeListener +(JNIEnv *env, jobject object, jobject listener) +{ + VALIDATE_CALLBACK(env, listener) + + SimulatorResourceSP resource = SimulatorResourceToCpp(env, object); + VALIDATE_OBJECT(env, resource) + + SimulatorResource::ResourceModelChangedCallback callback = std::bind( + [](const std::string & uri, SimulatorResourceModel & resModel, + const std::shared_ptr &listenerRef) + { + onResourceModelChange(listenerRef->get(), uri, resModel); + }, std::placeholders::_1, std::placeholders::_2, JniListenerHolder::create(env, listener)); + + try + { + resource->setModelChangeCallback(callback); + } + catch (InvalidArgsException &e) + { + throwInvalidArgsException(env, e.code(), e.what()); + } +} + +JNIEXPORT void JNICALL +Java_org_oic_simulator_server_SimulatorResource_start +(JNIEnv *env, jobject object) +{ + SimulatorResourceSP resource = SimulatorResourceToCpp(env, object); + VALIDATE_OBJECT(env, resource) + + try + { + resource->start(); + } + catch (SimulatorException &e) + { + throwSimulatorException(env, e.code(), e.what()); + } +} + +JNIEXPORT void JNICALL +Java_org_oic_simulator_server_SimulatorResource_stop +(JNIEnv *env, jobject object) +{ + SimulatorResourceSP resource = SimulatorResourceToCpp(env, object); + VALIDATE_OBJECT(env, resource) + + try + { + resource->stop(); + } + catch (SimulatorException &e) + { + throwSimulatorException(env, e.code(), e.what()); + } +} + +JNIEXPORT jobject JNICALL +Java_org_oic_simulator_server_SimulatorResource_getObservers +(JNIEnv *env, jobject object) +{ + SimulatorResourceSP resource = SimulatorResourceToCpp(env, object); + VALIDATE_OBJECT_RET(env, resource, nullptr) + + return createObserverInfoVector(env, resource->getObserversList()); +} + +JNIEXPORT void JNICALL +Java_org_oic_simulator_server_SimulatorResource_notifyObserver +(JNIEnv *env, jobject object, jint id) +{ + SimulatorResourceSP resource = SimulatorResourceToCpp(env, object); + VALIDATE_OBJECT(env, resource) + + try + { + resource->notify(id); + } + catch (SimulatorException &e) + { + throwSimulatorException(env, e.code(), e.what()); + } +} + +JNIEXPORT void JNICALL +Java_org_oic_simulator_server_SimulatorResource_notifyAllObservers +(JNIEnv *env, jobject object) +{ + SimulatorResourceSP resource = SimulatorResourceToCpp(env, object); + VALIDATE_OBJECT(env, resource) + + try + { + resource->notifyAll(); + } + catch (SimulatorException &e) + { + throwSimulatorException(env, e.code(), e.what()); + } +} + +#ifdef __cplusplus +} +#endif \ No newline at end of file diff --git a/service/simulator/java/jni/simulator_resource_jni_util.cpp b/service/simulator/java/jni/simulator_resource_jni_util.cpp deleted file mode 100644 index de2952b..0000000 --- a/service/simulator/java/jni/simulator_resource_jni_util.cpp +++ /dev/null @@ -1,206 +0,0 @@ -/****************************************************************** - * - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************/ -#include "simulator_resource_jni_util.h" -#include "simulator_common_jni.h" - -extern SimulatorClassRefs gSimulatorClassRefs; - -std::vector convertIntegerVector(JNIEnv *env, jobject jVectorInt) -{ - std::vector 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 convertDoubleVector(JNIEnv *env, jobject jVectorDouble) -{ - std::vector 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 convertStringVector(JNIEnv *env, jobject jVectorString) -{ - std::vector 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 &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 &observersList) -{ - if (observersList.empty()) - { - return NULL; - } - - jobject jObserverListMap = env->NewObject(gSimulatorClassRefs.classHashMap, - gSimulatorClassRefs.classHashMapCtor); - - for (auto it = observersList.begin(); it != observersList.end(); ++it) - { - jstring key = (*env).NewStringUTF( (*it).first.c_str() ); - jint value = (*it).second; - env->CallObjectMethod(jObserverListMap, gSimulatorClassRefs.classHashMapPut, key, value); - } - - return jObserverListMap; -} - -jobject convertStringVectorToJavaList(JNIEnv *env, std::vector &vector) -{ - jobject jList = env->NewObject(gSimulatorClassRefs.classLinkedList, - gSimulatorClassRefs.classLinkedListCtor); - if (!jList) return nullptr; - for (size_t i = 0; i < vector.size(); ++i) - { - jstring jStr = env->NewStringUTF(vector[i].c_str()); - if (!jStr) return nullptr; - env->CallBooleanMethod(jList, gSimulatorClassRefs.classLinkedListAddObject, jStr); - if (env->ExceptionCheck()) return nullptr; - env->DeleteLocalRef(jStr); - } - return jList; -} - - diff --git a/service/simulator/java/jni/simulator_resource_jni_util.h b/service/simulator/java/jni/simulator_resource_jni_util.h deleted file mode 100644 index d3c7e70..0000000 --- a/service/simulator/java/jni/simulator_resource_jni_util.h +++ /dev/null @@ -1,77 +0,0 @@ -/****************************************************************** - * - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************/ - -/** - * @file simulator_resource_jni_util.h - * - * @brief This file contains the utility functions for conversions from java to CPP - * and viceversa - */ - -#ifndef __SIMULATOR_RESOURCE_JNI_UTIL_H_ -#define __SIMULATOR_RESOURCE_JNI_UTIL_H_ - -#include -#include -#include -#include - -#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 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 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 convertStringVector(JNIEnv *env, jobject jVectorString); - -void convertJavaMapToQueryParamsMap(JNIEnv *env, jobject hashMap, - std::map &map); - -jobject convertHashMapToJavaMap(JNIEnv *env, - const std::map &observersList); - -jobject convertStringVectorToJavaList(JNIEnv *env, std::vector &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 index 65b9d9d..d363d0b 100644 --- a/service/simulator/java/jni/simulator_resource_model_jni.cpp +++ b/service/simulator/java/jni/simulator_resource_model_jni.cpp @@ -19,345 +19,806 @@ ******************************************************************/ #include "simulator_resource_model_jni.h" -#include "simulator_common_jni.h" -#include "resource_attributes_jni.h" #include "simulator_error_codes.h" -#include "simulator_jni_utils.h" +#include "simulator_exceptions_jni.h" +#include "simulator_utils_jni.h" +#include "jni_string.h" -using namespace std; - -extern SimulatorClassRefs gSimulatorClassRefs; - -JSimulatorResourceModel::JSimulatorResourceModel(SimulatorResourceModel resModel) - : m_resourceModel(resModel) -{} - -JSimulatorResourceModel::JSimulatorResourceModel(SimulatorResourceModelSP resModel) - : m_resModelPtr(resModel) -{} - -bool JSimulatorResourceModel::getResourceModel(JNIEnv *env, jobject thiz, - SimulatorResourceModel &resModel) +class JniTypeInfo { - JSimulatorResourceModel *resource = GetHandle(env, thiz); - if (env->ExceptionCheck()) - { - return false; - } - - if (nullptr != resource->m_resModelPtr) - resModel = *(resource->m_resModelPtr.get()); - else - resModel = resource->m_resourceModel; - return true; -} - -SimulatorResourceModelSP JSimulatorResourceModel::getResourceModelPtr(JNIEnv *env, jobject thiz) + public: + JniTypeInfo(JNIEnv *env) : m_env(env) {} + + SimulatorResourceModel::TypeInfo toCpp(jobject jAttributeValue) + { + static jmethodID typeInfoMID = m_env->GetMethodID(gSimulatorClassRefs.attributeValueCls, + "typeInfo", "()Lorg/oic/simulator/AttributeValue$TypeInfo;"); + static jfieldID typeFID = m_env->GetFieldID(gSimulatorClassRefs.attributeTypeInfoCls, + "mType", "Lorg/oic/simulator/AttributeValue$ValueType;"); + static jfieldID baseTypeFID = m_env->GetFieldID(gSimulatorClassRefs.attributeTypeInfoCls, + "mBaseType", "Lorg/oic/simulator/AttributeValue$ValueType;"); + static jfieldID depthFID = m_env->GetFieldID(gSimulatorClassRefs.attributeTypeInfoCls, + "mDepth", "I"); + + jobject jTypeInfo = m_env->CallObjectMethod(jAttributeValue, typeInfoMID); + jobject jType = m_env->GetObjectField(jTypeInfo, typeFID); + jobject jBaseType = m_env->GetObjectField(jTypeInfo, baseTypeFID); + jint jDepth = m_env->GetIntField(jTypeInfo, depthFID); + + return SimulatorResourceModel::TypeInfo(getValueType(jType), + getValueType(jBaseType), jDepth); + } + + private: + SimulatorResourceModel::ValueType getValueType(jobject jValueType) + { + static jmethodID ordinalMID = m_env->GetMethodID( + gSimulatorClassRefs.attributeValueTypeCls, "ordinal", "()I"); + + int ordinal = m_env->CallIntMethod(jValueType, ordinalMID); + return SimulatorResourceModel::ValueType(ordinal); + } + + JNIEnv *m_env; +}; + +class ValueConverterJava : public boost::static_visitor { - JSimulatorResourceModel *resource = GetHandle(env, thiz); - if (env->ExceptionCheck()) - { - return nullptr; - } - - if (nullptr != resource->m_resModelPtr) - return resource->m_resModelPtr; - return nullptr; -} - -jobject JSimulatorResourceModel::toJava(JNIEnv *env, jlong nativeHandle) + public: + ValueConverterJava(JNIEnv *env) : m_env(env) {} + + jobject operator ()(const int &value) + { + static jmethodID integerCtor = + m_env->GetMethodID(gSimulatorClassRefs.integerCls, "", "(I)V"); + return m_env->NewObject(gSimulatorClassRefs.integerCls, + integerCtor, value); + } + + jobject operator ()(const double &value) + { + static jmethodID doubleCtor = + m_env->GetMethodID(gSimulatorClassRefs.doubleCls, "", "(D)V"); + return m_env->NewObject(gSimulatorClassRefs.doubleCls, + doubleCtor, value); + } + + jobject operator ()(const bool &value) + { + static jmethodID booleanCtor = + m_env->GetMethodID(gSimulatorClassRefs.booleanCls, "", "(Z)V"); + return m_env->NewObject(gSimulatorClassRefs.booleanCls, + booleanCtor, value); + } + + jobject operator ()(const std::string &value) + { + jstring stringValue = m_env->NewStringUTF(value.c_str()); + return static_cast(stringValue); + } + + jobject operator ()(const SimulatorResourceModel &value) + { + return simulatorResourceModelToJava(m_env, const_cast(value)); + } + + template + jobject operator ()(const std::vector &values) + { + jobjectArray jArray = m_env->NewObjectArray(values.size(), getClass(values), nullptr); + if (!jArray) + return nullptr; + + for (size_t index = 0; index < values.size(); index++) + { + jobject element = operator()(values[index]); + m_env->SetObjectArrayElement(jArray, index, element); + } + + return jArray; + } + + template + jobject operator ()(const std::vector> &values) + { + jobjectArray jArray = m_env->NewObjectArray(values.size(), getClass(values), nullptr); + if (!jArray) + return nullptr; + + for (size_t index = 0; index < values.size(); index++) + { + jobject element = operator()(values[index]); + m_env->SetObjectArrayElement(jArray, index, element); + } + + return jArray; + } + + template + jobject operator ()(const std::vector>> &values) + { + jobjectArray jArray = m_env->NewObjectArray(values.size(), getClass(values), nullptr); + if (!jArray) + return nullptr; + + for (size_t index = 0; index < values.size(); index++) + { + jobject element = operator()(values[index]); + m_env->SetObjectArrayElement(jArray, index, element); + } + + return jArray; + } + + private: + jclass getClass(const std::vector &) + { + return gSimulatorClassRefs.integerCls; + } + + jclass getClass(const std::vector> &) + { + return gSimulatorClassRefs.integer1DArrayCls; + } + + jclass getClass(const std::vector>> &) + { + return gSimulatorClassRefs.integer2DArrayCls; + } + + jclass getClass(const std::vector &) + { + return gSimulatorClassRefs.doubleCls; + } + + jclass getClass(const std::vector> &) + { + return gSimulatorClassRefs.double1DArrayCls; + } + + jclass getClass(const std::vector>> &) + { + return gSimulatorClassRefs.double2DArrayCls; + } + + jclass getClass(const std::vector &) + { + return gSimulatorClassRefs.booleanCls; + } + + jclass getClass(const std::vector> &) + { + return gSimulatorClassRefs.boolean1DArrayCls; + } + + jclass getClass(const std::vector>> &) + { + return gSimulatorClassRefs.boolean2DArrayCls; + } + + jclass getClass(const std::vector &) + { + return gSimulatorClassRefs.stringCls; + } + + jclass getClass(const std::vector> &) + { + return gSimulatorClassRefs.string1DArrayCls; + } + + jclass getClass(const std::vector>> &) + { + return gSimulatorClassRefs.string2DArrayCls; + } + + jclass getClass(const std::vector &) + { + return gSimulatorClassRefs.simulatorResourceModelCls; + } + + jclass getClass(const std::vector> &) + { + return gSimulatorClassRefs.simulatorResModel1DArrayCls; + } + + jclass getClass(const std::vector>> &) + { + return gSimulatorClassRefs.simulatorResModel2DArrayCls; + } + + JNIEnv *m_env; +}; + +class ValueConverterCpp { - jobject resourceObj = (jobject) env->NewObject(gSimulatorClassRefs.classSimulatorResourceModel, - gSimulatorClassRefs.classSimulatorResourceModelCtor, nativeHandle); - if (!resourceObj) - { - return NULL; - } - return resourceObj; -} - -void JSimulatorResourceModel::toJava(JNIEnv *env, jobject thiz, jlong nativeHandle) + public: + ValueConverterCpp(JNIEnv *env, SimulatorResourceModel::TypeInfo &typeInfo, + jobject &value) : m_env(env), m_typeInfo(typeInfo), m_value(value) {} + + void convert() + { + switch (m_typeInfo.baseType()) + { + case SimulatorResourceModel::ValueType::INTEGER: + return handleByDepth(); + case SimulatorResourceModel::ValueType::DOUBLE: + return handleByDepth(); + case SimulatorResourceModel::ValueType::BOOLEAN: + return handleByDepth(); + case SimulatorResourceModel::ValueType::STRING: + return handleByDepth(); + case SimulatorResourceModel::ValueType::RESOURCE_MODEL: + return handleByDepth(); + case SimulatorResourceModel::ValueType::VECTOR: + case SimulatorResourceModel::ValueType::UNKNOWN: + break; + } + } + + SimulatorResourceModel::ValueVariant get() + { + return std::move(m_result); + } + + private: + template + void handleByDepth() + { + if (0 == m_typeInfo.depth()) + { + T value; + getValue(m_value, value); + m_result = value; + } + else if (1 == m_typeInfo.depth()) + { + std::vector value; + getValue(m_value, value); + m_result = value; + } + else if (2 == m_typeInfo.depth()) + { + std::vector> value; + getValue(m_value, value); + m_result = value; + } + else if (3 == m_typeInfo.depth()) + { + std::vector>> value; + getValue(m_value, value); + m_result = value; + } + } + + void getValue(jobject &jValue, int &value) + { + static jmethodID intValueMID = m_env->GetMethodID( + gSimulatorClassRefs.integerCls, "intValue", "()I"); + + jint temp = m_env->CallIntMethod(jValue, intValueMID); + value = temp; + } + + void getValue(jobject &jValue, std::vector &value) + { + jobjectArray array = (jobjectArray) jValue; + size_t length = m_env->GetArrayLength(array); + for (size_t i = 0; i < length; i++) + { + jobject jElement = m_env->GetObjectArrayElement(array, i); + + int element; + getValue(jElement, element); + value.push_back(element); + } + } + + void getValue(jobject &jValue, std::vector> &value) + { + jobjectArray array = (jobjectArray) jValue; + size_t length = m_env->GetArrayLength(array); + for (size_t i = 0; i < length; i++) + { + jobject jElement = m_env->GetObjectArrayElement(array, i); + + std::vector element; + getValue(jElement, element); + value.push_back(element); + } + } + + void getValue(jobject &jValue, std::vector>> &value) + { + jobjectArray array = (jobjectArray) jValue; + size_t length = m_env->GetArrayLength(array); + for (size_t i = 0; i < length; i++) + { + jobject jElement = m_env->GetObjectArrayElement(array, i); + + std::vector> element; + getValue(jElement, element); + value.push_back(element); + } + } + + void getValue(jobject &jValue, double &value) + { + static jmethodID doubleValueMID = m_env->GetMethodID( + gSimulatorClassRefs.doubleCls, "doubleValue", "()D"); + + value = m_env->CallDoubleMethod(jValue, doubleValueMID); + } + + void getValue(jobject &jValue, std::vector &value) + { + jobjectArray array = (jobjectArray) jValue; + size_t length = m_env->GetArrayLength(array); + for (size_t i = 0; i < length; i++) + { + jobject jElement = m_env->GetObjectArrayElement(array, i); + + double element; + getValue(jElement, element); + value.push_back(element); + } + } + + void getValue(jobject &jValue, std::vector> &value) + { + jobjectArray array = (jobjectArray) jValue; + size_t length = m_env->GetArrayLength(array); + for (size_t i = 0; i < length; i++) + { + jobject jElement = m_env->GetObjectArrayElement(array, i); + + std::vector element; + getValue(jElement, element); + value.push_back(element); + } + } + + void getValue(jobject &jValue, std::vector>> &value) + { + jobjectArray array = (jobjectArray) jValue; + size_t length = m_env->GetArrayLength(array); + for (size_t i = 0; i < length; i++) + { + jobject jElement = m_env->GetObjectArrayElement(array, i); + + std::vector> element; + getValue(jElement, element); + value.push_back(element); + } + } + + void getValue(jobject &jValue, bool &value) + { + static jmethodID boolValueMID = m_env->GetMethodID( + gSimulatorClassRefs.booleanCls, "booleanValue", "()Z"); + + value = m_env->CallBooleanMethod(jValue, boolValueMID); + } + + void getValue(jobject &jValue, std::vector &value) + { + jobjectArray array = (jobjectArray) jValue; + size_t length = m_env->GetArrayLength(array); + for (size_t i = 0; i < length; i++) + { + jobject jElement = m_env->GetObjectArrayElement(array, i); + + bool element; + getValue(jElement, element); + value.push_back(element); + } + } + + void getValue(jobject &jValue, std::vector> &value) + { + jobjectArray array = (jobjectArray) jValue; + size_t length = m_env->GetArrayLength(array); + for (size_t i = 0; i < length; i++) + { + jobject jElement = m_env->GetObjectArrayElement(array, i); + + std::vector element; + getValue(jElement, element); + value.push_back(element); + } + } + + void getValue(jobject &jValue, std::vector>> &value) + { + jobjectArray array = (jobjectArray) jValue; + size_t length = m_env->GetArrayLength(array); + for (size_t i = 0; i < length; i++) + { + jobject jElement = m_env->GetObjectArrayElement(array, i); + + std::vector> element; + getValue(jElement, element); + value.push_back(element); + } + } + + void getValue(jobject &jValue, std::string &value) + { + jstring stringValue = (jstring) jValue; + JniString jniValue(m_env, stringValue); + value = jniValue.get(); + } + + void getValue(jobject jValue, std::vector &value) + { + jobjectArray array = (jobjectArray) jValue; + size_t length = m_env->GetArrayLength(array); + for (size_t i = 0; i < length; i++) + { + jobject jElement = m_env->GetObjectArrayElement(array, i); + + std::string element; + getValue(jElement, element); + value.push_back(element); + } + } + + void getValue(jobject &jValue, std::vector> &value) + { + jobjectArray array = (jobjectArray) jValue; + size_t length = m_env->GetArrayLength(array); + for (size_t i = 0; i < length; i++) + { + jobject jElement = m_env->GetObjectArrayElement(array, i); + + std::vector element; + getValue(jElement, element); + value.push_back(element); + } + } + + void getValue(jobject &jValue, std::vector>> &value) + { + jobjectArray array = (jobjectArray) jValue; + size_t length = m_env->GetArrayLength(array); + for (size_t i = 0; i < length; i++) + { + jobject jElement = m_env->GetObjectArrayElement(array, i); + + std::vector> element; + getValue(jElement, element); + value.push_back(element); + } + } + + void getValue(jobject &jValue, SimulatorResourceModel &value) + { + } + + void getValue(jobject &jValue, std::vector &value) + { + } + + void getValue(jobject &jValue, std::vector> &value) + { + } + + void getValue(jobject &jValue, std::vector>> &value) + { + } + + JNIEnv *m_env; + SimulatorResourceModel::TypeInfo &m_typeInfo; + jobject &m_value; + SimulatorResourceModel::ValueVariant m_result; +}; + +class JniAttributeValue { - if (env && thiz && nativeHandle) - { - env->SetLongField(thiz, GetHandleField(env, thiz), nativeHandle); - } -} + public: + static jobject toJava(JNIEnv *env, SimulatorResourceModel::Attribute &attribute) + { + auto value = attribute.getValue(); + return toJava(env, value); + } + + static jobject toJava(JNIEnv *env, SimulatorResourceModel::ValueVariant &value) + { + ValueConverterJava converter(env); + jobject jValue = boost::apply_visitor(converter, value); + + static jmethodID attrValueCtor = env->GetMethodID( + gSimulatorClassRefs.attributeValueCls, "", "(Ljava/lang/Object;)V"); + + return env->NewObject(gSimulatorClassRefs.attributeValueCls, attrValueCtor, jValue); + } + + static SimulatorResourceModel::ValueVariant toCpp(JNIEnv *env, jobject &jAttributeValue) + { + static jmethodID getMID = env->GetMethodID(gSimulatorClassRefs.attributeValueCls, + "get", "()Ljava/lang/Object;"); + + SimulatorResourceModel::TypeInfo typeInfo = JniTypeInfo(env).toCpp(jAttributeValue); + jobject jValue = env->CallObjectMethod(jAttributeValue, getMID); + + ValueConverterCpp converter(env, typeInfo, jValue); + converter.convert(); + return converter.get(); + } +}; + +class JniAttributeProperty +{ + public: + static jobject toJava(JNIEnv *env, + SimulatorResourceModel::AttributeProperty &property) + { + jobject jAttributeProperty = nullptr; + if (SimulatorResourceModel::AttributeProperty::Type::RANGE == property.type()) + { + static jmethodID propertyCtor = env->GetMethodID( + gSimulatorClassRefs.attributePropertyCls, "", "(DD)V"); + + jAttributeProperty = env->NewObject(gSimulatorClassRefs.attributePropertyCls, propertyCtor, + property.min(), property.max()); + } + else + { + static jmethodID propertyCtor = env->GetMethodID( + gSimulatorClassRefs.attributePropertyCls, "", "([Lorg/oic/simulator/AttributeValue;)V"); + + jobjectArray jValueSet = env->NewObjectArray(property.valueSetSize(), + gSimulatorClassRefs.attributeValueCls, nullptr); + int index = 0; + for (auto &value : property.valueSet()) + { + jobject jValue = JniAttributeValue::toJava(env, value); + env->SetObjectArrayElement(jValueSet, index++, jValue); + } + + jAttributeProperty = env->NewObject(gSimulatorClassRefs.attributePropertyCls, propertyCtor, + jValueSet); + } + + // Add child property + if (jAttributeProperty && property.getChildProperty()) + { + SimulatorResourceModel::AttributeProperty childProperty = *(property.getChildProperty()); + jobject jChildProperty = JniAttributeProperty::toJava(env, property); + if (jChildProperty) + { + static jfieldID childPropFID = env->GetFieldID(gSimulatorClassRefs.attributePropertyCls, + "mChildProperty", "Lorg/oic/simulator/AttributeProperty;"); + env->SetObjectField(jAttributeProperty, childPropFID, jChildProperty); + } + } + + return jAttributeProperty; + } + + static SimulatorResourceModel::AttributeProperty toCpp(JNIEnv *env, jobject jAttributeProperty) + { + static jfieldID typeFID = env->GetFieldID(gSimulatorClassRefs.attributePropertyCls, + "mType", "Lorg/oic/simulator/AttributeProperty$Type;"); + static jfieldID minFID = env->GetFieldID(gSimulatorClassRefs.attributePropertyCls, + "mMin", "D"); + static jfieldID maxFID = env->GetFieldID(gSimulatorClassRefs.attributePropertyCls, + "mMax", "D"); + static jfieldID valueSetFID = env->GetFieldID(gSimulatorClassRefs.attributePropertyCls, + "mValueSet", "[Lorg/oic/simulator/AttributeValue;"); + static jfieldID childPropFID = env->GetFieldID(gSimulatorClassRefs.attributePropertyCls, + "mChildProperty", "Lorg/oic/simulator/AttributeProperty;"); + static jmethodID ordinalMID = env->GetMethodID( + gSimulatorClassRefs.attributePropertyTypeCls, "ordinal", "()I"); + + SimulatorResourceModel::AttributeProperty attributeProperty; + jobject jType = env->GetObjectField(jAttributeProperty, typeFID); + jdouble jMin = env->GetDoubleField(jAttributeProperty, minFID); + jdouble jMax = env->GetDoubleField(jAttributeProperty, maxFID); + jobjectArray jValueSet = (jobjectArray) env->GetObjectField(jAttributeProperty, valueSetFID); + jobject jChildProperty = env->GetObjectField(jAttributeProperty, childPropFID); + + int ordinal = env->CallIntMethod(jType, ordinalMID); + switch (SimulatorResourceModel::AttributeProperty::Type(ordinal)) + { + case SimulatorResourceModel::AttributeProperty::Type::RANGE: + { + attributeProperty = SimulatorResourceModel::AttributeProperty(jMin, jMax); + } + break; + + case SimulatorResourceModel::AttributeProperty::Type::VALUE_SET: + { + std::vector valueSet; + size_t length = env->GetArrayLength(jValueSet); + for (size_t i = 0; i < length; i++) + { + jobject jAttributeValue = env->GetObjectArrayElement(jValueSet, i); + valueSet.push_back(JniAttributeValue::toCpp(env, jAttributeValue)); + } + + attributeProperty = SimulatorResourceModel::AttributeProperty(valueSet); + } + break; + } + + // Set child property + if (jChildProperty) + { + SimulatorResourceModel::AttributeProperty childProperty = + JniAttributeProperty::toCpp(env, jAttributeProperty); + attributeProperty.setChildProperty(childProperty); + } + + return attributeProperty; + } +}; static jobject createHashMap(JNIEnv *env) { - jobject mapobj = env->NewObject(gSimulatorClassRefs.classHashMap, - gSimulatorClassRefs.classHashMapCtor); - return mapobj; + static jmethodID hashMapCtor = env->GetMethodID( + gSimulatorClassRefs.hashMapCls, "", "()V"); + return env->NewObject(gSimulatorClassRefs.hashMapCls, hashMapCtor); } static void addEntryToHashMap(JNIEnv *env, jobject mapobj, jobject key, jobject value) { if (!mapobj || !key || !value) - { return; - } - env->CallObjectMethod(mapobj, gSimulatorClassRefs.classHashMapPut, key, value); -} - -JNIEXPORT void JNICALL -Java_org_oic_simulator_SimulatorResourceModel_create -(JNIEnv *env, jobject thiz) -{ - SimulatorResourceModelSP resModel = std::make_shared(); - JSimulatorResourceModel *jresModel = new JSimulatorResourceModel(resModel); - JSimulatorResourceModel::toJava(env, thiz, reinterpret_cast(jresModel)); + static jmethodID hashMapPutMethod = env->GetMethodID(gSimulatorClassRefs.hashMapCls, + "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;"); + env->CallObjectMethod(mapobj, hashMapPutMethod, key, value); } -JNIEXPORT jint JNICALL -Java_org_oic_simulator_SimulatorResourceModel_size -(JNIEnv *env, jobject thiz) +jobject simulatorResourceModelToJava(JNIEnv *env, SimulatorResourceModel &resModel) { - SimulatorResourceModel resourceModel; - bool result = JSimulatorResourceModel::getResourceModel(env, thiz, resourceModel); - if (!result) - { - throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "Resource model not found!"); - return SIMULATOR_BAD_OBJECT; - } - - return resourceModel.size(); -} - -JNIEXPORT jobject JNICALL -Java_org_oic_simulator_SimulatorResourceModel_getAttributes -(JNIEnv *env, jobject thiz) -{ - SimulatorResourceModel resourceModel; - bool result = JSimulatorResourceModel::getResourceModel(env, thiz, resourceModel); - if (!result) - { - throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "Resource model not found!"); + jobject attributesMap = createHashMap(env); + jobject propertiesMap = createHashMap(env); + if (!attributesMap || !propertiesMap) return nullptr; - } - map attributesMap = resourceModel.getAttributes(); - - // Create Java HashMap object - jobject jHashMap = NULL; - jHashMap = createHashMap(env); - if (!jHashMap) + for (auto &attributeEntry : resModel.getAttributes()) { - throwSimulatorException(env, SIMULATOR_ERROR, "Java map creation failed!"); - return nullptr; - } - - for (auto & attributeEntry : attributesMap) - { - SimulatorResourceModel::Attribute attribute(attributeEntry.second); - - // Create a object of ResourceAttribute java class - JResourceAttributeConverter converter(attribute); - jobject jAttribute = converter.toJava(env); - - // Add an entry with attribute.first and javaSimualatorResourceAttribute to the HashMap jstring jAttrName = env->NewStringUTF((attributeEntry.first).c_str()); - addEntryToHashMap(env, jHashMap, static_cast(jAttrName), jAttribute); - env->DeleteLocalRef(jAttrName); - } - - return jHashMap; -} - -JNIEXPORT jobject JNICALL -Java_org_oic_simulator_SimulatorResourceModel_getAttribute -(JNIEnv *env, jobject thiz, jstring jAttrName) -{ - if (!jAttrName) - { - throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid attribute name!"); - return nullptr; - } - - const char *attrName = env->GetStringUTFChars(jAttrName, NULL); - if (!attrName) - { - throwSimulatorException(env, SIMULATOR_ERROR, "String error!"); - return nullptr; - } - - SimulatorResourceModel resourceModel; - bool result = JSimulatorResourceModel::getResourceModel(env, thiz, resourceModel); - if (!result) - { - env->ReleaseStringUTFChars(jAttrName, attrName); - throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "Resource model not found!"); - return nullptr; - } + jobject jAttributeValue = JniAttributeValue::toJava(env, attributeEntry.second); + addEntryToHashMap(env, attributesMap, jAttrName, jAttributeValue); - SimulatorResourceModel::Attribute attribute; - bool found = resourceModel.getAttribute(attrName, attribute); - if (!found) - { - env->ReleaseStringUTFChars(jAttrName, attrName); - throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Attribute does not exist!"); - return nullptr; + jobject jAttributeProperty = JniAttributeProperty::toJava(env, attributeEntry.second.getProperty()); + addEntryToHashMap(env, propertiesMap, jAttrName, jAttributeProperty); } - env->ReleaseStringUTFChars(jAttrName, attrName); + static jmethodID simulatorResourceModelCtor = env->GetMethodID( + gSimulatorClassRefs.simulatorResourceModelCls, "", "(Ljava/util/Map;Ljava/util/Map;)V"); - // Create a object of ResourceAttribute java class - JResourceAttributeConverter converter(attribute); - return converter.toJava(env); + return env->NewObject(gSimulatorClassRefs.simulatorResourceModelCls, + simulatorResourceModelCtor, attributesMap, propertiesMap); } -JNIEXPORT void JNICALL -Java_org_oic_simulator_SimulatorResourceModel_addAttributeInt -(JNIEnv *env, jobject thiz, jstring jname, jint jvalue) +jobject simulatorResourceAttributeToJava(JNIEnv *env, SimulatorResourceModel::Attribute &attribute) { - if (!jname) - { - throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid attribute name!"); - return; - } - - SimulatorResourceModelSP resModelPtr; - resModelPtr = JSimulatorResourceModel::getResourceModelPtr(env, thiz); - if (!resModelPtr) - { - throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "Resource model not found!"); - return; - } - - const char *nameCstr = env->GetStringUTFChars(jname, NULL); - if (!nameCstr) - { - throwSimulatorException(env, SIMULATOR_ERROR, "String error!"); - return; - } + static jmethodID simulatorResAttributeCtor = env->GetMethodID( + gSimulatorClassRefs.simulatorResourceAttributeCls, "", + "(Ljava/lang/String;Lorg/oic/simulator/AttributeValue;Lorg/oic/simulator/AttributeProperty;)V"); - std::string attrName(nameCstr); - int value = static_cast(jvalue); - resModelPtr->addAttribute(attrName, value); + jstring jAttrName = env->NewStringUTF(attribute.getName().c_str()); + jobject jAttributeValue = JniAttributeValue::toJava(env, attribute); + jobject jAttributeProperty = JniAttributeProperty::toJava(env, attribute.getProperty()); - // Release created c string - env->ReleaseStringUTFChars(jname, nameCstr); + return env->NewObject(gSimulatorClassRefs.simulatorResourceAttributeCls, + simulatorResAttributeCtor, jAttrName, jAttributeValue, jAttributeProperty); } -JNIEXPORT void JNICALL -Java_org_oic_simulator_SimulatorResourceModel_addAttributeDouble -(JNIEnv *env, jobject thiz, jstring jname, jdouble jvalue) +bool simulatorResourceModelToCpp(JNIEnv *env, jobject jResModel, SimulatorResourceModel &resModel) { - if (!jname) - { - throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid attribute name!"); - return; - } + if (!jResModel) + return false; - SimulatorResourceModelSP resModelPtr; - resModelPtr = JSimulatorResourceModel::getResourceModelPtr(env, thiz); - if (!resModelPtr) + static jfieldID valuesFID = env->GetFieldID(gSimulatorClassRefs.simulatorResourceModelCls, + "mValues", "Ljava/util/Map;"); + static jfieldID propertiesFID = env->GetFieldID(gSimulatorClassRefs.simulatorResourceModelCls, + "mProperties", "Ljava/util/Map;"); + static jmethodID entrySetMID = env->GetMethodID(gSimulatorClassRefs.mapCls, "entrySet", + "()Ljava/util/Set;"); + static jmethodID iteratorMID = env->GetMethodID(gSimulatorClassRefs.setCls, "iterator", + "()Ljava/util/Iterator;"); + static jmethodID hasNextMID = env->GetMethodID(gSimulatorClassRefs.iteratorCls, "hasNext", + "()Z"); + static jmethodID nextMID = env->GetMethodID(gSimulatorClassRefs.iteratorCls, "next", + "()Ljava/lang/Object;"); + static jmethodID getKeyMID = env->GetMethodID(gSimulatorClassRefs.mapEntryCls, "getKey", + "()Ljava/lang/Object;"); + static jmethodID getValueMID = env->GetMethodID(gSimulatorClassRefs.mapEntryCls, "getValue", + "()Ljava/lang/Object;"); + + jobject jValues = env->GetObjectField(jResModel, valuesFID); + jobject jProperties = env->GetObjectField(jResModel, propertiesFID); + + if (jValues) { - throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "Resource model not found!"); - return; + jobject entrySet = env->CallObjectMethod(jValues, entrySetMID); + jobject iterator = env->CallObjectMethod(entrySet, iteratorMID); + if (entrySet && iterator) + { + while (env->CallBooleanMethod(iterator, hasNextMID)) + { + jobject entry = env->CallObjectMethod(iterator, nextMID); + jstring key = (jstring) env->CallObjectMethod(entry, getKeyMID); + jobject value = env->CallObjectMethod(entry, getValueMID); + resModel.add(JniString(env, key).get(), JniAttributeValue::toCpp(env, value)); + + env->DeleteLocalRef(entry); + env->DeleteLocalRef(key); + env->DeleteLocalRef(value); + } + } } - const char *nameCstr = env->GetStringUTFChars(jname, NULL); - if (!nameCstr) + if (jProperties) { - throwSimulatorException(env, SIMULATOR_ERROR, "String error!"); - return; + jobject entrySet = env->CallObjectMethod(jProperties, entrySetMID); + jobject iterator = env->CallObjectMethod(entrySet, iteratorMID); + if (entrySet && iterator) + { + while (env->CallBooleanMethod(iterator, hasNextMID)) + { + jobject entry = env->CallObjectMethod(iterator, nextMID); + jstring key = (jstring) env->CallObjectMethod(entry, getKeyMID); + jobject value = env->CallObjectMethod(entry, getValueMID); + resModel.setAttributeProperty(JniString(env, key).get(), + JniAttributeProperty::toCpp(env, value)); + + env->DeleteLocalRef(entry); + env->DeleteLocalRef(key); + env->DeleteLocalRef(value); + } + } } - std::string attrName(nameCstr); - double value = static_cast(jvalue); - resModelPtr->addAttribute(attrName, value); - - // Release created c string - env->ReleaseStringUTFChars(jname, nameCstr); + return true; } -JNIEXPORT void JNICALL -Java_org_oic_simulator_SimulatorResourceModel_addAttributeBoolean -(JNIEnv *env, jobject thiz, jstring jname, jboolean jvalue) +bool simulatorResourceAttributeToCpp(JNIEnv *env, jobject jAttribute, + SimulatorResourceModel::Attribute &attribute) { - if (!jname) - { - throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid attribute name!"); - return; - } - - SimulatorResourceModelSP resModelPtr; - resModelPtr = JSimulatorResourceModel::getResourceModelPtr(env, thiz); - if (!resModelPtr) - { - throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "Resource model not found!"); - return; - } - - const char *nameCstr = env->GetStringUTFChars(jname, NULL); - if (!nameCstr) - { - throwSimulatorException(env, SIMULATOR_ERROR, "String error!"); - return; - } - - std::string attrName(nameCstr); - bool value = static_cast(jvalue); - resModelPtr->addAttribute(attrName, value); + if (!jAttribute) + return false; - // Release created c string - env->ReleaseStringUTFChars(jname, nameCstr); -} + static jfieldID nameFID = env->GetFieldID(gSimulatorClassRefs.simulatorResourceAttributeCls, + "mName", "Ljava/lang/String;"); + static jfieldID valueFID = env->GetFieldID(gSimulatorClassRefs.simulatorResourceAttributeCls, + "mValue", "Lorg/oic/simulator/AttributeValue;"); + static jfieldID propertyFID = env->GetFieldID(gSimulatorClassRefs.simulatorResourceAttributeCls, + "mProperty", "Lorg/oic/simulator/AttributeProperty;"); -JNIEXPORT void JNICALL -Java_org_oic_simulator_SimulatorResourceModel_addAttributeString -(JNIEnv *env, jobject thiz, jstring jname, jstring jvalue) -{ - if (!jname) - { - throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid attribute name!"); - return; - } - - if (!jvalue) - { - throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Attribute value cannot be null!"); - return; - } + jstring jAttributeName = (jstring) env->GetObjectField(jAttribute, nameFID); + jobject jAttributeValue = env->GetObjectField(jAttribute, valueFID); + jobject jAttributeProperty = env->GetObjectField(jAttribute, propertyFID); - SimulatorResourceModelSP resModelPtr; - resModelPtr = JSimulatorResourceModel::getResourceModelPtr(env, thiz); - if (!resModelPtr) - { - throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "Resource model not found!"); - return; - } + if (!jAttributeName || !jAttributeValue) + return false; - const char *nameCstr = env->GetStringUTFChars(jname, NULL); - if (!nameCstr) - { - throwSimulatorException(env, SIMULATOR_ERROR, "String error!"); - return; - } + JniString attrName(env, jAttributeName); + SimulatorResourceModel::ValueVariant value = JniAttributeValue::toCpp(env, jAttributeValue); - const char *valueCstr = env->GetStringUTFChars(jvalue, NULL); - if (!valueCstr) + attribute.setName(attrName.get()); + attribute.setValue(value); + if (jAttributeProperty) { - env->ReleaseStringUTFChars(jname, nameCstr); - throwSimulatorException(env, SIMULATOR_ERROR, "String error!"); - return; + SimulatorResourceModel::AttributeProperty property = JniAttributeProperty::toCpp(env, + jAttributeProperty); + attribute.setProperty(property); } - std::string attrName(nameCstr); - std::string value(valueCstr); - resModelPtr->addAttribute(attrName, value); - - // Release created c string - env->ReleaseStringUTFChars(jname, nameCstr); - env->ReleaseStringUTFChars(jvalue, valueCstr); + return true; } -JNIEXPORT void JNICALL -Java_org_oic_simulator_SimulatorResourceModel_dispose -(JNIEnv *env, jobject thiz) +bool AttributeValueToCpp(JNIEnv *env, jobject jAttributeValue, + SimulatorResourceModel::ValueVariant &value) { - JSimulatorResourceModel *resourceModel = GetHandle(env, thiz); - delete resourceModel; + if (!jAttributeValue) + return false; + + value = JniAttributeValue::toCpp(env, jAttributeValue); + return true; } + diff --git a/service/simulator/java/jni/simulator_resource_model_jni.h b/service/simulator/java/jni/simulator_resource_model_jni.h index 2e4d35d..ca23b3b 100644 --- a/service/simulator/java/jni/simulator_resource_model_jni.h +++ b/service/simulator/java/jni/simulator_resource_model_jni.h @@ -24,66 +24,12 @@ #include #include "simulator_resource_model.h" -class JSimulatorResourceModel -{ - public: - JSimulatorResourceModel(SimulatorResourceModel resModel); - JSimulatorResourceModel(SimulatorResourceModelSP resModel); - - static jobject toJava(JNIEnv *env, jlong nativeHandle); - static void toJava(JNIEnv *env, jobject thiz, jlong nativeHandle); - static bool getResourceModel(JNIEnv *env, jobject thiz, SimulatorResourceModel &resModel); - static SimulatorResourceModelSP getResourceModelPtr(JNIEnv *env, jobject thiz); - - private: - SimulatorResourceModel m_resourceModel; - SimulatorResourceModelSP m_resModelPtr; -}; - - -#ifdef __cplusplus -extern "C" { -#endif - -JNIEXPORT void JNICALL -Java_org_oic_simulator_SimulatorResourceModel_create -(JNIEnv *, jobject); - -JNIEXPORT jint JNICALL -Java_org_oic_simulator_SimulatorResourceModel_size -(JNIEnv *, jobject); - -JNIEXPORT jobject JNICALL -Java_org_oic_simulator_SimulatorResourceModel_getAttributes -(JNIEnv *, jobject); - -JNIEXPORT jobject JNICALL -Java_org_oic_simulator_SimulatorResourceModel_getAttribute -(JNIEnv *, jobject, jstring); - -JNIEXPORT void JNICALL -Java_org_oic_simulator_SimulatorResourceModel_addAttributeInt -(JNIEnv *, jobject, jstring, jint); - -JNIEXPORT void JNICALL -Java_org_oic_simulator_SimulatorResourceModel_addAttributeDouble -(JNIEnv *, jobject, jstring, jdouble); - -JNIEXPORT void JNICALL -Java_org_oic_simulator_SimulatorResourceModel_addAttributeBoolean -(JNIEnv *, jobject, jstring, jboolean); - -JNIEXPORT void JNICALL -Java_org_oic_simulator_SimulatorResourceModel_addAttributeString -(JNIEnv *, jobject, jstring, jstring); - -JNIEXPORT void JNICALL -Java_org_oic_simulator_SimulatorResourceModel_dispose -(JNIEnv *, jobject); - - -#ifdef __cplusplus -} -#endif +jobject simulatorResourceModelToJava(JNIEnv *env, SimulatorResourceModel &resModel); +jobject simulatorResourceAttributeToJava(JNIEnv *env, SimulatorResourceModel::Attribute &attribute); +bool simulatorResourceModelToCpp(JNIEnv *env, jobject jResModel, SimulatorResourceModel &resModel); +bool simulatorResourceAttributeToCpp(JNIEnv *env, jobject jAttribute, + SimulatorResourceModel::Attribute &attribute); +bool AttributeValueToCpp(JNIEnv *env, jobject jAttributeValue, + SimulatorResourceModel::ValueVariant &value); #endif diff --git a/service/simulator/java/jni/simulator_resource_server_jni.cpp b/service/simulator/java/jni/simulator_resource_server_jni.cpp deleted file mode 100644 index 209ef47..0000000 --- a/service/simulator/java/jni/simulator_resource_server_jni.cpp +++ /dev/null @@ -1,840 +0,0 @@ -/****************************************************************** - * - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************/ - -#include "simulator_resource_server_jni.h" -#include "simulator_resource_jni_util.h" -#include "simulator_common_jni.h" -#include "simulator_resource_model_jni.h" -#include "simulator_jni_utils.h" -#include "simulator_logger.h" -#include "simulator_jni_utils.h" - -extern SimulatorClassRefs gSimulatorClassRefs; - -JniSimulatorResource::JniSimulatorResource(SimulatorResourceServerSP &resource) - : m_sharedResource(resource) {} - -SimulatorResourceServerSP JniSimulatorResource::getJniSimulatorResourceSP(JNIEnv *env, - jobject thiz) -{ - JniSimulatorResource *resource = GetHandle(env, thiz); - if (env->ExceptionCheck()) - { - return NULL; - } - return resource->m_sharedResource; -} - -jobject JniSimulatorResource::toJava(JNIEnv *env, jlong resource) -{ - jobject resourceObj = (jobject) env->NewObject(gSimulatorClassRefs.classSimulatorResource, - gSimulatorClassRefs.classSimulatorResourceCtor, resource); - if (NULL == resourceObj) - { - return NULL; - } - return resourceObj; -} - -void JniSimulatorResource::setResourceInfo(JNIEnv *env, jobject jobj) -{ - if (!env || !jobj) - return; - - std::string uri = m_sharedResource->getURI(); - std::string resourceType = m_sharedResource->getResourceType(); - std::string name = m_sharedResource->getName(); - std::string interfaceType = m_sharedResource->getInterfaceType(); - - jfieldID fieldID = env->GetFieldID(gSimulatorClassRefs.classSimulatorResource, "resourceURI", - "Ljava/lang/String;"); - jstring jUri = env->NewStringUTF(uri.c_str()); - env->SetObjectField(jobj, fieldID, jUri); - - fieldID = env->GetFieldID(gSimulatorClassRefs.classSimulatorResource, "resourceName", - "Ljava/lang/String;"); - jstring jName = env->NewStringUTF(name.c_str()); - env->SetObjectField(jobj, fieldID, jName); - - fieldID = env->GetFieldID(gSimulatorClassRefs.classSimulatorResource, "resourceType", - "Ljava/lang/String;"); - jstring jResourceType = env->NewStringUTF(resourceType.c_str()); - env->SetObjectField(jobj, fieldID, jResourceType); - - fieldID = env->GetFieldID(gSimulatorClassRefs.classSimulatorResource, "interfaceType", - "Ljava/lang/String;"); - jstring jInterfaceType = env->NewStringUTF(interfaceType.c_str()); - env->SetObjectField(jobj, fieldID, jInterfaceType); - - env->DeleteLocalRef(jUri); - env->DeleteLocalRef(jName); - env->DeleteLocalRef(jResourceType); - env->DeleteLocalRef(jInterfaceType); -} - -void onAutomationComplete(jweak jlistenerRef, const std::string &uri, - const int automationID) -{ - JNIEnv *env = getEnv(); - if (nullptr == env) - return; - - jobject autoCompleteListener = env->NewLocalRef(jlistenerRef); - if (!autoCompleteListener) - { - releaseEnv(); - return; - } - - jclass autoCompleteCls = env->GetObjectClass(autoCompleteListener); - if (!autoCompleteCls) - { - releaseEnv(); - return; - } - - jmethodID autoCompleteMId = env->GetMethodID(autoCompleteCls, "onAutomationComplete", - "(Ljava/lang/String;I)V"); - if (!autoCompleteMId) - { - releaseEnv(); - return; - } - - jstring jUri = env->NewStringUTF(uri.c_str()); - - env->CallVoidMethod(autoCompleteListener, autoCompleteMId, jUri, automationID); - if ((env)->ExceptionCheck()) - { - releaseEnv(); - return; - } - - env->DeleteLocalRef(jUri); - - releaseEnv(); -} - -JNIEXPORT jobject JNICALL -Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_getModel -(JNIEnv *env, jobject object) -{ - SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object); - if (!resource) - { - throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!"); - return nullptr; - } - - SimulatorResourceModel resModel = resource->getModel(); - JSimulatorResourceModel *model = new JSimulatorResourceModel(resModel); - jobject jModel = JSimulatorResourceModel::toJava(env, reinterpret_cast(model)); - return jModel; -} - -JNIEXPORT void JNICALL -Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_addAttributeInteger -(JNIEnv *env, jobject jobject, jstring jKey, jint jValue) -{ - if (!jKey) - { - throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid Attribute name!"); - return; - } - - SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, - jobject); - if (!resource) - { - throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!"); - return; - } - - std::string str = env->GetStringUTFChars(jKey, NULL); - SimulatorResourceModel::Attribute att; - att.setName(str); - att.setValue(static_cast(jValue)); - resource->addAttribute(att); -} - -JNIEXPORT void JNICALL -Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_addAttributeDouble -(JNIEnv *env, jobject jobject, jstring jKey, jdouble jValue) -{ - if (!jKey) - { - throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid Attribute name!"); - return; - } - - SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, - jobject); - if (!resource) - { - throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!"); - return; - } - - std::string str = env->GetStringUTFChars(jKey, NULL); - SimulatorResourceModel::Attribute att; - att.setName(str); - att.setValue(static_cast(jValue)); - resource->addAttribute(att); -} - -JNIEXPORT void JNICALL -Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_addAttributeBoolean -(JNIEnv *env, jobject jobject, jstring jKey, jboolean jValue) -{ - if (!jKey) - { - throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid Attribute name!"); - return; - } - - SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, - jobject); - if (!resource) - { - throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!"); - return; - } - - std::string str = env->GetStringUTFChars(jKey, NULL); - SimulatorResourceModel::Attribute att; - att.setName(str); - att.setValue(static_cast(jValue)); - resource->addAttribute(att); -} - -JNIEXPORT void JNICALL -Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_addAttributeString -(JNIEnv *env, jobject jobject, jstring jKey, jstring jValue) -{ - if (!jKey) - { - throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid Attribute name!"); - return; - } - - if (!jValue) - { - throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Attribute value cannot be null!"); - return; - } - - SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, - jobject); - if (!resource) - { - throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!"); - return; - } - - std::string key = env->GetStringUTFChars(jKey, NULL); - std::string value = env->GetStringUTFChars(jValue, NULL); - SimulatorResourceModel::Attribute att; - att.setName(key); - att.setValue(value); - resource->addAttribute(att); -} - -JNIEXPORT void JNICALL -Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_updateAttributeInteger -(JNIEnv *env, jobject jobject, jstring jKey, jint jValue) -{ - if (!jKey) - { - throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid Attribute name!"); - return; - } - - SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, - jobject); - if (!resource) - { - throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!"); - return; - } - - std::string str = env->GetStringUTFChars(jKey, NULL); - resource->updateAttributeValue(str, static_cast(jValue)); -} - -JNIEXPORT void JNICALL -Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_updateAttributeDouble -(JNIEnv *env, jobject jobject, jstring jKey, jdouble jValue) -{ - if (!jKey) - { - throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid Attribute name!"); - return; - } - - SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, - jobject); - if (!resource) - { - throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!"); - return; - } - - std::string str = env->GetStringUTFChars(jKey, NULL); - resource->updateAttributeValue(str, static_cast(jValue)); -} - -JNIEXPORT void JNICALL -Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_updateAttributeBoolean -(JNIEnv *env, jobject jobject, jstring jKey, jboolean jValue) -{ - if (!jKey) - { - throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid Attribute name!"); - return; - } - - SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, - jobject); - if (!resource) - { - throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!"); - return; - } - - std::string str = env->GetStringUTFChars(jKey, NULL); - resource->updateAttributeValue(str, static_cast(jValue)); -} - -JNIEXPORT void JNICALL -Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_updateAttributeString -(JNIEnv *env, jobject jobject, jstring jKey, jstring jValue) -{ - if (!jKey) - { - throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid Attribute name!"); - return; - } - - SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, - jobject); - if (!resource) - { - throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!"); - return; - } - - std::string key = env->GetStringUTFChars(jKey, NULL); - std::string value = env->GetStringUTFChars(jValue, NULL); - - resource->updateAttributeValue(key, value); -} - -JNIEXPORT void JNICALL -Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_updateAttributeFromAllowedValues -(JNIEnv *env, jobject object, jstring attrName, jint index) -{ - if (!attrName || index < 0) - { - throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid parameter!"); - return; - } - - SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object); - if (!resource) - { - throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!"); - return; - } - - const char *attrNameCStr = env->GetStringUTFChars(attrName, NULL); - if (!attrNameCStr) - { - throwSimulatorException(env, SIMULATOR_ERROR, "String error!"); - return; - } - - resource->updateAttributeValue(attrNameCStr, static_cast(index)); - env->ReleaseStringUTFChars(attrName, attrNameCStr); -} - -JNIEXPORT void JNICALL -Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_setRange -(JNIEnv *env, jobject object, jstring attrName, jint min, jint max) -{ - if (!attrName) - { - throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid parameter!"); - return; - } - - SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object); - if (!resource) - { - throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!"); - return; - } - - const char *attrNameCStr = env->GetStringUTFChars(attrName, NULL); - if (!attrNameCStr) - { - throwSimulatorException(env, SIMULATOR_ERROR, "String error!"); - return; - } - - resource->setRange(attrNameCStr, static_cast(min), static_cast(max)); - env->ReleaseStringUTFChars(attrName, attrNameCStr); -} - -JNIEXPORT void JNICALL -Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_setAllowedValuesInteger -(JNIEnv *env, jobject object, jstring jKey, jobject jAllowedValues) -{ - if (!jKey || !jAllowedValues) - { - throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid parameter!"); - return; - } - - SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object); - if (!resource) - { - throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!"); - return; - } - - const char *keyCStr = env->GetStringUTFChars(jKey, NULL); - if (!keyCStr) - { - throwSimulatorException(env, SIMULATOR_ERROR, "String error!"); - return; - } - - resource->setAllowedValues(keyCStr, convertIntegerVector(env, jAllowedValues)); - env->ReleaseStringUTFChars(jKey, keyCStr); -} - -JNIEXPORT void JNICALL -Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_setAllowedValuesDouble -(JNIEnv *env, jobject object, jstring jKey, jobject jAllowedValues) -{ - if (!jKey || !jAllowedValues) - { - throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid parameter!"); - return; - } - - SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object); - if (!resource) - { - throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!"); - return; - } - - const char *keyCStr = env->GetStringUTFChars(jKey, NULL); - if (!keyCStr) - { - throwSimulatorException(env, SIMULATOR_ERROR, "String error!"); - return; - } - - resource->setAllowedValues(keyCStr, convertDoubleVector(env, jAllowedValues)); - env->ReleaseStringUTFChars(jKey, keyCStr); -} - -JNIEXPORT void JNICALL -Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_setAllowedValuesString -(JNIEnv *env, jobject object, jstring jKey, jobject jAllowedValues) -{ - if (!jKey || !jAllowedValues) - { - throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid parameter!"); - return; - } - - SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object); - if (!resource) - { - throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!"); - return; - } - - const char *keyCStr = env->GetStringUTFChars(jKey, NULL); - if (!keyCStr) - { - throwSimulatorException(env, SIMULATOR_ERROR, "String error!"); - return; - } - - resource->setAllowedValues(keyCStr, convertStringVector(env, jAllowedValues)); - env->ReleaseStringUTFChars(jKey, keyCStr); -} - -JNIEXPORT jint JNICALL -Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_startResourceAutomation -(JNIEnv *env, jobject object, jint automationType, jint updateInterval, jobject listener) -{ - SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object); - if (!resource) - { - throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!"); - return SIMULATOR_BAD_OBJECT; - } - - if (!listener) - { - throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, - "Start Resource Automation failed! Callback not set"); - return SIMULATOR_INVALID_CALLBACK; - } - - jweak jlistenerRef = env->NewWeakGlobalRef(listener); - updateCompleteCallback callback = [jlistenerRef](const std::string & uri, const int automationID) - { - onAutomationComplete(jlistenerRef, uri, automationID); - }; - - AutomationType type = AutomationType::NORMAL; - if (1 == automationType) - { - type = AutomationType::RECURRENT; - } - - int automationId = -1; - - try - { - automationId = resource->startUpdateAutomation(type, updateInterval, callback); - } - catch (InvalidArgsException &e) - { - throwInvalidArgsException(env, e.code(), e.what()); - } - catch (SimulatorException &e) - { - throwSimulatorException(env, e.code(), e.what()); - } - catch (...) - { - throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception"); - } - return automationId; -} - -JNIEXPORT jint JNICALL -Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_startAttributeAutomation -(JNIEnv *env, jobject object, jstring attrName, jint automationType, jint updateInterval, jobject listener) -{ - SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object); - if (!resource) - { - throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!"); - return SIMULATOR_BAD_OBJECT; - } - - if (!attrName) - { - throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid Attribute name!"); - return SIMULATOR_INVALID_PARAM; - } - - if (!listener) - { - throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, - "Start Attribute Automation failed! Callback not set"); - return SIMULATOR_INVALID_CALLBACK; - } - - jweak jlistenerRef = env->NewWeakGlobalRef(listener); - updateCompleteCallback callback = [jlistenerRef](const std::string & uri, const int automationID) - { - onAutomationComplete(jlistenerRef, uri, automationID); - }; - - const char *attrNamePtr = env->GetStringUTFChars(attrName, NULL); - - AutomationType type = AutomationType::NORMAL; - if (1 == automationType) - { - type = AutomationType::RECURRENT; - } - - int automationId = -1; - try - { - automationId = resource->startUpdateAutomation(attrNamePtr, type, updateInterval, callback); - } - catch (InvalidArgsException &e) - { - throwInvalidArgsException(env, e.code(), e.what()); - return -1; - } - catch (SimulatorException &e) - { - throwSimulatorException(env, e.code(), e.what()); - return -1; - } - catch (...) - { - throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception"); - return -1; - } - env->ReleaseStringUTFChars(attrName, attrNamePtr); - return automationId; -} - -JNIEXPORT void JNICALL -Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_stopAutomation -(JNIEnv *env, jobject object, jint automationId) -{ - SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object); - if (!resource) - { - throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!"); - return; - } - - try - { - resource->stopUpdateAutomation(automationId); - } - catch (SimulatorException &e) - { - throwSimulatorException(env, e.code(), e.what()); - } - catch (...) - { - throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception"); - } - - SIM_LOG(ILogger::INFO, "Automation has been forcibly stopped.") -} - -JNIEXPORT void JNICALL -Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_removeAttribute -(JNIEnv *env, jobject jobject, jstring jKey) -{ - if (!jKey) - { - throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Invalid Attribute name!"); - return; - } - - SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, - jobject); - if (!resource) - { - throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!"); - return; - } - - std::string str = env->GetStringUTFChars(jKey, NULL); - try - { - resource->removeAttribute(str); - } - catch (InvalidArgsException &e) - { - throwInvalidArgsException(env, e.code(), e.what()); - return; - } - catch (SimulatorException &e) - { - throwSimulatorException(env, e.code(), e.what()); - return; - } - catch (...) - { - throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception"); - return; - } -} - -JNIEXPORT jobjectArray JNICALL -Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_getObserversList -(JNIEnv *env, jobject object) -{ - SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object); - if (!resource) - { - throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!"); - return nullptr; - } - - std::vector observersList; - observersList = resource->getObserversList(); - - // Construct the object array and send it java layer - jobjectArray jobserversArray = env->NewObjectArray(observersList.size(), - gSimulatorClassRefs.classObserverInfo, NULL); - if (jobserversArray) - { - for (size_t i = 0; i < observersList.size(); i++) - { - jstring jaddress = env->NewStringUTF(observersList[i].address.c_str()); - jobject jobserver = (jobject) env->NewObject(gSimulatorClassRefs.classObserverInfo, - gSimulatorClassRefs.classObserverInfoCtor, observersList[i].id, - jaddress, observersList[i].port); - - env->SetObjectArrayElement(jobserversArray, i, jobserver); - env->DeleteLocalRef(jaddress); - } - } - - return jobserversArray; -} - -void onObserverChange(jweak jlistenerRef, const std::string &uri, - ObservationStatus state, const ObserverInfo &observerInfo) -{ - JNIEnv *env = getEnv(); - if (nullptr == env) - return; - - jobject observerChangeListener = env->NewLocalRef(jlistenerRef); - if (!observerChangeListener) - { - releaseEnv(); - return; - } - - jclass observerChangeCls = env->GetObjectClass(observerChangeListener); - if (!observerChangeCls) - { - releaseEnv(); - return; - } - - jmethodID observerChangeMId = env->GetMethodID(observerChangeCls, "onObserverChanged", - "(Ljava/lang/String;ILorg/oic/simulator/serviceprovider/ObserverInfo;)V"); - if (!observerChangeMId) - { - releaseEnv(); - return; - } - - // Convert URI - jstring jUri = env->NewStringUTF(uri.c_str()); - - // Convert state - jint jstate = (state == ObservationStatus::OBSERVE_REGISTER) ? 0 : 1; - - // Construct the java object of observerinfo - jstring jaddress = env->NewStringUTF(observerInfo.address.c_str()); - jobject jobserver = (jobject) env->NewObject(gSimulatorClassRefs.classObserverInfo, - gSimulatorClassRefs.classObserverInfoCtor, observerInfo.id, - jaddress, observerInfo.port); - - env->CallVoidMethod(observerChangeListener, observerChangeMId, jUri, jstate, jobserver); - env->DeleteLocalRef(jaddress); - if ((env)->ExceptionCheck()) - { - releaseEnv(); - return; - } - - env->DeleteLocalRef(jUri); - - releaseEnv(); -} - -JNIEXPORT void JNICALL -Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_setObserverCallback -(JNIEnv *env, jobject object, jobject jcallback) -{ - if (!jcallback) - { - throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, "Callback not set"); - return; - } - - jweak jlistenerRef = env->NewWeakGlobalRef(jcallback); - SimulatorResourceServer::ObserverCB callback = [jlistenerRef](const std::string & uri, - ObservationStatus state, const ObserverInfo & observerInfo) - { - onObserverChange(jlistenerRef, uri, state, observerInfo); - }; - - SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object); - if (!resource) - { - throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!"); - return; - } - - resource->setObserverCallback(callback); -} - -JNIEXPORT void JNICALL -Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_notifyObserver -(JNIEnv *env, jobject object, jint jId) -{ - SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object); - if (!resource) - { - throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!"); - return; - } - - try - { - resource->notify(jId); - } - catch (SimulatorException &e) - { - throwSimulatorException(env, e.code(), e.what()); - } - catch (...) - { - throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception"); - } -} - -JNIEXPORT void JNICALL -Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_notifyAllObservers -(JNIEnv *env, jobject object) -{ - SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object); - if (!resource) - { - throwSimulatorException(env, SIMULATOR_BAD_OBJECT, "No resource!"); - return; - } - - try - { - resource->notifyAll(); - } - catch (SimulatorException &e) - { - throwSimulatorException(env, e.code(), e.what()); - } - catch (...) - { - throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception"); - } -} - -JNIEXPORT void JNICALL Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_dispose -(JNIEnv *env, jobject thiz) -{ - JniSimulatorResource *resource = GetHandle(env, thiz); - delete resource; -} - diff --git a/service/simulator/java/jni/simulator_resource_server_jni.h b/service/simulator/java/jni/simulator_resource_server_jni.h deleted file mode 100644 index 298071a..0000000 --- a/service/simulator/java/jni/simulator_resource_server_jni.h +++ /dev/null @@ -1,137 +0,0 @@ -/****************************************************************** - * - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************/ - -#ifndef SIMULATOR_RESOURCE_JNI_H_ -#define SIMULATOR_RESOURCE_JNI_H_ - -#include -#include "simulator_resource_server.h" - -class JniSimulatorResource -{ - public: - JniSimulatorResource(SimulatorResourceServerSP &resource); - - static jobject toJava(JNIEnv *env, jlong resource); - void setResourceInfo(JNIEnv *env, jobject jobj); - static SimulatorResourceServerSP getJniSimulatorResourceSP(JNIEnv *env, jobject thiz); - private: - SimulatorResourceServerSP m_sharedResource; -}; - - -#ifdef __cplusplus -extern "C" { - -JNIEXPORT jobject JNICALL -Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_getModel -(JNIEnv *, jobject); - -JNIEXPORT void JNICALL -Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_addAttributeInteger -(JNIEnv *, jobject, jstring, jint); - -JNIEXPORT void JNICALL -Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_addAttributeDouble -(JNIEnv *, jobject, jstring, jdouble); - -JNIEXPORT void JNICALL -Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_addAttributeBoolean -(JNIEnv *, jobject, jstring, jboolean); - -JNIEXPORT void JNICALL -Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_addAttributeString -(JNIEnv *, jobject, jstring, jstring); - -JNIEXPORT void JNICALL -Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_updateAttributeInteger -(JNIEnv *, jobject, jstring, jint); - -JNIEXPORT void JNICALL -Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_updateAttributeDouble -(JNIEnv *, jobject, jstring, jdouble); - -JNIEXPORT void JNICALL -Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_updateAttributeBoolean -(JNIEnv *, jobject, jstring, jboolean); - -JNIEXPORT void JNICALL -Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_updateAttributeString -(JNIEnv *, jobject, jstring, jstring); - -JNIEXPORT void JNICALL -Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_updateAttributeFromAllowedValues -(JNIEnv *, jobject, jstring, jint); - -JNIEXPORT void JNICALL -Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_setRange -(JNIEnv *, jobject, jstring, jint, jint); - -JNIEXPORT void JNICALL -Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_setAllowedValuesInteger -(JNIEnv *, jobject, jstring, jobject); - -JNIEXPORT void JNICALL -Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_setAllowedValuesDouble -(JNIEnv *, jobject, jstring, jobject); - -JNIEXPORT void JNICALL -Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_setAllowedValuesString -(JNIEnv *, jobject, jstring, jobject); - -JNIEXPORT jint JNICALL -Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_startResourceAutomation -(JNIEnv *, jobject, jint, jint, jobject); - -JNIEXPORT jint JNICALL -Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_startAttributeAutomation -(JNIEnv *, jobject, jstring, jint, jint, jobject); - -JNIEXPORT void JNICALL -Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_stopAutomation -(JNIEnv *, jobject, jint); - -JNIEXPORT void JNICALL -Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_removeAttribute -(JNIEnv *, jobject, jstring); - -JNIEXPORT void JNICALL -Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_setObserverCallback -(JNIEnv *env, jobject object, jobject observer); - -JNIEXPORT jobjectArray JNICALL -Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_getObserversList -(JNIEnv *env, jobject object); - -JNIEXPORT void JNICALL -Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_notifyObserver -(JNIEnv *env, jobject object, jint jId); - -JNIEXPORT void JNICALL -Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_notifyAllObservers -(JNIEnv *env, jobject object); - -JNIEXPORT void JNICALL -Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_dispose -(JNIEnv *, jobject); - -} -#endif -#endif //SIMULATOR_RESOURCE_JNI_H_ diff --git a/service/simulator/java/jni/simulator_resource_utils_jni.cpp b/service/simulator/java/jni/simulator_resource_utils_jni.cpp new file mode 100644 index 0000000..8a23727 --- /dev/null +++ b/service/simulator/java/jni/simulator_resource_utils_jni.cpp @@ -0,0 +1,158 @@ +/****************************************************************** + * + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +#include "simulator_resource_utils_jni.h" +#include "simulator_utils_jni.h" +#include "jni_sharedobject_holder.h" +#include "jni_vector.h" + +jobject createSingleResource(JNIEnv *env, SimulatorResourceSP singleResource) +{ + if (!singleResource) + return nullptr; + + auto *objectHolder = JniSharedObjectHolder::create(singleResource); + if (!objectHolder) + return nullptr; + + static jmethodID simulatorSingleResourceCtor = env->GetMethodID( + gSimulatorClassRefs.simulatorSingleResourceCls, "", "(J)V"); + + jobject resource = (jobject) env->NewObject(gSimulatorClassRefs.simulatorSingleResourceCls, + simulatorSingleResourceCtor, reinterpret_cast(objectHolder)); + if (!resource) + { + delete objectHolder; + return nullptr; + } + + return resource; +} + +jobject createCollectionResource(JNIEnv *env, SimulatorResourceSP collectionResource) +{ + if (!collectionResource) + return nullptr; + + auto *objectHolder = JniSharedObjectHolder::create(collectionResource); + if (!objectHolder) + return nullptr; + + static jmethodID simulatorCollectionResourceCtor = env->GetMethodID( + gSimulatorClassRefs.simulatorCollectionResourceCls, "", "(J)V"); + jobject resource = (jobject) env->NewObject(gSimulatorClassRefs.simulatorCollectionResourceCls, + simulatorCollectionResourceCtor, reinterpret_cast(objectHolder)); + if (!resource) + { + delete objectHolder; + return nullptr; + } + + return resource; +} + +jobject createSimulatorResource(JNIEnv *env, SimulatorResourceSP resource) +{ + if (!resource) + return nullptr; + + if (SimulatorResource::Type::COLLECTION_RESOURCE == resource->getType()) + return createCollectionResource(env, resource); + return createSingleResource(env, resource); +} + +jobject createSimulatorResourceVector(JNIEnv *env, std::vector &resources) +{ + if (!resources.size()) + return nullptr; + + jobject vectorObject = JniVector(env).toJava(); + if (!vectorObject) + return nullptr; + + static jmethodID addMethod = env->GetMethodID(gSimulatorClassRefs.vectorCls, + "add", "(Ljava/lang/Object;)Z"); + + for (auto &resource : resources) + env->CallBooleanMethod(vectorObject, addMethod, createSimulatorResource(env, resource)); + + return vectorObject; +} + +jobject createSimulatorRemoteResource(JNIEnv *env, SimulatorRemoteResourceSP &remoteResource) +{ + if (!remoteResource) + return nullptr; + + auto *objectHolder = JniSharedObjectHolder::create(remoteResource); + if (!objectHolder) + return nullptr; + + static jmethodID simulatorRemoteResourceCtor = env->GetMethodID( + gSimulatorClassRefs.simulatorRemoteResourceCls, "", "(J)V"); + + jobject resource = (jobject) env->NewObject(gSimulatorClassRefs.simulatorRemoteResourceCls, + simulatorRemoteResourceCtor, reinterpret_cast(objectHolder)); + if (!resource) + { + delete objectHolder; + return nullptr; + } + + // Setting all required fields + static jfieldID uriID = env->GetFieldID(gSimulatorClassRefs.simulatorRemoteResourceCls, + "mUri", "Ljava/lang/String;"); + static jfieldID connTypeID = env->GetFieldID(gSimulatorClassRefs.simulatorRemoteResourceCls, + "mConnType", "I"); + static jfieldID hostID = env->GetFieldID(gSimulatorClassRefs.simulatorRemoteResourceCls, + "mHost", "Ljava/lang/String;"); + static jfieldID uidID = env->GetFieldID(gSimulatorClassRefs.simulatorRemoteResourceCls, + "mId", "Ljava/lang/String;"); + static jfieldID resTypesID = env->GetFieldID(gSimulatorClassRefs.simulatorRemoteResourceCls, + "mResTypes", "Ljava/util/Vector;"); + static jfieldID interfacesID = env->GetFieldID(gSimulatorClassRefs.simulatorRemoteResourceCls, + "mResInterfaces", "Ljava/util/Vector;"); + static jfieldID isObservableID = env->GetFieldID(gSimulatorClassRefs.simulatorRemoteResourceCls, + "mIsObservable", "Z"); + + jstring uri = env->NewStringUTF(remoteResource->getURI().c_str()); + env->SetObjectField(resource, uriID, uri); + + jint connType = remoteResource->getConnectivityType(); + env->SetIntField(resource, connTypeID, connType); + + jstring host = env->NewStringUTF(remoteResource->getHost().c_str()); + env->SetObjectField(resource, hostID, host); + + jstring uid = env->NewStringUTF(remoteResource->getID().c_str()); + env->SetObjectField(resource, uidID, uid); + + std::vector resourceTypes = remoteResource->getResourceTypes(); + jobject ResTypes = JniVector(env).toJava(resourceTypes); + env->SetObjectField(resource, resTypesID, ResTypes); + + std::vector interfaceTypes = remoteResource->getResourceInterfaces(); + jobject resInterfaces = JniVector(env).toJava(interfaceTypes); + env->SetObjectField(resource, interfacesID, resInterfaces); + + env->SetBooleanField(resource, isObservableID, remoteResource->isObservable()); + + return resource; +} \ No newline at end of file diff --git a/service/simulator/java/jni/simulator_resource_utils_jni.h b/service/simulator/java/jni/simulator_resource_utils_jni.h new file mode 100644 index 0000000..bfcb1d6 --- /dev/null +++ b/service/simulator/java/jni/simulator_resource_utils_jni.h @@ -0,0 +1,35 @@ +/****************************************************************** + * + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +#ifndef SIMULATOR_RESOURCE_UTILS_JNI_H_ +#define SIMULATOR_RESOURCE_UTILS_JNI_H_ + +#include +#include "simulator_single_resource.h" +#include "simulator_collection_resource.h" +#include "simulator_remote_resource.h" + +jobject createSingleResource(JNIEnv *env, SimulatorResourceSP singleResource); +jobject createCollectionResource(JNIEnv *env, SimulatorResourceSP collectionResource); +jobject createSimulatorResource(JNIEnv *env, SimulatorResourceSP resource); +jobject createSimulatorResourceVector(JNIEnv *env, std::vector &resources); +jobject createSimulatorRemoteResource(JNIEnv *env, SimulatorRemoteResourceSP &remoteResource); + +#endif diff --git a/service/simulator/java/jni/simulator_single_resource_jni.cpp b/service/simulator/java/jni/simulator_single_resource_jni.cpp new file mode 100644 index 0000000..638f816 --- /dev/null +++ b/service/simulator/java/jni/simulator_single_resource_jni.cpp @@ -0,0 +1,248 @@ +/****************************************************************** + * + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +#include "simulator_resource_model_jni.h" +#include "simulator_exceptions_jni.h" +#include "simulator_utils_jni.h" +#include "jni_sharedobject_holder.h" +#include "jni_listener_holder.h" +#include "jni_string.h" +#include "jni_vector.h" + +#include "simulator_single_resource.h" + +#define VALIDATE_OBJECT(ENV, OBJECT) if (!OBJECT){throwBadObjectException(ENV, "No corresponsing native object!"); return;} +#define VALIDATE_OBJECT_RET(ENV, OBJECT, RET) if (!OBJECT){throwBadObjectException(ENV, "No corresponsing native object!"); return RET;} + +SimulatorSingleResourceSP simulatorSingleResourceToCpp(JNIEnv *env, jobject object) +{ + JniSharedObjectHolder *jniResource = + GetHandle>(env, object); + if (jniResource) + return jniResource->get(); + return nullptr; +} + +static AutomationType AutomationTypeToCpp(JNIEnv *env, jobject jType) +{ + static jmethodID ordinalMID = env->GetMethodID( + gSimulatorClassRefs.automationTypeCls, "ordinal", "()I"); + + int ordinal = env->CallIntMethod(jType, ordinalMID); + return AutomationType(ordinal); +} + +static void onAutoUpdationComplete(jobject listener, const std::string &uri, const int id) +{ + JNIEnv *env = getEnv(); + if (!env) + return; + + jclass listenerCls = env->GetObjectClass(listener); + jmethodID listenerMethod = env->GetMethodID(listenerCls, "onUpdateComplete", + "(Ljava/lang/String;I)V"); + + jstring jUri = env->NewStringUTF(uri.c_str()); + env->CallVoidMethod(listener, listenerMethod, jUri, id); + releaseEnv(); +} + +#ifdef __cplusplus +extern "C" { +#endif + +JNIEXPORT jobject JNICALL +Java_org_oic_simulator_server_SimulatorSingleResource_getAttribute +(JNIEnv *env, jobject object, jstring attrName) +{ + VALIDATE_INPUT_RET(env, !attrName, "Attribute name is null!", nullptr) + + SimulatorSingleResourceSP singleResource = simulatorSingleResourceToCpp(env, object); + VALIDATE_OBJECT_RET(env, singleResource, nullptr) + + JniString jniAttrName(env, attrName); + SimulatorResourceModel::Attribute attribute; + if (singleResource->getAttribute(jniAttrName.get(), attribute)) + return simulatorResourceAttributeToJava(env, attribute); + return nullptr; +} + +JNIEXPORT void JNICALL +Java_org_oic_simulator_server_SimulatorSingleResource_addAttribute +(JNIEnv *env, jobject object, jobject resAttribute) +{ + VALIDATE_INPUT(env, !resAttribute, "Resource attribute is null!") + + SimulatorSingleResourceSP singleResource = simulatorSingleResourceToCpp(env, object); + VALIDATE_OBJECT(env, singleResource) + + try + { + SimulatorResourceModel::Attribute attribute; + if (!simulatorResourceAttributeToCpp(env, resAttribute, attribute)) + { + throwSimulatorException(env, SIMULATOR_ERROR, + "Failed to covnert SimulatorResourceAttribute java object!"); + return; + } + + singleResource->addAttribute(attribute); + } + catch (SimulatorException &e) + { + throwSimulatorException(env, e.code(), e.what()); + } +} + +JNIEXPORT void JNICALL +Java_org_oic_simulator_server_SimulatorSingleResource_updateAttribute +(JNIEnv *env, jobject object, jstring attrName, jobject attrValue) +{ + VALIDATE_INPUT(env, !attrName, "Attribute name is null!") + VALIDATE_INPUT(env, !attrValue, "Attribute value is null!") + + SimulatorSingleResourceSP singleResource = simulatorSingleResourceToCpp(env, object); + VALIDATE_OBJECT(env, singleResource) + + SimulatorResourceModel::ValueVariant value; + if (!AttributeValueToCpp(env, attrValue, value)) + { + throwSimulatorException(env, SIMULATOR_ERROR, + "Failed to covnert AttributeValue java object!"); + return; + } + + SimulatorResourceModel::Attribute attribute(JniString(env, attrName).get()); + attribute.setValue(value); + singleResource->updateAttributeValue(attribute); +} + +JNIEXPORT void JNICALL +Java_org_oic_simulator_server_SimulatorSingleResource_removeAttribute +(JNIEnv *env, jobject object, jstring attrName) +{ + VALIDATE_INPUT(env, !attrName, "Attribute name is null!") + + SimulatorSingleResourceSP singleResource = simulatorSingleResourceToCpp(env, object); + VALIDATE_OBJECT(env, singleResource) + + try + { + JniString jniAttrName(env, attrName); + singleResource->removeAttribute(jniAttrName.get()); + } + catch (InvalidArgsException &e) + { + throwInvalidArgsException(env, e.code(), e.what()); + } +} + +JNIEXPORT jint JNICALL +Java_org_oic_simulator_server_SimulatorSingleResource_startResourceUpdation +(JNIEnv *env, jobject object, jint type, jint interval, jobject listener) +{ + VALIDATE_CALLBACK_RET(env, listener, -1) + + SimulatorSingleResourceSP singleResource = simulatorSingleResourceToCpp(env, object); + VALIDATE_OBJECT_RET(env, singleResource, -1) + + jobject listenerRef = env->NewGlobalRef(listener); + updateCompleteCallback callback = [listenerRef](const std::string & uri, const int id) + { + onAutoUpdationComplete(listenerRef, uri, id); + }; + + try + { + int id = singleResource->startResourceUpdation((1 == type) ? AutomationType::RECURRENT : + AutomationType::NORMAL, interval, callback); + return id; + } + catch (InvalidArgsException &e) + { + throwInvalidArgsException(env, e.code(), e.what()); + } + catch (SimulatorException &e) + { + throwSimulatorException(env, e.code(), e.what()); + } + + return -1; +} + +JNIEXPORT jint JNICALL +Java_org_oic_simulator_server_SimulatorSingleResource_startAttributeUpdation +(JNIEnv *env, jobject object, jstring attrName, jobject type, jint interval, jobject listener) +{ + VALIDATE_INPUT_RET(env, !attrName, "Attribute name is null!", -1) + VALIDATE_CALLBACK_RET(env, listener, -1) + + SimulatorSingleResourceSP singleResource = simulatorSingleResourceToCpp(env, object); + VALIDATE_OBJECT_RET(env, singleResource, -1) + + jobject listenerRef = env->NewGlobalRef(listener); + updateCompleteCallback callback = [listenerRef](const std::string & uri, const int id) + { + onAutoUpdationComplete(listenerRef, uri, id); + }; + + JniString jniAttrName(env, attrName); + AutomationType automationType = AutomationTypeToCpp(env, type); + + try + { + int id = singleResource->startAttributeUpdation(jniAttrName.get(), automationType, + interval, callback); + return id; + } + catch (InvalidArgsException &e) + { + throwInvalidArgsException(env, e.code(), e.what()); + } + catch (SimulatorException &e) + { + throwSimulatorException(env, e.code(), e.what()); + } + + return -1; +} + +JNIEXPORT void JNICALL +Java_org_oic_simulator_server_SimulatorSingleResource_stopUpdation +(JNIEnv *env, jobject object, jint id) +{ + SimulatorSingleResourceSP singleResource = simulatorSingleResourceToCpp(env, object); + VALIDATE_OBJECT(env, singleResource) + + singleResource->stopUpdation(id); +} + +JNIEXPORT void JNICALL +Java_org_oic_simulator_server_SimulatorSingleResource_dispose +(JNIEnv *env, jobject object) +{ + JniSharedObjectHolder *resource = + GetHandle>(env, object); + delete resource; +} + +#ifdef __cplusplus +} +#endif diff --git a/service/simulator/java/jni/simulator_utils_jni.cpp b/service/simulator/java/jni/simulator_utils_jni.cpp new file mode 100644 index 0000000..1f971ce --- /dev/null +++ b/service/simulator/java/jni/simulator_utils_jni.cpp @@ -0,0 +1,293 @@ +/****************************************************************** + * + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +#include "simulator_utils_jni.h" + +jobject simulatorResultToJava(JNIEnv *env, SimulatorResult errorCode) +{ + switch (errorCode) + { + case SIMULATOR_OK: + { + static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls, + "SIMULATOR_OK", "Lorg/oic/simulator/SimulatorResult;"); + return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID); + } + case SIMULATOR_RESOURCE_CREATED: + { + static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls, + "SIMULATOR_RESOURCE_CREATED", "Lorg/oic/simulator/SimulatorResult;"); + return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID); + } + case SIMULATOR_RESOURCE_DELETED: + { + static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls, + "SIMULATOR_RESOURCE_DELETED", "Lorg/oic/simulator/SimulatorResult;"); + return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID); + } + case SIMULATOR_CONTINUE: + { + static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls, + "SIMULATOR_CONTINUE", "Lorg/oic/simulator/SimulatorResult;"); + return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID); + } + case SIMULATOR_INVALID_URI: + { + static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls, + "SIMULATOR_INVALID_URI", "Lorg/oic/simulator/SimulatorResult;"); + return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID); + } + case SIMULATOR_INVALID_QUERY: + { + static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls, + "SIMULATOR_INVALID_QUERY", "Lorg/oic/simulator/SimulatorResult;"); + return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID); + } + case SIMULATOR_INVALID_IP: + { + static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls, + "SIMULATOR_INVALID_IP", "Lorg/oic/simulator/SimulatorResult;"); + return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID); + } + case SIMULATOR_INVALID_PORT: + { + static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls, + "SIMULATOR_INVALID_PORT", "Lorg/oic/simulator/SimulatorResult;"); + return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID); + } + case SIMULATOR_INVALID_CALLBACK: + { + static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls, + "SIMULATOR_INVALID_CALLBACK", "Lorg/oic/simulator/SimulatorResult;"); + return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID); + } + case SIMULATOR_INVALID_METHOD: + { + static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls, + "SIMULATOR_INVALID_METHOD", "Lorg/oic/simulator/SimulatorResult;"); + return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID); + } + case SIMULATOR_INVALID_PARAM: + { + static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls, + "SIMULATOR_INVALID_PARAM", "Lorg/oic/simulator/SimulatorResult;"); + return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID); + } + case SIMULATOR_INVALID_OBSERVE_PARAM: + { + static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls, + "SIMULATOR_INVALID_OBSERVE_PARAM", "Lorg/oic/simulator/SimulatorResult;"); + return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID); + } + case SIMULATOR_NO_MEMORY: + { + static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls, + "SIMULATOR_NO_MEMORY", "Lorg/oic/simulator/SimulatorResult;"); + return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID); + } + case SIMULATOR_COMM_ERROR: + { + static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls, + "SIMULATOR_COMM_ERROR", "Lorg/oic/simulator/SimulatorResult;"); + return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID); + } + case SIMULATOR_TIMEOUT: + { + static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls, + "SIMULATOR_TIMEOUT", "Lorg/oic/simulator/SimulatorResult;"); + return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID); + } + case SIMULATOR_ADAPTER_NOT_ENABLED: + { + static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls, + "SIMULATOR_ADAPTER_NOT_ENABLED", "Lorg/oic/simulator/SimulatorResult;"); + return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID); + } + case SIMULATOR_NOTIMPL: + { + static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls, + "SIMULATOR_NOTIMPL", "Lorg/oic/simulator/SimulatorResult;"); + return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID); + } + case SIMULATOR_NO_RESOURCE: + { + static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls, + "SIMULATOR_NO_RESOURCE", "Lorg/oic/simulator/SimulatorResult;"); + return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID); + } + case SIMULATOR_RESOURCE_ERROR: + { + static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls, + "SIMULATOR_RESOURCE_ERROR", "Lorg/oic/simulator/SimulatorResult;"); + return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID); + } + case SIMULATOR_SLOW_RESOURCE: + { + static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls, + "SIMULATOR_SLOW_RESOURCE", "Lorg/oic/simulator/SimulatorResult;"); + return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID); + } + case SIMULATOR_DUPLICATE_REQUEST: + { + static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls, + "SIMULATOR_DUPLICATE_REQUEST", "Lorg/oic/simulator/SimulatorResult;"); + return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID); + } + case SIMULATOR_NO_OBSERVERS: + { + static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls, + "SIMULATOR_NO_OBSERVERS", "Lorg/oic/simulator/SimulatorResult;"); + return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID); + } + case SIMULATOR_OBSERVER_NOT_FOUND: + { + static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls, + "SIMULATOR_OBSERVER_NOT_FOUND", "Lorg/oic/simulator/SimulatorResult;"); + return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID); + } + case SIMULATOR_VIRTUAL_DO_NOT_HANDLE: + { + static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls, + "SIMULATOR_VIRTUAL_DO_NOT_HANDLE", "Lorg/oic/simulator/SimulatorResult;"); + return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID); + } + case SIMULATOR_INVALID_OPTION: + { + static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls, + "SIMULATOR_INVALID_OPTION", "Lorg/oic/simulator/SimulatorResult;"); + return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID); + } + case SIMULATOR_MALFORMED_RESPONSE: + { + static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls, + "SIMULATOR_MALFORMED_RESPONSE", "Lorg/oic/simulator/SimulatorResult;"); + return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID); + } + case SIMULATOR_PERSISTENT_BUFFER_REQUIRED: + { + static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls, + "SIMULATOR_PERSISTENT_BUFFER_REQUIRED", "Lorg/oic/simulator/SimulatorResult;"); + return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID); + } + case SIMULATOR_INVALID_REQUEST_HANDLE: + { + static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls, + "SIMULATOR_INVALID_REQUEST_HANDLE", "Lorg/oic/simulator/SimulatorResult;"); + return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID); + } + case SIMULATOR_INVALID_DEVICE_INFO: + { + static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls, + "SIMULATOR_INVALID_DEVICE_INFO", "Lorg/oic/simulator/SimulatorResult;"); + return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID); + } + case SIMULATOR_INVALID_JSON: + { + static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls, + "SIMULATOR_INVALID_JSON", "Lorg/oic/simulator/SimulatorResult;"); + return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID); + } + case SIMULATOR_UNAUTHORIZED_REQ: + { + static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls, + "SIMULATOR_UNAUTHORIZED_REQ", "Lorg/oic/simulator/SimulatorResult;"); + return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID); + } +#ifdef WITH_PRESENCE + case SIMULATOR_PRESENCE_STOPPED: + { + static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls, + "SIMULATOR_PRESENCE_STOPPED", "Lorg/oic/simulator/SimulatorResult;"); + return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID); + } + case SIMULATOR_PRESENCE_TIMEOUT: + { + static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls, + "SIMULATOR_PRESENCE_TIMEOUT", "Lorg/oic/simulator/SimulatorResult;"); + return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID); + } + case SIMULATOR_PRESENCE_DO_NOT_HANDLE: + { + static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls, + "SIMULATOR_PRESENCE_DO_NOT_HANDLE", "Lorg/oic/simulator/SimulatorResult;"); + return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID); + } +#endif + case SIMULATOR_INVALID_TYPE: + { + static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls, + "SIMULATOR_INVALID_TYPE", "Lorg/oic/simulator/SimulatorResult;"); + return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID); + } + case SIMULATOR_NOT_SUPPORTED: + { + static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls, + "SIMULATOR_NOT_SUPPORTED", "Lorg/oic/simulator/SimulatorResult;"); + return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID); + } + case SIMULATOR_OPERATION_NOT_ALLOWED: + { + static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls, + "SIMULATOR_OPERATION_NOT_ALLOWED", "Lorg/oic/simulator/SimulatorResult;"); + return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID); + } + case SIMULATOR_OPERATION_IN_PROGRESS: + { + static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls, + "SIMULATOR_OPERATION_IN_PROGRESS", "Lorg/oic/simulator/SimulatorResult;"); + return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID); + } + case SIMULATOR_INVALID_RESPONSE_CODE: + { + static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls, + "SIMULATOR_INVALID_RESPONSE_CODE", "Lorg/oic/simulator/SimulatorResult;"); + return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID); + } + case SIMULATOR_UKNOWN_PROPERTY: + { + static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls, + "SIMULATOR_UKNOWN_PROPERTY", "Lorg/oic/simulator/SimulatorResult;"); + return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID); + } + case SIMULATOR_TYPE_MISMATCH: + { + static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls, + "SIMULATOR_TYPE_MISMATCH", "Lorg/oic/simulator/SimulatorResult;"); + return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID); + } + case SIMULATOR_BAD_VALUE: + { + static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls, + "SIMULATOR_BAD_VALUE", "Lorg/oic/simulator/SimulatorResult;"); + return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID); + } + case SIMULATOR_BAD_OBJECT: + { + static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls, + "SIMULATOR_BAD_OBJECT", "Lorg/oic/simulator/SimulatorResult;"); + return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID); + } + } + + static jfieldID fieldID = env->GetStaticFieldID(gSimulatorClassRefs.simulatorResultCls, + "SIMULATOR_ERROR", "Lorg/oic/simulator/SimulatorResult;"); + return env->GetStaticObjectField(gSimulatorClassRefs.simulatorResultCls, fieldID); +} + diff --git a/service/simulator/java/jni/simulator_utils_jni.h b/service/simulator/java/jni/simulator_utils_jni.h new file mode 100644 index 0000000..f3ec682 --- /dev/null +++ b/service/simulator/java/jni/simulator_utils_jni.h @@ -0,0 +1,113 @@ +/****************************************************************** + * + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +#ifndef SIMULATOR_UTILS_JNI_H_ +#define SIMULATOR_UTILS_JNI_H_ + +#include +#include "simulator_error_codes.h" + +typedef struct +{ + jclass objectCls; + jclass integerCls; + jclass doubleCls; + jclass booleanCls; + jclass stringCls; + jclass hashMapCls; + jclass vectorCls; + jclass mapCls; + jclass mapEntryCls; + jclass setCls; + jclass iteratorCls; + + jclass interfaceTypeCls; + jclass simulatorResourceCls; + jclass simulatorResourceTypeCls; + jclass simulatorSingleResourceCls; + jclass simulatorCollectionResourceCls; + jclass simulatorResourceModelCls; + jclass simulatorResourceAttributeCls; + jclass automationTypeCls; + jclass attributeValueCls; + jclass attributeValueTypeCls; + jclass attributeTypeInfoCls; + jclass attributePropertyCls; + jclass attributePropertyTypeCls; + jclass simulatorRemoteResourceCls; + jclass observerCls; + jclass deviceInfoCls; + jclass platformInfoCls; + jclass simulatorExceptionCls; + jclass invalidArgsExceptionCls; + jclass noSupportExceptionCls; + jclass operationInProgressExceptionCls; + jclass simulatorResultCls; + + jclass integer1DArrayCls; + jclass integer2DArrayCls; + jclass integer3DArrayCls; + jclass double1DArrayCls; + jclass double2DArrayCls; + jclass double3DArrayCls; + jclass boolean1DArrayCls; + jclass boolean2DArrayCls; + jclass boolean3DArrayCls; + jclass string1DArrayCls; + jclass string2DArrayCls; + jclass string3DArrayCls; + jclass simulatorResModel1DArrayCls; + jclass simulatorResModel2DArrayCls; + jclass simulatorResModel3DArrayCls; +} SimulatorClassRefs; + +#define VALIDATE_INPUT(ENV, CONDITION, MSG) if (CONDITION) {throwInvalidArgsException(ENV, SIMULATOR_INVALID_PARAM, MSG); return;} +#define VALIDATE_INPUT_RET(ENV, CONDITION, MSG, RET) if (CONDITION) {throwInvalidArgsException(ENV, SIMULATOR_INVALID_PARAM, MSG); return RET;} + +#define VALIDATE_CALLBACK(ENV, CALLBACK) if (!CALLBACK){throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, "Invalid callback!"); return;} +#define VALIDATE_CALLBACK_RET(ENV, CALLBACK, RET) if (!CALLBACK){throwInvalidArgsException(env, SIMULATOR_INVALID_CALLBACK, "Invalid callback!"); return RET;} + +static jfieldID GetHandleField(JNIEnv *env, jobject jobj) +{ + jclass cls = env->GetObjectClass(jobj); + return env->GetFieldID(cls, "mNativeHandle", "J"); +} + +template +static T *GetHandle(JNIEnv *env, jobject jobj) +{ + jlong handle = env->GetLongField(jobj, GetHandleField(env, jobj)); + return reinterpret_cast(handle); +} + +template +static void SetHandle(JNIEnv *env, jobject jobj, T *type) +{ + jlong handle = reinterpret_cast(type); + env->SetLongField(jobj, GetHandleField(env, jobj), handle); +} + +extern JNIEnv *getEnv(); +extern void releaseEnv(); +extern SimulatorClassRefs gSimulatorClassRefs; + +jobject simulatorResultToJava(JNIEnv *env, SimulatorResult errorCode); + +#endif diff --git a/service/simulator/java/sdk/src/org/oic/simulator/AttributeProperty.java b/service/simulator/java/sdk/src/org/oic/simulator/AttributeProperty.java new file mode 100644 index 0000000..b555f0e --- /dev/null +++ b/service/simulator/java/sdk/src/org/oic/simulator/AttributeProperty.java @@ -0,0 +1,169 @@ +/* + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.oic.simulator; + +/** + * This class represents the resource attribute's vaule property. + */ +public class AttributeProperty { + + private Type mType = Type.UNKNOWN; + private double mMin = -1; + private double mMax = -1; + private AttributeValue[] mValueSet = null; + private AttributeProperty mChildProperty = null; + + /** + * Enum to represent propety type. + */ + public enum Type { + UNKNOWN, RANGE, VALUESET + } + + /** + * Constructs {@AttributeProperty} of type + * {@AttributeProperty.Type.Range} with min + * and max values. + * + * @param min + * Minimun value the attribute can have. + * @param max + * Maximum value the attribute can have. + */ + public AttributeProperty(double min, double max) { + mType = Type.RANGE; + mMin = min; + mMax = max; + } + + /** + * Constructs {@AttributeProperty} of type + * {@AttributeProperty.Type.VALUESET} with + * array of integer. + * + * @param values + * Array of int type values. + */ + public AttributeProperty(int[] values) { + mType = Type.VALUESET; + mValueSet = new AttributeValue[values.length]; + for (int i = 0; i < values.length; i++) + mValueSet[i] = new AttributeValue(values[i]); + } + + /** + * Constructs {@AttributeProperty} of type + * {@AttributeProperty.Type.VALUESET} with + * array of double. + * + * @param values + * Array of double type values. + */ + public AttributeProperty(double[] values) { + mType = Type.VALUESET; + mValueSet = new AttributeValue[values.length]; + for (int i = 0; i < values.length; i++) + mValueSet[i] = new AttributeValue(values[i]); + } + + /** + * Constructs {@AttributeProperty} of type + * {@AttributeProperty.Type.VALUESET} with + * array of boolean. + * + * @param values + * Array of boolean type values. + */ + public AttributeProperty(boolean[] values) { + mType = Type.VALUESET; + mValueSet = new AttributeValue[values.length]; + for (int i = 0; i < values.length; i++) + mValueSet[i] = new AttributeValue(values[i]); + } + + /** + * Constructs {@AttributeProperty} of type + * {@AttributeProperty.Type.VALUESET} with + * array of Strings. + * + * @param values + * Array of strings. + */ + public AttributeProperty(String[] values) { + mType = Type.VALUESET; + mValueSet = new AttributeValue[values.length]; + for (int i = 0; i < values.length; i++) + mValueSet[i] = new AttributeValue(values[i]); + } + + /** + * API to get type of property. + * + * @return {@AttributeProperty.Type}. + */ + public Type type() { + return mType; + } + + /** + * API to get minimum value which was set as property. + */ + public double min() { + return mMin; + } + + /** + * API to get maximum value which was set as property. + */ + public double max() { + return mMax; + } + + /** + * API to get array of values which was set as property. + * + * @return array of {@AttributeValue}. + */ + public AttributeValue[] valueSet() { + return mValueSet; + } + + /** + * API to set child attribute propety. + * + * @param childProperty + * Child element property this property used if the + * Attribute value is of array type. + */ + public void setChildProperty(AttributeProperty childProperty) { + mChildProperty = childProperty; + } + + /** + * API to get child attribute propety. + * + * @return Child element property. + */ + public AttributeProperty getChildProperty() { + return mChildProperty; + } + + private AttributeProperty(AttributeValue[] values) { + mType = Type.VALUESET; + mValueSet = values; + } +} diff --git a/service/simulator/java/sdk/src/org/oic/simulator/AttributeValue.java b/service/simulator/java/sdk/src/org/oic/simulator/AttributeValue.java new file mode 100644 index 0000000..76bc72c --- /dev/null +++ b/service/simulator/java/sdk/src/org/oic/simulator/AttributeValue.java @@ -0,0 +1,512 @@ +/* + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.oic.simulator; + +/** + * This class accommodate different type of values as Object. + */ +public class AttributeValue { + + private Object mValue = null; + + /** + * Enum to represent value type. + */ + public enum ValueType { + UNKNOWN, INTEGER, DOUBLE, BOOLEAN, STRING, RESOURCEMODEL, ARRAY + } + + /** + * Class provides the value type information in detail. + */ + public class TypeInfo { + public ValueType mType; + public ValueType mBaseType; + public int mDepth; + + /** + * Constructs {@AttributeValue.TypeInfo} with + * default values. + */ + TypeInfo() { + mType = ValueType.UNKNOWN; + mBaseType = ValueType.UNKNOWN; + mDepth = 0; + } + + /** + * Constructs {@AttributeValue.TypeInfo} with + * given {AttributeValue.ValueType}. + * + * @param type + * Value type. + */ + TypeInfo(ValueType type) { + mType = type; + mBaseType = type; + mDepth = 0; + } + + /** + * Constructs {@AttributeValue.TypeInfo} with + * given {AttributeValue.ValueType}s and depth information. + * + * @param type + * Value type. + * @param baseType + * Value base type. This type is useful when vaule is of + * array type. + * @param depth + * Depth of array type value. This type is useful when vaule + * is of array type. + */ + TypeInfo(ValueType type, ValueType baseType, int depth) { + mType = type; + mBaseType = baseType; + mDepth = depth; + } + } + + /** + * Constructs {@AttributeValue} with int type value. + * + * @param value + * int type value. + */ + public AttributeValue(int value) { + mValue = new Integer(value); + } + + /** + * Constructs {@AttributeValue} with double type value. + * + * @param value + * double type value. + */ + public AttributeValue(double value) { + mValue = new Double(value); + } + + /** + * Constructs {@AttributeValue} with boolean type value. + * + * @param value + * boolean type value. + */ + public AttributeValue(boolean value) { + mValue = new Boolean(value); + } + + /** + * Constructs {@AttributeValue} with String type value. + * + * @param value + * String type value. + */ + public AttributeValue(String value) { + mValue = value; + } + + /** + * Constructs {@AttributeValue} with SimulatorResourceModel + * type value. + * + * @param value + * SimulatorResourceModel type value. + */ + public AttributeValue(SimulatorResourceModel value) { + mValue = value; + } + + /** + * Constructs {@AttributeValue} with array of int type + * values. + * + * @param values + * Array of int type values. + */ + public AttributeValue(int[] values) { + Integer[] newValues = new Integer[values.length]; + for (int i = 0; i < values.length; i++) + newValues[i] = Integer.valueOf(values[i]); + mValue = newValues; + } + + /** + * Constructs {@AttributeValue} with array of Integer type + * values. + * + * @param values + * Array of Integer type values. + */ + public AttributeValue(Integer[] values) { + mValue = values; + } + + /** + * Constructs {@AttributeValue} with array of double type + * values. + * + * @param values + * Array of double type values. + */ + public AttributeValue(double[] values) { + Double[] newValues = new Double[values.length]; + for (int i = 0; i < values.length; i++) + newValues[i] = Double.valueOf(values[i]); + mValue = newValues; + } + + /** + * Constructs {@AttributeValue} with array of Double type + * values. + * + * @param values + * Array of Double type values. + */ + public AttributeValue(Double[] values) { + mValue = values; + } + + /** + * Constructs {@AttributeValue} with array of boolean type + * values. + * + * @param values + * Array of boolean type values. + */ + public AttributeValue(boolean[] values) { + Boolean[] newValues = new Boolean[values.length]; + for (int i = 0; i < values.length; i++) + newValues[i] = Boolean.valueOf(values[i]); + mValue = newValues; + } + + /** + * Constructs {@AttributeValue} with array of Boolean type + * values. + * + * @param values + * Array of Boolean type values. + */ + public AttributeValue(Boolean[] values) { + mValue = values; + } + + /** + * Constructs {@AttributeValue} with array of String type + * values. + * + * @param values + * Array of String type values. + */ + public AttributeValue(String[] values) { + mValue = values; + } + + /** + * Constructs {@AttributeValue} with array of + * SimulatorResourceModel type values. + * + * @param values + * Array of SimulatorResourceModel type values. + */ + public AttributeValue(SimulatorResourceModel[] values) { + mValue = values; + } + + /** + * Constructs {@AttributeValue} with 2 dimensional array of + * int type values. + * + * @param values + * 2 dimensional array of int type values. + */ + public AttributeValue(int[][] values) { + Integer[][] newValues = new Integer[values.length][]; + for (int i = 0; i < values.length; i++) { + newValues[i] = new Integer[values[i].length]; + for (int j = 0; j < values[i].length; j++) { + newValues[i][j] = Integer.valueOf(values[i][j]); + } + } + mValue = newValues; + } + + /** + * Constructs {@AttributeValue} with 2 dimensional array of + * Integer type values. + * + * @param values + * 2 dimensional array of Integer type values. + */ + public AttributeValue(Integer[][] values) { + mValue = values; + } + + /** + * Constructs {@AttributeValue} with 2 dimensional array of + * double type values. + * + * @param values + * 2 dimensional array of double type values. + */ + public AttributeValue(double[][] values) { + Double[][] newValues = new Double[values.length][]; + for (int i = 0; i < values.length; i++) { + newValues[i] = new Double[values[i].length]; + for (int j = 0; j < values[i].length; j++) { + newValues[i][j] = Double.valueOf(values[i][j]); + } + } + mValue = newValues; + } + + /** + * Constructs {@AttributeValue} with 2 dimensional array of + * Double type values. + * + * @param values + * 2 dimensional array of Double type values. + */ + public AttributeValue(Double[][] values) { + mValue = values; + } + + /** + * Constructs {@AttributeValue} with 2 dimensional array of + * boolean type values. + * + * @param values + * 2 dimensional array of boolean type values. + */ + public AttributeValue(boolean[][] values) { + Boolean[][] newValues = new Boolean[values.length][]; + for (int i = 0; i < values.length; i++) { + newValues[i] = new Boolean[values[i].length]; + for (int j = 0; j < values[i].length; j++) { + newValues[i][j] = Boolean.valueOf(values[i][j]); + } + } + mValue = newValues; + } + + /** + * Constructs {@AttributeValue} with 2 dimensional array of + * Boolean type values. + * + * @param values + * 2 dimensional array of Boolean type values. + */ + public AttributeValue(Boolean[][] values) { + mValue = values; + } + + /** + * Constructs {@AttributeValue} with 2 dimensional array of + * String type values. + * + * @param values + * 2 dimensional array of String type values. + */ + public AttributeValue(String[][] values) { + mValue = values; + } + + /** + * Constructs {@AttributeValue} with 2 dimensional array of + * SimulatorResourceModel type values. + * + * @param values + * 2 dimensional array of SimulatorResourceModel type values. + */ + public AttributeValue(SimulatorResourceModel[][] values) { + mValue = values; + } + + /** + * Constructs {@AttributeValue} with 3 dimensional array of + * int type values. + * + * @param values + * 3 dimensional array of int type values. + */ + public AttributeValue(int[][][] values) { + Integer[][][] newValues = new Integer[values.length][][]; + for (int i = 0; i < values.length; i++) { + newValues[i] = new Integer[values[i].length][]; + for (int j = 0; j < values[i].length; j++) { + newValues[i][j] = new Integer[values[i][j].length]; + for (int k = 0; k < values[j].length; k++) { + newValues[i][j][k] = Integer.valueOf(values[i][j][k]); + } + } + } + mValue = newValues; + } + + /** + * Constructs {@AttributeValue} with 3 dimensional array of + * Integer type values. + * + * @param values + * 3 dimensional array of Integer type values. + */ + public AttributeValue(Integer[][][] values) { + mValue = values; + } + + /** + * Constructs {@AttributeValue} with 3 dimensional array of + * double type values. + * + * @param values + * 3 dimensional array of double type values. + */ + public AttributeValue(double[][][] values) { + Double[][][] newValues = new Double[values.length][][]; + for (int i = 0; i < values.length; i++) { + newValues[i] = new Double[values[i].length][]; + for (int j = 0; j < values[i].length; j++) { + newValues[i][j] = new Double[values[i][j].length]; + for (int k = 0; k < values[j].length; k++) { + newValues[i][j][k] = Double.valueOf(values[i][j][k]); + } + } + } + mValue = newValues; + } + + /** + * Constructs {@AttributeValue} with 3 dimensional array of + * Double type values. + * + * @param values + * 3 dimensional array of Double type values. + */ + public AttributeValue(Double[][][] values) { + mValue = values; + } + + /** + * Constructs {@AttributeValue} with 3 dimensional array of + * boolean type values. + * + * @param values + * 3 dimensional array of boolean type values. + */ + public AttributeValue(boolean[][][] values) { + Boolean[][][] newValues = new Boolean[values.length][][]; + for (int i = 0; i < values.length; i++) { + newValues[i] = new Boolean[values[i].length][]; + for (int j = 0; j < values[i].length; j++) { + newValues[i][j] = new Boolean[values[i][j].length]; + for (int k = 0; k < values[j].length; k++) { + newValues[i][j][k] = Boolean.valueOf(values[i][j][k]); + } + } + } + mValue = newValues; + } + + /** + * Constructs {@AttributeValue} with 3 dimensional array of + * Boolean type values. + * + * @param values + * 3 dimensional array of Boolean type values. + */ + public AttributeValue(Boolean[][][] values) { + mValue = values; + } + + /** + * Constructs {@AttributeValue} with 3 dimensional array of + * String type values. + * + * @param values + * 3 dimensional array of String type values. + */ + public AttributeValue(String[][][] values) { + mValue = values; + } + + /** + * Constructs {@AttributeValue} with 3 dimensional array of + * SimulatorResourceModel type values. + * + * @param values + * 3 dimensional array of SimulatorResourceModel type values. + */ + public AttributeValue(SimulatorResourceModel[][][] values) { + mValue = values; + } + + /** + * API to get value type information. + * + * @return {@AttributeValue.TypeInfo}. + */ + public TypeInfo typeInfo() { + return createTypeInfo(mValue); + } + + /** + * API to get value as Object. + * + * @return Value as Object. + */ + public Object get() { + return mValue; + } + + private AttributeValue(Object value) { + mValue = value; + } + + private TypeInfo createTypeInfo(Object value) { + TypeInfo typeInfo = new TypeInfo(); + String className = value.getClass().getName(); + if (className.contains(Integer.class.getName())) { + typeInfo.mBaseType = ValueType.INTEGER; + typeInfo.mType = ValueType.INTEGER; + } else if (className.contains(Double.class.getName())) { + typeInfo.mBaseType = ValueType.DOUBLE; + typeInfo.mType = ValueType.DOUBLE; + } else if (className.contains(Boolean.class.getName())) { + typeInfo.mBaseType = ValueType.BOOLEAN; + typeInfo.mType = ValueType.BOOLEAN; + } else if (className.contains(String.class.getName())) { + typeInfo.mBaseType = ValueType.STRING; + typeInfo.mType = ValueType.STRING; + } else if (className.contains(SimulatorResourceModel.class.getName())) { + typeInfo.mBaseType = ValueType.RESOURCEMODEL; + typeInfo.mType = ValueType.RESOURCEMODEL; + } + + // For array types + if (value.getClass().isArray()) { + typeInfo.mType = ValueType.ARRAY; + for (char ch : className.toCharArray()) { + if (ch == '[') + typeInfo.mDepth++; + } + } + + return typeInfo; + } +} diff --git a/service/simulator/java/sdk/src/org/oic/simulator/AttributeValueValidation.java b/service/simulator/java/sdk/src/org/oic/simulator/AttributeValueValidation.java new file mode 100644 index 0000000..935588f --- /dev/null +++ b/service/simulator/java/sdk/src/org/oic/simulator/AttributeValueValidation.java @@ -0,0 +1,323 @@ +package org.oic.simulator; + +public class AttributeValueValidation implements AttributeValueVisitor.VisitingMethods { + private AttributeProperty mProperty = null; + + public AttributeValueValidation(AttributeProperty property) { + mProperty = property; + } + + public boolean validate(AttributeValue value) { + AttributeValueVisitor visitor = new AttributeValueVisitor(value, this); + Boolean result = (Boolean) visitor.visit(); + return result.booleanValue(); + } + + @Override + public Boolean visitingValue(Integer value) { + if (mProperty == null) + return false; + + if (checkRange(value.doubleValue()) || checkValueSet(value)) + return true; + return false; + } + + @Override + public Boolean visitingValue(Double value) { + if (mProperty == null) + return false; + + if (checkRange(value.doubleValue()) || checkValueSet(value)) + return true; + return false; + } + + @Override + public Boolean visitingValue(Boolean value) { + if (mProperty == null) + return false; + + if (checkValueSet(value)) + return true; + return false; + } + + @Override + public Boolean visitingValue(String value) { + if (mProperty == null) + return false; + + if (checkRange(value.length()) || checkValueSet(value)) + return true; + return false; + } + + @Override + public Boolean visitingValue(SimulatorResourceModel value) { + return false; + } + + @Override + public Boolean visitingValue(Integer[] values) { + if (mProperty == null) + return false; + + if (!checkRange(values.length)) + return false; + + if (mProperty.getChildProperty() != null) { + AttributeValueValidation rangeValidation = new AttributeValueValidation(mProperty.getChildProperty()); + for (Integer value : values) { + if (rangeValidation.visitingValue(value) == false) + return false; + } + } + + return true; + } + + @Override + public Boolean visitingValue(Double[] values) { + if (mProperty == null) + return false; + + if (!checkRange(values.length)) + return false; + + if (mProperty.getChildProperty() != null) { + AttributeValueValidation rangeValidation = new AttributeValueValidation(mProperty.getChildProperty()); + for (Double value : values) { + if (rangeValidation.visitingValue(value) == false) + return false; + } + } + + return true; + } + + @Override + public Boolean visitingValue(Boolean[] values) { + if (mProperty == null) + return false; + + if (!checkRange(values.length)) + return false; + + if (mProperty.getChildProperty() != null) { + AttributeValueValidation rangeValidation = new AttributeValueValidation(mProperty.getChildProperty()); + for (Boolean value : values) { + if (rangeValidation.visitingValue(value) == false) + return false; + } + } + + return true; + } + + @Override + public Boolean visitingValue(String[] values) { + if (mProperty == null) + return false; + + if (!checkRange(values.length)) + return false; + + if (mProperty.getChildProperty() != null) { + AttributeValueValidation rangeValidation = new AttributeValueValidation(mProperty.getChildProperty()); + for (String value : values) { + if (rangeValidation.visitingValue(value) == false) + return false; + } + } + + return true; + } + + @Override + public Boolean visitingValue(SimulatorResourceModel[] value) { + return false; + } + + @Override + public Boolean visitingValue(Integer[][] values) { + if (mProperty == null) + return false; + + if (!checkRange(values.length)) + return false; + + if (mProperty.getChildProperty() != null) { + AttributeValueValidation rangeValidation = new AttributeValueValidation(mProperty.getChildProperty()); + for (Integer[] value : values) { + if (rangeValidation.visitingValue(value) == false) + return false; + } + } + + return true; + } + + @Override + public Boolean visitingValue(Double[][] values) { + if (mProperty == null) + return false; + + if (!checkRange(values.length)) + return false; + + if (mProperty.getChildProperty() != null) { + AttributeValueValidation rangeValidation = new AttributeValueValidation(mProperty.getChildProperty()); + for (Double[] value : values) { + if (rangeValidation.visitingValue(value) == false) + return false; + } + } + + return true; + } + + @Override + public Boolean visitingValue(Boolean[][] values) { + if (mProperty == null) + return false; + + if (!checkRange(values.length)) + return false; + + if (mProperty.getChildProperty() != null) { + AttributeValueValidation rangeValidation = new AttributeValueValidation(mProperty.getChildProperty()); + for (Boolean[] value : values) { + if (rangeValidation.visitingValue(value) == false) + return false; + } + } + + return true; + } + + @Override + public Boolean visitingValue(String[][] values) { + if (mProperty == null) + return false; + + if (!checkRange(values.length)) + return false; + + if (mProperty.getChildProperty() != null) { + AttributeValueValidation rangeValidation = new AttributeValueValidation(mProperty.getChildProperty()); + for (String[] value : values) { + if (rangeValidation.visitingValue(value) == false) + return false; + } + } + + return true; + } + + @Override + public Boolean visitingValue(SimulatorResourceModel[][] value) { + return false; + } + + @Override + public Boolean visitingValue(Integer[][][] values) { + if (mProperty == null) + return false; + + if (!checkRange(values.length)) + return false; + + if (mProperty.getChildProperty() != null) { + AttributeValueValidation rangeValidation = new AttributeValueValidation(mProperty.getChildProperty()); + for (Integer[][] value : values) { + if (rangeValidation.visitingValue(value) == false) + return false; + } + } + + return true; + } + + @Override + public Boolean visitingValue(Double[][][] values) { + if (mProperty == null) + return false; + + if (!checkRange(values.length)) + return false; + + if (mProperty.getChildProperty() != null) { + AttributeValueValidation rangeValidation = new AttributeValueValidation(mProperty.getChildProperty()); + for (Double[][] value : values) { + if (rangeValidation.visitingValue(value) == false) + return false; + } + } + + return true; + } + + @Override + public Boolean visitingValue(Boolean[][][] values) { + if (mProperty == null) + return false; + + if (!checkRange(values.length)) + return false; + + if (mProperty.getChildProperty() != null) { + AttributeValueValidation rangeValidation = new AttributeValueValidation(mProperty.getChildProperty()); + for (Boolean[][] value : values) { + if (rangeValidation.visitingValue(value) == false) + return false; + } + } + + return true; + } + + @Override + public Boolean visitingValue(String[][][] values) { + if (mProperty == null) + return false; + + if (!checkRange(values.length)) + return false; + + if (mProperty.getChildProperty() != null) { + AttributeValueValidation rangeValidation = new AttributeValueValidation(mProperty.getChildProperty()); + for (String[][] value : values) { + if (rangeValidation.visitingValue(value) == false) + return false; + } + } + + return true; + } + + @Override + public Boolean visitingValue(SimulatorResourceModel[][][] value) { + return false; + } + + private boolean checkRange(double value) { + if (AttributeProperty.Type.RANGE == mProperty.type() + && (value >= mProperty.min() && value <= mProperty.max())) { + return true; + } + + return false; + } + + private boolean checkValueSet(T value) { + if (AttributeProperty.Type.VALUESET == mProperty.type() && null != mProperty.valueSet()) { + for (AttributeValue allowedValue : mProperty.valueSet()) { + if (allowedValue.get().equals(value)) + return true; + } + } + + return false; + } +} diff --git a/service/simulator/java/sdk/src/org/oic/simulator/AttributeValueVisitor.java b/service/simulator/java/sdk/src/org/oic/simulator/AttributeValueVisitor.java new file mode 100644 index 0000000..28fc0fb --- /dev/null +++ b/service/simulator/java/sdk/src/org/oic/simulator/AttributeValueVisitor.java @@ -0,0 +1,118 @@ +package org.oic.simulator; + +public class AttributeValueVisitor { + private AttributeValue mValue; + private VisitingMethods mListener; + + public interface VisitingMethods { + public T visitingValue(Integer value); + + public T visitingValue(Double value); + + public T visitingValue(Boolean value); + + public T visitingValue(String value); + + public T visitingValue(SimulatorResourceModel value); + + public T visitingValue(Integer[] value); + + public T visitingValue(Double[] value); + + public T visitingValue(Boolean[] value); + + public T visitingValue(String[] value); + + public T visitingValue(SimulatorResourceModel[] value); + + public T visitingValue(Integer[][] value); + + public T visitingValue(Double[][] value); + + public T visitingValue(Boolean[][] value); + + public T visitingValue(String[][] value); + + public T visitingValue(SimulatorResourceModel[][] value); + + public T visitingValue(Integer[][][] value); + + public T visitingValue(Double[][][] value); + + public T visitingValue(Boolean[][][] value); + + public T visitingValue(String[][][] value); + + public T visitingValue(SimulatorResourceModel[][][] value); + } + + public AttributeValueVisitor(AttributeValue value, VisitingMethods listener) { + mValue = value; + mListener = listener; + } + + public Object visit() { + if (null == mValue || null == mListener) + return null; + + AttributeValue.TypeInfo typeInfo = mValue.typeInfo(); + if (AttributeValue.ValueType.INTEGER == typeInfo.mBaseType) { + if (AttributeValue.ValueType.INTEGER == typeInfo.mType) + return mListener.visitingValue((Integer) mValue.get()); + else if (AttributeValue.ValueType.ARRAY == typeInfo.mType) { + if (1 == typeInfo.mDepth) + return mListener.visitingValue((Integer[]) mValue.get()); + if (2 == typeInfo.mDepth) + return mListener.visitingValue((Integer[][]) mValue.get()); + if (3 == typeInfo.mDepth) + return mListener.visitingValue((Integer[][][]) mValue.get()); + } + } else if (AttributeValue.ValueType.DOUBLE == typeInfo.mBaseType) { + if (AttributeValue.ValueType.DOUBLE == typeInfo.mType) + return mListener.visitingValue((Double) mValue.get()); + else if (AttributeValue.ValueType.ARRAY == typeInfo.mType) { + if (1 == typeInfo.mDepth) + return mListener.visitingValue((Double[]) mValue.get()); + if (2 == typeInfo.mDepth) + return mListener.visitingValue((Double[][]) mValue.get()); + if (3 == typeInfo.mDepth) + return mListener.visitingValue((Double[][][]) mValue.get()); + } + } else if (AttributeValue.ValueType.BOOLEAN == typeInfo.mBaseType) { + if (AttributeValue.ValueType.BOOLEAN == typeInfo.mType) + return mListener.visitingValue((Boolean) mValue.get()); + else if (AttributeValue.ValueType.ARRAY == typeInfo.mType) { + if (1 == typeInfo.mDepth) + return mListener.visitingValue((Boolean[]) mValue.get()); + if (2 == typeInfo.mDepth) + return mListener.visitingValue((Boolean[][]) mValue.get()); + if (3 == typeInfo.mDepth) + return mListener.visitingValue((Boolean[][][]) mValue.get()); + } + } else if (AttributeValue.ValueType.STRING == typeInfo.mBaseType) { + if (AttributeValue.ValueType.STRING == typeInfo.mType) + return mListener.visitingValue((String) mValue.get()); + else if (AttributeValue.ValueType.ARRAY == typeInfo.mType) { + if (1 == typeInfo.mDepth) + return mListener.visitingValue((String[]) mValue.get()); + if (2 == typeInfo.mDepth) + return mListener.visitingValue((String[][]) mValue.get()); + if (3 == typeInfo.mDepth) + return mListener.visitingValue((String[][][]) mValue.get()); + } + } else if (AttributeValue.ValueType.RESOURCEMODEL == typeInfo.mBaseType) { + if (AttributeValue.ValueType.RESOURCEMODEL == typeInfo.mType) + return mListener.visitingValue((SimulatorResourceModel) mValue.get()); + else if (AttributeValue.ValueType.ARRAY == typeInfo.mType) { + if (1 == typeInfo.mDepth) + return mListener.visitingValue((SimulatorResourceModel[]) mValue.get()); + if (2 == typeInfo.mDepth) + return mListener.visitingValue((SimulatorResourceModel[][]) mValue.get()); + if (3 == typeInfo.mDepth) + return mListener.visitingValue((SimulatorResourceModel[][][]) mValue.get()); + } + } + + return null; + } +} diff --git a/service/simulator/java/sdk/src/org/oic/simulator/DeviceInfo.java b/service/simulator/java/sdk/src/org/oic/simulator/DeviceInfo.java index 49e8e39..66a45ce 100644 --- a/service/simulator/java/sdk/src/org/oic/simulator/DeviceInfo.java +++ b/service/simulator/java/sdk/src/org/oic/simulator/DeviceInfo.java @@ -17,7 +17,7 @@ package org.oic.simulator; /** - * This class contains remote device information and provides APIs to access it. + * This class contains remote device information. */ public class DeviceInfo { private String mName; diff --git a/service/simulator/java/sdk/src/org/oic/simulator/IDeviceInfo.java b/service/simulator/java/sdk/src/org/oic/simulator/DeviceListener.java similarity index 85% rename from service/simulator/java/sdk/src/org/oic/simulator/IDeviceInfo.java rename to service/simulator/java/sdk/src/org/oic/simulator/DeviceListener.java index cb541ad..f6254b0 100644 --- a/service/simulator/java/sdk/src/org/oic/simulator/IDeviceInfo.java +++ b/service/simulator/java/sdk/src/org/oic/simulator/DeviceListener.java @@ -17,11 +17,11 @@ package org.oic.simulator; /** - * Interface for getting device information. + * Listener for getting device information. */ -public interface IDeviceInfo { +public interface DeviceListener { /** - * Callback method which provides remote device information. + * Method which provides remote device information. * * @param devInfo * {@link DeviceInfo} object holding the device information. diff --git a/service/simulator/java/sdk/src/org/oic/simulator/IAutomation.java b/service/simulator/java/sdk/src/org/oic/simulator/IAutomation.java deleted file mode 100644 index 1338fd5..0000000 --- a/service/simulator/java/sdk/src/org/oic/simulator/IAutomation.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.oic.simulator; - -/** - * Interface for receiving notifications on completion of automation. - */ -public interface IAutomation { - /** - * Callback method for receiving automation complete notifications. - * - * @param resourceURI - * URI of the resource on which the automation has occurred. - * @param automationId - * Unique Id of the automation. - */ - public void onAutomationComplete(String resourceURI, int automationId); -} diff --git a/service/simulator/java/sdk/src/org/oic/simulator/ILogger.java b/service/simulator/java/sdk/src/org/oic/simulator/ILogger.java index 082e59e..eedc935 100644 --- a/service/simulator/java/sdk/src/org/oic/simulator/ILogger.java +++ b/service/simulator/java/sdk/src/org/oic/simulator/ILogger.java @@ -28,8 +28,7 @@ public interface ILogger { } /** - * This callback method will be called to notify the application about the - * status or problems along with their severity. + * This method will be used to deliver the log messages from native layer. * * @param time * Local time information when action/event logged. diff --git a/service/simulator/java/sdk/src/org/oic/simulator/InvalidArgsException.java b/service/simulator/java/sdk/src/org/oic/simulator/InvalidArgsException.java index d62fbdd..256e3eb 100644 --- a/service/simulator/java/sdk/src/org/oic/simulator/InvalidArgsException.java +++ b/service/simulator/java/sdk/src/org/oic/simulator/InvalidArgsException.java @@ -21,7 +21,16 @@ package org.oic.simulator; */ @SuppressWarnings("serial") public class InvalidArgsException extends SimulatorException { - public InvalidArgsException(int errorCode, String errMessage) { - super(errorCode, errMessage); + + public InvalidArgsException(int code, String message) { + super(code, message); + } + + public InvalidArgsException(SimulatorResult code, String message) { + super(code, message); + } + + public InvalidArgsException(String message) { + super(SimulatorResult.SIMULATOR_INVALID_PARAM, message); } } diff --git a/service/simulator/java/sdk/src/org/oic/simulator/NoSupportException.java b/service/simulator/java/sdk/src/org/oic/simulator/NoSupportException.java index 914641f..7e6348a 100644 --- a/service/simulator/java/sdk/src/org/oic/simulator/NoSupportException.java +++ b/service/simulator/java/sdk/src/org/oic/simulator/NoSupportException.java @@ -21,7 +21,12 @@ package org.oic.simulator; */ @SuppressWarnings("serial") public class NoSupportException extends SimulatorException { - public NoSupportException(int errorCode, String errMessage) { - super(errorCode, errMessage); + + public NoSupportException(String message) { + super(SimulatorResult.SIMULATOR_NOT_SUPPORTED, message); + } + + public NoSupportException(SimulatorResult code, String message) { + super(code, message); } } \ No newline at end of file diff --git a/service/simulator/java/sdk/src/org/oic/simulator/OperationInProgressException.java b/service/simulator/java/sdk/src/org/oic/simulator/OperationInProgressException.java index c9127b5..e0c259c 100644 --- a/service/simulator/java/sdk/src/org/oic/simulator/OperationInProgressException.java +++ b/service/simulator/java/sdk/src/org/oic/simulator/OperationInProgressException.java @@ -22,7 +22,12 @@ package org.oic.simulator; */ @SuppressWarnings("serial") public class OperationInProgressException extends SimulatorException { - public OperationInProgressException(int errorCode, String errMessage) { - super(errorCode, errMessage); + + public OperationInProgressException(String message) { + super(SimulatorResult.SIMULATOR_OPERATION_IN_PROGRESS, message); + } + + public OperationInProgressException(SimulatorResult code, String message) { + super(code, message); } } diff --git a/service/simulator/java/sdk/src/org/oic/simulator/PlatformInfo.java b/service/simulator/java/sdk/src/org/oic/simulator/PlatformInfo.java index 7956e92..8ff3a60 100644 --- a/service/simulator/java/sdk/src/org/oic/simulator/PlatformInfo.java +++ b/service/simulator/java/sdk/src/org/oic/simulator/PlatformInfo.java @@ -22,16 +22,16 @@ package org.oic.simulator; */ public class PlatformInfo { private String mPlatformId; - private String m_manufacturerName; - private String m_manufacturerUrl; - private String m_modelNumber; - private String m_dateOfManufacture; - private String m_platformVersion; - private String m_operationSystemVersion; - private String m_hardwareVersion; - private String m_firmwareVersion; - private String m_supportUrl; - private String m_systemTime; + private String mManufacturerName; + private String mManufacturerUrl; + private String mModelNumber; + private String mDateOfManufacture; + private String mPlatformVersion; + private String mOperationSystemVersion; + private String mHardwareVersion; + private String mFirmwareVersion; + private String mSupportUrl; + private String mSystemTime; /** * This method is for getting platform id. @@ -58,7 +58,7 @@ public class PlatformInfo { * @return Manufacturer name. */ public String getManufacturerName() { - return m_manufacturerName; + return mManufacturerName; } /** @@ -68,7 +68,7 @@ public class PlatformInfo { * Manufacturer name. */ public void setManufacturerName(String m_manufacturerName) { - this.m_manufacturerName = m_manufacturerName; + this.mManufacturerName = m_manufacturerName; } /** @@ -77,7 +77,7 @@ public class PlatformInfo { * @return Manufacturer URL. */ public String getManufacturerUrl() { - return m_manufacturerUrl; + return mManufacturerUrl; } /** @@ -87,7 +87,7 @@ public class PlatformInfo { * Manufacturer URL. */ public void setManufacturerUrl(String m_manufacturerUrl) { - this.m_manufacturerUrl = m_manufacturerUrl; + this.mManufacturerUrl = m_manufacturerUrl; } /** @@ -96,7 +96,7 @@ public class PlatformInfo { * @return Model number. */ public String getModelNumber() { - return m_modelNumber; + return mModelNumber; } /** @@ -106,7 +106,7 @@ public class PlatformInfo { * Model number. */ public void setModelNumber(String m_modelNumber) { - this.m_modelNumber = m_modelNumber; + this.mModelNumber = m_modelNumber; } /** @@ -115,7 +115,7 @@ public class PlatformInfo { * @return Date of manufacture. */ public String getDateOfManufacture() { - return m_dateOfManufacture; + return mDateOfManufacture; } /** @@ -125,7 +125,7 @@ public class PlatformInfo { * Date of manufacture. */ public void setDateOfManufacture(String m_dateOfManufacture) { - this.m_dateOfManufacture = m_dateOfManufacture; + this.mDateOfManufacture = m_dateOfManufacture; } /** @@ -134,7 +134,7 @@ public class PlatformInfo { * @return Platform version. */ public String getPlatformVersion() { - return m_platformVersion; + return mPlatformVersion; } /** @@ -144,7 +144,7 @@ public class PlatformInfo { * Platform version. */ public void setPlatformVersion(String m_platformVersion) { - this.m_platformVersion = m_platformVersion; + this.mPlatformVersion = m_platformVersion; } /** @@ -153,7 +153,7 @@ public class PlatformInfo { * @return Operation system version. */ public String getOperationSystemVersion() { - return m_operationSystemVersion; + return mOperationSystemVersion; } /** @@ -163,7 +163,7 @@ public class PlatformInfo { * Operation system version. */ public void setOperationSystemVersion(String m_operationSystemVersion) { - this.m_operationSystemVersion = m_operationSystemVersion; + this.mOperationSystemVersion = m_operationSystemVersion; } /** @@ -172,7 +172,7 @@ public class PlatformInfo { * @return Hardware version. */ public String getHardwareVersion() { - return m_hardwareVersion; + return mHardwareVersion; } /** @@ -182,7 +182,7 @@ public class PlatformInfo { * Hardware version. */ public void setHardwareVersion(String m_hardwareVersion) { - this.m_hardwareVersion = m_hardwareVersion; + this.mHardwareVersion = m_hardwareVersion; } /** @@ -191,7 +191,7 @@ public class PlatformInfo { * @return Firmware version. */ public String getFirmwareVersion() { - return m_firmwareVersion; + return mFirmwareVersion; } /** @@ -201,7 +201,7 @@ public class PlatformInfo { * Firmware version. */ public void setFirmwareVersion(String m_firmwareVersion) { - this.m_firmwareVersion = m_firmwareVersion; + this.mFirmwareVersion = m_firmwareVersion; } /** @@ -210,7 +210,7 @@ public class PlatformInfo { * @return URL of support link. */ public String getSupportUrl() { - return m_supportUrl; + return mSupportUrl; } /** @@ -220,7 +220,7 @@ public class PlatformInfo { * URL of support link. */ public void setSupportUrl(String m_supportUrl) { - this.m_supportUrl = m_supportUrl; + this.mSupportUrl = m_supportUrl; } /** @@ -229,7 +229,7 @@ public class PlatformInfo { * @return System time. */ public String getSystemTime() { - return m_systemTime; + return mSystemTime; } /** @@ -239,6 +239,6 @@ public class PlatformInfo { * System time. */ public void setSystemTime(String m_systemTime) { - this.m_systemTime = m_systemTime; + this.mSystemTime = m_systemTime; } } diff --git a/service/simulator/java/sdk/src/org/oic/simulator/IPlatformInfo.java b/service/simulator/java/sdk/src/org/oic/simulator/PlatformListener.java similarity index 84% rename from service/simulator/java/sdk/src/org/oic/simulator/IPlatformInfo.java rename to service/simulator/java/sdk/src/org/oic/simulator/PlatformListener.java index 120ec01..531729d 100644 --- a/service/simulator/java/sdk/src/org/oic/simulator/IPlatformInfo.java +++ b/service/simulator/java/sdk/src/org/oic/simulator/PlatformListener.java @@ -17,11 +17,11 @@ package org.oic.simulator; /** - * Interface for getting platform information. + * Listener for getting platform information. */ -public interface IPlatformInfo { +public interface PlatformListener { /** - * Callback method which provides remote device platform information. + * Method which provides remote device platform information. * * @param platformInfo * {@link PlatformInfo} object holding the platform information. diff --git a/service/simulator/java/sdk/src/org/oic/simulator/ResourceAttribute.java b/service/simulator/java/sdk/src/org/oic/simulator/ResourceAttribute.java deleted file mode 100644 index 0822e76..0000000 --- a/service/simulator/java/sdk/src/org/oic/simulator/ResourceAttribute.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.oic.simulator; - -/** - * This class represents an attribute of a resource. It has a set of native - * methods for getting the attribute's information. - */ -public class ResourceAttribute { - /** - * Type of attribute value. - */ - public enum Type { - UNKNOWN, INT, DOUBLE, BOOL, STRING; - - private static Type[] m_cvalues = Type.values(); - - @SuppressWarnings("unused") - private static Type getType(int x) { - return m_cvalues[x]; - } - }; - - /** - * Class contains range property in min and max value. - */ - public class Range { - public int getMin() { - return m_min; - } - - public int getMax() { - return m_max; - } - - private Range(int min, int max) { - m_min = min; - m_max = max; - } - - private int m_min; - private int m_max; - } - - @SuppressWarnings("unused") - private void setRange(int min, int max) { - m_range = new Range(min, max); - } - - /** - * This generic API is used to get the value of an attribute whose type is - * given by the caller of the method. - * - * @param - * This specifies the type in which the value has to be returned. - * - * @return The attribute's value in a specified type. - */ - public 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 - * Attribute's allowed values whose type is given by the caller - * of the method. - * - * @return Attribute's value range as {@link Range}. - */ - public 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 index 7b4c5c8..95e22fa 100644 --- a/service/simulator/java/sdk/src/org/oic/simulator/SimulatorException.java +++ b/service/simulator/java/sdk/src/org/oic/simulator/SimulatorException.java @@ -23,19 +23,24 @@ package org.oic.simulator; @SuppressWarnings("serial") public class SimulatorException extends Exception { - private SimulatorResult errorCode; - private String errorMessage; + private SimulatorResult code; + private String message; - public SimulatorException(int errorCode, String errMessage) { - this.errorCode = SimulatorResult.get(errorCode); - this.errorMessage = errMessage; + public SimulatorException(int code, String message) { + this.code = SimulatorResult.get(code); + this.message = message; + } + + public SimulatorException(SimulatorResult code, String message) { + this.code = code; + this.message = new String(message); } public SimulatorResult code() { - return errorCode; + return code; } public String message() { - return errorMessage; + return message; } } \ No newline at end of file diff --git a/service/simulator/java/sdk/src/org/oic/simulator/SimulatorManager.java b/service/simulator/java/sdk/src/org/oic/simulator/SimulatorManager.java index a16ce67..4f4fb5e 100644 --- a/service/simulator/java/sdk/src/org/oic/simulator/SimulatorManager.java +++ b/service/simulator/java/sdk/src/org/oic/simulator/SimulatorManager.java @@ -16,9 +16,10 @@ package org.oic.simulator; -import org.oic.simulator.clientcontroller.IFindResourceListener; -import org.oic.simulator.serviceprovider.IResourceModelChangedListener; -import org.oic.simulator.serviceprovider.SimulatorResourceServer; +import java.util.Vector; + +import org.oic.simulator.client.FindResourceListener; +import org.oic.simulator.server.SimulatorResource; /** * This class provides a set of methods for creation, discovery and deletion of @@ -26,15 +27,14 @@ import org.oic.simulator.serviceprovider.SimulatorResourceServer; */ public class SimulatorManager { + private SimulatorManager() { + } + /** - * API for creating a resource from a RAML configuration file whose path is - * given as a parameter. + * API for creating a resource from a RAML configuration file. * * @param configPath * Path to RAML configuration file. - * @param listener - * Listener for receiving notifications whenever there is a - * change in the resource model. * * @return {@link SimulatorResourceServer} - Created resource on success, * otherwise null. @@ -44,30 +44,16 @@ public class SimulatorManager { * @throws SimulatorException * Thrown for other errors. */ - public static SimulatorResourceServer createResource(String configPath, - IResourceModelChangedListener listener) - throws InvalidArgsException, SimulatorException { - if (configPath.isEmpty() || null == listener) - throw new InvalidArgsException( - SimulatorResult.SIMULATOR_INVALID_PARAM.ordinal(), - "Parameter passed in invalid"); - SimulatorResourceServer simulatorResourceServerObj; - simulatorResourceServerObj = SimulatorManagerNativeInterface - .createResource(configPath, listener); - return simulatorResourceServerObj; - } + public static native SimulatorResource createResource(String configPath) + throws InvalidArgsException, SimulatorException; /** - * API for creating a set of resources from a RAML configuration file whose - * path is given as a parameter. + * API for creating a set of resources from a RAML configuration file. * * @param configPath * Path to RAML configuration file. * @param count * Number of resources to be created. - * @param listener - * Listener for receiving notifications whenever there is a - * change in the resource model. * * @return Returns an array of {@link SimulatorResourceServer} objects one * for each created resource on success, otherwise null. @@ -77,51 +63,34 @@ public class SimulatorManager { * @throws SimulatorException * Thrown for other errors. */ - public static SimulatorResourceServer[] createResource(String configPath, - int count, IResourceModelChangedListener listener) - throws InvalidArgsException, SimulatorException { - if (configPath.isEmpty() || count < 0 || null == listener) - throw new InvalidArgsException( - SimulatorResult.SIMULATOR_INVALID_PARAM.ordinal(), - "Parameter passed in invalid"); - SimulatorResourceServer[] simulatorResourceServers; - simulatorResourceServers = SimulatorManagerNativeInterface - .createResources(configPath, count, listener); - return simulatorResourceServers; - } + public static Vector createResource(String configPath, + int count) throws InvalidArgsException, SimulatorException { + return createResources(configPath, count); + }; /** - * API for deleting a specific resource. + * API for creating a resource either single or collection type. * - * @param resource - * {@link SimulatorResourceServer} object of the resource to be - * deleted. + * @param configPath + * Path to RAML configuration file. + * + * @return {@link SimulatorResourceServer} - Created resource on success, + * otherwise null. * * @throws InvalidArgsException - * Thrown if the input parameter is empty. + * Thrown if the input parameters are empty. * @throws SimulatorException * Thrown for other errors. */ - public static void deleteResource(SimulatorResourceServer resource) + public static SimulatorResource createResource(SimulatorResource.Type type, + String name, String uri, String resourceType) throws InvalidArgsException, SimulatorException { - SimulatorManagerNativeInterface.deleteResource(resource); - } - - /** - * API for deleting either all the resources or resources of a specific - * type. Ex: If resourceType is oic.light, all resources of oic.light type - * will be deleted. If resourceType is null, then all of the resources will - * be deleted. - * - * @param resourceType - * Type of resource to be deleted. - * - * @throws SimulatorException - * Thrown for other errors. - */ - public static void deleteResources(String resourceType) - throws SimulatorException { - SimulatorManagerNativeInterface.deleteResources(resourceType); + SimulatorResource resource = null; + if (type == SimulatorResource.Type.SINGLE) + resource = createSingleResource(name, uri, resourceType); + else + resource = createCollectionResource(name, uri, resourceType); + return resource; } /** @@ -136,9 +105,9 @@ public class SimulatorManager { * @throws SimulatorException * Thrown for other errors. */ - public static void findResource(IFindResourceListener listener) + public static void findResource(FindResourceListener listener) throws InvalidArgsException, SimulatorException { - SimulatorManagerNativeInterface.findResource(null, listener); + searchResource(null, listener); } /** @@ -156,24 +125,15 @@ public class SimulatorManager { * Thrown for other errors. */ public static void findResource(String resourceType, - IFindResourceListener listener) throws InvalidArgsException, + FindResourceListener listener) throws InvalidArgsException, SimulatorException { if (null == resourceType || resourceType.isEmpty()) { throw new InvalidArgsException( - SimulatorResult.SIMULATOR_INVALID_PARAM.ordinal(), - "Resource type is empty"); + SimulatorResult.SIMULATOR_INVALID_PARAM, + "Invalid resource type!"); } - SimulatorManagerNativeInterface.findResource(resourceType, listener); - } - /** - * API to set the listener for receiving log messages. - * - * @param logger - * {@link ILogger} to receive the log messages. - */ - public static void setLogger(ILogger logger) { - SimulatorManagerNativeInterface.setLogger(logger); + searchResource(resourceType, listener); } /** @@ -182,20 +142,17 @@ public class SimulatorManager { * @param deviceInfo * Device information. */ - public static void setDeviceInfo(String deviceInfo) { - SimulatorManagerNativeInterface.setDeviceInfo(deviceInfo); - } + public static native void setDeviceInfo(String deviceInfo) + throws InvalidArgsException, SimulatorException; /** - * API to get the device information asynchronously via callback - * using {@link IDeviceInfo}. + * API to search for devices in the network. * * @param listener - * Interface for receiving the device information. + * Listener for receiving the device information. */ - public static void getDeviceInfo(IDeviceInfo listener) { - SimulatorManagerNativeInterface.getDeviceInfo(listener); - } + public static native void findDevices(DeviceListener listener) + throws InvalidArgsException, SimulatorException; /** * API to set the platform information. @@ -203,18 +160,36 @@ public class SimulatorManager { * @param platformInfo * {@link PlatformInfo} - Platform information. */ - public static void setPlatformInfo(PlatformInfo platformInfo) { - SimulatorManagerNativeInterface.setPlatformInfo(platformInfo); - } + public static native void setPlatformInfo(PlatformInfo platformInfo) + throws InvalidArgsException, SimulatorException; /** - * API to get the platform information asynchronously via callback - * using {@link IPlatformInfo}.. + * API to find all devices' platform information in the network. * * @param listener - * Interface for receiving the platform information. + * Listener for receiving the platform information. */ - public static void getPlatformInfo(IPlatformInfo listener) { - SimulatorManagerNativeInterface.getPlatformInfo(listener); - } + public static native void getPlatformInformation(PlatformListener listener) + throws InvalidArgsException, SimulatorException; + + /** + * API to set the listener for receiving log messages. + * + * @param logger + * {@link ILogger} to receive the log messages. + */ + public static native void setLogger(ILogger logger) + throws SimulatorException; + + private static native Vector createResources( + String configPath, int count); + + private static native SimulatorResource createSingleResource(String name, + String uri, String resourceType); + + private static native SimulatorResource createCollectionResource( + String name, String uri, String resourceType); + + private static native void searchResource(String resourceType, + FindResourceListener listener); } \ No newline at end of file diff --git a/service/simulator/java/sdk/src/org/oic/simulator/SimulatorManagerNativeInterface.java b/service/simulator/java/sdk/src/org/oic/simulator/SimulatorManagerNativeInterface.java deleted file mode 100644 index 5fd2185..0000000 --- a/service/simulator/java/sdk/src/org/oic/simulator/SimulatorManagerNativeInterface.java +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.oic.simulator; - -import org.oic.simulator.clientcontroller.IFindResourceListener; -import org.oic.simulator.serviceprovider.IResourceModelChangedListener; -import org.oic.simulator.serviceprovider.SimulatorResourceServer; - -/** - * This class provides a set of native functions for creation, discovery and - * deletion of resources. - */ -class SimulatorManagerNativeInterface { - - /** - * Native function for creating a resource. - * - * @param configPath - * Path to RAML configuration file. - * @param listener - * Listener for receiving notifications whenever there is a - * change in the resource model. - * - * @return {@link SimulatorResourceServer} object on success, otherwise - * null. - * - * @throws InvalidArgsException - * Thrown if the input parameters are empty. - * @throws SimulatorException - * Thrown for other errors. - */ - public static native SimulatorResourceServer createResource( - String configPath, IResourceModelChangedListener listener) - throws InvalidArgsException, SimulatorException; - - /** - * Native function for creating several resources. - * - * @param configPath - * Path to RAML configuration file. - * @param count - * Number of instances. - * @param listener - * Listener for receiving notifications whenever there is a - * change in the resource model. - * - * @return An array of {@link SimulatorResourceServer} objects on success, - * otherwise null. - * - * @throws InvalidArgsException - * Thrown if the input parameters are empty. - * @throws SimulatorException - * Thrown for other errors. - */ - public static native SimulatorResourceServer[] createResources( - String configPath, int count, IResourceModelChangedListener listener) - throws InvalidArgsException, SimulatorException; - - /** - * Native function to delete a specific resource. - * - * @param resource - * {@link SimulatorResourceServer} object of the resource to be - * deleted. - * - * @throws InvalidArgsException - * Thrown if the input parameter is empty. - * @throws SimulatorException - * Thrown for other errors. - */ - public static native void deleteResource(SimulatorResourceServer resource) - throws InvalidArgsException, SimulatorException; - - /** - * Native function to delete all resources or resources of a specific type. - * - * @param resourceType - * Type of the resource. - * - * @throws InvalidArgsException - * Thrown if the input parameter is empty. - * @throws SimulatorException - * Thrown for other errors. - */ - public static native void deleteResources(String resourceType) - throws SimulatorException; - - /** - * Native function for discovering resources. - * - * @param resourceType - * required resource type - * @param listener - * Interface to receive the discovered remote resources. - * - * @throws InvalidArgsException - * Thrown if the input parameter is empty. - * @throws SimulatorException - * Thrown for other errors. - */ - public static native void findResource(String resourceType, - IFindResourceListener listener) throws InvalidArgsException, - SimulatorException; - - /** - * Native function to set the logger listener for receiving the log messages - * from native layer. - * - * @param logger - * Interface to receive log. - */ - public static native void setLogger(ILogger logger); - - /** - * Native function to set the device information. - * - * @param deviceInfo - * Device information. - */ - public static native void setDeviceInfo(String deviceInfo); - - /** - * Native function to get the device information asynchronously via the - * listener. - * - * @param listener - * Interface for receiving the device information. - */ - public static native void getDeviceInfo(IDeviceInfo listener); - - /** - * Native function to set the platform information. - * - * @param platformInfo - * Platform information. - */ - public static native void setPlatformInfo(PlatformInfo platformInfo); - - /** - * Native function to get the platform information asynchronously via the - * listener. - * - * @param listener - * Interface for receiving the platform information. - */ - public static native void getPlatformInfo(IPlatformInfo listener); -} \ No newline at end of file diff --git a/service/simulator/java/sdk/src/org/oic/simulator/SimulatorResourceAttribute.java b/service/simulator/java/sdk/src/org/oic/simulator/SimulatorResourceAttribute.java new file mode 100644 index 0000000..e2db0f4 --- /dev/null +++ b/service/simulator/java/sdk/src/org/oic/simulator/SimulatorResourceAttribute.java @@ -0,0 +1,99 @@ +/* + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.oic.simulator; + +/** + * This class represents the resource attribute which contains attribute value + * and its property. + */ +public class SimulatorResourceAttribute { + + private String mName = null; + private AttributeValue mValue = null; + private AttributeProperty mProperty = null; + + /** + * Constructs {@SimulatorResourceAttribute} + * with attribute name, value and its property. + * + * @param name + * Name of the attribute. + * @param value + * Value of the attribute. + * @param property + * Property of attribute value. + */ + public SimulatorResourceAttribute(String name, AttributeValue value, + AttributeProperty property) { + mName = new String(name); + mValue = value; + mProperty = property; + } + + /** + * Constructs {@SimulatorResourceAttribute} + * with attribute name, value. + * + * @param name + * Name of the attribute. + * @param value + * Value of the attribute. + */ + public SimulatorResourceAttribute(String name, AttributeValue value) { + mName = new String(name); + mValue = value; + mProperty = null; + } + + /** + * API to get name of attribute. + * + * @return Attribute's name. + */ + public String name() { + return mName; + } + + /** + * API to get value of attribute. + * + * @return Attribute's value {@AttributeValue}. + */ + public AttributeValue value() { + return mValue; + } + + /** + * API to get propety of attribute's value. + * + * @return Attribute's value property {@AttributeProperty + * }. + */ + public AttributeProperty property() { + return mProperty; + } + + /** + * API to set the value of attribute. + * + * @param value + * Value of the attribute. + */ + public void setValue(AttributeValue value) { + this.mValue = value; + } +} diff --git a/service/simulator/java/sdk/src/org/oic/simulator/SimulatorResourceModel.java b/service/simulator/java/sdk/src/org/oic/simulator/SimulatorResourceModel.java index 63961e9..04c2de5 100644 --- a/service/simulator/java/sdk/src/org/oic/simulator/SimulatorResourceModel.java +++ b/service/simulator/java/sdk/src/org/oic/simulator/SimulatorResourceModel.java @@ -16,155 +16,212 @@ package org.oic.simulator; -import org.oic.simulator.ResourceAttribute; +import java.util.HashMap; import java.util.Map; /** - * This class represents the resource model of a resource and it provides a set - * of native methods for accessing the resource model. + * This class represents the resource model of a resource. */ public class SimulatorResourceModel { + private Map mValues = null; + private Map mProperties = null; + /** - * Constructor for creating a native resource model object. Client requests - * such as PUT and POST uses this method for passing the new/updated - * resource model. + * Constructs new {@SimulatorResourceModel} object. */ public SimulatorResourceModel() { - create(); + mValues = new HashMap<>(); + mProperties = new HashMap<>(); } /** - * API to add an attribute of type integer. + * API to add an attribute to resource model. * - * @param name - * Name of the attribute + * @param attrName + * Name of the attribute. * @param value - * Value of the attribute + * Value of the attribute. * * @throws InvalidArgsException - * This exception will be thrown if the attribute name is - * invalid. - * @throws SimulatorException - * This exception will be thrown either if the resource model is - * not found or for some general errors. + * This exception will be thrown on invalid input. */ - public native void addAttributeInt(String name, int value) - throws InvalidArgsException, SimulatorException; + public void addAttribute(String attrName, AttributeValue value) + throws InvalidArgsException { + if (null == attrName || attrName.isEmpty()) + throw new InvalidArgsException("Invalid attribute name!"); + + if (null == value) + throw new InvalidArgsException("Attribute value is null!"); + + mValues.put(attrName, value); + } /** - * API to add an attribute of type double. + * API to add an attribute to resource model. * - * @param name - * Name of the attribute - * @param value - * Value of the attribute + * @param attribute + * {@link SimulatorResourceAttribute} to be add to resource + * model. * * @throws InvalidArgsException - * This exception will be thrown if the attribute name is - * invalid. - * @throws SimulatorException - * This exception will be thrown either if the resource model is - * not found or for some general errors. + * This exception will be thrown on invalid input. */ - public native void addAttributeDouble(String name, double value) - throws InvalidArgsException, SimulatorException; + public void addAttribute(SimulatorResourceAttribute attribute) + throws InvalidArgsException { + if (null == attribute || null == attribute.name() + || attribute.name().isEmpty() || null == attribute.value()) + throw new InvalidArgsException("Invalid attribute!"); + + mValues.put(attribute.name(), attribute.value()); + } /** - * API to add an attribute of type boolean. + * API to set attribute's property. * - * @param name - * Name of the attribute - * @param value - * Value of the attribute + * @param attrName + * Name of the attribute. + * @param property + * {@link AttributeProperty} to be set for attribute. * * @throws InvalidArgsException - * This exception will be thrown if the attribute name is - * invalid. - * @throws SimulatorException - * This exception will be thrown either if the resource model is - * not found or for some general errors. + * This exception will be thrown on invalid input. */ - public native void addAttributeBoolean(String name, boolean value) - throws InvalidArgsException, SimulatorException; + public void setAttributeProperty(String attrName, AttributeProperty property) + throws InvalidArgsException { + if (null == attrName || attrName.isEmpty()) + throw new InvalidArgsException("Invalid attribute!"); + + if (null == property) + throw new InvalidArgsException("Invalid attribute property!"); + + mProperties.put(attrName, property); + } /** - * API to add an attribute of type string. + * API to set attribute's value. * - * @param name - * Name of the attribute + * @param attrName + * Name of the attribute. * @param value - * Value of the attribute + * {@link AttributeValue} to be set for attribute. * * @throws InvalidArgsException - * This exception will be thrown if the attribute name is - * invalid. - * @throws SimulatorException - * This exception will be thrown either if the resource model is - * not found or for some general errors. + * This exception will be thrown on invalid input. */ - public native void addAttributeString(String name, String value) - throws InvalidArgsException, SimulatorException; + public void setAttributeValue(String attrName, AttributeValue value) + throws InvalidArgsException { + if (null == attrName || attrName.isEmpty()) + throw new InvalidArgsException("Invalid attribute name!"); + + if (null == value) + throw new InvalidArgsException("Attribute value is null!"); + + mValues.put(attrName, value); + } /** - * API to get number of attributes for this model. - * - * @return Number of attributes. + * API to get all the attributes of resource model. * - * @throws SimulatorException - * This exception will be thrown either if the resource model is - * not found or for some general errors. + * @return Map of attributes with attribute name as key and its + * corresponding {@link SimulatorResourceAttribute} as value. */ - public native int size() throws SimulatorException; + public Map getAttributes() { + if (mValues.size() == 0) + return null; + + Map attributes = new HashMap<>(); + for (Map.Entry entry : mValues.entrySet()) { + SimulatorResourceAttribute attribute = new SimulatorResourceAttribute( + entry.getKey(), entry.getValue(), mProperties.get(entry + .getKey())); + attributes.put(entry.getKey(), attribute); + } + + return attributes; + } /** - * API for getting all attributes. + * API to get attribute by name. * - * @return Map of attributes with attribute name as the key and its - * corresponding {@link ResourceAttribute} object as the value. + * @param attrName + * Name of the attribute. * - * @throws SimulatorException - * This exception will be thrown either if the resource model is - * not found or for some general errors. + * @return {@link SimulatorResourceAttribute}. */ - public native Map getAttributes() - throws SimulatorException; + public SimulatorResourceAttribute getAttribute(String attrName) { + if (mValues.containsKey(attrName)) { + SimulatorResourceAttribute attribute = new SimulatorResourceAttribute( + attrName, mValues.get(attrName), mProperties.get(attrName)); + return attribute; + } + + return null; + } /** - * API to get attribute by its name. + * API to check whether resource model has attribute. * - * @param name - * Name of the attribute + * @param attrName + * Name of the attribute. * - * @return An object of {@link ResourceAttribute}. + * @return true if resource model has an attribute with given name, + * otherwise false. + */ + public boolean containsAttribute(String attrName) { + if (mValues.containsKey(attrName)) + return true; + return false; + } + + /** + * API to get value type information of attribute. * - * @throws InvalidArgsException - * This exception will be thrown if the attribute does not - * exist. + * @param attrName + * Name of the attribute. * - * @throws SimulatorException - * This exception will be thrown either if the resource model is - * not found or for some general errors. + * @return Attribute value type information {@AttributeValue.TypeInfo + * }. */ - public native ResourceAttribute getAttribute(String name) - throws InvalidArgsException, SimulatorException; - - private SimulatorResourceModel(long nativeHandle) { - this.nativeHandle = nativeHandle; + public AttributeValue.TypeInfo getAttributeType(String attrName) { + if (mValues.containsKey(attrName)) + return mValues.get(attrName).typeInfo(); + return null; } - @Override - protected void finalize() throws Throwable { - try { - dispose(); - } finally { - super.finalize(); + /** + * API to remove attribute from resource model. + * + * @param attrName + * Name of the attribute. + * + * @return true if resource model has attribute it is removed, otherwise + * false. + */ + public boolean removeAttribute(String attrName) { + if (mValues.containsKey(attrName)) { + mValues.remove(attrName); + if (mProperties.containsKey(attrName)) + mProperties.remove(attrName); + return true; } - } - private native void create(); + return false; + } - private native void dispose(); + /** + * API to get number of attributes present in resource model. + * + * @return Number of attributes present in resource model. + */ + public int size() { + return mValues.size(); + } - private long nativeHandle; -} \ No newline at end of file + // Methods used in native code + private SimulatorResourceModel(Map values, + Map properties) { + mValues = values; + mProperties = properties; + } +} diff --git a/service/simulator/java/sdk/src/org/oic/simulator/SimulatorResult.java b/service/simulator/java/sdk/src/org/oic/simulator/SimulatorResult.java index 8e4b9eb..f40eaca 100644 --- a/service/simulator/java/sdk/src/org/oic/simulator/SimulatorResult.java +++ b/service/simulator/java/sdk/src/org/oic/simulator/SimulatorResult.java @@ -21,53 +21,15 @@ package org.oic.simulator; */ public enum SimulatorResult { /** STACK error codes - START */ - SIMULATOR_OK, - SIMULATOR_RESOURCE_CREATED, - SIMULATOR_RESOURCE_DELETED, - SIMULATOR_CONTINUE, - SIMULATOR_INVALID_URI, - SIMULATOR_INVALID_QUERY, - SIMULATOR_INVALID_IP, - SIMULATOR_INVALID_PORT, - SIMULATOR_INVALID_CALLBACK, - SIMULATOR_INVALID_METHOD, - SIMULATOR_INVALID_PARAM, - SIMULATOR_INVALID_OBSERVE_PARAM, - SIMULATOR_NO_MEMORY, - SIMULATOR_COMM_ERROR, - SIMULATOR_TIMEOUT, - SIMULATOR_ADAPTER_NOT_ENABLED, - SIMULATOR_NOTIMPL, - SIMULATOR_NO_RESOURCE, - SIMULATOR_RESOURCE_ERROR, - SIMULATOR_SLOW_RESOURCE, - SIMULATOR_DUPLICATE_REQUEST, - SIMULATOR_NO_OBSERVERS, - SIMULATOR_OBSERVER_NOT_FOUND, - SIMULATOR_VIRTUAL_DO_NOT_HANDLE, - SIMULATOR_INVALID_OPTION, - SIMULATOR_MALFORMED_RESPONSE, - SIMULATOR_PERSISTENT_BUFFER_REQUIRED, - SIMULATOR_INVALID_REQUEST_HANDLE, - SIMULATOR_INVALID_DEVICE_INFO, - SIMULATOR_INVALID_JSON, - SIMULATOR_UNAUTHORIZED_REQ, + SIMULATOR_OK, SIMULATOR_RESOURCE_CREATED, SIMULATOR_RESOURCE_DELETED, SIMULATOR_CONTINUE, SIMULATOR_INVALID_URI, SIMULATOR_INVALID_QUERY, SIMULATOR_INVALID_IP, SIMULATOR_INVALID_PORT, SIMULATOR_INVALID_CALLBACK, SIMULATOR_INVALID_METHOD, SIMULATOR_INVALID_PARAM, SIMULATOR_INVALID_OBSERVE_PARAM, SIMULATOR_NO_MEMORY, SIMULATOR_COMM_ERROR, SIMULATOR_TIMEOUT, SIMULATOR_ADAPTER_NOT_ENABLED, SIMULATOR_NOTIMPL, SIMULATOR_NO_RESOURCE, SIMULATOR_RESOURCE_ERROR, SIMULATOR_SLOW_RESOURCE, SIMULATOR_DUPLICATE_REQUEST, SIMULATOR_NO_OBSERVERS, SIMULATOR_OBSERVER_NOT_FOUND, SIMULATOR_VIRTUAL_DO_NOT_HANDLE, SIMULATOR_INVALID_OPTION, SIMULATOR_MALFORMED_RESPONSE, SIMULATOR_PERSISTENT_BUFFER_REQUIRED, SIMULATOR_INVALID_REQUEST_HANDLE, SIMULATOR_INVALID_DEVICE_INFO, SIMULATOR_INVALID_JSON, SIMULATOR_UNAUTHORIZED_REQ, - SIMULATOR_PRESENCE_STOPPED, - SIMULATOR_PRESENCE_TIMEOUT, - SIMULATOR_PRESENCE_DO_NOT_HANDLE, + SIMULATOR_PRESENCE_STOPPED, SIMULATOR_PRESENCE_TIMEOUT, SIMULATOR_PRESENCE_DO_NOT_HANDLE, /** STACK error codes - END */ /** Simulator specific error codes - START */ - SIMULATOR_INVALID_TYPE, - SIMULATOR_NOT_SUPPORTED, - SIMULATOR_OPERATION_NOT_ALLOWED, - SIMULATOR_OPERATION_IN_PROGRESS, + SIMULATOR_INVALID_TYPE, SIMULATOR_NOT_SUPPORTED, SIMULATOR_OPERATION_NOT_ALLOWED, SIMULATOR_OPERATION_IN_PROGRESS, - SIMULATOR_INVALID_RESPONSE_CODE, - SIMULATOR_UKNOWN_PROPERTY, - SIMULATOR_TYPE_MISMATCH, - SIMULATOR_BAD_VALUE, + SIMULATOR_INVALID_RESPONSE_CODE, SIMULATOR_UKNOWN_PROPERTY, SIMULATOR_TYPE_MISMATCH, SIMULATOR_BAD_VALUE, SIMULATOR_BAD_OBJECT, /** Simulator specific error codes - END */ SIMULATOR_ERROR; diff --git a/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IFindResourceListener.java b/service/simulator/java/sdk/src/org/oic/simulator/client/FindResourceListener.java similarity index 66% rename from service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IFindResourceListener.java rename to service/simulator/java/sdk/src/org/oic/simulator/client/FindResourceListener.java index dcd9557..be935ae 100644 --- a/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IFindResourceListener.java +++ b/service/simulator/java/sdk/src/org/oic/simulator/client/FindResourceListener.java @@ -14,22 +14,20 @@ * limitations under the License. */ -package org.oic.simulator.clientcontroller; +package org.oic.simulator.client; -import org.oic.simulator.clientcontroller.SimulatorRemoteResource; +import org.oic.simulator.client.SimulatorRemoteResource; /** - * Provides interface for getting notification when resources are discovered in - * network. + * Listener for getting notification when resources are discovered in network. */ -public interface IFindResourceListener { +public interface FindResourceListener { /** - * This callback method will be called when resource is discovered in the - * network. + * 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); + public void onResourceFound(SimulatorRemoteResource resource); } diff --git a/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/SimulatorConnectivityType.java b/service/simulator/java/sdk/src/org/oic/simulator/client/SimulatorConnectivityType.java similarity index 98% rename from service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/SimulatorConnectivityType.java rename to service/simulator/java/sdk/src/org/oic/simulator/client/SimulatorConnectivityType.java index a751acb..9812d3d 100644 --- a/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/SimulatorConnectivityType.java +++ b/service/simulator/java/sdk/src/org/oic/simulator/client/SimulatorConnectivityType.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.oic.simulator.clientcontroller; +package org.oic.simulator.client; /** * Supported connectivity types. diff --git a/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/SimulatorRemoteResource.java b/service/simulator/java/sdk/src/org/oic/simulator/client/SimulatorRemoteResource.java similarity index 57% rename from service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/SimulatorRemoteResource.java rename to service/simulator/java/sdk/src/org/oic/simulator/client/SimulatorRemoteResource.java index 1697681..3e8f8a1 100644 --- a/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/SimulatorRemoteResource.java +++ b/service/simulator/java/sdk/src/org/oic/simulator/client/SimulatorRemoteResource.java @@ -14,10 +14,10 @@ * limitations under the License. */ -package org.oic.simulator.clientcontroller; +package org.oic.simulator.client; -import java.util.LinkedList; import java.util.Map; +import java.util.Vector; import org.oic.simulator.InvalidArgsException; import org.oic.simulator.NoSupportException; @@ -31,10 +31,36 @@ import org.oic.simulator.SimulatorResult; * 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 { +public final class SimulatorRemoteResource { + + private long mNativeHandle; + private String mUri; + private int mConnType; + private String mHost; + private String mId; + private Vector mResTypes; + private Vector mResInterfaces; + private boolean mIsObservable; + + private native void dispose(); private SimulatorRemoteResource(long nativeHandle) { - this.nativeHandle = nativeHandle; + mNativeHandle = nativeHandle; + } + + @Override + protected void finalize() throws Throwable { + try { + dispose(); + } catch (Throwable t) { + throw t; + } finally { + super.finalize(); + } + } + + public enum VerificationType { + GET, PUT, POST, DELETE; } /** @@ -42,20 +68,11 @@ public class SimulatorRemoteResource { * * @return Resource URI */ - public String getUri() { + public String getURI() { return mUri; } /** - * API to get the observe policy of this resource. - * - * @return True if the resource is observable, otherwise false. - */ - public boolean getIsObservable() { - return mIsObservable; - } - - /** * API to get the connectivity type for this resource. * * @return Connectivity type. @@ -67,18 +84,18 @@ public class SimulatorRemoteResource { /** * API to get the list of resource types. * - * @return List of resource types. + * @return Array of resource types. */ - public LinkedList getResourceTypes() { + public Vector getResourceTypes() { return mResTypes; } /** * API to get the list of resource interfaces. * - * @return List of resource interfaces. + * @return Array of resource interfaces. */ - public LinkedList getResourceInterfaces() { + public Vector getResourceInterfaces() { return mResInterfaces; } @@ -101,45 +118,19 @@ public class SimulatorRemoteResource { } /** - * API to start observing the resource. - * - * @param observeType - * Allows the client to specify how it wants to observe. - * @param queryParamsMap - * Map which can have the query parameter names and values. - * @param onObserveListener - * The handler method which will be invoked with a map of - * attribute names and values whenever there is a change in - * resource model of the remote resource. - * - * @throws InvalidArgsException - * This exception will be thrown if any parameter has invalid - * values. - * @throws SimulatorException - * This exception will be thrown for other errors. - */ - public native void startObserve(SimulatorObserveType observeType, - Map queryParamsMap, - IObserveListener onObserveListener) throws InvalidArgsException, - SimulatorException; - - /** - * API to stop observing the resource. + * API to get the observe policy of this 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. + * @return True if the resource is observable, otherwise false. */ - public native void stopObserve() throws InvalidArgsException, - SimulatorException; + public boolean isObservable() { + return mIsObservable; + } /** * API to send GET request to the resource. Response will be notified * asynchronously via callback set for {@link IGetListener}. * - * @param queryParamsMap + * @param queryParams * Map which can have the query parameter name and value. * @param onGetListener * Event handler which will be invoked with the response for GET @@ -148,20 +139,13 @@ public class SimulatorRemoteResource { * @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 queryParamsMap, - IGetListener onGetListener) throws InvalidArgsException, - NoSupportException, SimulatorException { - if (null == onGetListener) - throw new InvalidArgsException( - SimulatorResult.SIMULATOR_INVALID_PARAM.ordinal(), - "Parameter passed in invalid"); - this.nativeGet(null, queryParamsMap, onGetListener); + public void get(Map queryParams, + GetResponseListener onGetListener) throws InvalidArgsException, + SimulatorException { + nativeGet(null, queryParams, onGetListener); } /** @@ -170,7 +154,7 @@ public class SimulatorRemoteResource { * * @param resourceInterface * Interface type of the resource to operate on. - * @param queryParamsMap + * @param queryParams * Map which can have the query parameter name and value. * @param onGetListener * Event handler which will be invoked with the response for GET @@ -179,35 +163,28 @@ public class SimulatorRemoteResource { * @throws InvalidArgsException * This exception will be thrown if any parameter has invalid * values. - * @throws NoSupportException - * This exception will be thrown if we cannot send GET request - * to the remote resource. * @throws SimulatorException * This exception will be thrown for other errors. */ - public void get(String resourceInterface, - Map queryParamsMap, IGetListener onGetListener) - throws InvalidArgsException, NoSupportException, SimulatorException { - if (null == resourceInterface || resourceInterface.isEmpty() || null == onGetListener) + public void get(String resourceInterface, Map queryParams, + GetResponseListener onGetListener) throws InvalidArgsException, + SimulatorException { + if (null == resourceInterface || resourceInterface.isEmpty()) throw new InvalidArgsException( - SimulatorResult.SIMULATOR_INVALID_PARAM.ordinal(), - "Parameter passed in invalid"); - this.nativeGet(resourceInterface, queryParamsMap, onGetListener); + SimulatorResult.SIMULATOR_INVALID_PARAM, + "Invalid resource interface!"); + nativeGet(resourceInterface, queryParams, onGetListener); } - private native void nativeGet(String resourceInterface, - Map queryParamsMap, IGetListener onGetListener) - throws InvalidArgsException, NoSupportException, SimulatorException; - /** * API to send PUT request to the resource. Response will be notified * asynchronously via callback set for {@link IPutListener}. * + * @param queryParams + * Map which can have the query parameter name and value. * @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. @@ -215,20 +192,14 @@ public class SimulatorRemoteResource { * @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 queryParamsMap, IPutListener onPutListener) - throws InvalidArgsException, NoSupportException, SimulatorException { - if (null == representation || null == onPutListener) - throw new InvalidArgsException( - SimulatorResult.SIMULATOR_INVALID_PARAM.ordinal(), - "Parameter passed in invalid"); - this.nativePut(null, representation, queryParamsMap, onPutListener); + public void put(Map queryParams, + SimulatorResourceModel representation, + PutResponseListener onPutListener) throws InvalidArgsException, + SimulatorException { + nativePut(null, queryParams, representation, onPutListener); } /** @@ -237,11 +208,11 @@ public class SimulatorRemoteResource { * * @param resourceInterface * Interface type of the resource to operate on. + * @param queryParams + * Map which can have the query parameter name and value. * @param representation * {@link SimulatorResourceModel} holding the representation of * the resource. - * @param 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. @@ -249,38 +220,29 @@ public class SimulatorRemoteResource { * @throws InvalidArgsException * This exception will be thrown if any parameter has invalid * value. - * @throws NoSupportException - * This exception will be thrown if we cannot send PUT request - * to the remote resource. * @throws SimulatorException * This exception will be thrown for other errors. */ - public void put(String resourceInterface, + public void put(String resourceInterface, Map queryParams, SimulatorResourceModel representation, - Map queryParamsMap, IPutListener onPutListener) - throws InvalidArgsException, NoSupportException, SimulatorException { - if (null == resourceInterface || resourceInterface.isEmpty() || - null == representation || null == onPutListener) + PutResponseListener onPutListener) throws InvalidArgsException, + SimulatorException { + if (null == resourceInterface || resourceInterface.isEmpty()) throw new InvalidArgsException( - SimulatorResult.SIMULATOR_INVALID_PARAM.ordinal(), - "Parameter passed in invalid"); - this.nativePut(resourceInterface, representation, queryParamsMap, onPutListener); + SimulatorResult.SIMULATOR_INVALID_PARAM, + "Invalid resource interface!"); + nativePut(resourceInterface, queryParams, representation, onPutListener); } - private native void nativePut(String resourceInterface, - SimulatorResourceModel representation, - Map queryParamsMap, IPutListener onPutListener) - throws InvalidArgsException, NoSupportException, SimulatorException; - /** * API to send POST request to the resource. Response will be notified * asynchronously via callback set for {@link IPostListener}. * + * @param queryParams + * Map which can have the query parameter name and value. * @param representation * {@link SimulatorResourceModel} holding the representation of - * the resource - * @param queryParamsMap - * Map which can have the query parameter name and value + * the resource. * @param onPostListener * Event handler which will be invoked with the response for POST * request with a map of attribute name and values. @@ -288,20 +250,14 @@ public class SimulatorRemoteResource { * @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 queryParamsMap, IPostListener onPostListener) - throws InvalidArgsException, NoSupportException, SimulatorException { - if (null == representation || null == onPostListener) - throw new InvalidArgsException( - SimulatorResult.SIMULATOR_INVALID_PARAM.ordinal(), - "Parameter passed in invalid"); - this.nativePost(null, representation, queryParamsMap, onPostListener); + public void post(Map queryParams, + SimulatorResourceModel representation, + PostResponseListener onPostListener) throws InvalidArgsException, + SimulatorException { + nativePost(null, queryParams, representation, onPostListener); } /** @@ -310,11 +266,11 @@ public class SimulatorRemoteResource { * * @param resourceInterface * Interface type of the resource to operate on. + * @param queryParams + * Map which can have the query parameter name and value. * @param representation * {@link SimulatorResourceModel} holding the representation of * the resource. - * @param 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. @@ -322,50 +278,77 @@ public class SimulatorRemoteResource { * @throws InvalidArgsException * This exception will be thrown if any parameter has invalid * value. - * @throws NoSupportException - * This exception will be thrown if we cannot send POST request - * on the remote resource. * @throws SimulatorException * This exception will be thrown for other errors. */ - public void post(String resourceInterface, + public void post(String resourceInterface, Map queryParams, SimulatorResourceModel representation, - Map queryParamsMap, IPostListener onPostListener) - throws InvalidArgsException, NoSupportException, SimulatorException { - if (null == resourceInterface || resourceInterface.isEmpty() || - null == representation || null == onPostListener) + PostResponseListener onPostListener) throws InvalidArgsException, + SimulatorException { + if (null == resourceInterface || resourceInterface.isEmpty()) throw new InvalidArgsException( - SimulatorResult.SIMULATOR_INVALID_PARAM.ordinal(), - "Parameter passed in invalid"); - this.nativePost(resourceInterface, representation, queryParamsMap, onPostListener); + SimulatorResult.SIMULATOR_INVALID_PARAM, + "Invalid resource interface!"); + nativePost(resourceInterface, queryParams, representation, + onPostListener); } - private native void nativePost(String resourceInterface, - SimulatorResourceModel representation, - Map queryParamsMap, IPostListener onPostListener) - throws InvalidArgsException, NoSupportException, SimulatorException; + /** + * API to start observing the resource. + * + * @param queryParams + * Map which can have the query parameter names and values. + * @param onObserveListener + * The handler method which will be invoked with a map of + * attribute names and values whenever there is a change in + * resource model of the remote resource. + * + * @throws InvalidArgsException + * This exception will be thrown if any parameter has invalid + * values. + * @throws SimulatorException + * This exception will be thrown for other errors. + */ + public native void startObserve(Map queryParams, + ObserveNotificationListener onObserveListener) + throws InvalidArgsException, SimulatorException; + + /** + * API to stop observing the resource. + * + * @throws InvalidArgsException + * This exception will be thrown if the native remote resource + * object is unavailable. + * @throws SimulatorException + * This exception will be thrown for other errors. + */ + public native void stopObserve() throws InvalidArgsException, + SimulatorException; /** - * API to provide remote resource configure information, - * which is required for using automation feature. + * API to provide remote resource configure information, which is required + * for using automation feature. * * @param path * Path to RAML file. * + * @return representation {@link SimulatorResourceModel} holding the + * representation of the remote resource. + * * @throws InvalidArgsException * Thrown if the RAML configuration file path is invalid. * @throws SimulatorException * Thrown for other errors. */ - public native void setConfigInfo(String path) + public native SimulatorResourceModel setConfigInfo(String path) throws InvalidArgsException, SimulatorException; /** - * API to send multiple requests for the resource, based on - * the configure file provided from {@link setConfigInfo}. - * This verifies response received as well. + * API to send multiple requests for the resource, based on the configure + * file provided from {@link setConfigInfo}. This verifies response received + * as well. * - * @param requestType + * @param type * Request type to verify. * @param onVerifyListener * This event handler will be invoked with the current status of @@ -385,51 +368,152 @@ public class SimulatorRemoteResource { * @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); + public int startVerification(VerificationType type, + VerificationListener onVerifyListener) throws InvalidArgsException, + NoSupportException, OperationInProgressException, + SimulatorException { + return startVerification(type.ordinal(), onVerifyListener); } /** - * API to stop sending requests which has been started using {@link setConfigInfo}. + * API to stop sending requests which has been started using + * {@link setConfigInfo}. * * @param id * Automation ID. * * @throws InvalidArgsException * Thrown if the automation ID is invalid. - * @throws NoSupportException - * Thrown if the resource is not configured with RAML. * @throws SimulatorException * Thrown for other errors. */ public native void stopVerification(int id) throws InvalidArgsException, - NoSupportException, SimulatorException; + SimulatorException; - private native int startVerification(int requestType, - IVerificationListener onVerifyListener) - throws InvalidArgsException, NoSupportException, - OperationInProgressException, SimulatorException; + /** + * Listener for receiving asynchronous response for GET request. + */ + public interface GetResponseListener { + /** + * Method will be called when response for GET request arrives. + * + * @param uid + * Unique Id of the resource. + * @param result + * Error code {@link SimulatorResult}. + * @param resourceModel + * {@link SimulatorResourceModel}. + */ + public void onGetResponse(String uid, SimulatorResult result, + SimulatorResourceModel resourceModel); + } - @Override - protected void finalize() throws Throwable { - try { - dispose(); - } finally { - super.finalize(); - } + /** + * Listener for receiving asynchronous response for PUT request. + */ + public interface PutResponseListener { + /** + * Method will be called when response for PUT request arrives. + * + * @param uid + * Unique Id of the resource. + * @param result + * Error code {@link SimulatorResult}. + * @param resourceModel + * {@link SimulatorResourceModel}. + */ + public void onPutResponse(String uid, SimulatorResult result, + SimulatorResourceModel resourceModel); } - private native void dispose(); + /** + * Listener for receiving asynchronous response for POST request. + */ + public interface PostResponseListener { + /** + * Method will be called when response for POST request arrives. + * + * @param uid + * Unique Id of the resource. + * @param result + * Error code {@link SimulatorResult}. + * @param resourceModel + * {@link SimulatorResourceModel}. + */ + public void onPostResponse(String uid, SimulatorResult result, + SimulatorResourceModel resourceModel); + } + + /** + * Listener for getting asynchronous notification whenever remote resource's + * representation gets changed. + */ + public interface ObserveNotificationListener { + /** + * This method will be called when there is a change in the resource + * model of the remote resource. + * + * @param uid + * Unique Id of the resource. + * @param resourceModel + * {@link SimulatorResourceModel}. + * @param sequenceNumber + * Sequential number for ordering the model change + * notifications. + */ + public void onObserveNotification(String uid, + SimulatorResourceModel resourceModel, int sequenceNumber); + } + + /** + * Listener for receiving the verification session status. + */ + public interface VerificationListener { + /** + * Called when the verification request is accepted and started. + * + * @param uid + * Unique Id of the resource. + * @param id + * Verification Id. + */ + public void onVerificationStarted(String uid, int id); + + /** + * Called when the verification is stopped before its completion. + * + * @param uid + * Unique Id of the resource. + * @param id + * Verification Id. + */ + public void onVerificationAborted(String uid, int id); + + /** + * Called when the verification is done. + * + * @param uid + * Unique Id of the resource. + * @param id + * Verification Id. + */ + public void onVerificationCompleted(String uid, int id); + } + + private native void nativeGet(String resourceInterface, + Map queryParamsMap, + GetResponseListener onGetListener); + + private native void nativePut(String resourceInterface, + Map queryParams, + SimulatorResourceModel representation, + PutResponseListener onPutListener); + + private native void nativePost(String resourceInterface, + Map queryParams, + SimulatorResourceModel representation, + PostResponseListener onPostListener); - private long nativeHandle; - private String mUri; - private int mConnType; - private String mHost; - private String mId; - private LinkedList mResTypes; - private LinkedList mResInterfaces; - private boolean mIsObservable; + private native int startVerification(int type, + VerificationListener onVerifyListener); } diff --git a/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IGetListener.java b/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IGetListener.java deleted file mode 100644 index db3e63c..0000000 --- a/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IGetListener.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.oic.simulator.clientcontroller; - -import org.oic.simulator.SimulatorResourceModel; - -/** - * Interface for receiving response for GET request. An IGetListener can be - * registered via the resource get call. Event listeners are notified - * asynchronously. - */ -public interface IGetListener { - /** - * This method will be called when response from the remote resource for GET - * request arrives. - * - * @param uId - * Unique Id of the resource. - * @param representation - * {@link SimulatorResourceModel}. - */ - public void onGetCompleted(String uId, SimulatorResourceModel representation); - - /** - * Called when there is an error in GET request. - * - * @param ex - * Error information. - */ - public void onGetFailed(Throwable ex); -} diff --git a/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IObserveListener.java b/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IObserveListener.java deleted file mode 100644 index 30ed0fb..0000000 --- a/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IObserveListener.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.oic.simulator.clientcontroller; - -import org.oic.simulator.SimulatorResourceModel; - -/** - * Provides interface for getting notification when resource model of an - * observed resource gets changed. An IObserveListener can be registered via the - * SimulatorRemoteResource observe call. Event listeners are notified - * asynchronously. - */ -public interface IObserveListener { - /** - * This method will be called when there is a change in the resource model - * of the remote resource. - * - * @param uId - * Unique Id of the resource. - * @param representation - * {@link SimulatorResourceModel}. - * @param sequenceNumber - * Sequential number for ordering the model change notifications. - */ - public void onObserveCompleted(String uId, - SimulatorResourceModel representation, int sequenceNumber); - - /** - * Called when there is an error in observe request. - * - * @param ex - * Error information. - */ - public void onObserveFailed(Throwable ex); -} diff --git a/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IPostListener.java b/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IPostListener.java deleted file mode 100644 index 9949ac9..0000000 --- a/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IPostListener.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.oic.simulator.clientcontroller; - -import org.oic.simulator.SimulatorResourceModel; - -/** - * Interface for receiving response for POST request. An IPostListener can be - * registered via the resource post call. Event listeners are notified - * asynchronously. - */ -public interface IPostListener { - /** - * This method will be called when response from the remote resource for - * POST request arrives. - * - * @param uId - * Unique Id of the resource. - * @param representation - * {@link SimulatorResourceModel}. - */ - public void onPostCompleted(String uId, - SimulatorResourceModel representation); - - /** - * Called when there is an error in POST request. - * - * @param ex - * Error information. - */ - public void onPostFailed(Throwable ex); -} diff --git a/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IPutListener.java b/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IPutListener.java deleted file mode 100644 index 91a44d9..0000000 --- a/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IPutListener.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.oic.simulator.clientcontroller; - -import org.oic.simulator.SimulatorResourceModel; - -/** - * Interface for receiving response for PUT request. An IPutListener can be - * registered via the resource put call. Event listeners are notified - * asynchronously. - */ -public interface IPutListener { - /** - * This method will be called when response from the remote resource for PUT - * request arrives. - * - * @param uId - * Unique Id of the resource. - * @param representation - * {@link SimulatorResourceModel}. - */ - public void onPutCompleted(String uId, SimulatorResourceModel representation); - - /** - * Called when there is an error in PUT request. - * - * @param ex - * Error information. - */ - public void onPutFailed(Throwable ex); -} - diff --git a/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IVerificationListener.java b/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IVerificationListener.java deleted file mode 100644 index e69cdd6..0000000 --- a/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IVerificationListener.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.oic.simulator.clientcontroller; - -/** - * Interface for receiving the verification status via callback. An - * IVerificationListener can be registered via the resource startVerification - * call. Event listeners are notified asynchronously. - */ -public interface IVerificationListener { - /** - * Called when the verification request is accepted and started. - * - * @param uId - * Unique Id of the resource. - * @param id - * Verification Id. - */ - public void onVerificationStarted(String uId, int id); - - /** - * Called when the verification is stopped before its completion. - * - * @param uId - * Unique Id of the resource. - * @param id - * Verification Id. - */ - public void onVerificationAborted(String uId, int id); - - /** - * Called when the verification is done. - * - * @param uId - * Unique Id of the resource. - * @param id - * Verification Id. - */ - public void onVerificationCompleted(String uId, int id); -} diff --git a/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/SimulatorVerificationType.java b/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/SimulatorVerificationType.java deleted file mode 100644 index ccb0c36..0000000 --- a/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/SimulatorVerificationType.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.oic.simulator.clientcontroller; - -/** - * Types of automatic verification. - */ -public enum SimulatorVerificationType { - RQ_TYPE_GET(0), RQ_TYPE_PUT(1), RQ_TYPE_POST(2), RQ_TYPE_DELETE(3); - - private int value; - - private SimulatorVerificationType(int value) { - this.value = value; - } - - public int getValue() { - return this.value; - } - - /** - * Method to get the {@link SimulatorVerificationType} from an integer - * value. - * - * @param value - * Integral value of {@link SimulatorVerificationType}. - * @return {@link SimulatorVerificationType} corresponding to the given - * value. - */ - public static SimulatorVerificationType getVerificationType(int value) { - SimulatorVerificationType result = null; - SimulatorVerificationType[] types = SimulatorVerificationType.values(); - for (SimulatorVerificationType type : types) { - if (type.getValue() == value) { - result = type; - break; - } - } - return result; - } -} diff --git a/service/simulator/java/sdk/src/org/oic/simulator/serviceprovider/ObserverInfo.java b/service/simulator/java/sdk/src/org/oic/simulator/server/Observer.java similarity index 76% rename from service/simulator/java/sdk/src/org/oic/simulator/serviceprovider/ObserverInfo.java rename to service/simulator/java/sdk/src/org/oic/simulator/server/Observer.java index 1672abc..26e3cca 100644 --- a/service/simulator/java/sdk/src/org/oic/simulator/serviceprovider/ObserverInfo.java +++ b/service/simulator/java/sdk/src/org/oic/simulator/server/Observer.java @@ -14,21 +14,21 @@ * limitations under the License. */ -package org.oic.simulator.serviceprovider; +package org.oic.simulator.server; /** * Class which represents the details of an observer. */ -public class ObserverInfo { +public class Observer { - private int id; - private String address; - private int port; + private int mId; + private String mAddress; + private int mPort; - private ObserverInfo(int id, String address, int port) { - this.id = id; - this.address = address; - this.port = port; + private Observer(int id, String address, int port) { + mId = id; + mAddress = address; + mPort = port; } /** @@ -37,7 +37,7 @@ public class ObserverInfo { * @return Observer's Id. */ public int getId() { - return id; + return mId; } /** @@ -46,7 +46,7 @@ public class ObserverInfo { * @return Observer's device address. */ public String getAddress() { - return address; + return mAddress; } /** @@ -55,6 +55,6 @@ public class ObserverInfo { * @return Observer's port number. */ public int getPort() { - return port; + return mPort; } } diff --git a/service/simulator/java/sdk/src/org/oic/simulator/server/SimulatorCollectionResource.java b/service/simulator/java/sdk/src/org/oic/simulator/server/SimulatorCollectionResource.java new file mode 100644 index 0000000..42c7b79 --- /dev/null +++ b/service/simulator/java/sdk/src/org/oic/simulator/server/SimulatorCollectionResource.java @@ -0,0 +1,86 @@ +/* + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.oic.simulator.server; + +import java.util.Vector; + +import org.oic.simulator.InvalidArgsException; +import org.oic.simulator.SimulatorException; + +public final class SimulatorCollectionResource extends SimulatorResource { + + private SimulatorCollectionResource(long nativeHandle) { + mNativeHandle = nativeHandle; + } + + /** + * API to add child resource to collection. + * + * @param resource + * Child resource to be added to collection. + * + * @throws InvalidArgsException + * This exception will be thrown on invalid input. + * @throws SimulatorException + * This exception will be thrown on occurrence of error in + * native. + */ + public native void addChildResource(SimulatorResource resource) + throws InvalidArgsException, SimulatorException; + + /** + * API to remove child resource from collection. + * + * @param resource + * Child resource to be removed from collection. + * + * @throws InvalidArgsException + * This exception will be thrown on invalid input. + * @throws SimulatorException + * This exception will be thrown on occurrence of error in + * native. + */ + public native void removeChildResource(SimulatorResource resource) + throws InvalidArgsException, SimulatorException; + + /** + * API to remove child resource from collection. + * + * @param uri + * URI of child resource to be removed from collection. + * + * @throws InvalidArgsException + * This exception will be thrown on invalid input. + * @throws SimulatorException + * This exception will be thrown on occurrence of error in + * native. + */ + public native void removeChildResourceByUri(String uri) + throws InvalidArgsException, SimulatorException; + + /** + * API to get list of child resources. + * + * @return Vector of child resources {@link SimulatorResource}. + * + * @throws SimulatorException + * This exception will be thrown on occurrence of error in + * native. + */ + public native Vector getChildResource() + throws SimulatorException; +} diff --git a/service/simulator/java/sdk/src/org/oic/simulator/server/SimulatorResource.java b/service/simulator/java/sdk/src/org/oic/simulator/server/SimulatorResource.java new file mode 100644 index 0000000..5120fd8 --- /dev/null +++ b/service/simulator/java/sdk/src/org/oic/simulator/server/SimulatorResource.java @@ -0,0 +1,362 @@ +/* + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.oic.simulator.server; + +import java.util.Vector; + +import org.oic.simulator.InvalidArgsException; +import org.oic.simulator.SimulatorException; +import org.oic.simulator.SimulatorResourceModel; + +public class SimulatorResource { + + private native void dispose(); + + protected long mNativeHandle; + + protected SimulatorResource() { + } + + @Override + protected void finalize() throws Throwable { + try { + dispose(); + } catch (Throwable t) { + throw t; + } finally { + super.finalize(); + } + } + + public enum Type { + SINGLE, COLLECTION + } + + public enum AutoUpdateType { + ONE_TIME, REPEAT + } + + /** + * API to get the name of the resource. + * + * @return Name of the resource. + * + * @throws SimulatorException + * This exception will be thrown if the native resource object + * does not exist or for some general errors. + */ + public native String getName() throws SimulatorException; + + /** + * API to get the type which indicates whether resource is single or + * collection resource. + * + * @return Type of resource. + * + * @throws SimulatorException + * This exception will be thrown if the native resource object + * does not exist or for some general errors. + */ + public native Type getType() throws SimulatorException; + + /** + * API to get the resource URI. + * + * @return Resource URI. + * + * @throws SimulatorException + * This exception will be thrown if the native resource object + * does not exist or for some general errors. + */ + public native String getURI() throws SimulatorException; + + /** + * API to get the resource type. + * + * @return Resource type. + * + * @throws SimulatorException + * This exception will be thrown if the native resource object + * does not exist or for some general errors. + */ + public native String getResourceType() throws SimulatorException; + + /** + * API to get the interfaces resource is bound with. + * + * @return Interface type. + * + * @throws SimulatorException + * This exception will be thrown if the native resource object + * does not exist or for some general errors. + */ + public native Vector getInterface() throws SimulatorException; + + /** + * API to get the observable state of resource. + * + * @return Observable state - true if resource is observable, otherwise + * false. + * + * @throws SimulatorException + * This exception will be thrown if the native resource object + * does not exist or for some general errors. + */ + public native boolean isObservable() throws SimulatorException; + + /** + * API to get the start state of resource. + * + * @return Start state - true if resource is started, otherwise false. + * + * @throws SimulatorException + * This exception will be thrown if the native resource object + * does not exist or for some general errors. + */ + public native boolean isStarted() throws SimulatorException; + + /** + * API to get the {@link SimulatorResourceModel} of the simulated resource. + * + * @return {@link SimulatorResourceModel} object on success, otherwise null. + * + * @throws SimulatorException + * This exception will be thrown if simulated resource is not + * proper. + */ + public native SimulatorResourceModel getResourceModel() + throws SimulatorException; + + /** + * API to set the name of the resource. + * + * @param name + * - Name to be set. + * + * @throws InvalidArgsException + * This exception will be thrown if the resource name is + * invalid. + * @throws SimulatorException + * This exception will be thrown if the native resource object + * does not exist or for some general errors. + */ + public native void setName(String name) throws InvalidArgsException, + SimulatorException; + + /** + * API to set the resource URI. + * + * @param uri + * - URI to be set. + * + * @throws InvalidArgsException + * This exception will be thrown if the resource URI is invalid. + * @throws SimulatorException + * This exception will be thrown if the native resource object + * does not exist or for some general errors. + */ + public native void setURI(String uri) throws InvalidArgsException, + SimulatorException; + + /** + * API to set the resource type. + * + * @param resourceType + * - resource type string. + * + * @throws InvalidArgsException + * This exception will be thrown if the resource type is + * invalid. + * @throws SimulatorException + * This exception will be thrown if the native resource object + * does not exist or for some general errors. + */ + public native void setResourceType(String resourceType) + throws InvalidArgsException, SimulatorException; + + /** + * API to add interface type for resource. + * + * @param interfaceType + * - interface to be added for resource. + * + * @throws InvalidArgsException + * This exception will be thrown if the interface type is + * invalid. + * @throws SimulatorException + * This exception will be thrown if the native resource object + * does not exist or for some general errors. + */ + public native void addInterface(String interfaceType) + throws InvalidArgsException, SimulatorException; + + /** + * API to make the resource observable or not. + * + * @param state + * - true make the resource observable, otherwise non-observable. + * + * @throws SimulatorException + * This exception will be thrown if the native resource object + * does not exist or for some general errors. + */ + public native void setObservable(boolean state) throws SimulatorException; + + /** + * API to set the listener for receiving the notifications when observer is + * registered or unregistered with resource. + * + * @param listener + * - Callback to be set for receiving the notifications. + * + * @throws InvalidArgsException + * This exception will be thrown if the listener is invalid. + * @throws SimulatorException + * This exception will be thrown if the native resource object + * does not exist or for some general errors. + */ + public native void setObserverListener(ObserverListener listener) + throws InvalidArgsException, SimulatorException; + + /** + * API to set listener for receiving notifications when resource's model + * gets changed. + * + * @param listener + * {@link ResourceModelChangeListener}. + * + * @throws InvalidArgsException + * This exception will be thrown on invalid input. + * @throws SimulatorException + * This exception will be thrown for other errors. + */ + public native void setResourceModelChangeListener( + ResourceModelChangeListener listener) throws InvalidArgsException, + SimulatorException; + + /** + * API to start the resource. + * + * @throws SimulatorException + * This exception will be thrown if the native resource object + * does not exist or for some general errors. + */ + public native void start() throws SimulatorException; + + /** + * API to stop the resource. + * + * @throws SimulatorException + * This exception will be thrown if the native resource object + * does not exist or for some general errors. + */ + public native void stop() throws SimulatorException; + + /** + * API to get observers which are registered with resource. + * + * @return observers as an array of {@link Observer}. + * + * @throws SimulatorException + * This exception will be thrown if the native resource object + * does not exist or for some general errors. + */ + public native Vector getObservers() throws SimulatorException; + + /** + * API to notify current resource model to specific observer. + * + * @param observerId + * - Observer ID to notify. + * + * @throws SimulatorException + * This exception will be thrown if the native resource object + * does not exist or for some general errors. + */ + public native void notifyObserver(int observerId) throws SimulatorException; + + /** + * API to notify all registered observers. + * + * @throws SimulatorException + * This exception will be thrown if the native resource object + * does not exist or for some general errors. + */ + public native void notifyAllObservers() throws SimulatorException; + + /** + * Listener for receiving notification when observer is registered or + * unregistered with the resource. + */ + public interface ObserverListener { + /** + * Method will be invoked when a observer is registered with resource. + * + * @param uri + * URI of the resource. + * @param observer + * {@link ObserverInfo} object containing the details of + * observer. + */ + public void onObserverAdded(String resourceURI, Observer observer); + + /** + * Method will be invoked when a observer is Unregistered with resource. + * + * @param resourceURI + * URI of the resource. + * @param observer + * {@link ObserverInfo} object containing the details of + * observer. + */ + public void onObserverRemoved(String resourceURI, Observer observer); + } + + /** + * Listener for receiving notification on completion of automatically + * updating attribute value from its range or value set property. + */ + public interface AutoUpdateListener { + /** + * Method for receiving automation complete notifications. + * + * @param uri + * URI of resource. + * @param id + * Identifier for auto resource/attribute update session. + */ + public void onUpdateComplete(String uri, int id); + } + + /** + * Listener for receiving notifications whenever there is a change in the + * resource model. + */ + public interface ResourceModelChangeListener { + /** + * Method will be invoked to notify about the changes in the resource + * model. + * + * @param uri + * URI of resource. + * @param resourceModel + * {@link SimulatorResourceModel} of the resource. + */ + public void onResourceModelChanged(String uri, + SimulatorResourceModel resourceModel); + } +} diff --git a/service/simulator/java/sdk/src/org/oic/simulator/server/SimulatorSingleResource.java b/service/simulator/java/sdk/src/org/oic/simulator/server/SimulatorSingleResource.java new file mode 100644 index 0000000..7a1d8ab --- /dev/null +++ b/service/simulator/java/sdk/src/org/oic/simulator/server/SimulatorSingleResource.java @@ -0,0 +1,156 @@ +/* + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.oic.simulator.server; + +import org.oic.simulator.AttributeValue; +import org.oic.simulator.InvalidArgsException; +import org.oic.simulator.SimulatorException; +import org.oic.simulator.SimulatorResourceAttribute; +import org.oic.simulator.SimulatorResourceModel; + +public final class SimulatorSingleResource extends SimulatorResource { + + private SimulatorSingleResource(long nativeHandle) { + mNativeHandle = nativeHandle; + } + + /** + * API to get attribute of resource. + * + * @param attrName + * Name of the attribute + * + * @return An object of {@link SimulatorResourceAttribute}, or null if + * resource doest not have attribute of this name. + * + * @throws InvalidArgsException + * This exception will be thrown if the attribute name is + * invalid. + * @throws SimulatorException + * This exception will be thrown either if the resource model is + * not found or for some general errors. + */ + public native SimulatorResourceAttribute getAttribute(String attrName) + throws InvalidArgsException, SimulatorException; + + /** + * API to add an attribute to resource's representation model. + * + * @param attrName + * Name of the attribute. + * @param attribute + * Attribute to be added to resource's representation model. + * + * @throws InvalidArgsException + * This exception will be thrown on invalid input. + * @throws SimulatorException + * This exception will be thrown for other errors. + */ + public native void addAttribute(SimulatorResourceAttribute attribute) + throws InvalidArgsException, SimulatorException; + + /** + * API to update the value of an attribute. + * + * @param attrName + * Name of the attribute. + * @param value + * New value of the attribute. + * + * @throws InvalidArgsException + * This exception will be thrown on invalid input. + * @throws SimulatorException + * This exception will be thrown for other errors. + */ + public native void updateAttribute(String attrName, AttributeValue value) + throws InvalidArgsException, SimulatorException; + + /** + * API to remove an attribute from the simulated resource. + * + * @param attrName + * Name of the attribute to be deleted. + * + * @throws InvalidArgsException + * This exception will be thrown on invalid input. + * @throws SimulatorException + * This exception will be thrown for other errors. + */ + public native void removeAttribute(String attrName) + throws InvalidArgsException, SimulatorException; + + /** + * API to start the resource level automation. This automation involves + * automatically updating all the possible values for all the attributes + * sequentially. + * + * @param type + * {@link AutomationType} indicating whether the automation is + * one-time or recursive. + * @param interval + * Interval time in milliseconds. + * @param listener + * Listener to be notified when value updation ends. + * + * @return Automation ID using which the automation can be stopped. + * + * @throws InvalidArgsException + * This exception will be thrown on invalid input. + * @throws SimulatorException + * This exception will be thrown for other errors. + */ + public native int startResourceUpdation(AutoUpdateType type, int interval, + AutoUpdateListener listener) throws InvalidArgsException, + SimulatorException; + + /** + * API to start the attribute level automation. This automation involves + * automatically updating all the possible values for a given attribute + * sequentially. + * + * @param attrName + * Name of the attribute to be automated. + * @param type + * {@link AutomationType} indicating whether the automation is + * one-time or recursive. + * @param interval + * Interval time in milliseconds. + * @param listener + * Listener to be notified when automation ends. + * + * @return Automation ID using which the automation can be stopped. + * + * @throws InvalidArgsException + * This exception will be thrown on invalid input. + * @throws SimulatorException + * This exception will be thrown for other errors. + */ + public native int startAttributeUpdation(String attrName, + AutoUpdateType type, int interval, AutoUpdateListener listener) + throws InvalidArgsException, SimulatorException; + + /** + * API to stop the automation based on automation id. + * + * @param id + * Using which a specific automation can be stopped. + * + * @throws SimulatorException + * This exception will be thrown for general errors. + */ + public native void stopUpdation(int id) throws SimulatorException; +} diff --git a/service/simulator/java/sdk/src/org/oic/simulator/serviceprovider/IObserver.java b/service/simulator/java/sdk/src/org/oic/simulator/serviceprovider/IObserver.java deleted file mode 100644 index 0dceda2..0000000 --- a/service/simulator/java/sdk/src/org/oic/simulator/serviceprovider/IObserver.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.oic.simulator.serviceprovider; - -/** - * Interface for receiving the observe notifications. - */ -public interface IObserver { - /** - * This callback method will be called when a new observer is added or an - * existing observer is removed. - * - * @param resourceURI - * URI of the resource. - * @param state - * Indicates whether an observer is added or removed. - * @param observer - * {@link ObserverInfo} object containing the details of - * observer. - */ - public void onObserverChanged(String resourceURI, int state, - ObserverInfo observer); -} diff --git a/service/simulator/java/sdk/src/org/oic/simulator/serviceprovider/IResourceModelChangedListener.java b/service/simulator/java/sdk/src/org/oic/simulator/serviceprovider/IResourceModelChangedListener.java deleted file mode 100644 index 744116b..0000000 --- a/service/simulator/java/sdk/src/org/oic/simulator/serviceprovider/IResourceModelChangedListener.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.oic.simulator.serviceprovider; - -import org.oic.simulator.SimulatorResourceModel; - -/** - * Interface for receiving notifications whenever there is a change in the - * resource model. - */ -public interface IResourceModelChangedListener { - /** - * This callback method will be called to notify about the changes in the - * resource model. - * - * @param resourceURI - * URI of resource. - * @param resourceModel - * {@link SimulatorResourceModel} of the resource. - */ - public void onResourceModelChanged(String resourceURI, - SimulatorResourceModel resourceModel); -} \ No newline at end of file diff --git a/service/simulator/java/sdk/src/org/oic/simulator/serviceprovider/SimulatorResourceServer.java b/service/simulator/java/sdk/src/org/oic/simulator/serviceprovider/SimulatorResourceServer.java deleted file mode 100644 index d601b53..0000000 --- a/service/simulator/java/sdk/src/org/oic/simulator/serviceprovider/SimulatorResourceServer.java +++ /dev/null @@ -1,488 +0,0 @@ -/* - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.oic.simulator.serviceprovider; - -import java.util.Vector; - -import org.oic.simulator.IAutomation; -import org.oic.simulator.InvalidArgsException; -import org.oic.simulator.SimulatorException; -import org.oic.simulator.SimulatorResourceModel; - -/** - * This class represents a resource in the simulator. It provides a set of - * native methods for manipulating the simulated resource by adding and removing - * attributes to its model, automating the attribute value updates, and changing - * the range of acceptable values of the attributes. - */ -public class SimulatorResourceServer { - - private String resourceName; - private String resourceURI; - private String resourceType; - private String interfaceType; - - private long nativeHandle; - - private SimulatorResourceServer(long nativeHandle) { - this.nativeHandle = nativeHandle; - } - - /** - * API to get the resource name. Example: Light, Fan, etc. - * - * @return Resource name. - */ - public String getName() { - return resourceName; - } - - /** - * API to get the resource URI. Example: /oic/light, /oic/fan, etc. - * - * @return Resource URI. - */ - public String getURI() { - return resourceURI; - } - - /** - * API to get the resource Type. Example: oic.light, oic.fan, etc. - * - * @return Resource type. - */ - public String getResourceType() { - return resourceType; - } - - /** - * API to get the interface type of the resource. Example: oic.if.baseline, - * oic.if.b, etc. - * - * @return Interface type of the resource. - */ - public String getInterfaceType() { - return interfaceType; - } - - /** - * API to get the {@link SimulatorResourceModel} of the - * simulated resource. - * - * @return {@link SimulatorResourceModel} object on success, otherwise null. - * - * @throws SimulatorException - * This exception will be thrown if simulated resource is not proper. - */ - public native SimulatorResourceModel getModel() - throws SimulatorException; - - /** - * API to add an attribute whose value is of type int. - * - * @param key - * Name of the attribute. - * @param value - * Initial value of the attribute. - * - * @throws InvalidArgsException - * This exception will be thrown if any parameter has invalid - * values. - * @throws SimulatorException - * This exception will be thrown for other errors. - */ - public native void addAttributeInteger(String key, int value) - throws InvalidArgsException, SimulatorException; - - /** - * API to add an attribute whose value is of type double. - * - * @param key - * Name of the attribute. - * @param value - * Initial value of the attribute. - * - * @throws InvalidArgsException - * This exception will be thrown if any parameter has invalid - * values. - * @throws SimulatorException - * This exception will be thrown for other errors. - */ - public native void addAttributeDouble(String key, double value) - throws InvalidArgsException, SimulatorException; - - /** - * API to add an attribute whose value is of type boolean. - * - * @param key - * Name of the attribute. - * @param value - * Initial value of the attribute. - * - * @throws InvalidArgsException - * This exception will be thrown if any parameter has invalid - * values. - * @throws SimulatorException - * This exception will be thrown for other errors. - */ - public native void addAttributeBoolean(String key, boolean value) - throws InvalidArgsException, SimulatorException; - - /** - * API to add an attribute whose value is of type String. - * - * @param key - * Name of the attribute. - * @param value - * Initial value of the attribute. - * - * @throws InvalidArgsException - * This exception will be thrown if any parameter has invalid - * values. - * @throws SimulatorException - * This exception will be thrown for other errors. - */ - public native void addAttributeString(String key, String value) - throws InvalidArgsException, SimulatorException; - - /** - * API to update the value of an attribute whose value is of - * type int. - * - * @param key - * Name of the attribute. - * @param value - * New value of the attribute. - * - * @throws InvalidArgsException - * This exception will be thrown if any parameter has invalid - * values. - * @throws SimulatorException - * This exception will be thrown for other errors. - */ - public native void updateAttributeInteger(String key, int value) - throws InvalidArgsException, SimulatorException; - - /** - * API to update the value of an attribute whose value is of - * type double. - * - * @param key - * Name of the attribute. - * @param value - * New value of the attribute. - * - * @throws InvalidArgsException - * This exception will be thrown if any parameter has invalid - * values. - * @throws SimulatorException - * This exception will be thrown for other errors. - */ - public native void updateAttributeDouble(String key, double value) - throws InvalidArgsException, SimulatorException; - - /** - * API to update the value of an attribute whose value is of - * type boolean. - * - * @param key - * Name of the attribute. - * @param value - * New value of the attribute. - * - * @throws InvalidArgsException - * This exception will be thrown if any parameter has invalid - * values. - * @throws SimulatorException - * This exception will be thrown for other errors. - */ - public native void updateAttributeBoolean(String key, boolean value) - throws InvalidArgsException, SimulatorException; - - /** - * API to update the value of an attribute whose value is of - * type String. - * - * @param key - * Name of the attribute. - * @param value - * New value of the attribute. - * - * @throws InvalidArgsException - * This exception will be thrown if any parameter has invalid - * values. - * @throws SimulatorException - * This exception will be thrown for other errors. - */ - public native void updateAttributeString(String key, String value) - throws InvalidArgsException, SimulatorException; - - /** - * API to update the value of an attribute from - * its allowed values. - * - * @param key - * Name of the attribute. - * @param index - * Index of the value in the allowed values. - * - * @throws InvalidArgsException - * This exception will be thrown if any parameter has invalid - * values. - * @throws SimulatorException - * This exception will be thrown for other errors. - */ - public native void updateAttributeFromAllowedValues(String key, - int index) throws InvalidArgsException, SimulatorException; - - /** - * API to set the range of allowed values. This function is - * intended to be used for integer type attributes. - * - * @param key - * Name of the attribute. - * @param min - * Minimum value in the range. - * @param max - * Maximum value in the range. - * - * @throws InvalidArgsException - * This exception will be thrown if any parameter has invalid - * values. - * @throws SimulatorException - * This exception will be thrown for other errors. - */ - public native void setRange(String key, int min, int max) - throws InvalidArgsException, SimulatorException; - - /** - * API to set the allowed values of attribute whose value is of - * type int. - * - * @param key - * Name of the attribute. - * @param allowedValues - * Allowed values of the attribute. - * - * @throws InvalidArgsException - * This exception will be thrown if any parameter has invalid - * values. - * @throws SimulatorException - * This exception will be thrown for other errors. - */ - public native void setAllowedValuesInteger(String key, - Vector allowedValues) throws InvalidArgsException, - SimulatorException; - - /** - * API to set the allowed values of attribute whose value is of - * type double. - * - * @param key - * Name of the attribute. - * @param allowedValues - * Allowed values of the attribute. - * - * @throws InvalidArgsException - * This exception will be thrown if any parameter has invalid - * values. - * @throws SimulatorException - * This exception will be thrown for other errors. - */ - public native void setAllowedValuesDouble(String key, - Vector allowedValues) throws InvalidArgsException, - SimulatorException; - - /** - * API to set the allowed values of attribute whose value is of - * type String. - * - * @param key - * Name of the attribute. - * @param allowedValues - * Allowed values of the attribute. - * - * @throws InvalidArgsException - * This exception will be thrown if any parameter has invalid - * values. - * @throws SimulatorException - * This exception will be thrown for other errors. - */ - public native void setAllowedValuesString(String key, - Vector allowedValues) throws InvalidArgsException, - SimulatorException; - - /** - * API to start the resource level automation. This automation - * involves automatically updating all the possible values for all the - * attributes sequentially. - * - * @param typeOfAutomation - * {@link AutomationType} indicating whether the automation is - * one-time or recursive. - * @param updateInterval - * Interval time in milliseconds for attribute value update automation. - * @param listener - * Listener to be notified when automation ends. - * - * @return Automation ID using which the automation can be stopped. - * - * @throws InvalidArgsException - * This exception will be thrown if any parameter has invalid - * values. - * @throws SimulatorException - * This exception will be thrown for other errors. - */ - public int startResourceAutomation(AutomationType typeOfAutomation, - int updateInterval, IAutomation listener) throws InvalidArgsException, - SimulatorException { - return startResourceAutomation(typeOfAutomation.getValue(), updateInterval, listener); - } - - /** - * API to start the attribute level automation. This automation - * involves automatically updating all the possible values for a given - * attribute sequentially. - * - * @param attrName - * Name of the attribute to be automated. - * @param typeOfAutomation - * {@link AutomationType} indicating whether the automation is - * one-time or recursive. - * @param updateInterval - * Interval time in milliseconds for attribute value update automation. - * @param listener - * Listener to be notified when automation ends. - * - * @return Automation ID using which the automation can be stopped. - * - * @throws InvalidArgsException - * This exception will be thrown if any parameter has invalid - * values. - * @throws SimulatorException - * This exception will be thrown for other errors. - */ - public int startAttributeAutomation(String attrName, - AutomationType typeOfAutomation, int updateInterval, - IAutomation listener) - throws InvalidArgsException, SimulatorException { - return startAttributeAutomation(attrName, typeOfAutomation.getValue(), - updateInterval, listener); - } - - /** - * API to stop the automation based on automation id. - * - * @param automationId - * Using which a specific automation can be stopped. - * - * @throws SimulatorException - * This exception will be thrown for other errors. - */ - public native void stopAutomation(int automationId) - throws SimulatorException; - - /** - * API to remove an attribute from the simulated resource. - * - * @param key - * Name of the attribute to be deleted. - * - * @throws InvalidArgsException - * This exception will be thrown either if the parameter has - * invalid value or the native resource object does not exist. - * @throws SimulatorException - * This exception will be thrown for other errors. - */ - public native void removeAttribute(String key) throws InvalidArgsException, - SimulatorException; - - /** - * API to get observers information. - * - * @return An array of {@link ObserverInfo} objects. - * - * @throws InvalidArgsException - * This exception will be thrown if the native resource object - * does not exist. - * @throws SimulatorException - * This exception will be thrown for other errors. - */ - public native ObserverInfo[] getObserversList() - throws InvalidArgsException, SimulatorException; - - /** - * API to set callback to receive notifications when observer is added/removed. - * - * @param observer - * Listener to be notified when clients start/stop observing. - * - * @throws InvalidArgsException - * This exception will be thrown either if the parameter has - * invalid value or the native resource object does not exist. - * @throws SimulatorException - * This exception will be thrown for other errors. - */ - public native void setObserverCallback(IObserver observer) - throws InvalidArgsException, SimulatorException; - - /** - * API to notify simulated resource's state to a specific observer. - * - * @param id - * Observer's Id. - * - * @throws InvalidArgsException - * This exception will be thrown if the native resource object - * does not exist. - * @throws SimulatorException - * This exception will be thrown for other errors. - */ - public native void notifyObserver(int id) throws InvalidArgsException, - SimulatorException; - - /** - * API to notify simualted resource's state to all observers. - * - * @throws InvalidArgsException - * This exception will be thrown if the native resource object - * does not exist. - * @throws SimulatorException - * This exception will be thrown for other errors. - */ - public native void notifyAllObservers() throws InvalidArgsException, - SimulatorException; - - private native int startResourceAutomation(int typeOfAutomation, - int updateInterval, IAutomation listener) throws InvalidArgsException, - SimulatorException; - - private native int startAttributeAutomation(String attrName, - int typeOfAutomation, int updateInterval, IAutomation listener) - throws InvalidArgsException, SimulatorException; - - @Override - protected void finalize() throws Throwable { - try { - dispose(); - } finally { - super.finalize(); - } - } - - private native void dispose(); -} diff --git a/service/simulator/ramlparser/SConscript b/service/simulator/ramlparser/SConscript index 38fe308..efaa23c 100755 --- a/service/simulator/ramlparser/SConscript +++ b/service/simulator/ramlparser/SConscript @@ -47,4 +47,3 @@ ramlsdk = raml_env.SharedLibrary('RamlParser', raml_src) raml_env.InstallTarget(ramlsdk, 'libRaml') SConscript('../../../extlibs/yaml/SConscript') -SConscript('example/SConscript') diff --git a/service/simulator/ramlparser/example/SConscript b/service/simulator/ramlparser/example/SConscript deleted file mode 100755 index 41ee9a0..0000000 --- a/service/simulator/ramlparser/example/SConscript +++ /dev/null @@ -1,49 +0,0 @@ -#****************************************************************** -# -# Copyright 2015 Samsung Electronics All Rights Reserved. -# -#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -import os -Import('env') -lib_env = env.Clone() -SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env') -raml_env = lib_env.Clone() - -###################################################################### -# Build flags -###################################################################### -raml_env.AppendUnique(CPPPATH = ['../../../../extlibs/timer']) -raml_env.AppendUnique(CPPPATH = ['../raml/model','../raml/jsonSchemaParser', '../raml' , '../../../../extlibs/yaml/yaml/src' , '../../../../extlibs/yaml/yaml/include']) -raml_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread']) -raml_env.AppendUnique(CPPDEFINES = ['LINUX']) - -raml_env.AppendUnique(CPPPATH = ['../../../../extlibs/cjson/']) -raml_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'libcoap']) -raml_env.AppendUnique(LIBS = ['pthread']) -raml_env.PrependUnique(LIBS = ['RamlParser','YamlParser']) - -raml_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')]) -raml_env.AppendUnique(RPATH = [env.get('BUILD_DIR')]) - -if raml_env.get('SECURED') == '1': - raml_env.AppendUnique(LIBS = ['tinydtls']) -###################################################################### -# Source files and Targets -###################################################################### -raml_parser = raml_env.Program('raml-parser', 'raml_parser.cpp') - -env.AppendTarget('raml_parser') diff --git a/service/simulator/ramlparser/example/raml_parser.cpp b/service/simulator/ramlparser/example/raml_parser.cpp deleted file mode 100755 index 068e643..0000000 --- a/service/simulator/ramlparser/example/raml_parser.cpp +++ /dev/null @@ -1,555 +0,0 @@ -/****************************************************************** - * - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************/ - -#include "RamlParser.h" -#include "Helpers.h" -#include -#include -#include - -//#define PRINT_PARAMS -//#define PRINT_PROTOCOLS -//#define PRINT_BASEURI -//#define PRINT_DOCUMENTATION -//#define PRINT_TYPES -//#define PRINT_TRAITS -//#define PRINT_RESOURCE_URI_BASEURI -//#define PRINT_ACTION_QUERY_PARAM -//#define PRINT_RESPONSE_HEADER -//#define PRINT_REQUEST_RESPONSE_BODY_PARAMS -//#define PRINT_ACTION_HEADERS -//#define PRINT_SCHEMAS -#define PRINT_RAML -#define PRINT_JSON -//#define PRINT_JSON_PROPERTIES - -using namespace RAML; - -void printParameters(AbstractParam abstractParam) -{ - -#ifdef PRINT_PARAMS - std::cout << "Description : " << abstractParam.getDescription() << std::endl; - std::cout << "DefaultValue : " << abstractParam.getDefaultValue() << std::endl; - std::cout << "Example : " << abstractParam.getExample() << std::endl; - std::cout << "displayName : " << abstractParam.getDisplayName() << std::endl; - std::cout << "Maxlength : " << abstractParam.getMaxLength() << std::endl; - std::cout << "Max : " << abstractParam.getMaximum() << std::endl; - std::cout << "Minlength : " << abstractParam.getMinLength() << std::endl; - std::cout << "Min : " << abstractParam.getMinimum() << std::endl; - std::cout << "Pattern : " << abstractParam.getPattern() << std::endl; - std::cout << "Type : " << abstractParam.getType() << std::endl; - std::cout << "Repeat : " << abstractParam.isRepeat() << std::endl; - std::cout << "Required : " << abstractParam.isRequired() << std::endl; - std::cout << "Enum : " ; - for (auto elem : abstractParam.getEnumeration()) - std::cout << elem << " "; - std::cout << std::endl; -#endif -} - -void printRequestResponseBody(const RequestResponseBodyPtr &body) -{ - std::cout << "Body : Type : " << body->getType() << std::endl; - if ( body->getSchema() == NULL ) return; - std::cout << "Body : Schema : " << body->getSchema()->getSchema() << std::endl; - std::cout << "Body : Schema : PROPERTIES :" << std::endl; - - for ( auto pro : body->getSchema()->getProperties()->getProperties() ) - { - std::cout << "-----------------------------" << std::endl; - std::cout << "Name : " << pro.second->getName() << std::endl; - std::cout << "-----------------------------" << std::endl; - try - { - switch (pro.second->getVariantType()) - { - case VariantType::INT : // Integer - std::cout << "Defaut: " << pro.second->getValueInt() << std::endl; - for (auto tt : pro.second->getAllowedValuesInt()) - { - std::cout << "enum value : " << tt << std::endl; - } - { - int min = 0, max = 0, mul = 0; - pro.second->getRange(min, max, mul); - std::cout << "Minimum: " << min << std::endl; - std::cout << "Maximum: " << max << std::endl; - } - break; - - case VariantType::DOUBLE : // Double - std::cout << "Defaut: " << pro.second->getValueDouble() << std::endl; - for (auto tt : pro.second->getAllowedValuesDouble()) - { - std::cout << "enum value : " << tt << std::endl; - } - { - double min = 0, max = 0; - int mul = 0; - pro.second->getRangeDouble(min, max, mul); - std::cout << "MinimumDouble: " << min << std::endl; - std::cout << "MaximumDouble: " << max << std::endl; - } - break; - - case VariantType::BOOL : // Boolean - std::cout << "Defaut: " << std::boolalpha << pro.second->getValueBool() << std::noboolalpha << - std::endl; - for (auto tt : pro.second->getAllowedValuesBool()) - { - std::cout << "enum value : " << tt << std::endl; - } - break; - - case VariantType::STRING : // String - std::cout << "Defaut: " << pro.second->getValueString() << std::endl; - for (auto tt : pro.second->getAllowedValuesString()) - { - std::cout << "enum value : " << tt << std::endl; - } - { - int min = 0, max = 0, mul = 0; - pro.second->getRange(min, max, mul); - std::cout << "MinimumLength: " << min << std::endl; - std::cout << "MaximumLength: " << max << std::endl; - } - break; - default: - break; - - } - } - catch (const boost::bad_lexical_cast &e) - { - std::cout << e.what() << std::endl; - } - catch ( ... ) - { - std::cout << "Unknown exception caught!" << std::endl; - } - - } - std::cout << "-----------------------------" << std::endl; - std::cout << "Body : example : " << body->getExample() << std::endl; - -#ifdef PRINT_REQUEST_RESPONSE_BODY_PARAMS - std::cout << "Body : FormParameters " << std::endl; - for (auto tw : body->getFormParameters()) - { - std::cout << "-----------------------------" << std::endl; - std::cout << tw.first << " : " << std::endl; - std::cout << "-----------------------------" << std::endl; - FormParameter formParameter = *tw.second; - printParameters((AbstractParam)formParameter); - } -#endif -} - - -void printResponse(const ResponsePtr &response) -{ - std::cout << "#############################################" << std::endl; - std::cout << "Response : Description : " << response->getDescription() << std::endl; - - for (auto tv : response->getResponseBody()) - printRequestResponseBody(tv.second); -#ifdef PRINT_RESPONSE_HEADER - std::cout << "Header" << std::endl; - for (auto tw : response->getHeaders()) - { - std::cout << "-----------------------------" << std::endl; - std::cout << tw.first << " : " << std::endl; - std::cout << "-----------------------------" << std::endl; - - Header header = *tw.second; - printParameters((AbstractParam)header); - } -#endif -} - -void printAction(const ActionPtr &action) -{ - std::cout << "Description : " << action->getDescription() << std::endl; - std::cout << "----Action Body--------------" << std::endl; - for (auto tv : action->getRequestBody()) - printRequestResponseBody(tv.second); - std::cout << "-----------------------------" << std::endl; - std::cout << "Responses " << std::endl; - for (auto tu : action->getResponses()) - { - std::cout << "Response : " << tu.first << std::endl; - printResponse(tu.second); - } -#ifdef PRINT_ACTION_QUERY_PARAM - std::cout << "QueryParameter" << std::endl; - for (auto tw : action->getQueryParameters()) - { - std::cout << "-----------------------------" << std::endl; - std::cout << tw.first << " : " << std::endl; - std::cout << "-----------------------------" << std::endl; - QueryParameter queryParam = *tw.second; - printParameters((AbstractParam)queryParam); - } -#endif -#ifdef PRINT_ACTION_HEADERS - std::cout << "Headers" << std::endl; - for (auto tw : action->getHeaders()) - { - std::cout << "-----------------------------" << std::endl; - std::cout << tw.first << " : " << std::endl; - std::cout << "-----------------------------" << std::endl; - Header header = *tw.second; - printParameters((AbstractParam)header); - } -#endif - -#ifdef PRINT_TRAITS - - std::cout << "Traits " << std::endl; - std::cout << "-----------------------------" << std::endl; - for (auto tt : action->getTraits()) - { - std::cout << tt << " "; - } - std::cout << std::endl << "-----------------------------" << std::endl; -#endif -} - -void printResource(const RamlResourcePtr &resource) -{ - std::cout << "Displayname : " << resource->getDisplayName() << std::endl; - std::cout << "Description : " << resource->getDescription() << std::endl; -#ifdef PRINT_RESOURCE_URI_BASEURI - std::cout << "#############################################" << std::endl; - std::cout << "ResourceURI " << resource->getResourceUri() << std::endl; - std::cout << "UriParameters " << std::endl; - for (auto tt : resource->getUriParameters()) - { - std::cout << "-----------------------------" << std::endl; - std::cout << tt.first << " : " << std::endl; - std::cout << "-----------------------------" << std::endl; - UriParameter uriParameter = *tt.second; - printParameters((AbstractParam)uriParameter); - } - std::cout << "#############################################" << std::endl; - std::cout << "BaseUriParameters " << std::endl; - for (auto tt : resource->getBaseUriParameters()) - { - std::cout << "-----------------------------" << std::endl; - std::cout << tt.first << " : " << std::endl; - std::cout << "-----------------------------" << std::endl; - - UriParameter uriParameter = *tt.second; - printParameters((AbstractParam)uriParameter); - } -#endif - std::cout << "Actions " << std::endl; - for (auto tt : resource->getActions()) - { - std::cout << "#############################################" << std::endl; - std::cout << "ActionsType " << std::endl; - printAction(tt.second); - } -#ifdef PRINT_TRAITS - std::cout << "Traits " << std::endl; - std::cout << "-----------------------------" << std::endl; - for (auto tt : resource->getTraits()) - { - std::cout << tt << " "; - } - std::cout << std::endl << "-----------------------------" << std::endl; -#endif - std::cout << "Number of Child Resource for " << resource->getDisplayName() << " : " << - resource->getResources().size() << std::endl; - - for (auto tt : resource->getResources()) - { - std::cout << "Child Resource" << std::endl; - std::cout << "-----------------------------" << std::endl; - std::cout << "ResourceName :" << tt.first << std::endl; - printResource(tt.second); - } - -} -void printProperties(const PropertiesPtr &prop) -{ -#ifdef PRINT_JSON_PROPERTIES - std::cout << "-------------------------------" << std::endl; -#endif - std::cout << "Name: " << prop->getName() << std::endl; -#ifdef PRINT_JSON_PROPERTIES - std::cout << "-------------------------------" << std::endl; - std::cout << "Type: " << prop->getType() << std::endl; - std::cout << "Description: " << prop->getDescription() << std::endl; - try - { - switch (prop->getVariantType()) - { - case VariantType::INT : // Integer - std::cout << "Defaut: " << prop->getValueInt() << std::endl; - for (auto tt : prop->getAllowedValuesInt()) - { - std::cout << "enum value : " << tt << std::endl; - } - { - int min = 0, max = 0, mul = 0; - prop->getRange(min, max, mul); - std::cout << "Minimum: " << min << std::endl; - std::cout << "Maximum: " << max << std::endl; - } - break; - - case VariantType::DOUBLE : // Double - std::cout << "Defaut: " << prop->getValueDouble() << std::endl; - for (auto tt : prop->getAllowedValuesDouble()) - { - std::cout << "enum value : " << tt << std::endl; - } - { - double min = 0, max = 0; - int mul = 0; - prop->getRangeDouble(min, max, mul); - std::cout << "MinimumDouble: " << min << std::endl; - std::cout << "MaximumDouble: " << max << std::endl; - } - break; - - case VariantType::BOOL : // Boolean - std::cout << "Defaut: " << std::boolalpha << prop->getValueBool() << std::noboolalpha << std::endl; - for (auto tt : prop->getAllowedValuesBool()) - { - std::cout << std::boolalpha << "enum value : " << tt << std::noboolalpha << std::endl; - } - break; - - case VariantType::STRING : // String - std::cout << "Defaut: " << prop->getValueString() << std::endl; - for (auto tt : prop->getAllowedValuesString()) - { - std::cout << "enum value : " << tt << std::endl; - } - { - int min = 0, max = 0, mul = 0; - prop->getRange(min, max, mul); - std::cout << "MinimumLength: " << min << std::endl; - std::cout << "MaximumLength: " << max << std::endl; - } - break; - default: - break; - - } - } - catch (const boost::bad_lexical_cast &e) - { - std::cout << e.what() << std::endl; - } - catch ( ... ) - { - std::cout << "Unknown exception caught!" << std::endl; - } - - if (prop->getType() == "array") - { - for (auto it : prop->getItems()) - { - std::cout << "items Type : " << it->getType() << std::endl; - if (it->getType() == "string") - for (auto tt : it->getAllowedValuesString()) - { - std::cout << "enum value : " << tt << std::endl; - } - for (auto tt : it->getProperties()) - { - printProperties(tt.second); - } - std::cout << "Item Required Values : " << std::endl; - for (auto tt : it->getRequiredValues()) - { - std::cout << tt << std::endl; - } - } - } -#endif - -} -void printJsonSchema(JsonSchemaPtr js) -{ - std::cout << "##############################" << std::endl; - std::cout << "------JSON Schema Parser------" << std::endl; - std::cout << "##############################" << std::endl; - - std::cout << "Id: " << js->getId() << std::endl; - std::cout << "Schema: " << js->getSchema() << std::endl; - std::cout << "Title: " << js->getTitle() << std::endl; - std::cout << "Type: " << js->getType() << std::endl; - std::cout << "Description: " << js->getDescription() << std::endl; - std::cout << "AdditionalProperties: " << js->getAdditionalProperties() << std::endl; - - std::cout << "-------------------------------" << std::endl; - std::cout << "Definitions." << std::endl; - for (auto tt : js->getDefinitions()) - { - std::cout << "-------------------------------" << std::endl; - std::cout << tt.first << std::endl; - for (auto it : tt.second->getProperties()) - { - printProperties(it.second); - } - } - - std::cout << "##############################" << std::endl; - std::cout << "Properties." << std::endl; - for (auto it : js->getProperties()) - { - printProperties(it.second); - } - std::cout << "-------------------------------" << std::endl; - std::cout << "Required." << std::endl; - std::cout << "-------------------------------" << std::endl; - for (auto it : js->getRequiredValues()) - { - std::cout << it << std::endl; - } - std::cout << "-------------------------------" << std::endl; -} - -int main(int argc, char *argv[]) -{ - if (argc == 1) - { - return 0; - } - char *value = argv[1]; - std::string s(value); - - try - { - std::shared_ptr ramlParser = std::make_shared(s); - RamlPtr m_raml = ramlParser->getRamlPtr(); -#ifdef PRINT_RAML - - std::cout << "#############################################" << std::endl; - std::cout << "Test Raml Parser" << std::endl; - std::cout << "#############################################" << std::endl; - - std::cout << "Title : " << m_raml->getTitle() << std::endl; - std::cout << "Version : " << m_raml->getVersion() << std::endl; -#ifdef PRINT_PROTOCOLS - std::cout << "Protocols : " ; - for (auto it : m_raml->getProtocols()) - { - std::cout << it << " "; - } - - std::cout << std::endl; -#endif -#ifdef PRINT_BASEURI - std::cout << "BaseUri : " << m_raml->getBaseUri() << std::endl; - - std::cout << "BaseUriParameters : " << std::endl; - for (auto it : m_raml->getBaseUriParameters()) - { - std::cout << "-----------------------------" << std::endl; - std::cout << it.first << " : " << std::endl; - std::cout << "-----------------------------" << std::endl; - UriParameter uriParameter = *it.second; - printParameters((AbstractParam)uriParameter); - } -#endif -#ifdef PRINT_SCHEMAS - std::cout << "#############################################" << std::endl; - std::cout << "Schemas" << std::endl; - std::cout << "-----------------------------" << std::endl; - for (auto it : m_raml->getSchemas()) - { - std::cout << it.first << " : " << it.second->getSchema() << std::endl; - } -#endif - std::cout << "MediaType : " << m_raml->getMediaType() << std::endl; - std::cout << "#############################################" << std::endl; -#ifdef PRINT_DOCUMENTATION - std::cout << "#############################################" << std::endl; - - std::cout << "Documentation" << std::endl; - std::cout << "-----------------------------" << std::endl; - for (auto it : m_raml->getDocumentation()) - { - std::cout << it->getTitle() << " : " << it->getContent() << std::endl; - } - std::cout << "#############################################" << std::endl; -#endif - - std::cout << "Resources" << std::endl; - for (auto it : m_raml->getResources()) - { - std::cout << "-----------------------------" << std::endl; - std::cout << "ResourceName :" << it.first << std::endl; - printResource(it.second); - } -#ifdef PRINT_TYPES - - std::cout << "#############################################" << std::endl; - - std::cout << "ResourceTypes " << std::endl; - for (auto it : m_raml->getResourceTypes()) - { - std::cout << "------------" << it.first << "-----------------" << std::endl; - printResource(it.second); - } -#endif -#ifdef PRINT_TRAITS - - std::cout << "#############################################" << std::endl; - - std::cout << "Traits " << std::endl; - for (auto it : m_raml->getTraits()) - { - std::cout << "-------------" << it.first << "----------------" << std::endl; - printAction(it.second); - } -#endif -#endif -#ifdef PRINT_JSON - for (auto it : m_raml->getResources()) - { - for (auto tt : it.second->getActions()) - { - for (auto tu : tt.second->getResponses()) - { - for (auto tv : tu.second->getResponseBody()) - { - auto pro = tv.second->getSchema()->getProperties(); - printJsonSchema(pro); - break; - } - } - } - } -#endif - } - catch (RamlException &e) - { - std::cout << e.what() << std::endl; - } - -} - diff --git a/service/simulator/ramlparser/raml/IncludeResolver.h b/service/simulator/ramlparser/raml/IncludeResolver.h index 2bd5ab2..80345b7 100755 --- a/service/simulator/ramlparser/raml/IncludeResolver.h +++ b/service/simulator/ramlparser/raml/IncludeResolver.h @@ -29,7 +29,7 @@ #include "yaml-cpp/yaml.h" #include "cJSON.h" -#include "Utils.h" +#include "RamlUtils.h" #include #include "yaml-cpp/exceptions.h" #include "RamlExceptions.h" diff --git a/service/simulator/ramlparser/raml/RamlParser.cpp b/service/simulator/ramlparser/raml/RamlParser.cpp index 38ed45d..07a57c9 100755 --- a/service/simulator/ramlparser/raml/RamlParser.cpp +++ b/service/simulator/ramlparser/raml/RamlParser.cpp @@ -45,17 +45,17 @@ namespace RAML { return; } - for (auto const & it : resource) + for (auto const &it : resource) { std::string type = getRamlPtr()->getMediaType(); - for (auto const & action : it.second->getActions()) + for (auto const &action : it.second->getActions()) { if (action.second->getRequestBody().empty()) { action.second->setRequestBody(type); } - for (auto const & response : action.second->getResponses()) + for (auto const &response : action.second->getResponses()) { if (response.second->getResponseBody().empty()) { @@ -72,11 +72,11 @@ namespace RAML { return; } - for (auto const & it : resource) + for (auto const &it : resource) { - for (auto const & action : it.second->getActions()) + for (auto const &action : it.second->getActions()) { - for (auto const & body : action.second->getRequestBody()) + for (auto const &body : action.second->getRequestBody()) { SchemaPtr schema = body.second->getSchema(); @@ -94,9 +94,9 @@ namespace RAML } } } - for (auto const & response : action.second->getResponses()) + for (auto const &response : action.second->getResponses()) { - for (auto const & body : response.second->getResponseBody()) + for (auto const &body : response.second->getResponseBody()) { SchemaPtr schema = body.second->getSchema(); if (schema != NULL) @@ -127,7 +127,7 @@ namespace RAML { return; } - for (auto const & it : resource) + for (auto const &it : resource) { auto const &resourceTypes = getRamlPtr()->getResourceTypes(); std::string typeValue = it.second->getResourceType(); @@ -158,12 +158,12 @@ namespace RAML { return; } - for (auto const & it : resource) + for (auto const &it : resource) { auto const &trait = getRamlPtr()->getTraits(); - for (auto const & act : it.second->getActions()) + for (auto const &act : it.second->getActions()) { - for (const std::string & traitValue : act.second->getTraits()) + for (const std::string &traitValue : act.second->getTraits()) { auto iter = trait.begin(); for (; iter != trait.end(); iter++) @@ -191,7 +191,7 @@ namespace RAML } } } - for (const std::string & traitValue : it.second->getTraits()) + for (const std::string &traitValue : it.second->getTraits()) { auto iter = trait.begin(); for (; iter != trait.end(); iter++) diff --git a/service/simulator/ramlparser/raml/RamlParser.h b/service/simulator/ramlparser/raml/RamlParser.h index 3949234..2cf1446 100755 --- a/service/simulator/ramlparser/raml/RamlParser.h +++ b/service/simulator/ramlparser/raml/RamlParser.h @@ -29,7 +29,7 @@ #include "yaml-cpp/yaml.h" #include "Raml.h" -#include "Utils.h" +#include "RamlUtils.h" #include "RequestResponseBody.h" #include "RamlResource.h" #include "Action.h" diff --git a/service/simulator/ramlparser/raml/Utils.h b/service/simulator/ramlparser/raml/RamlUtils.h old mode 100755 new mode 100644 similarity index 96% rename from service/simulator/ramlparser/raml/Utils.h rename to service/simulator/ramlparser/raml/RamlUtils.h index 0895f36..0fad867 --- a/service/simulator/ramlparser/raml/Utils.h +++ b/service/simulator/ramlparser/raml/RamlUtils.h @@ -1,198 +1,198 @@ -/****************************************************************** - * - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************/ - -/** - * @file Utils.h - * - * @brief This file provides utilities for RamlParser. - */ - -#ifndef UTILS_H -#define UTILS_H - -#include "yaml-cpp/yaml.h" -#include "ActionType.h" - -namespace RAML -{ - namespace Keys - { - /** Title - Raml title key.*/ - const std::string Title = "title"; - /** Version - Raml Version key.*/ - const std::string Version = "version"; - /** BaseUri - Raml BaseUri key.*/ - const std::string BaseUri = "baseUri"; - /** Protocols - Raml Protocols key.*/ - const std::string Protocols = "protocols"; - /** MediaType - Raml MediaType key.*/ - const std::string MediaType = "mediaType"; - /** Schemas - Raml Schemas key.*/ - const std::string Schemas = "schemas"; - /** ResourceTypes - Raml ResourceTypes key.*/ - const std::string ResourceTypes = "resourceTypes"; - /** Traits - Raml Traits key.*/ - const std::string Traits = "traits"; - /** IsTrait - Raml is key.*/ - const std::string IsTrait = "is"; - - /** Resource - Raml Resource key.*/ - const std::string Resource = "/"; - /** ActionType - Raml allowed ActionType key.*/ - const std::vector ActionType = {"get", "post", "put", "delete", - "head", "patch", "options", "trace" - }; - - /** Responses - Raml Responses key.*/ - const std::string Responses = "responses"; - /** Body - Raml Body key.*/ - const std::string Body = "body"; - /** Schema - Raml Schema key.*/ - const std::string Schema = "schema"; - /** Example - Raml Example key.*/ - const std::string Example = "example"; - - /** BaseUriParameters - Raml BaseUriParameters key.*/ - const std::string BaseUriParameters = "baseUriParameters"; - /** UriParameters - Raml UriParameters key.*/ - const std::string UriParameters = "uriParameters"; - /** Headers - Raml title Headers.*/ - const std::string Headers = "headers"; - /** QueryParameters - Raml QueryParameters key.*/ - const std::string QueryParameters = "queryParameters"; - /** FormParameters - Raml FormParameters key.*/ - const std::string FormParameters = "formParameters"; - /** DisplayName - Raml DisplayName key.*/ - const std::string DisplayName = "displayName"; - /** Description - Raml Description key.*/ - const std::string Description = "description"; - /** Type - Raml Type key.*/ - const std::string Type = "type"; - /** Enum - Raml Enum key.*/ - const std::string Enum = "enum"; - /** Pattern - Raml Pattern key.*/ - const std::string Pattern = "pattern"; - /** MinLength - Raml MinLength key.*/ - const std::string MinLength = "minLength"; - /** MaxLength - Raml MaxLength key.*/ - const std::string MaxLength = "maxLength"; - /** Minimum - Raml Minimum key.*/ - const std::string Minimum = "minimum"; - /** Maximum - Raml Maximum key.*/ - const std::string Maximum = "maximum"; - /** Repeat - Raml Repeat key.*/ - const std::string Repeat = "repeat"; - /** Required - Raml Required key.*/ - const std::string Required = "required"; - /** Default - Raml Default key.*/ - const std::string Default = "default"; - /** Title - Raml title key.*/ - - /** Documentation - Raml Documentation key.*/ - const std::string Documentation = "documentation"; - /** Content - Raml Content key.*/ - const std::string Content = "content"; - - /** Json - Raml Json key.*/ - const std::string Json = "json"; - /** AllowedRamlYamlTypes - Raml AllowedRamlYamlTypes key.*/ - const std::vector AllowedRamlYamlTypes = {"raml", "yaml", "yml"}; - - } - - /** - * This macro is reading yamlNode as String. - * - * @param yamlNode - reference to yamlNode - * - * @return value as string - */ - -#define READ_NODE_AS_STRING(yamlNode) \ -({ \ -(yamlNode).as(); \ -}) - - /** - * This macro is reading yamlNode as int. - * - * @param yamlNode - reference to yamlNode - * - * @return value as int - */ -#define READ_NODE_AS_INT(yamlNode) \ -({ \ - (yamlNode).as(); \ -}) - - /** - * This macro is reading yamlNode as long. - * - * @param yamlNode - reference to yamlNode - * - * @return value as long - */ -#define READ_NODE_AS_LONG(yamlNode) \ -({ \ - (yamlNode).as(); \ -}) - /** - * This macro is reading yamlNode as bool. - * - * @param yamlNode - reference to yamlNode - * - * @return value as bool - */ -#define READ_NODE_AS_BOOL(yamlNode) \ -({ \ - (yamlNode).as(); \ -}) - /** - * This macro is getting ActionType - * - * @param key - string - * - * @return ActionType - */ - -#define GET_ACTION_TYPE(key) \ -({ \ - ActionType actionType = ActionType::GET; \ - if (key == "get" ) \ - actionType = ActionType::GET; \ - else if (key == "post" ) \ - actionType = ActionType::POST; \ - else if (key == "put" ) \ - actionType = ActionType::PUT; \ - else if (key == "delete" ) \ - actionType = ActionType::DELETE; \ - else if (key == "head" ) \ - actionType = ActionType::HEAD; \ - else if (key == "patch" ) \ - actionType = ActionType::PATCH; \ - else if (key == "options" ) \ - actionType = ActionType::OPTIONS; \ - else if (key == "trace" ) \ - actionType = ActionType::TRACE; \ - actionType; \ -}) - -} -#endif +/****************************************************************** + * + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +/** + * @file Utils.h + * + * @brief This file provides utilities for RamlParser. + */ + +#ifndef RAML_UTILS_H +#define RAML_UTILS_H + +#include "yaml-cpp/yaml.h" +#include "ActionType.h" + +namespace RAML +{ + namespace Keys + { + /** Title - Raml title key.*/ + const std::string Title = "title"; + /** Version - Raml Version key.*/ + const std::string Version = "version"; + /** BaseUri - Raml BaseUri key.*/ + const std::string BaseUri = "baseUri"; + /** Protocols - Raml Protocols key.*/ + const std::string Protocols = "protocols"; + /** MediaType - Raml MediaType key.*/ + const std::string MediaType = "mediaType"; + /** Schemas - Raml Schemas key.*/ + const std::string Schemas = "schemas"; + /** ResourceTypes - Raml ResourceTypes key.*/ + const std::string ResourceTypes = "resourceTypes"; + /** Traits - Raml Traits key.*/ + const std::string Traits = "traits"; + /** IsTrait - Raml is key.*/ + const std::string IsTrait = "is"; + + /** Resource - Raml Resource key.*/ + const std::string Resource = "/"; + /** ActionType - Raml allowed ActionType key.*/ + const std::vector ActionType = {"get", "post", "put", "delete", + "head", "patch", "options", "trace" + }; + + /** Responses - Raml Responses key.*/ + const std::string Responses = "responses"; + /** Body - Raml Body key.*/ + const std::string Body = "body"; + /** Schema - Raml Schema key.*/ + const std::string Schema = "schema"; + /** Example - Raml Example key.*/ + const std::string Example = "example"; + + /** BaseUriParameters - Raml BaseUriParameters key.*/ + const std::string BaseUriParameters = "baseUriParameters"; + /** UriParameters - Raml UriParameters key.*/ + const std::string UriParameters = "uriParameters"; + /** Headers - Raml title Headers.*/ + const std::string Headers = "headers"; + /** QueryParameters - Raml QueryParameters key.*/ + const std::string QueryParameters = "queryParameters"; + /** FormParameters - Raml FormParameters key.*/ + const std::string FormParameters = "formParameters"; + /** DisplayName - Raml DisplayName key.*/ + const std::string DisplayName = "displayName"; + /** Description - Raml Description key.*/ + const std::string Description = "description"; + /** Type - Raml Type key.*/ + const std::string Type = "type"; + /** Enum - Raml Enum key.*/ + const std::string Enum = "enum"; + /** Pattern - Raml Pattern key.*/ + const std::string Pattern = "pattern"; + /** MinLength - Raml MinLength key.*/ + const std::string MinLength = "minLength"; + /** MaxLength - Raml MaxLength key.*/ + const std::string MaxLength = "maxLength"; + /** Minimum - Raml Minimum key.*/ + const std::string Minimum = "minimum"; + /** Maximum - Raml Maximum key.*/ + const std::string Maximum = "maximum"; + /** Repeat - Raml Repeat key.*/ + const std::string Repeat = "repeat"; + /** Required - Raml Required key.*/ + const std::string Required = "required"; + /** Default - Raml Default key.*/ + const std::string Default = "default"; + /** Title - Raml title key.*/ + + /** Documentation - Raml Documentation key.*/ + const std::string Documentation = "documentation"; + /** Content - Raml Content key.*/ + const std::string Content = "content"; + + /** Json - Raml Json key.*/ + const std::string Json = "json"; + /** AllowedRamlYamlTypes - Raml AllowedRamlYamlTypes key.*/ + const std::vector AllowedRamlYamlTypes = {"raml", "yaml", "yml"}; + + } + + /** + * This macro is reading yamlNode as String. + * + * @param yamlNode - reference to yamlNode + * + * @return value as string + */ + +#define READ_NODE_AS_STRING(yamlNode) \ +({ \ +(yamlNode).as(); \ +}) + + /** + * This macro is reading yamlNode as int. + * + * @param yamlNode - reference to yamlNode + * + * @return value as int + */ +#define READ_NODE_AS_INT(yamlNode) \ +({ \ + (yamlNode).as(); \ +}) + + /** + * This macro is reading yamlNode as long. + * + * @param yamlNode - reference to yamlNode + * + * @return value as long + */ +#define READ_NODE_AS_LONG(yamlNode) \ +({ \ + (yamlNode).as(); \ +}) + /** + * This macro is reading yamlNode as bool. + * + * @param yamlNode - reference to yamlNode + * + * @return value as bool + */ +#define READ_NODE_AS_BOOL(yamlNode) \ +({ \ + (yamlNode).as(); \ +}) + /** + * This macro is getting ActionType + * + * @param key - string + * + * @return ActionType + */ + +#define GET_ACTION_TYPE(key) \ +({ \ + ActionType actionType = ActionType::GET; \ + if (key == "get" ) \ + actionType = ActionType::GET; \ + else if (key == "post" ) \ + actionType = ActionType::POST; \ + else if (key == "put" ) \ + actionType = ActionType::PUT; \ + else if (key == "delete" ) \ + actionType = ActionType::DELETE; \ + else if (key == "head" ) \ + actionType = ActionType::HEAD; \ + else if (key == "patch" ) \ + actionType = ActionType::PATCH; \ + else if (key == "options" ) \ + actionType = ActionType::OPTIONS; \ + else if (key == "trace" ) \ + actionType = ActionType::TRACE; \ + actionType; \ +}) + +} +#endif diff --git a/service/simulator/ramlparser/raml/jsonSchemaParser/Definitions.h b/service/simulator/ramlparser/raml/jsonSchemaParser/Definitions.h index 401e448..d2eec8f 100755 --- a/service/simulator/ramlparser/raml/jsonSchemaParser/Definitions.h +++ b/service/simulator/ramlparser/raml/jsonSchemaParser/Definitions.h @@ -118,7 +118,7 @@ namespace RAML if (*it == reqValue) break; } - if (m_required.end() != it) + if (m_required.end() == it) { m_required.push_back(reqValue); } diff --git a/service/simulator/ramlparser/raml/jsonSchemaParser/Items.h b/service/simulator/ramlparser/raml/jsonSchemaParser/Items.h index b0a0e50..d2463b2 100755 --- a/service/simulator/ramlparser/raml/jsonSchemaParser/Items.h +++ b/service/simulator/ramlparser/raml/jsonSchemaParser/Items.h @@ -124,7 +124,7 @@ namespace RAML if (*it == reqValue) break; } - if (m_required.end() != it) + if (m_required.end() == it) { m_required.push_back(reqValue); } diff --git a/service/simulator/ramlparser/raml/jsonSchemaParser/JsonSchema.cpp b/service/simulator/ramlparser/raml/jsonSchemaParser/JsonSchema.cpp index 67968e2..0a0c11a 100755 --- a/service/simulator/ramlparser/raml/jsonSchemaParser/JsonSchema.cpp +++ b/service/simulator/ramlparser/raml/jsonSchemaParser/JsonSchema.cpp @@ -460,12 +460,12 @@ namespace RAML if (exclusiveMax) { if (exclusiveMax->type == cJSON_True) - property->setMaxDouble( --(Max->valuedouble)); + property->setMax( --(Max->valuedouble)); else - property->setMaxDouble(Max->valuedouble); + property->setMax(Max->valuedouble); } else - property->setMaxDouble(Max->valuedouble); + property->setMax(Max->valuedouble); } cJSON *Min = cJSON_GetObjectItem(childProperties, "minimum"); if (Min) @@ -474,12 +474,12 @@ namespace RAML if (exclusiveMin) { if (exclusiveMin->type == cJSON_True) - property->setMinDouble( ++(Min->valuedouble)); + property->setMin( ++(Min->valuedouble)); else - property->setMinDouble(Min->valuedouble); + property->setMin(Min->valuedouble); } else - property->setMinDouble(Min->valuedouble); + property->setMin(Min->valuedouble); } cJSON *multipleOf = cJSON_GetObjectItem(childProperties, "multipleOf"); if (multipleOf) diff --git a/service/simulator/ramlparser/raml/jsonSchemaParser/Properties.h b/service/simulator/ramlparser/raml/jsonSchemaParser/Properties.h index 7291635..c4dda1d 100755 --- a/service/simulator/ramlparser/raml/jsonSchemaParser/Properties.h +++ b/service/simulator/ramlparser/raml/jsonSchemaParser/Properties.h @@ -50,7 +50,7 @@ namespace RAML /** * Constructor of Properties. */ - Properties(): m_min(INT_MAX), m_max(INT_MAX), m_doubleMin(INT_MAX), m_doubleMax(INT_MAX), + Properties(): m_min(INT_MAX), m_max(INT_MAX), m_multipleOf(INT_MAX), m_unique(false), m_additionalItems(false) {} /** @@ -59,7 +59,7 @@ namespace RAML * @param name - Properties name as string. */ Properties(const std::string &name) : m_name(name), m_min(INT_MAX), m_max(INT_MAX), - m_doubleMin(INT_MAX), m_doubleMax(INT_MAX), m_multipleOf(INT_MAX), + m_multipleOf(INT_MAX), m_unique(false), m_additionalItems(false) {} /** @@ -188,7 +188,7 @@ namespace RAML * @param max - reference to hold Maximum value of Properties. * @param multipleOf - reference to hold multipleOf value of Properties. */ - inline void getRange(int &min, int &max, int &multipleOf) const + inline void getRange(double &min, double &max, int &multipleOf) const { min = m_min; max = m_max; @@ -196,24 +196,11 @@ namespace RAML } /** - * This method is for getting Range from Properties. - * - * @param min - reference to hold Minimum value of Properties. - * @param max - reference to hold Maximum value of Properties. - * @param multipleOf - reference to hold multipleOf value of Properties. - */ - inline void getRangeDouble(double &min, double &max, int &multipleOf) const - { - min = m_doubleMin; - max = m_doubleMax; - multipleOf = m_multipleOf; - } - /** - * This method is for setting Minimum to Properties + * This method is for setting Minimum to Properties. * * @param min - Minimum value of Properties. */ - inline void setMin(const int &min) + inline void setMin(double min) { m_min = min; } @@ -223,30 +210,10 @@ namespace RAML * * @param max - Maximum value of Properties. */ - inline void setMax(const int &max) + inline void setMax(double max) { m_max = max; } - - /** - * This method is for setting Minimum to Properties - * - * @param min - Minimum value of Properties. - */ - inline void setMinDouble(const double &min) - { - m_doubleMin = min; - } - - /** - * This method is for setting Maximum to Properties - * - * @param max - Maximum value of Properties. - */ - inline void setMaxDouble(const double &max) - { - m_doubleMax = max; - } /** * This method is for setting multipleOf to Properties * @@ -480,10 +447,8 @@ namespace RAML private: std::string m_name; ValueVariant m_value; - int m_min; - int m_max; - double m_doubleMin; - double m_doubleMax; + double m_min; + double m_max; int m_multipleOf; AllowedValues m_allowedValues; std::string m_type; diff --git a/service/simulator/ramlparser/raml/model/AbstractParam.h b/service/simulator/ramlparser/raml/model/AbstractParam.h index dd33564..dafba13 100755 --- a/service/simulator/ramlparser/raml/model/AbstractParam.h +++ b/service/simulator/ramlparser/raml/model/AbstractParam.h @@ -31,7 +31,7 @@ #include #include #include -#include "Utils.h" +#include "RamlUtils.h" namespace RAML diff --git a/service/simulator/ramlparser/raml/model/Action.h b/service/simulator/ramlparser/raml/model/Action.h index 6ee2abb..ff829c5 100755 --- a/service/simulator/ramlparser/raml/model/Action.h +++ b/service/simulator/ramlparser/raml/model/Action.h @@ -36,7 +36,7 @@ #include "RequestResponseBody.h" #include "UriParameter.h" #include "Response.h" -#include "Utils.h" +#include "RamlUtils.h" #include "IncludeResolver.h" namespace RAML diff --git a/service/simulator/ramlparser/raml/model/Raml.h b/service/simulator/ramlparser/raml/model/Raml.h index f90fdea..855d8f4 100755 --- a/service/simulator/ramlparser/raml/model/Raml.h +++ b/service/simulator/ramlparser/raml/model/Raml.h @@ -48,7 +48,7 @@ #include "yaml-cpp/yaml.h" #include "yaml-cpp/exceptions.h" #include "RamlExceptions.h" -#include "Utils.h" +#include "RamlUtils.h" #include "cJSON.h" diff --git a/service/simulator/ramlparser/raml/model/RamlResource.h b/service/simulator/ramlparser/raml/model/RamlResource.h index cac949d..1b4d748 100755 --- a/service/simulator/ramlparser/raml/model/RamlResource.h +++ b/service/simulator/ramlparser/raml/model/RamlResource.h @@ -33,7 +33,7 @@ #include "UriParameter.h" #include "ActionType.h" #include "Action.h" -#include "Utils.h" +#include "RamlUtils.h" #include "IncludeResolver.h" namespace RAML diff --git a/service/simulator/ramlparser/raml/model/RequestResponseBody.h b/service/simulator/ramlparser/raml/model/RequestResponseBody.h index 78aaee9..929f915 100755 --- a/service/simulator/ramlparser/raml/model/RequestResponseBody.h +++ b/service/simulator/ramlparser/raml/model/RequestResponseBody.h @@ -30,7 +30,7 @@ #include #include #include "FormParameter.h" -#include "Utils.h" +#include "RamlUtils.h" #include "IncludeResolver.h" #include "Schema.h" diff --git a/service/simulator/ramlparser/raml/model/Response.h b/service/simulator/ramlparser/raml/model/Response.h index 5d3ed62..be41192 100755 --- a/service/simulator/ramlparser/raml/model/Response.h +++ b/service/simulator/ramlparser/raml/model/Response.h @@ -32,7 +32,7 @@ #include #include "RequestResponseBody.h" #include "Header.h" -#include "Utils.h" +#include "RamlUtils.h" #include "IncludeResolver.h" namespace RAML diff --git a/service/simulator/src/client-controller/attribute_generator.cpp b/service/simulator/src/client-controller/attribute_generator.cpp deleted file mode 100644 index 03abd64..0000000 --- a/service/simulator/src/client-controller/attribute_generator.cpp +++ /dev/null @@ -1,187 +0,0 @@ -/****************************************************************** - * - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************/ - -#include "attribute_generator.h" - -AttributeGenerator::AttributeGenerator(const SimulatorResourceModel::Attribute &attribute) - : m_name(attribute.getName()), - m_min(INT_MIN), - m_max(INT_MAX), - m_rangeIndex(-1), - m_allowedValueIndex(0), - m_hasRange(false), - m_hasAllowedValue(false) -{ - if (attribute.getValueType() == - SimulatorResourceModel::Attribute::ValueType::INTEGER) - { - attribute.getRange(m_min, m_max); - if (INT_MIN != m_min && INT_MAX != m_max) - { - m_hasRange = true; - m_rangeIndex = m_min; - } - } - else - { - m_allowedValues = attribute.getAllowedValues(); - if (0 != m_allowedValues.size()) - { - m_hasAllowedValue = true; - } - } -} - -bool AttributeGenerator::hasNext() -{ - if (m_hasRange && m_rangeIndex <= m_max) - { - return true; - } - - if (m_hasAllowedValue && m_allowedValueIndex < m_allowedValues.size()) - { - return true; - } - - return false; -} - -bool AttributeGenerator::next(SimulatorResourceModel::Attribute &attribute) -{ - attribute.setName(m_name); - - if (m_hasRange) - { - attribute.setValue(m_rangeIndex++); - return true; - } - else if (m_hasAllowedValue) - { - attribute.setValue(m_allowedValues[m_allowedValueIndex++]); - return true; - } - - return false; -} - -SimulatorResourceModel::Attribute AttributeGenerator::current() -{ - SimulatorResourceModel::Attribute attribute; - - attribute.setName(m_name); - if (m_hasRange) - { - attribute.setValue(m_rangeIndex); - } - else if (m_hasAllowedValue) - { - attribute.setValue(m_allowedValues[m_allowedValueIndex]); - } - - return attribute; -} - -void AttributeGenerator::reset() -{ - if (m_hasRange) - { - m_rangeIndex = m_min; - } - else if (m_hasAllowedValue) - { - m_allowedValueIndex = 0; - } -} - -AttributeCombinationGen::AttributeCombinationGen( - const std::vector &attributes) -{ - for (auto &attr : attributes) - { - AttributeGenerator attrGen(attr); - m_attrGenList.push_back(attr); - } - - m_index = -1; -} - -bool AttributeCombinationGen::next(SimulatorResourceModel &resModel) -{ - if (!m_attrGenList.size()) - { - return false; - } - - std::lock_guard lock(m_lock); - - // This block will execute for only first time - if (-1 == m_index) - { - for (int index = 0; index < m_attrGenList.size(); index++) - { - // Add the attribute on resource model - addAttributeToModel(index); - } - - m_index = m_attrGenList.size() - 1; - resModel = m_resModel; - return true; - } - - // Get the next attribute from statck top element - if (m_attrGenList[m_index].hasNext()) - { - addAttributeToModel(m_index); - resModel = m_resModel; - return true; - } - else - { - for (int index = m_index; index >= 0; index--) - { - if (!m_attrGenList[index].hasNext()) - { - if (!index) - return false; - - m_attrGenList[index].reset(); - addAttributeToModel(index); - } - else - { - addAttributeToModel(index); - break; - } - } - - resModel = m_resModel; - return true; - } - - return false; -} - -void AttributeCombinationGen::addAttributeToModel(int index) -{ - SimulatorResourceModel::Attribute attribute; - m_attrGenList[index].next(attribute); - m_resModel.addAttribute(attribute, true); -} diff --git a/service/simulator/src/client-controller/simulator_client.cpp b/service/simulator/src/client-controller/simulator_client.cpp deleted file mode 100644 index 71645c9..0000000 --- a/service/simulator/src/client-controller/simulator_client.cpp +++ /dev/null @@ -1,93 +0,0 @@ -/****************************************************************** - * - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************/ - -#include "simulator_client.h" -#include "simulator_remote_resource_impl.h" -#include "simulator_logger.h" -#include "simulator_utils.h" -#include "logger.h" - -#define TAG "SIMULATOR_CLIENT" - -SimulatorClient *SimulatorClient::getInstance() -{ - static SimulatorClient s_instance; - return &s_instance; -} - -void SimulatorClient::findResources(ResourceFindCallback callback) -{ - if (!callback) - throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!"); - - typedef OCStackResult (*FindResource)(const std::string &, const std::string &, - OCConnectivityType, OC::FindCallback); - - invokeocplatform(static_cast(OC::OCPlatform::findResource), "", - OC_MULTICAST_DISCOVERY_URI, - CT_DEFAULT, - static_cast(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(OC::OCPlatform::findResource), "", query.str(), - CT_DEFAULT, - static_cast(std::bind(&SimulatorClient::onResourceFound, - this, std::placeholders::_1, callback))); -} - -void SimulatorClient::onResourceFound(std::shared_ptr ocResource, - ResourceFindCallback callback) -{ - if (!ocResource) - { - OC_LOG(ERROR, TAG, "Invalid OCResource !"); - return; - } - - // Construct SimulatorRemoteResource - SimulatorRemoteResourceSP simulatorResource = - std::make_shared(ocResource); - if (!simulatorResource) - { - OC_LOG(ERROR, TAG, "Failed to create simulator remote resource !"); - return; - } - - OC_LOG(DEBUG, TAG, "Invoking resource found client callback !"); - callback(simulatorResource); -} - - diff --git a/service/simulator/src/client-controller/simulator_client.h b/service/simulator/src/client-controller/simulator_client.h deleted file mode 100644 index ed669b3..0000000 --- a/service/simulator/src/client-controller/simulator_client.h +++ /dev/null @@ -1,87 +0,0 @@ -/****************************************************************** - * - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************/ - -/** - * @file simulator_client.h - * - * @brief This file provides a class for realizing simulator client functionality. - * - */ - -#ifndef SIMULATOR_CLIENT_H_ -#define SIMULATOR_CLIENT_H_ - -#include "simulator_client_types.h" -#include "simulator_remote_resource.h" -#include "simulator_exceptions.h" - -/** - * @class SimulatorClient - * @brief This class provides a set of functions for discovering the resources over the network. - */ -class SimulatorClient -{ - public: - - /** - * API for getting singleton instance of SimulatorClient class. - * - * @return Singleton instance of SimulatorClient class. - * - */ - static SimulatorClient *getInstance(void); - - /** - * API for discovering all type of resources. - * Discovered resources will be notified through the callback set using @callback parameter. - * - * @param callback - Method of type @ResourceFindCallback through which discoverd resources - * will be notified. - * - * NOTE: API throws @InvalidArgsException and @SimulatorException. - */ - void findResources(ResourceFindCallback callback); - - /** - * API for discovering resources of a particular resource type. - * Discovered resources will be notified through the callback set using @callback parameter. - * - * @param resourceType - Type of resource to be searched for - * @param callback - Method of type @ResourceFindCallback through which discoverd resources - * will be notified. - * - * NOTE: API throws @InvalidArgsException and @SimulatorException. - */ - void findResources(const std::string &resourceType, ResourceFindCallback callback); - - private: - SimulatorClient() = default; - ~SimulatorClient() = default; - SimulatorClient(const SimulatorClient &) = delete; - SimulatorClient &operator=(const SimulatorClient &) = delete; - SimulatorClient(const SimulatorClient &&) = delete; - SimulatorClient &operator=(const SimulatorClient && ) = delete; - - void onResourceFound(std::shared_ptr resource, - ResourceFindCallback callback); -}; - -#endif - diff --git a/service/simulator/src/client/attribute_generator.cpp b/service/simulator/src/client/attribute_generator.cpp new file mode 100644 index 0000000..7a1e140 --- /dev/null +++ b/service/simulator/src/client/attribute_generator.cpp @@ -0,0 +1,183 @@ +/****************************************************************** + * + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +#include "attribute_generator.h" + +AttributeGenerator::AttributeGenerator(const SimulatorResourceModel::Attribute &attribute) + : m_attribute(attribute), + m_curValue(INT_MIN), + m_valueSetIndex(0) +{ + if (m_attribute.getProperty().type() == SimulatorResourceModel::AttributeProperty::Type::RANGE) + { + m_curValue = m_attribute.getProperty().min(); + } + else if (m_attribute.getProperty().type() == + SimulatorResourceModel::AttributeProperty::Type::VALUE_SET) + { + m_supportedValues = m_attribute.getProperty().valueSet(); + } +} + +bool AttributeGenerator::hasNext() +{ + if (m_attribute.getProperty().type() == SimulatorResourceModel::AttributeProperty::Type::RANGE + && m_curValue <= m_attribute.getProperty().max()) + { + return true; + } + else if (m_attribute.getProperty().type() == + SimulatorResourceModel::AttributeProperty::Type::VALUE_SET + && m_valueSetIndex <= m_supportedValues.size() - 1) + { + return true; + } + + return false; +} + +bool AttributeGenerator::next(SimulatorResourceModel::Attribute &attribute) +{ + if (!hasNext()) + return false; + + attribute.setName(m_attribute.getName()); + if (m_attribute.getProperty().type() == SimulatorResourceModel::AttributeProperty::Type::RANGE + && m_curValue <= m_attribute.getProperty().max()) + { + if (SimulatorResourceModel::ValueType::INTEGER == m_attribute.getType().type()) + attribute.setValue(static_cast(m_curValue++)); + else + attribute.setValue(m_curValue++); + } + else if (m_attribute.getProperty().type() == + SimulatorResourceModel::AttributeProperty::Type::VALUE_SET + && m_valueSetIndex <= m_supportedValues.size() - 1) + { + attribute.setValue(m_supportedValues[m_valueSetIndex++]); + } + + return true; +} + +SimulatorResourceModel::Attribute AttributeGenerator::current() +{ + SimulatorResourceModel::Attribute attribute; + attribute.setName(m_attribute.getName()); + + if (m_attribute.getProperty().type() == SimulatorResourceModel::AttributeProperty::Type::RANGE + && m_curValue <= m_attribute.getProperty().max()) + { + if (SimulatorResourceModel::ValueType::INTEGER == m_attribute.getType().type()) + attribute.setValue(static_cast(m_curValue)); + else + attribute.setValue(m_curValue); + } + else if (m_attribute.getProperty().type() == + SimulatorResourceModel::AttributeProperty::Type::VALUE_SET + && m_valueSetIndex <= m_supportedValues.size() - 1) + { + attribute.setValue(m_supportedValues[m_valueSetIndex]); + } + + return attribute; +} + +void AttributeGenerator::reset() +{ + m_curValue = m_attribute.getProperty().min(); + m_valueSetIndex = 0; +} + +AttributeCombinationGen::AttributeCombinationGen( + const std::vector &attributes) +{ + for (auto &attr : attributes) + { + AttributeGenerator attrGen(attr); + m_attrGenList.push_back(attr); + m_resModel.add(attr); + } + + m_index = -1; +} + +bool AttributeCombinationGen::next(SimulatorResourceModel &resModel) +{ + if (!m_attrGenList.size()) + { + return false; + } + + std::lock_guard lock(m_lock); + + // This block will execute for only first time + if (-1 == m_index) + { + for (size_t index = 0; index < m_attrGenList.size(); index++) + { + // Add the attribute on resource model + updateAttributeInModel(index); + } + + m_index = m_attrGenList.size() - 1; + resModel = m_resModel; + return true; + } + + // Get the next attribute from statck top element + if (m_attrGenList[m_index].hasNext()) + { + updateAttributeInModel(m_index); + resModel = m_resModel; + return true; + } + else + { + for (int index = m_index; index >= 0; index--) + { + if (!m_attrGenList[index].hasNext()) + { + if (!index) + return false; + + m_attrGenList[index].reset(); + updateAttributeInModel(index); + } + else + { + updateAttributeInModel(index); + break; + } + } + + resModel = m_resModel; + return true; + } + + return false; +} + +void AttributeCombinationGen::updateAttributeInModel(int index) +{ + SimulatorResourceModel::Attribute attribute; + if (m_attrGenList[index].next(attribute)) + m_resModel.updateValue(attribute); +} diff --git a/service/simulator/src/client-controller/attribute_generator.h b/service/simulator/src/client/attribute_generator.h similarity index 83% rename from service/simulator/src/client-controller/attribute_generator.h rename to service/simulator/src/client/attribute_generator.h index fab888f..ca0439c 100644 --- a/service/simulator/src/client-controller/attribute_generator.h +++ b/service/simulator/src/client/attribute_generator.h @@ -35,14 +35,10 @@ class AttributeGenerator void reset(); private: - std::string m_name; - int m_min; - int m_max; - int m_rangeIndex; - int m_allowedValueIndex; - bool m_hasRange; - bool m_hasAllowedValue; - std::vector m_allowedValues; + SimulatorResourceModel::Attribute m_attribute; + double m_curValue; + size_t m_valueSetIndex; + std::vector m_supportedValues; }; class AttributeCombinationGen @@ -52,7 +48,7 @@ class AttributeCombinationGen bool next(SimulatorResourceModel &resModel); private: - void addAttributeToModel(int index); + void updateAttributeInModel(int index); std::mutex m_lock; std::vector m_attrGenList; diff --git a/service/simulator/src/client-controller/auto_request_gen.cpp b/service/simulator/src/client/auto_request_gen.cpp similarity index 100% rename from service/simulator/src/client-controller/auto_request_gen.cpp rename to service/simulator/src/client/auto_request_gen.cpp diff --git a/service/simulator/src/client-controller/auto_request_gen.h b/service/simulator/src/client/auto_request_gen.h similarity index 100% rename from service/simulator/src/client-controller/auto_request_gen.h rename to service/simulator/src/client/auto_request_gen.h diff --git a/service/simulator/src/client-controller/auto_request_gen_mngr.cpp b/service/simulator/src/client/auto_request_gen_mngr.cpp similarity index 99% rename from service/simulator/src/client-controller/auto_request_gen_mngr.cpp rename to service/simulator/src/client/auto_request_gen_mngr.cpp index 56adc4a..10aaf14 100644 --- a/service/simulator/src/client-controller/auto_request_gen_mngr.cpp +++ b/service/simulator/src/client/auto_request_gen_mngr.cpp @@ -206,7 +206,7 @@ bool AutoRequestGenMngr::isValid(int id) bool AutoRequestGenMngr::isInProgress(RequestType type) { std::lock_guard lock(m_lock); - for (auto & session : m_requestGenList) + for (auto &session : m_requestGenList) { if ((session.second)->type() == type) return true; diff --git a/service/simulator/src/client-controller/auto_request_gen_mngr.h b/service/simulator/src/client/auto_request_gen_mngr.h similarity index 100% rename from service/simulator/src/client-controller/auto_request_gen_mngr.h rename to service/simulator/src/client/auto_request_gen_mngr.h diff --git a/service/simulator/src/client-controller/get_request_generator.cpp b/service/simulator/src/client/get_request_generator.cpp similarity index 100% rename from service/simulator/src/client-controller/get_request_generator.cpp rename to service/simulator/src/client/get_request_generator.cpp diff --git a/service/simulator/src/client-controller/get_request_generator.h b/service/simulator/src/client/get_request_generator.h similarity index 100% rename from service/simulator/src/client-controller/get_request_generator.h rename to service/simulator/src/client/get_request_generator.h diff --git a/service/simulator/src/client-controller/post_request_generator.cpp b/service/simulator/src/client/post_request_generator.cpp similarity index 93% rename from service/simulator/src/client-controller/post_request_generator.cpp rename to service/simulator/src/client/post_request_generator.cpp index b8c8ebb..a8c397d 100644 --- a/service/simulator/src/client-controller/post_request_generator.cpp +++ b/service/simulator/src/client/post_request_generator.cpp @@ -94,19 +94,19 @@ void POSTRequestGenerator::SendAllRequests() // Get the next possible queryParameter std::map queryParam = m_queryParamGen.next(); - for (auto & attributeGen : attributeGenList) + for (auto &attributeGen : attributeGenList) { while (attributeGen.hasNext()) { SimulatorResourceModelSP repModel(new SimulatorResourceModel); SimulatorResourceModel::Attribute attribute; if (true == attributeGen.next(attribute)) - repModel->addAttribute(attribute); + repModel->add(attribute); // Send the request m_requestSender->sendRequest(queryParam, repModel, - std::bind(&POSTRequestGenerator::onResponseReceived, - this, std::placeholders::_1, std::placeholders::_2), true); + std::bind(&POSTRequestGenerator::onResponseReceived, + this, std::placeholders::_1, std::placeholders::_2), true); m_requestCnt++; } diff --git a/service/simulator/src/client-controller/post_request_generator.h b/service/simulator/src/client/post_request_generator.h similarity index 100% rename from service/simulator/src/client-controller/post_request_generator.h rename to service/simulator/src/client/post_request_generator.h diff --git a/service/simulator/src/client-controller/put_request_generator.cpp b/service/simulator/src/client/put_request_generator.cpp similarity index 95% rename from service/simulator/src/client-controller/put_request_generator.cpp rename to service/simulator/src/client/put_request_generator.cpp index 56bee77..d54a52d 100644 --- a/service/simulator/src/client-controller/put_request_generator.cpp +++ b/service/simulator/src/client/put_request_generator.cpp @@ -109,8 +109,8 @@ void PUTRequestGenerator::SendAllRequests() // Send the request m_requestSender->sendRequest(queryParam, repModel, - std::bind(&PUTRequestGenerator::onResponseReceived, this, - std::placeholders::_1, std::placeholders::_2), true); + std::bind(&PUTRequestGenerator::onResponseReceived, this, + std::placeholders::_1, std::placeholders::_2), true); m_requestCnt++; } diff --git a/service/simulator/src/client-controller/put_request_generator.h b/service/simulator/src/client/put_request_generator.h similarity index 100% rename from service/simulator/src/client-controller/put_request_generator.h rename to service/simulator/src/client/put_request_generator.h diff --git a/service/simulator/src/client-controller/query_param_generator.cpp b/service/simulator/src/client/query_param_generator.cpp similarity index 100% rename from service/simulator/src/client-controller/query_param_generator.cpp rename to service/simulator/src/client/query_param_generator.cpp diff --git a/service/simulator/src/client-controller/query_param_generator.h b/service/simulator/src/client/query_param_generator.h similarity index 100% rename from service/simulator/src/client-controller/query_param_generator.h rename to service/simulator/src/client/query_param_generator.h diff --git a/service/simulator/src/client-controller/request_list.h b/service/simulator/src/client/request_list.h similarity index 100% rename from service/simulator/src/client-controller/request_list.h rename to service/simulator/src/client/request_list.h diff --git a/service/simulator/src/client-controller/request_sender.cpp b/service/simulator/src/client/request_sender.cpp similarity index 80% rename from service/simulator/src/client-controller/request_sender.cpp rename to service/simulator/src/client/request_sender.cpp index 4e5ba75..b577a00 100644 --- a/service/simulator/src/client-controller/request_sender.cpp +++ b/service/simulator/src/client/request_sender.cpp @@ -42,15 +42,15 @@ void RequestSender::sendRequest(const std::string &interfaceType, } void RequestSender::sendRequest(const std::map &queryParam, - SimulatorResourceModelSP repModel, + SimulatorResourceModelSP resourceModel, ResponseCallback responseCb, bool verifyResponse) { - sendRequest(std::string(), queryParam, repModel, responseCb, verifyResponse); + sendRequest(std::string(), queryParam, resourceModel, responseCb, verifyResponse); } void RequestSender::sendRequest(const std::string &interfaceType, const std::map &queryParam, - SimulatorResourceModelSP repModel, + SimulatorResourceModelSP resourceModel, ResponseCallback responseCb, bool verifyResponse) { // Add query paramter "if" if interfaceType is not empty @@ -62,13 +62,13 @@ void RequestSender::sendRequest(const std::string &interfaceType, RequestDetailSP requestDetail(new RequestDetail); requestDetail->type = m_type; requestDetail->queryParam = queryParamCpy; - requestDetail->body = repModel; + requestDetail->body = resourceModel; requestDetail->verifyResponse = verifyResponse; requestDetail->responseCb = responseCb; int requestId = m_requestList.add(requestDetail); - OCStackResult ocResult = send(queryParamCpy, repModel, std::bind( + OCStackResult ocResult = send(queryParamCpy, resourceModel, std::bind( &RequestSender::onResponseReceived, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, requestId)); if (OC_STACK_OK != ocResult) @@ -87,14 +87,12 @@ void RequestSender::setRequestModel(const RequestModelSP &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)); + SIM_LOG(ILogger::INFO, "Response received..." << "\n" << getPayloadString(rep)); // Ignore the response recieved for invalid requests RequestDetailSP request = m_requestList.remove(requestId); if (!request) - { return; - } // Validate the response as per the schema given by RAML ValidationStatus validationStatus {false, SIMULATOR_ERROR}; @@ -105,17 +103,19 @@ void RequestSender::onResponseReceived(const OC::HeaderOptions &headerOptions, validationStatus.isVerified = true; } - SimulatorResourceModelSP repModel = SimulatorResourceModel::create(rep); - request->responseCb(static_cast(errorCode), repModel); + SimulatorResourceModelSP resourceModel = std::make_shared( + SimulatorResourceModel::build(rep)); + request->responseCb(static_cast(errorCode), resourceModel); } GETRequestSender::GETRequestSender(std::shared_ptr &ocResource) : RequestSender(RequestType::RQ_TYPE_GET, ocResource) {} OCStackResult GETRequestSender::send(OC::QueryParamsMap &queryParams, - SimulatorResourceModelSP &repModel, OC::GetCallback callback) + SimulatorResourceModelSP &resourceModel, OC::GetCallback callback) { - SIM_LOG(ILogger::INFO, "Sending GET request..." << "\n" << getRequestString(queryParams)); + SIM_LOG(ILogger::INFO, "Sending GET request..." << "\n**Payload Details**\n" << getRequestString( + queryParams)); return m_ocResource->get(queryParams, callback); } @@ -124,15 +124,14 @@ PUTRequestSender::PUTRequestSender(std::shared_ptr &ocResource) : RequestSender(RequestType::RQ_TYPE_PUT, ocResource) {} OCStackResult PUTRequestSender::send(OC::QueryParamsMap &queryParams, - SimulatorResourceModelSP &repModel, OC::GetCallback callback) + SimulatorResourceModelSP &resourceModel, OC::GetCallback callback) { OC::OCRepresentation ocRep; - if (repModel) - { - ocRep = repModel->getOCRepresentation(); - } + if (resourceModel) + ocRep = resourceModel->getOCRepresentation(); - SIM_LOG(ILogger::INFO, "Sending PUT request..." << "\n" << getRequestString(queryParams, ocRep)); + SIM_LOG(ILogger::INFO, "Sending PUT request..." << "\n**Payload Details**\n" << getRequestString( + queryParams, ocRep)); return m_ocResource->put(ocRep, queryParams, callback); } @@ -140,12 +139,13 @@ POSTRequestSender::POSTRequestSender(std::shared_ptr &ocResource : RequestSender(RequestType::RQ_TYPE_POST, ocResource) {} OCStackResult POSTRequestSender::send(OC::QueryParamsMap &queryParams, - SimulatorResourceModelSP &repModel, OC::GetCallback callback) + SimulatorResourceModelSP &resourceModel, OC::GetCallback callback) { OC::OCRepresentation ocRep; - if (repModel) - ocRep = repModel->getOCRepresentation(); + if (resourceModel) + ocRep = resourceModel->getOCRepresentation(); - SIM_LOG(ILogger::INFO, "Sending POST request..." << "\n" << getRequestString(queryParams, ocRep)); + SIM_LOG(ILogger::INFO, "Sending POST request..." << "\n**Payload Details**\n" << getRequestString( + queryParams, ocRep)); return m_ocResource->post(ocRep, queryParams, callback); } diff --git a/service/simulator/src/client-controller/request_sender.h b/service/simulator/src/client/request_sender.h similarity index 87% rename from service/simulator/src/client-controller/request_sender.h rename to service/simulator/src/client/request_sender.h index 46457e9..fa6de91 100644 --- a/service/simulator/src/client-controller/request_sender.h +++ b/service/simulator/src/client/request_sender.h @@ -44,19 +44,19 @@ class RequestSender ResponseCallback responseCb, bool verifyResponse = false); void sendRequest(const std::map &queryParam, - SimulatorResourceModelSP repModel, + SimulatorResourceModelSP resourceModel, ResponseCallback responseCb, bool verifyResponse = false); void sendRequest(const std::string &interfaceType, const std::map &queryParam, - SimulatorResourceModelSP repModel, + SimulatorResourceModelSP resourceModel, ResponseCallback responseCb, bool verifyResponse = false); void setRequestModel(const RequestModelSP &requestModel); protected: virtual OCStackResult send(OC::QueryParamsMap &queryParams, - SimulatorResourceModelSP &repModel, OC::GetCallback callback) = 0; + SimulatorResourceModelSP &resourceModel, OC::GetCallback callback) = 0; void onResponseReceived(const OC::HeaderOptions &headerOptions, const OC::OCRepresentation &rep, const int errorCode, int requestId); @@ -84,7 +84,7 @@ class GETRequestSender : public RequestSender GETRequestSender(std::shared_ptr &ocResource); OCStackResult send(OC::QueryParamsMap &queryParams, - SimulatorResourceModelSP &repModel, OC::GetCallback callback); + SimulatorResourceModelSP &resourceModel, OC::GetCallback callback); }; class PUTRequestSender : public RequestSender @@ -93,7 +93,7 @@ class PUTRequestSender : public RequestSender PUTRequestSender(std::shared_ptr &ocResource); OCStackResult send(OC::QueryParamsMap &queryParams, - SimulatorResourceModelSP &repModel, OC::GetCallback callback); + SimulatorResourceModelSP &resourceModel, OC::GetCallback callback); }; class POSTRequestSender : public RequestSender @@ -102,7 +102,7 @@ class POSTRequestSender : public RequestSender POSTRequestSender(std::shared_ptr &ocResource); OCStackResult send(OC::QueryParamsMap &queryParams, - SimulatorResourceModelSP &repModel, OC::GetCallback callback); + SimulatorResourceModelSP &resourceModel, OC::GetCallback callback); }; typedef std::shared_ptr RequestSenderSP; diff --git a/service/simulator/src/client-controller/simulator_remote_resource_impl.cpp b/service/simulator/src/client/simulator_remote_resource_impl.cpp similarity index 76% rename from service/simulator/src/client-controller/simulator_remote_resource_impl.cpp rename to service/simulator/src/client/simulator_remote_resource_impl.cpp index 178dccb..336c3ba 100644 --- a/service/simulator/src/client-controller/simulator_remote_resource_impl.cpp +++ b/service/simulator/src/client/simulator_remote_resource_impl.cpp @@ -21,6 +21,8 @@ #include "simulator_remote_resource_impl.h" #include "request_model_builder.h" #include "simulator_exceptions.h" +#include "simulator_utils.h" +#include "simulator_logger.h" #include "logger.h" #define TAG "SIMULATOR_REMOTE_RESOURCE" @@ -75,41 +77,37 @@ bool SimulatorRemoteResourceImpl::isObservable() const void SimulatorRemoteResourceImpl::observe(ObserveType type, ObserveNotificationCallback callback) { - if (!callback) - { - OC_LOG(ERROR, TAG, "Invalid callback!"); - throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!"); - } + VALIDATE_CALLBACK(callback) - std::lock_guard lock(m_observeMutex); + std::lock_guard lock(m_observeLock); 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) + OC::ObserveCallback observeCallback = std::bind( + [](const OC::HeaderOptions & headerOptions, const OC::OCRepresentation & ocRep, + const int errorCode, const int sqNum, std::string id, ObserveNotificationCallback callback) { - // Convert OCRepresentation to SimulatorResourceModel - SimulatorResourceModelSP repModel = SimulatorResourceModel::create(rep); - callback(m_id, static_cast(errorCode), repModel, sequenceNum); - }; + SIM_LOG(ILogger::INFO, "Observe response received..." << "\n" << getPayloadString(ocRep)); + + SimulatorResourceModelSP resourceModel( + new SimulatorResourceModel(SimulatorResourceModel::build(ocRep))); + callback(id, static_cast(errorCode), resourceModel, sqNum); + }, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4, + m_id, callback); OC::ObserveType observeType = OC::ObserveType::Observe; if (type == ObserveType::OBSERVE_ALL) - { observeType = OC::ObserveType::ObserveAll; - } try { OCStackResult ocResult = m_ocResource->observe(observeType, OC::QueryParamsMap(), observeCallback); if (OC_STACK_OK != ocResult) - { throw SimulatorException(static_cast(ocResult), OC::OCException::reason(ocResult)); - } + + SIM_LOG(ILogger::INFO, "OBSERVE request sent"); } catch (OC::OCException &e) { @@ -125,16 +123,16 @@ void SimulatorRemoteResourceImpl::cancelObserve() { OCStackResult ocResult = m_ocResource->cancelObserve(OC::QualityOfService::HighQos); if (OC_STACK_OK != ocResult) - { throw SimulatorException(static_cast(ocResult), OC::OCException::reason(ocResult)); - } + + SIM_LOG(ILogger::INFO, "OBSERVE CANCEL request sent"); } catch (OC::OCException &e) { throw SimulatorException(static_cast(e.code()), e.reason()); } - std::lock_guard lock(m_observeMutex); + std::lock_guard lock(m_observeLock); m_observeState = false; } @@ -142,11 +140,7 @@ void SimulatorRemoteResourceImpl::get(const std::string &interfaceType, const std::map &queryParams, ResponseCallback callback) { - if (!callback) - { - OC_LOG(ERROR, TAG, "Invalid callback!"); - throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!"); - } + VALIDATE_CALLBACK(callback) if (!m_getRequestSender) { @@ -163,11 +157,7 @@ void SimulatorRemoteResourceImpl::get(const std::string &interfaceType, void SimulatorRemoteResourceImpl::get(const std::map &queryParams, ResponseCallback callback) { - if (!callback) - { - OC_LOG(ERROR, TAG, "Invalid callback!"); - throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!"); - } + VALIDATE_CALLBACK(callback) if (!m_getRequestSender) { @@ -183,14 +173,10 @@ void SimulatorRemoteResourceImpl::get(const std::map & void SimulatorRemoteResourceImpl::put(const std::string &interfaceType, const std::map &queryParams, - SimulatorResourceModelSP representation, + SimulatorResourceModelSP resourceModel, ResponseCallback callback) { - if (!callback) - { - OC_LOG(ERROR, TAG, "Invalid callback!"); - throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!"); - } + VALIDATE_CALLBACK(callback) if (!m_putRequestSender) { @@ -199,20 +185,16 @@ void SimulatorRemoteResourceImpl::put(const std::string &interfaceType, } m_putRequestSender->sendRequest(interfaceType, queryParams, - representation, std::bind( + resourceModel, std::bind( &SimulatorRemoteResourceImpl::onResponseReceived, this, std::placeholders::_1, std::placeholders::_2, callback)); } void SimulatorRemoteResourceImpl::put(const std::map &queryParams, - SimulatorResourceModelSP representation, + SimulatorResourceModelSP resourceModel, ResponseCallback callback) { - if (!callback) - { - OC_LOG(ERROR, TAG, "Invalid callback!"); - throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!"); - } + VALIDATE_CALLBACK(callback) if (!m_putRequestSender) { @@ -221,21 +203,17 @@ void SimulatorRemoteResourceImpl::put(const std::map & } m_putRequestSender->sendRequest(std::string(), queryParams, - representation, std::bind( + resourceModel, std::bind( &SimulatorRemoteResourceImpl::onResponseReceived, this, std::placeholders::_1, std::placeholders::_2, callback)); } void SimulatorRemoteResourceImpl::post(const std::string &interfaceType, const std::map &queryParams, - SimulatorResourceModelSP representation, + SimulatorResourceModelSP resourceModel, ResponseCallback callback) { - if (!callback) - { - OC_LOG(ERROR, TAG, "Invalid callback!"); - throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!"); - } + VALIDATE_CALLBACK(callback) if (!m_postRequestSender) { @@ -244,20 +222,16 @@ void SimulatorRemoteResourceImpl::post(const std::string &interfaceType, } m_postRequestSender->sendRequest(interfaceType, queryParams, - representation, std::bind( + resourceModel, std::bind( &SimulatorRemoteResourceImpl::onResponseReceived, this, std::placeholders::_1, std::placeholders::_2, callback)); } void SimulatorRemoteResourceImpl::post(const std::map &queryParams, - SimulatorResourceModelSP representation, + SimulatorResourceModelSP resourceModel, ResponseCallback callback) { - if (!callback) - { - OC_LOG(ERROR, TAG, "Invalid callback!"); - throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!"); - } + VALIDATE_CALLBACK(callback) if (!m_postRequestSender) { @@ -266,7 +240,7 @@ void SimulatorRemoteResourceImpl::post(const std::map } m_postRequestSender->sendRequest(std::string(), queryParams, - representation, std::bind( + resourceModel, std::bind( &SimulatorRemoteResourceImpl::onResponseReceived, this, std::placeholders::_1, std::placeholders::_2, callback)); } @@ -274,11 +248,7 @@ void SimulatorRemoteResourceImpl::post(const std::map int SimulatorRemoteResourceImpl::startVerification(RequestType type, StateCallback callback) { - if (!callback) - { - OC_LOG(ERROR, TAG, "Invalid callback!"); - throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!"); - } + VALIDATE_CALLBACK(callback) if (!m_autoRequestGenMngr) { @@ -302,8 +272,8 @@ int SimulatorRemoteResourceImpl::startVerification(RequestType type, if (m_getRequestSender) { return m_autoRequestGenMngr->startOnGET(m_getRequestSender, - m_requestModelList[RequestType::RQ_TYPE_GET]->getQueryParams(), - localCallback); + m_requestModelList[RequestType::RQ_TYPE_GET]->getQueryParams(), + localCallback); } break; @@ -311,19 +281,19 @@ int SimulatorRemoteResourceImpl::startVerification(RequestType type, if (m_putRequestSender) { return m_autoRequestGenMngr->startOnPUT(m_putRequestSender, - m_requestModelList[RequestType::RQ_TYPE_PUT]->getQueryParams(), - m_requestModelList[RequestType::RQ_TYPE_PUT]->getRepSchema(), - localCallback); + m_requestModelList[RequestType::RQ_TYPE_PUT]->getQueryParams(), + m_requestModelList[RequestType::RQ_TYPE_PUT]->getRepSchema(), + localCallback); } break; case RequestType::RQ_TYPE_POST: if (m_postRequestSender) { - return m_autoRequestGenMngr->startOnPOST(m_putRequestSender, - m_requestModelList[RequestType::RQ_TYPE_POST]->getQueryParams(), - m_requestModelList[RequestType::RQ_TYPE_POST]->getRepSchema(), - localCallback); + return m_autoRequestGenMngr->startOnPOST(m_postRequestSender, + m_requestModelList[RequestType::RQ_TYPE_POST]->getQueryParams(), + m_requestModelList[RequestType::RQ_TYPE_POST]->getRepSchema(), + localCallback); } break; @@ -352,18 +322,28 @@ void SimulatorRemoteResourceImpl::stopVerification(int id) m_autoRequestGenMngr->stop(id); } -void SimulatorRemoteResourceImpl::configure(const std::string &path) +SimulatorResourceModelSP 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!"); - } + VALIDATE_INPUT(path.empty(), "Path is empty!") std::shared_ptr ramlParser = std::make_shared(path); RAML::RamlPtr raml = ramlParser->getRamlPtr(); configure(raml); + + if (m_requestModelList.empty()) + throw InvalidArgsException(SIMULATOR_INVALID_PARAM, "RAML file is invalid for the resource!"); + + for (auto &model : m_requestModelList) + { + SimulatorResourceModelSP schema = (model.second)->getRepSchema(); + if (schema) + { + return std::make_shared(*(schema.get())); + } + } + + return std::make_shared(); } void SimulatorRemoteResourceImpl::configure(std::shared_ptr &raml) @@ -394,10 +374,9 @@ void SimulatorRemoteResourceImpl::configure(std::shared_ptr &raml) } void SimulatorRemoteResourceImpl::onResponseReceived(SimulatorResult result, - SimulatorResourceModelSP repModel, - ResponseCallback clientCallback) + SimulatorResourceModelSP resourceModel, ResponseCallback clientCallback) { - clientCallback(m_id, result, repModel); + clientCallback(m_id, result, resourceModel); } SimulatorConnectivityType SimulatorRemoteResourceImpl::convertConnectivityType( @@ -423,4 +402,4 @@ SimulatorConnectivityType SimulatorRemoteResourceImpl::convertConnectivityType( 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/simulator_remote_resource_impl.h similarity index 90% rename from service/simulator/src/client-controller/simulator_remote_resource_impl.h rename to service/simulator/src/client/simulator_remote_resource_impl.h index bd64e98..9948ea3 100644 --- a/service/simulator/src/client-controller/simulator_remote_resource_impl.h +++ b/service/simulator/src/client/simulator_remote_resource_impl.h @@ -59,35 +59,35 @@ class SimulatorRemoteResourceImpl : public SimulatorRemoteResource ResponseCallback callback); void put(const std::map &queryParams, - SimulatorResourceModelSP representation, + SimulatorResourceModelSP resourceModel, ResponseCallback callback); void put(const std::string &interfaceType, const std::map &queryParams, - SimulatorResourceModelSP representation, + SimulatorResourceModelSP resourceModel, ResponseCallback callback); void post(const std::map &queryParams, - SimulatorResourceModelSP representation, + SimulatorResourceModelSP resourceModel, ResponseCallback callback); void post(const std::string &interfaceType, const std::map &queryParams, - SimulatorResourceModelSP representation, + SimulatorResourceModelSP resourceModel, ResponseCallback callback); int startVerification(RequestType type, StateCallback callback); void stopVerification(int id); - void configure(const std::string &path); + SimulatorResourceModelSP configure(const std::string &path); private: void configure(std::shared_ptr &raml); - void onResponseReceived(SimulatorResult result, SimulatorResourceModelSP repModel, + void onResponseReceived(SimulatorResult result, SimulatorResourceModelSP resourceModel, ResponseCallback clientCallback); SimulatorConnectivityType convertConnectivityType(OCConnectivityType type) const; std::string m_id; - std::mutex m_observeMutex; + std::mutex m_observeLock; bool m_observeState; GETRequestSenderSP m_getRequestSender; PUTRequestSenderSP m_putRequestSender; diff --git a/service/simulator/src/common/request_model_builder.cpp b/service/simulator/src/common/request_model_builder.cpp index 9a20021..b181433 100644 --- a/service/simulator/src/common/request_model_builder.cpp +++ b/service/simulator/src/common/request_model_builder.cpp @@ -34,14 +34,14 @@ std::map RequestModelBuilder::build(const std::stri return modelList; } - for (auto & resource : m_raml->getResources()) + for (auto &resource : m_raml->getResources()) { // Pick the resource based on the resource uri. if (std::string::npos == uri.find((resource.second)->getResourceUri())) continue; - // Construcut Request and Response Model from RAML::Action - for (auto & action : (resource.second)->getActions()) + // Construct Request and Response Model from RAML::Action + for (auto &action : (resource.second)->getActions()) { RequestModelSP requestModel = createRequestModel(action.second); if (requestModel) @@ -71,9 +71,9 @@ RequestModelSP RequestModelBuilder::createRequestModel(const RAML::ActionPtr &ac RequestModelSP requestModel(new RequestModel(getRequestType(actionType))); // Get the allowed query parameters of the request - for (auto & qpEntry : action->getQueryParameters()) + for (auto &qpEntry : action->getQueryParameters()) { - for (auto & value : (qpEntry.second)->getEnumeration()) + for (auto &value : (qpEntry.second)->getEnumeration()) { requestModel->addQueryParam(qpEntry.first, value); } @@ -84,7 +84,7 @@ RequestModelSP RequestModelBuilder::createRequestModel(const RAML::ActionPtr &ac requestModel->setRepSchema(repSchema); // Corresponsing responses - for (auto & responseEntry : action->getResponses()) + for (auto &responseEntry : action->getResponses()) { std::string codeStr = responseEntry.first; int code = boost::lexical_cast(codeStr); @@ -115,6 +115,7 @@ SimulatorResourceModelSP RequestModelBuilder::createRepSchema(const RAML::Reques { return nullptr; } + RAML::SchemaPtr schema = rep->getSchema(); if (!schema) { @@ -126,7 +127,7 @@ SimulatorResourceModelSP RequestModelBuilder::createRepSchema(const RAML::Reques return nullptr; SimulatorResourceModelSP repSchema = std::make_shared(); - for (auto & propertyEntry : properties->getProperties()) + for (auto &propertyEntry : properties->getProperties()) { std::string propName = propertyEntry.second->getName(); if ("rt" == propName || "resourceType" == propName || "if" == propName @@ -139,33 +140,29 @@ SimulatorResourceModelSP RequestModelBuilder::createRepSchema(const RAML::Reques case 0: // Integer { // Add the attribute with value - repSchema->addAttribute(propertyEntry.second->getName(), propertyEntry.second->getValue()); + repSchema->add(propertyEntry.second->getName(), propertyEntry.second->getValue()); - // Set the range - int min, max, multipleof; - propertyEntry.second->getRange(min, max, multipleof); - repSchema->setRange(propertyEntry.second->getName(), min, max); + // Convert supported values + std::vector allowedValues = propertyEntry.second->getAllowedValuesInt(); + if (allowedValues.size() > 0) + { + SimulatorResourceModel::AttributeProperty attrProp(allowedValues); + repSchema->setAttributeProperty(propName, attrProp); + } } break; case 1: // Double { // Add the attribute with value - repSchema->addAttribute(propertyEntry.second->getName(), propertyEntry.second->getValue()); + repSchema->add(propertyEntry.second->getName(), propertyEntry.second->getValue()); - std::vector propValues = - propertyEntry.second->getAllowedValues(); - - // TODO: Use RAML function once available - if (0 < propertyEntry.second->getAllowedValuesSize()) + // Convert suppoted values + std::vector allowedValues = propertyEntry.second->getAllowedValuesDouble(); + if (allowedValues.size() > 0) { - std::vector allowedValues; - for (auto & propValue : propValues) - { - double value = boost::lexical_cast (propValue); - allowedValues.push_back(value); - } - repSchema->setAllowedValues(propertyEntry.second->getName(), allowedValues); + SimulatorResourceModel::AttributeProperty attrProp(allowedValues); + repSchema->setAttributeProperty(propName, attrProp); } } break; @@ -173,33 +170,43 @@ SimulatorResourceModelSP RequestModelBuilder::createRepSchema(const RAML::Reques case 2: // Boolean { // Add the attribute with value - repSchema->addAttribute(propertyEntry.second->getName(), propertyEntry.second->getValue()); + repSchema->add(propertyEntry.second->getName(), propertyEntry.second->getValue()); + // Convert supported values + std::vector allowedValues = propertyEntry.second->getAllowedValuesBool(); + if (allowedValues.size() > 0) + { + SimulatorResourceModel::AttributeProperty attrProp(allowedValues); + repSchema->setAttributeProperty(propName, attrProp); + } } break; case 3: // String { // Add the attribute with value - repSchema->addAttribute(propertyEntry.second->getName(), - propertyEntry.second->getValue()); + repSchema->add(propertyEntry.second->getName(), + propertyEntry.second->getValue()); - std::vector propValues = - propertyEntry.second->getAllowedValues(); - - // TODO: Use RAML function once available - if (0 < propertyEntry.second->getAllowedValuesSize()) + // Convert suppored values + std::vector allowedValues = propertyEntry.second->getAllowedValuesString(); + if (allowedValues.size() > 0) { - std::vector allowedValues; - for (auto & propValue : propValues) - { - std::string value = boost::lexical_cast (propValue); - allowedValues.push_back(value); - } - repSchema->setAllowedValues(propertyEntry.second->getName(), allowedValues); + SimulatorResourceModel::AttributeProperty attrProp(allowedValues); + repSchema->setAttributeProperty(propName, attrProp); } } break; } + + // Set the range property if its present + double min, max; + int multipleof; + propertyEntry.second->getRange(min, max, multipleof); + if (min != INT_MIN && max != INT_MAX) + { + SimulatorResourceModel::AttributeProperty attrProp(min, max); + repSchema->setAttributeProperty(propName, attrProp); + } } return repSchema; @@ -209,8 +216,6 @@ RequestType RequestModelBuilder::getRequestType(RAML::ActionType actionType) { switch (actionType) { - case RAML::ActionType::GET: - return RequestType::RQ_TYPE_GET; case RAML::ActionType::PUT: return RequestType::RQ_TYPE_PUT; case RAML::ActionType::POST: @@ -218,5 +223,7 @@ RequestType RequestModelBuilder::getRequestType(RAML::ActionType actionType) case RAML::ActionType::DELETE: return RequestType::RQ_TYPE_DELETE; } + + return RequestType::RQ_TYPE_GET; } diff --git a/service/simulator/src/common/response_model.cpp b/service/simulator/src/common/response_model.cpp index 8398a18..9cae27a 100644 --- a/service/simulator/src/common/response_model.cpp +++ b/service/simulator/src/common/response_model.cpp @@ -27,98 +27,10 @@ void ResponseModel::setRepSchema(SimulatorResourceModelSP &repSchema) m_repSchema = repSchema; } -SimulatorResult ResponseModel::verifyResponse(const OC::OCRepresentation &rep) +SimulatorResult ResponseModel::verifyResponse(const OC::OCRepresentation &ocRep) { - for (auto & ocAttribute : rep) - { - SimulatorResourceModel::Attribute attribute; - if (false == m_repSchema->getAttribute(ocAttribute.attrname(), attribute)) - { - return SIMULATOR_UKNOWN_PROPERTY; - } - - switch (attribute.getValueType()) - { - case SimulatorResourceModel::Attribute::ValueType::INTEGER : // Integer - { - SimulatorResult result = validateAttributeInteger(attribute, ocAttribute); - if (SIMULATOR_OK != result) - { - return result; - } - } - break; - - case SimulatorResourceModel::Attribute::ValueType::DOUBLE : // Double - { - SimulatorResult result = validateAttributeDouble(attribute, ocAttribute); - if (SIMULATOR_OK != result) - { - return result; - } - } - break; - - case SimulatorResourceModel::Attribute::ValueType::STRING : // String - { - SimulatorResult result = validateAttributeString(attribute, ocAttribute); - if (SIMULATOR_OK != result) - { - return result; - } - } - break; - } - } - - return SIMULATOR_OK; -} - -SimulatorResult ResponseModel::validateAttributeInteger( - SimulatorResourceModel::Attribute &attrSchema, - const OC::OCRepresentation::AttributeItem &ocAttribute) -{ - // Check the value type - if (OC::AttributeType::Integer != ocAttribute.type()) - { - return SIMULATOR_TYPE_MISMATCH; - } - - // Check value if it is in range - int min, max, value; - attrSchema.getRange(min, max); - value = ocAttribute.getValue(); - if (value < min || value > max) - { - return SIMULATOR_BAD_VALUE; - } - - return SIMULATOR_OK; -} - -SimulatorResult ResponseModel::validateAttributeDouble( - SimulatorResourceModel::Attribute &attrSchema, - const OC::OCRepresentation::AttributeItem &ocAttribute) -{ - // Check the value type - if (OC::AttributeType::Double != ocAttribute.type()) - { - return SIMULATOR_TYPE_MISMATCH; - } - - return SIMULATOR_OK; + SimulatorResourceModel resModel = SimulatorResourceModel::build(ocRep); + if (m_repSchema->match(resModel)) + return SIMULATOR_OK; + return SIMULATOR_ERROR; } - -SimulatorResult ResponseModel::validateAttributeString( - SimulatorResourceModel::Attribute &attrSchema, - const OC::OCRepresentation::AttributeItem &ocAttribute) -{ - // Check the value type - if (OC::AttributeType::String != ocAttribute.type()) - { - return SIMULATOR_TYPE_MISMATCH; - } - - // TODO: Check the allowed values - return SIMULATOR_OK; -} \ No newline at end of file diff --git a/service/simulator/src/common/response_model.h b/service/simulator/src/common/response_model.h index 77cb2bb..f52626e 100644 --- a/service/simulator/src/common/response_model.h +++ b/service/simulator/src/common/response_model.h @@ -30,18 +30,11 @@ class ResponseModel public: friend class RequestModelBuilder; - SimulatorResult verifyResponse(const OC::OCRepresentation &rep); + SimulatorResult verifyResponse(const OC::OCRepresentation &ocRep); private: ResponseModel(int code); void setRepSchema(SimulatorResourceModelSP &repSchema); - SimulatorResult validateAttributeInteger(SimulatorResourceModel::Attribute &attrSchema, - const OC::OCRepresentation::AttributeItem &ocAttribute); - SimulatorResult validateAttributeDouble(SimulatorResourceModel::Attribute &attrSchema, - const OC::OCRepresentation::AttributeItem &ocAttribute); - SimulatorResult validateAttributeString(SimulatorResourceModel::Attribute &attrSchema, - const OC::OCRepresentation::AttributeItem &ocAttribute); - int m_code; SimulatorResourceModelSP m_repSchema; }; diff --git a/service/simulator/src/common/simulator_resource_model.cpp b/service/simulator/src/common/simulator_resource_model.cpp index 2a1a67d..f309ec4 100644 --- a/service/simulator/src/common/simulator_resource_model.cpp +++ b/service/simulator/src/common/simulator_resource_model.cpp @@ -21,375 +21,1085 @@ #include "simulator_resource_model.h" #include "simulator_exceptions.h" #include "logger.h" -#include "OCPlatform.h" -#include + #include +#include + +#define TAG "SIM_RESOURCE_MODEL" template -struct TypeConverter -{ - constexpr static SimulatorResourceModel::Attribute::ValueType type = - SimulatorResourceModel::Attribute::ValueType::UNKNOWN; -}; +struct TypeConverter {}; template <> struct TypeConverter { - constexpr static SimulatorResourceModel::Attribute::ValueType type = - SimulatorResourceModel::Attribute::ValueType::INTEGER; + constexpr static SimulatorResourceModel::ValueType type = + SimulatorResourceModel::ValueType::INTEGER; }; template <> struct TypeConverter { - constexpr static SimulatorResourceModel::Attribute::ValueType type = - SimulatorResourceModel::Attribute::ValueType::DOUBLE; + constexpr static SimulatorResourceModel::ValueType type = + SimulatorResourceModel::ValueType::DOUBLE; }; template <> struct TypeConverter { - constexpr static SimulatorResourceModel::Attribute::ValueType type = - SimulatorResourceModel::Attribute::ValueType::BOOLEAN; + constexpr static SimulatorResourceModel::ValueType type = + SimulatorResourceModel::ValueType::BOOLEAN; }; template <> struct TypeConverter { - constexpr static SimulatorResourceModel::Attribute::ValueType type = - SimulatorResourceModel::Attribute::ValueType::STRING; + constexpr static SimulatorResourceModel::ValueType type = + SimulatorResourceModel::ValueType::STRING; +}; + +template <> +struct TypeConverter +{ + constexpr static SimulatorResourceModel::ValueType type = + SimulatorResourceModel::ValueType::RESOURCE_MODEL; +}; + +template +struct TypeDetails +{ + constexpr static SimulatorResourceModel::ValueType type = + TypeConverter::type; + constexpr static SimulatorResourceModel::ValueType baseType = + TypeConverter::type; + constexpr static int depth = 0; +}; + +template +struct TypeDetails> +{ + constexpr static SimulatorResourceModel::ValueType type = + SimulatorResourceModel::ValueType::VECTOR; + constexpr static SimulatorResourceModel::ValueType baseType = + TypeDetails::baseType; + constexpr static int depth = 1 + TypeDetails::depth; }; -class attribute_type_visitor : public boost::static_visitor< - SimulatorResourceModel::Attribute::ValueType> +class AttributeTypeVisitor : public boost::static_visitor<> { public: + AttributeTypeVisitor() : m_type(SimulatorResourceModel::ValueType::UNKNOWN), + m_baseType(SimulatorResourceModel::ValueType::UNKNOWN), m_depth(0) {} + template - result_type operator ()(const T &) + void operator ()(const T &) { - return TypeConverter::type; + m_type = TypeDetails::type; + m_baseType = TypeDetails::baseType; + m_depth = TypeDetails::depth; } + + SimulatorResourceModel::ValueType m_type; + SimulatorResourceModel::ValueType m_baseType; + int m_depth; }; -class to_string_visitor : public boost::static_visitor +class OCRepresentationBuilder { public: - template - result_type operator ()(const T &value) + class ValueConverter : public boost::static_visitor<> { - try - { - return boost::lexical_cast(value); - } - catch (const boost::bad_lexical_cast &e) + public: + ValueConverter(OC::OCRepresentation &rep, const std::string &key) + : m_rep(rep), m_key(key) {} + + template + void operator ()(const T &value) + { + m_rep.setValue(m_key, value); + } + + void operator ()(const SimulatorResourceModel &value) + { + OC::OCRepresentation ocRep; + for (auto &element : value.getValues()) + { + ValueConverter visitor(ocRep, element.first); + boost::apply_visitor(visitor, element.second); + } + + m_rep.setValue(m_key, ocRep); + } + + template + void operator ()(const std::vector &values) + { + m_rep.setValue(m_key, values); + } + + void operator ()(const std::vector &values) + { + std::vector ocRepArray(values.size()); + for (size_t i = 0; i < values.size(); i++) + { + for (auto &element : values[i].getValues()) + { + ValueConverter visitor(ocRepArray[i], element.first); + boost::apply_visitor(visitor, element.second); + } + } + + m_rep.setValue(m_key, ocRepArray); + } + + template + void operator ()(const std::vector> &values) + { + m_rep.setValue(m_key, values); + } + + void operator ()(const std::vector> &values) + { + std::vector> ocRepArray; + for (size_t i = 0; i < values.size(); i++) + { + for (size_t j = 0; j < values[i].size(); j++) + { + for (auto &element : values[i][j].getValues()) + { + ValueConverter visitor(ocRepArray[i][j], element.first); + boost::apply_visitor(visitor, element.second); + } + } + } + + m_rep.setValue(m_key, ocRepArray); + } + + template + void operator ()(const std::vector>> &values) + { + m_rep.setValue(m_key, values); + } + + void operator ()(const std::vector>> &values) + { + std::vector>> ocRepArray; + for (size_t i = 0; i < values.size(); i++) + { + for (size_t j = 0; j < values[i].size(); j++) + { + for (size_t k = 0; j < values[i][j].size(); k++) + { + for (auto &element : values[i][j][k].getValues()) + { + ValueConverter visitor(ocRepArray[i][j][k], element.first); + boost::apply_visitor(visitor, element.second); + } + } + } + } + + m_rep.setValue(m_key, ocRepArray); + } + + private: + OC::OCRepresentation &m_rep; + std::string m_key; + }; + + OC::OCRepresentation build(SimulatorResourceModel &model) + { + OC::OCRepresentation ocRep; + for (auto &element : model.getValues()) { - return ""; + ValueConverter visitor(ocRep, element.first); + boost::apply_visitor(visitor, element.second); } + + return std::move(ocRep); } }; -class add_to_representation : public boost::static_visitor<> +// TODO: Class is very heavy, revisit again to clean +class SimulatorResourceModelBuilder { public: - add_to_representation(OC::OCRepresentation &rep, const std::string &key) - : m_rep(rep), m_key(key) {} + SimulatorResourceModel build(const OC::OCRepresentation &ocRep) + { + SimulatorResourceModel resModel; + handleRepresentationType(resModel, ocRep); + return std::move(resModel); + } - template - void operator ()(const T &value) + private: + void handleRepresentationType(SimulatorResourceModel &resModel, + const OC::OCRepresentation &ocRep) { - m_rep.setValue(m_key, value); + for (auto &ocAttribute : ocRep) + { + if (OC::AttributeType::Integer == ocAttribute.type()) + { + resModel.add(ocAttribute.attrname(), ocAttribute.getValue()); + } + else if (OC::AttributeType::Double == ocAttribute.type()) + { + resModel.add(ocAttribute.attrname(), ocAttribute.getValue()); + } + else if (OC::AttributeType::Boolean == ocAttribute.type()) + { + resModel.add(ocAttribute.attrname(), ocAttribute.getValue()); + } + else if (OC::AttributeType::String == ocAttribute.type()) + { + resModel.add(ocAttribute.attrname(), ocAttribute.getValue()); + } + else if (OC::AttributeType::OCRepresentation == ocAttribute.type()) + { + SimulatorResourceModel subResModel; + OC::OCRepresentation ocSubRep = ocAttribute.getValue(); + handleRepresentationType(subResModel, ocSubRep); + resModel.add(ocAttribute.attrname(), subResModel); + } + else if (OC::AttributeType::Vector == ocAttribute.type()) + { + handleVectorType(resModel, ocAttribute); + } + } } - OC::OCRepresentation &&getRep() + void handleVectorType(SimulatorResourceModel &resModel, + const OC::OCRepresentation::AttributeItem &ocAttribute) { - return std::move(m_rep); + if (1 == ocAttribute.depth()) + { + handleVectorTypeDepth1(resModel, ocAttribute); + } + else if (2 == ocAttribute.depth()) + { + handleVectorTypeDepth2(resModel, ocAttribute); + } + else if (3 == ocAttribute.depth()) + { + handleVectorTypeDepth3(resModel, ocAttribute); + } } - private: - OC::OCRepresentation m_rep; - std::string m_key; + void handleVectorTypeDepth1(SimulatorResourceModel &resModel, + const OC::OCRepresentation::AttributeItem &ocAttribute) + { + if (OC::AttributeType::Integer == ocAttribute.base_type()) + { + resModel.add(ocAttribute.attrname(), ocAttribute.getValue>()); + } + else if (OC::AttributeType::Double == ocAttribute.base_type()) + { + resModel.add(ocAttribute.attrname(), ocAttribute.getValue>()); + } + else if (OC::AttributeType::Boolean == ocAttribute.base_type()) + { + resModel.add(ocAttribute.attrname(), ocAttribute.getValue>()); + } + else if (OC::AttributeType::String == ocAttribute.base_type()) + { + resModel.add(ocAttribute.attrname(), ocAttribute.getValue>()); + } + else if (OC::AttributeType::OCRepresentation == ocAttribute.base_type()) + { + std::vector ocSubRepArray = + ocAttribute.getValue>(); + + std::vector subResModelArray(ocSubRepArray.size()); + for (size_t i = 0; i < ocSubRepArray.size(); i++) + { + handleRepresentationType(subResModelArray[i], ocSubRepArray[i]); + } + + resModel.add>(ocAttribute.attrname(), subResModelArray); + } + } + + void handleVectorTypeDepth2(SimulatorResourceModel &resModel, + const OC::OCRepresentation::AttributeItem &ocAttribute) + { + if (OC::AttributeType::Integer == ocAttribute.base_type()) + { + resModel.add(ocAttribute.attrname(), ocAttribute.getValue>>()); + } + else if (OC::AttributeType::Double == ocAttribute.base_type()) + { + resModel.add(ocAttribute.attrname(), ocAttribute.getValue>>()); + } + else if (OC::AttributeType::Boolean == ocAttribute.base_type()) + { + resModel.add(ocAttribute.attrname(), ocAttribute.getValue>>()); + } + else if (OC::AttributeType::String == ocAttribute.base_type()) + { + resModel.add(ocAttribute.attrname(), ocAttribute.getValue>>()); + } + else if (OC::AttributeType::OCRepresentation == ocAttribute.base_type()) + { + std::vector> ocSubRepArray = + ocAttribute.getValue>>(); + + std::vector> subResModelArray(ocSubRepArray.size()); + for (size_t i = 0; i < ocSubRepArray.size(); i++) + { + std::vector innerArray1(ocSubRepArray[i].size()); + for (size_t j = 0; j < ocSubRepArray[i].size(); j++) + handleRepresentationType(innerArray1[j], ocSubRepArray[i][j]); + subResModelArray[i] = innerArray1; + } + + resModel.add>>( + ocAttribute.attrname(), subResModelArray); + } + } + + void handleVectorTypeDepth3(SimulatorResourceModel &resModel, + const OC::OCRepresentation::AttributeItem &ocAttribute) + { + if (OC::AttributeType::Integer == ocAttribute.base_type()) + { + resModel.add(ocAttribute.attrname(), + ocAttribute.getValue>>>()); + } + else if (OC::AttributeType::Double == ocAttribute.base_type()) + { + resModel.add(ocAttribute.attrname(), + ocAttribute.getValue>>>()); + } + else if (OC::AttributeType::Boolean == ocAttribute.base_type()) + { + resModel.add(ocAttribute.attrname(), + ocAttribute.getValue>>>()); + } + else if (OC::AttributeType::String == ocAttribute.base_type()) + { + resModel.add(ocAttribute.attrname(), + ocAttribute.getValue>>>()); + } + else if (OC::AttributeType::OCRepresentation == ocAttribute.base_type()) + { + std::vector>> ocSubRepArray = + ocAttribute.getValue>>>(); + + std::vector>> subResModelArray(ocSubRepArray.size()); + for (size_t i = 0; i < ocSubRepArray.size(); i++) + { + std::vector> innerArray1(ocSubRepArray[i].size()); + for (size_t j = 0; j < ocSubRepArray[i].size(); j++) + { + std::vector innerArray2(ocSubRepArray[i][j].size()); + for (size_t k = 0; k < ocSubRepArray[i][j].size(); k++) + { + handleRepresentationType(innerArray2[k], ocSubRepArray[i][j][k]); + } + innerArray1[j] = innerArray2; + } + subResModelArray[i] = innerArray1; + } + + resModel.add>>>( + ocAttribute.attrname(), subResModelArray); + } + } }; -class range_validation : public boost::static_visitor +class RangeValidator : public boost::static_visitor { public: - range_validation (SimulatorResourceModel::Attribute &attrItem) - : m_attrItem(attrItem) {} + RangeValidator(SimulatorResourceModel::AttributeProperty &property) : + m_property(property) {} + + bool operator ()(const int &value) + { + if (checkRange(value) || checkSupportedValueSet(value)) + return true; + return false; + } - bool operator ()(int &value) + bool operator ()(const double &value) { - int min, max; - m_attrItem.getRange(min, max); - if (value >= min && value <= max) + if (checkRange(value) || checkSupportedValueSet(value)) return true; return false; } - bool operator ()(double &value) + bool operator ()(const bool &value) { - std::vector values - = m_attrItem.getAllowedValues(); - if(0 == values.size()) + if (checkSupportedValueSet(value)) return true; - for (SimulatorResourceModel::Attribute::ValueVariant & val : values) + return false; + } + + bool operator ()(const std::string &value) + { + int len = value.length(); + if (checkRange(len) || checkSupportedValueSet(value)) + return true; + return false; + } + + bool operator ()(const SimulatorResourceModel &) + { + return true; + } + + template + bool operator ()(const std::vector &values) + { + // Verify array property + int length = values.size(); + if (!checkRange(length)) + return false; + + // Verify array element property + if (!m_property.getChildProperty()) + return true; + + m_property = *(m_property.getChildProperty()); + for (int index = 0; index < length; index++) { - SimulatorResourceModel::Attribute::ValueVariant vVal = value; - if (val == vVal) - return true; + if (!operator ()(values[index])) + return false; } - return false; + + return true; } - bool operator ()(bool &value) + template + bool operator ()(const std::vector> &values) { + // Verify array property + int length = values.size(); + if (!checkRange(length)) + return false; + + // Verify array element property + if (!m_property.getChildProperty()) + return true; + + m_property = *(m_property.getChildProperty()); + for (int index = 0; index < length; index++) + { + if (!operator ()(values[index])) + return false; + } + return true; } - bool operator ()(std::string &value) + template + bool operator ()(const std::vector>> &values) { - std::vector values - = m_attrItem.getAllowedValues(); - if(0 == values.size()) + // Verify array property + int length = values.size(); + if (!checkRange(length)) + return false; + + // Verify array element property + if (!m_property.getChildProperty()) return true; - for (SimulatorResourceModel::Attribute::ValueVariant & vVal : values) + + m_property = *(m_property.getChildProperty()); + for (int index = 0; index < length; index++) { - std::string val = boost::get(vVal); - if (val == value) + if (!operator ()(values[index])) + return false; + } + + return true; + } + + private: + inline bool isValidProperty() + { + if (SimulatorResourceModel::AttributeProperty::Type::UNKNOWN != + m_property.type()) + return true; + return false; + } + + bool checkRange(const double &value) + { + if (SimulatorResourceModel::AttributeProperty::Type::RANGE == + m_property.type()) + { + if (value >= m_property.min() && value <= m_property.max()) return true; } return false; } - private: - SimulatorResourceModel::Attribute &m_attrItem; + template + bool checkSupportedValueSet(const T &value) + { + if (SimulatorResourceModel::AttributeProperty::Type::VALUE_SET == + m_property.type()) + { + for (auto &element : m_property.valueSet()) + { + T allowedValue = boost::get(element); + if (allowedValue == value) + return true; + } + } + + return false; + } + + SimulatorResourceModel::AttributeProperty m_property; +}; + +class ToStringConverter +{ + public: + class ValueVisitor : public boost::static_visitor + { + public: + + // Single basic type value conversion to string + template + std::string operator ()(const T &value) + { + try + { + return boost::lexical_cast(value); + } + catch (const boost::bad_lexical_cast &e) + { + return "CONVERSION_FAILED!"; + } + } + + // SimulatorResourceModel conversion to string + std::string operator ()(const SimulatorResourceModel &value) + { + std::ostringstream out; + out << "{ "; + for (auto &element : value.getValues()) + { + out << "\"" << element.first << "\" : "; + + ValueVisitor visitor; + out << boost::apply_visitor(visitor, element.second); + + out << ", "; + } + out << "}"; + return out.str(); + } + + template + std::string operator ()(const std::vector &values) + { + std::ostringstream out; + out << "[ "; + + for (size_t i = 0; i < values.size(); i++) + { + out << operator ()(values[i]); + out << " "; + } + + out << "]"; + return out.str(); + } + + template + std::string operator ()(const std::vector> &values) + { + std::ostringstream out; + out << "[ "; + + for (size_t i = 0; i < values.size(); i++) + { + out << operator ()(values[i]); + out << " "; + } + + out << "]"; + return out.str(); + } + + template + std::string operator ()(const std::vector>> &values) + { + std::ostringstream out; + out << "[ "; + + for (size_t i = 0; i < values.size(); i++) + { + out << operator ()(values[i]); + out << " "; + } + + out << "]"; + return out.str(); + } + }; + + std::string getStringRepresentation(const SimulatorResourceModel &resModel) + { + ValueVisitor visitor; + SimulatorResourceModel::ValueVariant value = resModel; + return boost::apply_visitor(visitor, value); + } + + std::string getStringRepresentation(const SimulatorResourceModel::ValueVariant &value) + { + ValueVisitor visitor; + return boost::apply_visitor(visitor, value); + } }; -SimulatorResourceModel::Attribute::ValueVariant -&SimulatorResourceModel::Attribute::AllowedValues::at(unsigned int index) +SimulatorResourceModel::TypeInfo::TypeInfo( + SimulatorResourceModel::ValueType type = SimulatorResourceModel::ValueType::UNKNOWN, + SimulatorResourceModel::ValueType baseType = SimulatorResourceModel::ValueType::UNKNOWN, + int depth = 0) + : m_type (type), m_baseType(baseType), m_depth(depth) {} + +SimulatorResourceModel::ValueType SimulatorResourceModel::TypeInfo::type() const +{ + return m_type; +} + +SimulatorResourceModel::ValueType SimulatorResourceModel::TypeInfo::baseType() const +{ + return m_baseType; +} + +int SimulatorResourceModel::TypeInfo::depth() const { - return m_values.at(index); + return m_depth; +} + +bool SimulatorResourceModel::TypeInfo::operator==( + const SimulatorResourceModel::TypeInfo &rhs ) const +{ + if (m_type == rhs.type() && m_baseType == rhs.baseType() + && m_depth == rhs.depth()) + return true; + return false; } -int SimulatorResourceModel::Attribute::AllowedValues::size() const +bool SimulatorResourceModel::TypeInfo::operator!=( + const SimulatorResourceModel::TypeInfo &rhs ) const { - return m_values.size(); + if (m_type != rhs.type() || m_baseType != rhs.baseType() + || m_depth != rhs.depth()) + return true; + return false; } -std::vector SimulatorResourceModel::Attribute::AllowedValues::toString() const +SimulatorResourceModel::AttributeProperty::AttributeProperty() + : m_type(SimulatorResourceModel::AttributeProperty::Type::UNKNOWN), + m_min(INT_MIN), + m_max(INT_MAX) {} + +SimulatorResourceModel::AttributeProperty::AttributeProperty(double min, double max) + : m_type(SimulatorResourceModel::AttributeProperty::Type::RANGE), + m_min(min), + m_max(max) {} + +SimulatorResourceModel::AttributeProperty::AttributeProperty( + const std::vector &valueSet) + : m_type(SimulatorResourceModel::AttributeProperty::Type::VALUE_SET), + m_min(INT_MIN), + m_max(INT_MAX), + m_valueSet(valueSet.begin(), valueSet.end()) {} + +SimulatorResourceModel::AttributeProperty::AttributeProperty( + const std::vector &valueSet) + : m_type(SimulatorResourceModel::AttributeProperty::Type::VALUE_SET), + m_min(INT_MIN), + m_max(INT_MAX), + m_valueSet(valueSet.begin(), valueSet.end()) {} + +SimulatorResourceModel::AttributeProperty::AttributeProperty( + const std::vector &valueSet) + : m_type(SimulatorResourceModel::AttributeProperty::Type::VALUE_SET), + m_min(INT_MIN), + m_max(INT_MAX), + m_valueSet(valueSet.begin(), valueSet.end()) {} + +SimulatorResourceModel::AttributeProperty::AttributeProperty( + const std::vector &valueSet) + : m_type(SimulatorResourceModel::AttributeProperty::Type::VALUE_SET), + m_min(INT_MIN), + m_max(INT_MAX), + m_valueSet(valueSet.begin(), valueSet.end()) {} + +SimulatorResourceModel::AttributeProperty::AttributeProperty( + const std::vector &valueSet) + : m_type(SimulatorResourceModel::AttributeProperty::Type::VALUE_SET), + m_min(INT_MIN), + m_max(INT_MAX), + m_valueSet(valueSet.begin(), valueSet.end()) {} + +SimulatorResourceModel::AttributeProperty::Type +SimulatorResourceModel::AttributeProperty::type() const { - std::vector values; + return m_type; +} - for (auto & value : m_values) +double SimulatorResourceModel::AttributeProperty::min() const +{ + return m_min; +} + +double SimulatorResourceModel::AttributeProperty::max() const +{ + return m_max; +} + +int SimulatorResourceModel::AttributeProperty::valueSetSize() const +{ + return m_valueSet.size(); +} + +std::vector +SimulatorResourceModel::AttributeProperty::valueSet() const +{ + return m_valueSet; +} + +std::string SimulatorResourceModel::AttributeProperty::valueSetToString() const +{ + std::ostringstream out; + out << "[ "; + for (auto &value : m_valueSet) { - to_string_visitor visitor; - values.push_back(boost::apply_visitor(visitor, value)); + out << ToStringConverter().getStringRepresentation(value); + out << ", "; } - return values; + out << "]"; + return out.str(); +} + +void SimulatorResourceModel::AttributeProperty::setChildProperty(AttributeProperty &childProperty) +{ + m_childProperty.reset(new SimulatorResourceModel::AttributeProperty(childProperty)); } -std::vector -SimulatorResourceModel::Attribute::AllowedValues::getValues() const +std::shared_ptr SimulatorResourceModel::AttributeProperty::getChildProperty() { - return m_values; + return m_childProperty; } -std::string SimulatorResourceModel::Attribute::getName(void) const +std::string SimulatorResourceModel::Attribute::getName() const { return m_name; } -void SimulatorResourceModel::Attribute::setName(const std::string &name) +SimulatorResourceModel::TypeInfo SimulatorResourceModel::Attribute::getType() const { - m_name = name; + if (m_value) + { + AttributeTypeVisitor typeVisitor; + boost::apply_visitor(typeVisitor, *(m_value.get())); + SimulatorResourceModel::TypeInfo typeInfo(typeVisitor.m_type, typeVisitor.m_baseType, + typeVisitor.m_depth); + return typeInfo; + } + + return SimulatorResourceModel::TypeInfo(); } -void SimulatorResourceModel::Attribute::getRange(int &min, int &max) const +const SimulatorResourceModel::AttributeProperty & +SimulatorResourceModel::Attribute::getProperty() const { - min = m_min; - max = m_max; + return m_property; } -void SimulatorResourceModel::Attribute::setRange(const int &min, const int &max) +SimulatorResourceModel::AttributeProperty &SimulatorResourceModel::Attribute::getProperty() { - m_min = min; - m_max = max; + return m_property; } -int SimulatorResourceModel::Attribute::getAllowedValuesSize() const +void SimulatorResourceModel::Attribute::setName(const std::string &name) { - return m_allowedValues.size(); + m_name = name; } -void SimulatorResourceModel::Attribute::setFromAllowedValue(unsigned int index) +void SimulatorResourceModel::Attribute::setProperty( + const SimulatorResourceModel::AttributeProperty &property) { - m_value = m_allowedValues.at(index); + m_property = property; } -SimulatorResourceModel::Attribute::ValueType SimulatorResourceModel::Attribute::getValueType() const +std::string SimulatorResourceModel::Attribute::toString() const { - attribute_type_visitor typeVisitor; - return boost::apply_visitor(typeVisitor, m_value); + return ToStringConverter().getStringRepresentation(*m_value); } -std::string SimulatorResourceModel::Attribute::valueToString() const +bool SimulatorResourceModel::add(const SimulatorResourceModel::Attribute &attribute) { - to_string_visitor visitor; - return boost::apply_visitor(visitor, m_value); + if (attribute.getName().empty()) + return false; + + if (m_attributes.end() == m_attributes.find(attribute.getName())) + { + m_attributes[attribute.getName()] = attribute.getValue(); + if (SimulatorResourceModel::AttributeProperty::Type::UNKNOWN != + attribute.getProperty().type()) + { + m_attrProperties[attribute.getName()] = attribute.getProperty(); + } + return true; + } + + return false; } -std::vector SimulatorResourceModel::Attribute::allowedValuesToString() const +bool SimulatorResourceModel::updateValue(const SimulatorResourceModel::Attribute &attribute, + bool overwrite) { - return m_allowedValues.toString(); + return setAttributeValue(attribute.getName(), attribute.getValue(), false, overwrite); } -void SimulatorResourceModel::Attribute::addValuetoRepresentation(OC::OCRepresentation &rep, - const std::string &key) const +bool SimulatorResourceModel::containsAttribute(const std::string &key) { - add_to_representation visitor(rep, key); - boost::apply_visitor(visitor, m_value); - rep = visitor.getRep(); + if (m_attributes.end() != m_attributes.find(key)) + return true; + return false; } -bool SimulatorResourceModel::Attribute::compare(SimulatorResourceModel::Attribute &attribute) +bool SimulatorResourceModel::setAttributeProperty(const std::string &key, + const SimulatorResourceModel::AttributeProperty &property) { - // Check the value types - if (m_value.which() != attribute.getValue().which()) + if (!key.empty() && m_attributes.end() != m_attributes.find(key)) { - return false; + m_attrProperties[key] = property; + return true; + } + + return false; +} + +bool SimulatorResourceModel::getAttributeProperty(const std::string &key, + SimulatorResourceModel::AttributeProperty &property) +{ + if (m_attrProperties.end() != m_attrProperties.find(key)) + { + property = m_attrProperties[key]; + return true; } - // Check the value in allowed range - range_validation visitor(*this); - return boost::apply_visitor(visitor, attribute.getValue()); + return false; } -std::vector -SimulatorResourceModel::Attribute::getAllowedValues() const +int SimulatorResourceModel::size() const { - return m_allowedValues.getValues(); + return m_attributes.size(); } -bool SimulatorResourceModel::getAttribute(const std::string &attrName, Attribute &value) +SimulatorResourceModel::TypeInfo SimulatorResourceModel::getType(const std::string &key) { - if (m_attributes.end() != m_attributes.find(attrName)) + if (m_attributes.end() != m_attributes.find(key)) { - value = m_attributes[attrName]; - return true; + return getTypeInfo(m_attributes.find(key)->second); } - return false; + return SimulatorResourceModel::TypeInfo(); } -std::map SimulatorResourceModel::getAttributes() +SimulatorResourceModel::TypeInfo SimulatorResourceModel::getTypeInfo(const ValueVariant &value) +const +{ + AttributeTypeVisitor typeVisitor; + boost::apply_visitor(typeVisitor, value); + SimulatorResourceModel::TypeInfo typeInfo(typeVisitor.m_type, typeVisitor.m_baseType, + typeVisitor.m_depth); + return typeInfo; +} + +std::map SimulatorResourceModel::getValues() const { return m_attributes; } -void SimulatorResourceModel::addAttribute(const SimulatorResourceModel::Attribute &attribute, bool overwrite) +std::map SimulatorResourceModel::getAttributes() { - if (!attribute.getName().empty() && - (m_attributes.end() == m_attributes.find(attribute.getName()) || overwrite)) + std::map attributes; + for (auto &element : m_attributes) { - m_attributes[attribute.getName()] = attribute; + SimulatorResourceModel::Attribute attribute(element.first); + attribute.setValue(element.second); + + if (m_attrProperties.end() != m_attrProperties.find(element.first)) + attribute.setProperty(m_attrProperties[element.first]); + + attributes[element.first] = attribute; } + + return attributes; } -void SimulatorResourceModel::setRange(const std::string &attrName, const int min, const int max) +bool SimulatorResourceModel::getAttribute(const std::string &key, + SimulatorResourceModel::Attribute &attribute) { - if (m_attributes.end() != m_attributes.find(attrName)) - m_attributes[attrName].setRange(min, max); + if (m_attributes.end() != m_attributes.find(key)) + { + attribute.setName(m_attributes.find(key)->first); + attribute.setValue(m_attributes.find(key)->second); + + if (m_attrProperties.end() != m_attrProperties.find(key)) + attribute.setProperty(m_attrProperties[key]); + + return true; + } + + return false; } -void SimulatorResourceModel::setUpdateInterval(const std::string &attrName, int interval) +bool SimulatorResourceModel::removeAttribute(const std::string &key) { - if (m_attributes.end() != m_attributes.find(attrName)) - m_attributes[attrName].setUpdateFrequencyTime(interval); + if (m_attributes.end() == m_attributes.find(key)) + { + return false; + } + + m_attributes.erase(m_attributes.find(key)); + return true; } -void SimulatorResourceModel::updateAttributeFromAllowedValues(const std::string &attrName, - unsigned int index) +bool SimulatorResourceModel::update(OC::OCRepresentation &ocRep) { - if (m_attributes.end() != m_attributes.find(attrName)) - m_attributes[attrName].setFromAllowedValue(index); + SimulatorResourceModel resModel = SimulatorResourceModel::build(ocRep); + return update(resModel); } -void SimulatorResourceModel::removeAttribute(const std::string &attrName) +OC::OCRepresentation SimulatorResourceModel::getOCRepresentation() { - if (attrName.empty() || m_attributes.end() == m_attributes.find(attrName)) - { - OC_LOG(ERROR, TAG, "Attribute name is empty or not found in model!"); - throw InvalidArgsException(SIMULATOR_INVALID_PARAM, "Attribute not found in model!"); - } + OCRepresentationBuilder ocRepBuilder; + return ocRepBuilder.build(*this); +} - m_attributes.erase(attrName); - return; +SimulatorResourceModel SimulatorResourceModel::build(const OC::OCRepresentation &ocRep) +{ + SimulatorResourceModelBuilder resModelBuilder; + return resModelBuilder.build(ocRep); } -OC::OCRepresentation SimulatorResourceModel::getOCRepresentation() const +bool SimulatorResourceModel::update(SimulatorResourceModel &resModel) { - OC::OCRepresentation rep; - for (auto & attribute : m_attributes) + if (false == match(resModel)) + { + return false; + } + + for (auto &element : resModel.getValues()) { - (attribute.second).addValuetoRepresentation(rep, attribute.first); + if (m_attributes.end() != m_attributes.find(element.first)) + { + m_attributes[element.first] = element.second; + } } - return rep; + return true; } -bool SimulatorResourceModel::update(OC::OCRepresentation &ocRep) +bool SimulatorResourceModel::setAttributeValue(const std::string &key, + const ValueVariant &newValue, bool create, bool overwrite) { - if (0 == ocRep.size()) - return true; + if (key.empty()) + { + OC_LOG(ERROR, TAG, "key is empty!"); + return false; + } - // Convert OCRepresentation to SimulatorResourceModel - SimulatorResourceModelSP resModel = create(ocRep); + /* + * Add new entry to attributes map table if key doest not exist, + * othewise check the value update policy before setting value. + */ + if (m_attributes.end() == m_attributes.find(key) && create) + { + m_attributes[key] = newValue; + } + else + { + if (true == match(key, newValue)) + { + m_attributes[key] = newValue; + } + else if (overwrite) + { + m_attributes[key] = newValue; + m_attrProperties.erase(m_attrProperties.find(key)); + } + else + { + return false; + } + } - return update(resModel); + return true; } -bool SimulatorResourceModel::update(SimulatorResourceModelSP &repModel) +bool SimulatorResourceModel::match(const std::string &key, + const SimulatorResourceModel::ValueVariant &newValue) { - std::map attributes = repModel->getAttributes(); - for (auto & attributeItem : attributes) + if (m_attributes.end() != m_attributes.find(key)) { - // Check the attribute presence - SimulatorResourceModel::Attribute attribute; - if (false == getAttribute((attributeItem.second).getName(), attribute)) + // Check the type of values + if (getTypeInfo(m_attributes[key]) != getTypeInfo(newValue)) { return false; } - // Check the validity of the value to be set - if (false == attribute.compare(attributeItem.second)) + // Check the value based on attribute property + SimulatorResourceModel::AttributeProperty prop; + if (getAttributeProperty(key, prop) + && SimulatorResourceModel::AttributeProperty::Type::UNKNOWN != prop.type()) { - return false; + RangeValidator rangeValidator(prop); + return boost::apply_visitor(rangeValidator, newValue); } - m_attributes[(attributeItem.second).getName()].setValue((attributeItem.second).getValue()); + + return true; } - return true; + return false; } -SimulatorResourceModelSP SimulatorResourceModel::create(const OC::OCRepresentation &ocRep) +bool SimulatorResourceModel::match(const SimulatorResourceModel &resModel, bool strict) { - SimulatorResourceModelSP resModel(new SimulatorResourceModel); - for (auto & attributeItem : ocRep) + for (auto &element : resModel.getValues()) { - SimulatorResourceModel::Attribute attribute; - if (attributeItem.type() == OC::AttributeType::Integer) - attribute.setValue(attributeItem.getValue()); - if (attributeItem.type() == OC::AttributeType::Double) - attribute.setValue(attributeItem.getValue()); - if (attributeItem.type() == OC::AttributeType::String) - attribute.setValue(attributeItem.getValue()); - if (attributeItem.type() == OC::AttributeType::Boolean) - attribute.setValue(attributeItem.getValue()); - - attribute.setName(attributeItem.attrname()); - resModel->m_attributes[attributeItem.attrname()] = attribute; + // Attribute presence check + if (m_attributes.end() == m_attributes.find(element.first) && !strict) + { + continue; + } + else if (strict) + { + return false; + } + + // Attribute value type check + if (getTypeInfo(m_attributes[element.first]) != getTypeInfo(element.second)) + { + return false; + } + + SimulatorResourceModel::AttributeProperty prop; + if (getAttributeProperty(element.first, prop) + && SimulatorResourceModel::AttributeProperty::Type::UNKNOWN != prop.type()) + { + RangeValidator rangeValidator(prop); + return boost::apply_visitor(rangeValidator, element.second); + } } - return resModel; + + return true; } +std::string SimulatorResourceModel::toString() const +{ + return ToStringConverter().getStringRepresentation(*this); +} diff --git a/service/simulator/src/common/simulator_utils.cpp b/service/simulator/src/common/simulator_utils.cpp index 08ca59f..042f156 100644 --- a/service/simulator/src/common/simulator_utils.cpp +++ b/service/simulator/src/common/simulator_utils.cpp @@ -23,39 +23,132 @@ std::string getPayloadString(const OC::OCRepresentation &rep) { - std::ostringstream data; OCRepPayload *payload = rep.getPayload(); if (!payload) { - return "Payload: No payload"; + return "Empty payload"; } + std::ostringstream data; + std::ostringstream dummy; - // URI - data << "URI: " << payload->uri << std::endl; + std::string payloadType; + OCStringLL *types; + OCStringLL *interfaces; + OCRepPayloadValue *values; - // Attributes - data << "Attributes:" << std::endl; - OCRepPayloadValue *values = payload->values; - while (NULL != values) + // Iterate the payload list + while (payload) { - data << values->name << ":" << rep.getValueToString(values->name) << std::endl; - values = values->next; + // Payload type + payloadType = getPayloadTypeString(payload->base.type); + if (!payloadType.empty()) + data << "Payload type: " << payloadType << std::endl; + + // URI + if (NULL != payload->uri && strlen(payload->uri) > 0) + data << "URI: " << payload->uri << std::endl; + + // Types + types = payload->types; + while (types) + { + if (NULL != types->value && strlen(types->value) > 0) + { + dummy << types->value; + if (types->next) + dummy << ", "; + } + types = types->next; + } + if (!dummy.str().empty()) + { + data << "Types: " << dummy.str() << std::endl; + dummy.str(""); + } + + // Interfaces + interfaces = payload->interfaces; + while (interfaces) + { + if (NULL != interfaces->value && strlen(interfaces->value) > 0) + { + dummy << interfaces->value; + if (interfaces->next) + dummy << ", "; + } + interfaces = interfaces->next; + } + if (!dummy.str().empty()) + { + data << "Interfaces: " << dummy.str() << std::endl; + dummy.str(""); + } + + // Values + values = payload->values; + while (values) + { + dummy << "\t" << values->name << ":" << rep.getValueToString(values->name) << std::endl; + values = values->next; + } + if (!dummy.str().empty()) + { + data << "Values:-" << std::endl; + data << dummy.str(); + dummy.str(""); + } + payload = payload->next; + if (payload) + data << "----------------" << std::endl; } return data.str(); } +std::string getPayloadTypeString(OCPayloadType type) +{ + std::string typeStr; + switch (type) + { + case PAYLOAD_TYPE_INVALID: + typeStr = "PAYLOAD_TYPE_INVALID"; + break; + case PAYLOAD_TYPE_DISCOVERY: + typeStr = "PAYLOAD_TYPE_DISCOVERY"; + break; + case PAYLOAD_TYPE_DEVICE: + typeStr = "PAYLOAD_TYPE_DEVICE"; + break; + case PAYLOAD_TYPE_PLATFORM: + typeStr = "PAYLOAD_TYPE_PLATFORM"; + break; + case PAYLOAD_TYPE_REPRESENTATION: + typeStr = "PAYLOAD_TYPE_REPRESENTATION"; + break; + case PAYLOAD_TYPE_SECURITY: + typeStr = "PAYLOAD_TYPE_SECURITY"; + break; + case PAYLOAD_TYPE_PRESENCE: + typeStr = "PAYLOAD_TYPE_PRESENCE"; + break; + } + return typeStr; +} + std::string getRequestString(const std::map &queryParams, const OC::OCRepresentation &rep) { std::ostringstream data; - data << "qp: "; + std::ostringstream dummy; if (queryParams.size() > 0) { - for (auto & qp : queryParams) - data << qp.second << ","; + for (auto &qp : queryParams) + dummy << qp.second << ","; + } + if (!dummy.str().empty()) + { + data << "qp: " << dummy.str() << std::endl; } - data << getPayloadString(rep); return data.str(); } @@ -63,13 +156,16 @@ std::string getRequestString(const std::map &queryPara std::string getRequestString(const std::map &queryParams) { std::ostringstream data; - data << "qp: "; + std::ostringstream dummy; if (queryParams.size() > 0) { - for (auto & qp : queryParams) - data << qp.second << ","; + for (auto &qp : queryParams) + dummy << qp.second << ","; + } + if (!dummy.str().empty()) + { + data << "qp: " << dummy.str() << std::endl; } - data << "Payload: No payload"; return data.str(); -} \ No newline at end of file +} diff --git a/service/simulator/src/common/simulator_utils.h b/service/simulator/src/common/simulator_utils.h index 23dd47f..c6fb66e 100644 --- a/service/simulator/src/common/simulator_utils.h +++ b/service/simulator/src/common/simulator_utils.h @@ -34,7 +34,7 @@ #include /** - * Utilities for Invokation of OC platfrom level APIs. + * Utilities for Invocation of OC platfrom level APIs. */ template typename std::enable_if()(std::declval()...))>::value>::type @@ -62,8 +62,13 @@ namespace OC } std::string getPayloadString(const OC::OCRepresentation &); +std::string getPayloadTypeString(OCPayloadType type); std::string getRequestString(const std::map &queryParams, const OC::OCRepresentation &rep); std::string getRequestString(const std::map &queryParams); + +#define VALIDATE_INPUT(CONDITION, MSG) if (CONDITION) {throw InvalidArgsException(SIMULATOR_INVALID_PARAM, MSG);} +#define VALIDATE_CALLBACK(CALLBACK) if (!CALLBACK){throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!");} + #endif \ No newline at end of file diff --git a/service/simulator/src/service-provider/resource_update_automation.cpp b/service/simulator/src/server/resource_update_automation.cpp similarity index 58% rename from service/simulator/src/service-provider/resource_update_automation.cpp rename to service/simulator/src/server/resource_update_automation.cpp index f2f2bc0..766d42f 100644 --- a/service/simulator/src/service-provider/resource_update_automation.cpp +++ b/service/simulator/src/server/resource_update_automation.cpp @@ -19,7 +19,7 @@ ******************************************************************/ #include "resource_update_automation.h" -#include "simulator_resource_server_impl.h" +#include "simulator_single_resource_impl.h" #include "attribute_generator.h" #include "simulator_exceptions.h" #include "simulator_logger.h" @@ -30,36 +30,27 @@ #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, +AttributeUpdateAutomation::AttributeUpdateAutomation(int id, SimulatorSingleResource *resource, + const SimulatorResourceModel::Attribute &attribute, AutomationType type, int interval, updateCompleteCallback callback, std::function finishedCallback) : m_resource(resource), - m_attrName(attrName), m_type(type), m_id(id), m_stopRequested(false), m_updateInterval(interval), + m_attributeGen(attribute), m_callback(callback), m_finishedCallback(finishedCallback), - m_thread(nullptr) {} - -void AttributeUpdateAutomation::start() + m_thread(nullptr) { - // 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_updateInterval = 0; } +} +void AttributeUpdateAutomation::start() +{ m_thread = new std::thread(&AttributeUpdateAutomation::updateAttribute, this); } @@ -72,20 +63,37 @@ void AttributeUpdateAutomation::stop() void AttributeUpdateAutomation::updateAttribute() { + SimulatorSingleResourceImpl *resourceImpl = + dynamic_cast(m_resource); + + if (!resourceImpl) + return; + do { try { - setAttributeValue(); + SimulatorResourceModel::Attribute attribute; + while (!m_stopRequested && true == m_attributeGen.next(attribute)) + { + if (false == m_resource->updateAttributeValue(attribute)) + { + OC_LOG_V(ERROR, ATAG, "Failed to update the attribute![%s]", attribute.getName().c_str()); + continue; + } + resourceImpl->notifyApp(); + + SLEEP_FOR(m_updateInterval); + } + + m_attributeGen.reset(); } catch (SimulatorException &e) { break; } - if (m_stopRequested) - break; } - while (AutomationType::RECURRENT == m_type); + while (!m_stopRequested && AutomationType::RECURRENT == m_type); if (!m_stopRequested) { @@ -93,7 +101,7 @@ void AttributeUpdateAutomation::updateAttribute() SIM_LOG(ILogger::INFO, "Automation of " << m_attrName << " attribute is completed."); } - // Notify application + // Notify application through callback if (m_callback) m_callback(m_resource->getURI(), m_id); @@ -101,43 +109,7 @@ void AttributeUpdateAutomation::updateAttribute() m_finishedCallback(m_id); } -void AttributeUpdateAutomation::setAttributeValue() -{ - SimulatorResourceServerImpl *resourceImpl = - dynamic_cast(m_resource); - if (!resourceImpl) - return; - - if (SimulatorResourceModel::Attribute::ValueType::INTEGER == - m_attribute.getValueType()) // For integer type values - { - int min; - int max; - - m_attribute.getRange(min, max); - for (int value = min; value <= max; value++) - { - if (m_stopRequested) - break; - resourceImpl->updateAttributeValue(m_attribute.getName(), value); - resourceImpl->notifyApp(); - SLEEP_FOR(m_updateInterval); - } - } - else - { - for (int index = 0; index < m_attribute.getAllowedValuesSize(); index++) - { - if (m_stopRequested) - break; - resourceImpl->updateFromAllowedValues(m_attribute.getName(), index); - resourceImpl->notifyApp(); - SLEEP_FOR(m_updateInterval); - } - } -} - -ResourceUpdateAutomation::ResourceUpdateAutomation(int id, SimulatorResourceServer *resource, +ResourceUpdateAutomation::ResourceUpdateAutomation(int id, SimulatorSingleResource *resource, AutomationType type, int interval, updateCompleteCallback callback, std::function finishedCallback) : m_resource(resource), @@ -151,19 +123,18 @@ ResourceUpdateAutomation::ResourceUpdateAutomation(int id, SimulatorResourceServ void ResourceUpdateAutomation::start() { - SimulatorResourceModel resModel = m_resource->getModel(); - std::map attributesTable = - resModel.getAttributes(); - if (0 == attributesTable.size()) + std::vector attributes; + for (auto &attributeEntry : m_resource->getResourceModel().getAttributes()) + { + attributes.push_back(attributeEntry.second); + } + + if (0 == attributes.size()) { OC_LOG(ERROR, RTAG, "Resource has zero attributes!"); throw SimulatorException(SIMULATOR_ERROR, "Resource has zero attributes!"); } - std::vector attributes; - for (auto &attributeEntry : attributesTable) - attributes.push_back(attributeEntry.second); - m_thread = new std::thread(&ResourceUpdateAutomation::updateAttributes, this, attributes); } @@ -175,23 +146,30 @@ void ResourceUpdateAutomation::stop() } void ResourceUpdateAutomation::updateAttributes( - std::vector attributes) + std::vector attributes) { - SimulatorResourceServerImpl *resourceImpl = - dynamic_cast(m_resource); + SimulatorSingleResourceImpl *resourceImpl = + dynamic_cast(m_resource); + + if (!resourceImpl) + return; - AttributeCombinationGen attrCombGen(attributes); - SimulatorResourceModel resModel; - while (!m_stopRequested && attrCombGen.next(resModel)) + do { - for (auto &attributeEntry : resModel.getAttributes()) + AttributeCombinationGen attrCombGen(attributes); + SimulatorResourceModel resModel; + while (!m_stopRequested && attrCombGen.next(resModel)) { - resourceImpl->updateAttributeValue(attributeEntry.first, attributeEntry.second.getValue()); - } + for (auto &attributeEntry : resModel.getAttributes()) + { + resourceImpl->updateAttributeValue(attributeEntry.second); + } - resourceImpl->notifyApp(); - SLEEP_FOR(m_updateInterval); + resourceImpl->notifyApp(); + SLEEP_FOR(m_updateInterval); + } } + while (!m_stopRequested && AutomationType::RECURRENT == m_type); // Notify application if (m_callback) diff --git a/service/simulator/src/service-provider/resource_update_automation.h b/service/simulator/src/server/resource_update_automation.h similarity index 81% rename from service/simulator/src/service-provider/resource_update_automation.h rename to service/simulator/src/server/resource_update_automation.h index 6ae1f0e..a3dc6d1 100644 --- a/service/simulator/src/service-provider/resource_update_automation.h +++ b/service/simulator/src/server/resource_update_automation.h @@ -21,14 +21,16 @@ #ifndef RESOURCE_UPDATE_AUTOMATION_H_ #define RESOURCE_UPDATE_AUTOMATION_H_ -#include "simulator_resource_server.h" +#include "simulator_single_resource.h" +#include "attribute_generator.h" #include class AttributeUpdateAutomation { public: - AttributeUpdateAutomation(int id, SimulatorResourceServer *resource, - const std::string &attrName, AutomationType type, int interval, + AttributeUpdateAutomation(int id, SimulatorSingleResource *resource, + const SimulatorResourceModel::Attribute &attribute, + AutomationType type, int interval, updateCompleteCallback callback, std::function finishedCallback); @@ -38,15 +40,14 @@ class AttributeUpdateAutomation private: void updateAttribute(); - void setAttributeValue(); - SimulatorResourceServer *m_resource; + SimulatorSingleResource *m_resource; std::string m_attrName; AutomationType m_type; int m_id; bool m_stopRequested; int m_updateInterval; - SimulatorResourceModel::Attribute m_attribute; + AttributeGenerator m_attributeGen; updateCompleteCallback m_callback; std::function m_finishedCallback; std::thread *m_thread; @@ -57,7 +58,7 @@ typedef std::shared_ptr AttributeUpdateAutomationSP; class ResourceUpdateAutomation { public: - ResourceUpdateAutomation(int id, SimulatorResourceServer *resource, + ResourceUpdateAutomation(int id, SimulatorSingleResource *resource, AutomationType type, int interval, updateCompleteCallback callback, std::function finishedCallback); @@ -69,7 +70,7 @@ class ResourceUpdateAutomation private: void updateAttributes(std::vector attributes); - SimulatorResourceServer *m_resource; + SimulatorSingleResource *m_resource; AutomationType m_type; int m_id; bool m_stopRequested; diff --git a/service/simulator/src/service-provider/resource_update_automation_mngr.cpp b/service/simulator/src/server/resource_update_automation_mngr.cpp similarity index 87% rename from service/simulator/src/service-provider/resource_update_automation_mngr.cpp rename to service/simulator/src/server/resource_update_automation_mngr.cpp index 94eb2c5..1b52c70 100644 --- a/service/simulator/src/service-provider/resource_update_automation_mngr.cpp +++ b/service/simulator/src/server/resource_update_automation_mngr.cpp @@ -28,7 +28,7 @@ UpdateAutomationMngr::UpdateAutomationMngr() : m_id(0) {} -int UpdateAutomationMngr::startResourceAutomation(SimulatorResourceServer *resource, +int UpdateAutomationMngr::startResourceAutomation(SimulatorSingleResource *resource, AutomationType type, int interval, updateCompleteCallback callback) { if (!callback) @@ -51,7 +51,7 @@ int UpdateAutomationMngr::startResourceAutomation(SimulatorResourceServer *resou return m_id++; } -int UpdateAutomationMngr::startAttributeAutomation(SimulatorResourceServer *resource, +int UpdateAutomationMngr::startAttributeAutomation(SimulatorSingleResource *resource, const std::string &attrName, AutomationType type, int interval, updateCompleteCallback callback) { @@ -61,8 +61,16 @@ int UpdateAutomationMngr::startAttributeAutomation(SimulatorResourceServer *reso throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!"); } + // Check the validity of attribute + SimulatorResourceModel::Attribute attribute; + if (false == resource->getAttribute(attrName, attribute)) + { + OC_LOG_V(ERROR, TAG, "Attribute:%s not present in resource!", attrName.c_str()); + throw SimulatorException(SIMULATOR_ERROR, "Attribute is not present in resource!"); + } + AttributeUpdateAutomationSP attributeAutomation(new AttributeUpdateAutomation( - m_id, resource, attrName, type, interval, callback, + m_id, resource, attribute, type, interval, callback, std::bind(&UpdateAutomationMngr::automationCompleted, this, std::placeholders::_1))); std::lock_guard lock(m_lock); @@ -82,7 +90,7 @@ std::vector UpdateAutomationMngr::getResourceAutomationIds() { std::vector ids; std::lock_guard lock(m_lock); - for (auto & automation : m_resourceUpdationList) + for (auto &automation : m_resourceUpdationList) ids.push_back(automation.first); return ids; @@ -92,7 +100,7 @@ std::vector UpdateAutomationMngr::getAttributeAutomationIds() { std::vector ids; std::lock_guard lock(m_lock); - for (auto & automation : m_attrUpdationList) + for (auto &automation : m_attrUpdationList) ids.push_back(automation.first); return ids; @@ -113,9 +121,6 @@ void UpdateAutomationMngr::stop(int id) m_attrUpdationList.erase(m_attrUpdationList.find(id)); return; } - - //Throw SimulatorException - throw SimulatorException(SIMULATOR_ERROR, "No automation is currently in progress for the given automation Id!"); } void UpdateAutomationMngr::stopAll() diff --git a/service/simulator/src/service-provider/resource_update_automation_mngr.h b/service/simulator/src/server/resource_update_automation_mngr.h similarity index 90% rename from service/simulator/src/service-provider/resource_update_automation_mngr.h rename to service/simulator/src/server/resource_update_automation_mngr.h index 985d79c..68227fd 100644 --- a/service/simulator/src/service-provider/resource_update_automation_mngr.h +++ b/service/simulator/src/server/resource_update_automation_mngr.h @@ -21,7 +21,7 @@ #ifndef RESOURCE_UPDATE_AUTOMATION_MNGR_H_ #define RESOURCE_UPDATE_AUTOMATION_MNGR_H_ -#include "simulator_resource_server.h" +#include "simulator_single_resource.h" #include "resource_update_automation.h" class UpdateAutomationMngr @@ -29,10 +29,10 @@ class UpdateAutomationMngr public: UpdateAutomationMngr(); - int startResourceAutomation(SimulatorResourceServer *resource, + int startResourceAutomation(SimulatorSingleResource *resource, AutomationType type, int interval, updateCompleteCallback callback); - int startAttributeAutomation(SimulatorResourceServer *resource, + int startAttributeAutomation(SimulatorSingleResource *resource, const std::string &attrName, AutomationType type, int interval, updateCompleteCallback callback); diff --git a/service/simulator/src/server/simulator_collection_resource_impl.cpp b/service/simulator/src/server/simulator_collection_resource_impl.cpp new file mode 100644 index 0000000..ef74e41 --- /dev/null +++ b/service/simulator/src/server/simulator_collection_resource_impl.cpp @@ -0,0 +1,562 @@ +/****************************************************************** + * + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +#include "simulator_collection_resource_impl.h" +#include "simulator_utils.h" +#include "simulator_logger.h" +#include "logger.h" + +#define TAG "SIM_COLLECTION_RESOURCE" + +SimulatorCollectionResourceImpl::SimulatorCollectionResourceImpl() + : m_type(SimulatorResource::Type::COLLECTION_RESOURCE), + m_interfaces {OC::DEFAULT_INTERFACE, OC::LINK_INTERFACE}, + m_resourceHandle(NULL) +{ + m_property = static_cast(OC_DISCOVERABLE | OC_OBSERVABLE); +} + +std::string SimulatorCollectionResourceImpl::getName() const +{ + return m_name; +} + +SimulatorResource::Type SimulatorCollectionResourceImpl::getType() const +{ + return m_type; +} + +std::string SimulatorCollectionResourceImpl::getURI() const +{ + return m_uri; +} + +std::string SimulatorCollectionResourceImpl::getResourceType() const +{ + return m_resourceType; +} + +std::vector SimulatorCollectionResourceImpl::getInterface() const +{ + return m_interfaces; +} + +void SimulatorCollectionResourceImpl::setInterface(const std::vector &interfaces) +{ + m_interfaces = interfaces; +} + +void SimulatorCollectionResourceImpl::setName(const std::string &name) +{ + VALIDATE_INPUT(name.empty(), "Name is empty!") + + std::lock_guard lock(m_objectLock); + if (m_resourceHandle) + { + throw SimulatorException(SIMULATOR_OPERATION_NOT_ALLOWED, + "Name can not be set when collection is started!"); + } + + m_name = name; +} + +void SimulatorCollectionResourceImpl::setURI(const std::string &uri) +{ + VALIDATE_INPUT(uri.empty(), "Uri is empty!") + + std::lock_guard lock(m_objectLock); + if (m_resourceHandle) + { + throw SimulatorException(SIMULATOR_OPERATION_NOT_ALLOWED, + "URI can not be set when collection is started!"); + } + + m_uri = uri; +} + +void SimulatorCollectionResourceImpl::setResourceType(const std::string &resourceType) +{ + VALIDATE_INPUT(resourceType.empty(), "Resource type is empty!") + + std::lock_guard lock(m_objectLock); + if (m_resourceHandle) + { + throw SimulatorException(SIMULATOR_OPERATION_NOT_ALLOWED, + "Resource type can not be set when collection is started!"); + } + + m_resourceType = resourceType; +} + +void SimulatorCollectionResourceImpl::addInterface(std::string interfaceType) +{ + VALIDATE_INPUT(interfaceType.empty(), "Interface type is empty!") + + if (interfaceType == OC::GROUP_INTERFACE) + { + throw NoSupportException("Collection resource does not support this interface type!"); + } + + std::lock_guard lock(m_objectLock); + if (m_resourceHandle) + { + throw SimulatorException(SIMULATOR_OPERATION_NOT_ALLOWED, + "Interface type can not be set when resource is started!"); + } + + auto found = std::find(m_interfaces.begin(), m_interfaces.end(), interfaceType); + if (found != m_interfaces.end()) + m_interfaces.push_back(interfaceType); +} + +void SimulatorCollectionResourceImpl::setObservable(bool state) +{ + std::lock_guard lock(m_objectLock); + if (m_resourceHandle) + { + throw SimulatorException(SIMULATOR_OPERATION_NOT_ALLOWED, + "Observation state can not be changed when resource is started!"); + } + + if (true == state) + m_property = static_cast(m_property | OC_OBSERVABLE); + else + m_property = static_cast(m_property ^ OC_OBSERVABLE); +} + +void SimulatorCollectionResourceImpl::setObserverCallback(ObserverCallback callback) +{ + VALIDATE_CALLBACK(callback) + m_observeCallback = callback; +} + +void SimulatorCollectionResourceImpl::setModelChangeCallback(ResourceModelChangedCallback callback) +{ + VALIDATE_CALLBACK(callback) + m_modelCallback = callback; +} + +bool SimulatorCollectionResourceImpl::isObservable() +{ + return (m_property & OC_OBSERVABLE); +} + +bool SimulatorCollectionResourceImpl::isStarted() +{ + return (nullptr != m_resourceHandle); +} + +void SimulatorCollectionResourceImpl::start() +{ + std::lock_guard lock(m_objectLock); + if (m_resourceHandle) + { + throw SimulatorException(SIMULATOR_ERROR, "Collection already registered!"); + } + + if (m_uri.empty() || m_resourceType.empty()) + { + throw SimulatorException(SIMULATOR_ERROR, "Found incomplete data to start resource!"); + } + + typedef OCStackResult (*RegisterResource)(OCResourceHandle &, std::string &, const std::string &, + const std::string &, OC::EntityHandler, uint8_t); + + invokeocplatform(static_cast(OC::OCPlatform::registerResource), + m_resourceHandle, m_uri, m_resourceType, m_interfaces[0], + std::bind(&SimulatorCollectionResourceImpl::handleRequests, + this, std::placeholders::_1), m_property); + + for (size_t index = 1; m_interfaces.size() > 1 && index < m_interfaces.size(); index++) + { + typedef OCStackResult (*bindInterfaceToResource)(const OCResourceHandle &, + const std::string &); + + try + { + invokeocplatform(static_cast( + OC::OCPlatform::bindInterfaceToResource), m_resourceHandle, + m_interfaces[index]); + } + catch (SimulatorException &e) + { + stop(); + throw; + } + } +} + +void SimulatorCollectionResourceImpl::stop() +{ + std::lock_guard lock(m_objectLock); + if (!m_resourceHandle) + return; + + typedef OCStackResult (*UnregisterResource)(const OCResourceHandle &); + + invokeocplatform(static_cast(OC::OCPlatform::unregisterResource), + m_resourceHandle); + + m_resourceHandle = nullptr; +} + +SimulatorResourceModel SimulatorCollectionResourceImpl::getResourceModel() +{ + std::lock_guard lock(m_modelLock); + return m_resModel; +} + +void SimulatorCollectionResourceImpl::setResourceModel(const SimulatorResourceModel &resModel) +{ + std::lock_guard lock(m_modelLock); + m_resModel = resModel; +} + +std::vector SimulatorCollectionResourceImpl::getObserversList() +{ + return m_observersList; +} + +void SimulatorCollectionResourceImpl::notify(int id) +{ + std::lock_guard lock(m_objectLock); + if (!m_resourceHandle) + return; + + OC::ObservationIds observers {static_cast(id)}; + sendNotification(observers); +} + +void SimulatorCollectionResourceImpl::notifyAll() +{ + std::lock_guard lock(m_objectLock); + if (!m_resourceHandle) + return; + + if (!m_observersList.size()) + return; + + OC::ObservationIds observers; + for (auto &observer : m_observersList) + observers.push_back(observer.id); + sendNotification(observers); +} + +std::vector SimulatorCollectionResourceImpl::getSupportedResources() +{ + return m_supportedTypes; +} + +void SimulatorCollectionResourceImpl::addChildResource(SimulatorResourceSP &resource) +{ + VALIDATE_INPUT(!resource, "Invalid child resource!") + + std::lock_guard lock(m_childResourcesLock); + if (m_childResources.end() != m_childResources.find(resource->getURI())) + { + throw SimulatorException(SIMULATOR_ERROR, "Child resource with same URI is already exisit!"); + } + + m_childResources[resource->getURI()] = resource; + addLink(resource); + + // Notify application and observers + if (m_modelCallback) + m_modelCallback(m_uri, m_resModel); + notifyAll(); +} + +void SimulatorCollectionResourceImpl::removeChildResource(SimulatorResourceSP &resource) +{ + VALIDATE_INPUT(!resource, "Invalid child resource!") + + std::lock_guard lock(m_childResourcesLock); + if (m_childResources.end() == m_childResources.find(resource->getURI())) + { + throw SimulatorException(SIMULATOR_ERROR, "Child resource not found in collection!"); + } + + removeLink(resource->getURI()); + m_childResources.erase(m_childResources.find(resource->getURI())); + + // Notify application and observers + if (m_modelCallback) + m_modelCallback(m_uri, m_resModel); + notifyAll(); +} + +void SimulatorCollectionResourceImpl::removeChildResource(const std::string &uri) +{ + VALIDATE_INPUT(uri.empty(), "Uri is empty!") + + std::lock_guard lock(m_childResourcesLock); + if (m_childResources.end() == m_childResources.find(uri)) + { + throw SimulatorException(SIMULATOR_ERROR, "Child resource not found in collection!"); + } + + removeLink(uri); + m_childResources.erase(m_childResources.find(uri)); + + // Notify application and observers + if (m_modelCallback) + m_modelCallback(m_uri, m_resModel); + notifyAll(); +} + +std::vector SimulatorCollectionResourceImpl::getChildResources() +{ + std::lock_guard lock(m_childResourcesLock); + + std::vector result; + for (auto &entry : m_childResources) + result.push_back(entry.second); + + return result; +} + +OCEntityHandlerResult SimulatorCollectionResourceImpl::handleRequests( + std::shared_ptr request) +{ + if (!request) + return OC_EH_ERROR; + + if (OC::RequestHandlerFlag::RequestFlag & request->getRequestHandlerFlag()) + { + { + OC::OCRepresentation rep = request->getResourceRepresentation(); + std::string payload = getPayloadString(rep); + SIM_LOG(ILogger::INFO, "[" << m_name << "] " << request->getRequestType() + << " request received. \n**Payload details**\n" << payload) + } + + // Handover the request to appropriate interface handler + std::string interfaceType(OC::DEFAULT_INTERFACE); + OC::QueryParamsMap queryParams = request->getQueryParameters(); + if (queryParams.end() != queryParams.find("if")) + interfaceType = queryParams["if"]; + + std::shared_ptr response; + if (interfaceType == OC::DEFAULT_INTERFACE) + { + response = requestOnBaseLineInterface(request); + } + else if (interfaceType == OC::LINK_INTERFACE) + { + response = requestOnLinkListInterface(request); + } + else if (interfaceType == OC::BATCH_INTERFACE) + { + response = requestOnBatchInterface(request); + } + + // Send response if the request handled by resource + if (response) + { + if (OC_STACK_OK != OC::OCPlatform::sendResponse(response)) + return OC_EH_ERROR; + } + else + { + SIM_LOG(ILogger::ERROR, "[" << m_name << "] " << "Unsupported request received!") + return OC_EH_ERROR; + } + } + + if (OC::RequestHandlerFlag::ObserverFlag & request->getRequestHandlerFlag()) + { + if (!isObservable()) + { + SIM_LOG(ILogger::INFO, "[" << m_uri << "] OBSERVE request received") + SIM_LOG(ILogger::INFO, "[" << m_uri << "] Sending error as resource is in unobservable state!") + return OC_EH_ERROR; + } + + OC::ObservationInfo observationInfo = request->getObservationInfo(); + if (OC::ObserveAction::ObserveRegister == observationInfo.action) + { + SIM_LOG(ILogger::INFO, "[" << m_uri << "] OBSERVE REGISTER request received"); + + ObserverInfo info {observationInfo.obsId, observationInfo.address, observationInfo.port}; + m_observersList.push_back(info); + + if (m_observeCallback) + m_observeCallback(m_uri, ObservationStatus::REGISTER, info); + } + else if (OC::ObserveAction::ObserveUnregister == observationInfo.action) + { + SIM_LOG(ILogger::INFO, "[" << m_uri << "] OBSERVE UNREGISTER request received"); + + ObserverInfo info; + for (auto iter = m_observersList.begin(); iter != m_observersList.end(); iter++) + { + if ((info = *iter), info.id == observationInfo.obsId) + { + m_observersList.erase(iter); + break; + } + } + + if (m_observeCallback) + m_observeCallback(m_uri, ObservationStatus::UNREGISTER, info); + } + } + + return OC_EH_OK; +} + +std::shared_ptr SimulatorCollectionResourceImpl::requestOnBaseLineInterface( + std::shared_ptr request) +{ + std::shared_ptr response; + if ("GET" == request->getRequestType()) + { + // Construct the representation + OC::OCRepresentation ocRep = m_resModel.getOCRepresentation(); + response = std::make_shared(); + response->setErrorCode(200); + response->setResponseResult(OC_EH_OK); + response->setResourceRepresentation(ocRep); + std::string resPayload = getPayloadString(ocRep); + SIM_LOG(ILogger::INFO, "[" << m_uri << + "] Sending response for GET request. \n**Payload details**" << resPayload) + } + + // TODO: Handle PUT, POST and DELETE requests + + if (response) + { + response->setRequestHandle(request->getRequestHandle()); + response->setResourceHandle(request->getResourceHandle()); + } + + return response; +} + +std::shared_ptr SimulatorCollectionResourceImpl::requestOnLinkListInterface( + std::shared_ptr request) +{ + std::lock_guard lock(m_childResourcesLock); + std::shared_ptr response; + if ("GET" == request->getRequestType()) + { + // Construct the representation + OC::OCRepresentation ocRep; + std::vector links; + for (auto &entry : m_childResources) + { + OC::OCRepresentation oicLink; + oicLink.setValue("href", entry.second->getURI()); + oicLink.setValue("rt", entry.second->getResourceType()); + oicLink.setValue("if", entry.second->getInterface()[0]); + links.push_back(oicLink); + } + + ocRep.setValue("links", links); + + response = std::make_shared(); + response->setRequestHandle(request->getRequestHandle()); + response->setResourceHandle(request->getResourceHandle()); + response->setErrorCode(200); + response->setResponseResult(OC_EH_OK); + response->setResourceRepresentation(ocRep); + std::string resPayload = getPayloadString(ocRep); + SIM_LOG(ILogger::INFO, "[" << m_uri << + "] Sending response for GET request. \n**Payload details**" << resPayload) + } + + return nullptr; +} + +std::shared_ptr SimulatorCollectionResourceImpl::requestOnBatchInterface( + std::shared_ptr) +{ + // TODO: Handle this interface + return nullptr; +} + +void SimulatorCollectionResourceImpl::sendNotification(OC::ObservationIds &observers) +{ + std::lock_guard lock(m_objectLock); + std::shared_ptr response(new OC::OCResourceResponse()); + response->setErrorCode(200); + response->setResponseResult(OC_EH_OK); + + OC::OCRepresentation ocRep = m_resModel.getOCRepresentation(); + response->setResourceRepresentation(ocRep, OC::DEFAULT_INTERFACE); + + typedef OCStackResult (*NotifyListOfObservers)(OCResourceHandle, OC::ObservationIds &, + const std::shared_ptr); + + invokeocplatform(static_cast(OC::OCPlatform::notifyListOfObservers), + m_resourceHandle, observers, response); +} + +void SimulatorCollectionResourceImpl::addLink(SimulatorResourceSP &resource) +{ + std::lock_guard lock(m_modelLock); + if (!m_resModel.containsAttribute("links")) + return; + + // Create new OIC Link + SimulatorResourceModel newLink; + newLink.add("href", resource->getURI()); + newLink.add("rt", resource->getResourceType()); + newLink.add("if", resource->getInterface()[0]); + + // Add OIC Link if it is not present + bool found = false; + std::vector links = m_resModel.get>("links"); + for (auto &link : links) + { + std::string linkURI = link.get("href"); + if (linkURI == resource->getURI()) + { + break; + found = true; + } + } + + if (false == found) + { + links.push_back(newLink); + m_resModel.updateValue("links", links); + } +} + +void SimulatorCollectionResourceImpl::removeLink(std::string uri) +{ + std::lock_guard lock(m_modelLock); + if (!m_resModel.containsAttribute("links")) + return; + + // Add OIC Link if it is not present + std::vector links = m_resModel.get>("links"); + for (size_t i = 0; i < links.size(); i++) + { + std::string linkURI = links[i].get("href"); + if (linkURI == uri) + { + links.erase(links.begin()+i); + m_resModel.updateValue("links", links); + break; + } + } +} diff --git a/service/simulator/src/server/simulator_collection_resource_impl.h b/service/simulator/src/server/simulator_collection_resource_impl.h new file mode 100644 index 0000000..0b11440 --- /dev/null +++ b/service/simulator/src/server/simulator_collection_resource_impl.h @@ -0,0 +1,96 @@ +/****************************************************************** + * + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +#ifndef SIMULATOR_COLLECTION_RESOURCE_IMPL_H_ +#define SIMULATOR_COLLECTION_RESOURCE_IMPL_H_ + +#include "simulator_collection_resource.h" + +class SimulatorResourceFactory; +class SimulatorCollectionResourceImpl : public SimulatorCollectionResource +{ + public: + friend class SimulatorResourceFactory; + + std::string getName() const; + SimulatorResource::Type getType() const; + std::string getURI() const; + std::string getResourceType() const; + std::vector getInterface() const; + bool isObservable(); + bool isStarted(); + SimulatorResourceModel getResourceModel(); + void setInterface(const std::vector &interfaces); + void setName(const std::string &name); + void setURI(const std::string &uri); + void setResourceType(const std::string &resourceType); + void addInterface(std::string interfaceType); + void setObservable(bool state); + void setObserverCallback(ObserverCallback callback); + void setModelChangeCallback(ResourceModelChangedCallback callback); + void start(); + void stop(); + std::vector getObserversList(); + void notify(int id); + void notifyAll(); + + std::vector getSupportedResources(); + void addChildResource(SimulatorResourceSP &resource); + void removeChildResource(SimulatorResourceSP &resource); + void removeChildResource(const std::string &uri); + std::vector getChildResources(); + + void setResourceModel(const SimulatorResourceModel &resModel); + + private: + SimulatorCollectionResourceImpl(); + + OCEntityHandlerResult handleRequests(std::shared_ptr request); + std::shared_ptr requestOnBaseLineInterface( + std::shared_ptr request); + std::shared_ptr requestOnLinkListInterface( + std::shared_ptr request); + std::shared_ptr requestOnBatchInterface( + std::shared_ptr request); + void sendNotification(OC::ObservationIds &observers); + void addLink(SimulatorResourceSP &resource); + void removeLink(std::string uri); + + SimulatorResource::Type m_type; + std::string m_name; + std::string m_uri; + std::string m_resourceType; + std::vector m_interfaces; + + std::mutex m_modelLock; + SimulatorResourceModel m_resModel; + std::recursive_mutex m_objectLock; + std::mutex m_childResourcesLock; + std::map m_childResources; + std::vector m_supportedTypes; + std::vector m_observersList; + ObserverCallback m_observeCallback; + ResourceModelChangedCallback m_modelCallback; + + OCResourceProperty m_property; + OCResourceHandle m_resourceHandle; +}; + +#endif diff --git a/service/simulator/src/server/simulator_resource_factory.cpp b/service/simulator/src/server/simulator_resource_factory.cpp new file mode 100644 index 0000000..be3b19c --- /dev/null +++ b/service/simulator/src/server/simulator_resource_factory.cpp @@ -0,0 +1,429 @@ +/****************************************************************** + * + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +#include "simulator_resource_factory.h" +#include "simulator_single_resource_impl.h" +#include "simulator_collection_resource_impl.h" +#include "simulator_logger.h" +#include "logger.h" + +#define TAG "SIM_RESOURCE_FACTORY" + +SimulatorResourceFactory *SimulatorResourceFactory::getInstance() +{ + static SimulatorResourceFactory s_instance; + return &s_instance; +} + +std::shared_ptr SimulatorResourceFactory::createResource( + const std::string &configPath) +{ + // Parse the RAML file + std::shared_ptr ramlParser = std::make_shared(configPath); + RAML::RamlPtr raml = ramlParser->getRamlPtr(); + + // Get the first resource model from RAML + RAML::RamlResourcePtr ramlResource; + if (0 == raml->getResources().size() + || nullptr == (ramlResource = raml->getResources().begin()->second)) + { + OC_LOG(ERROR, TAG, "Zero resources detected from RAML!"); + return nullptr; + } + + return buildResource(ramlResource); +} + +std::vector > SimulatorResourceFactory::createResource( + const std::string &configPath, unsigned int count) +{ + std::vector> resources; + + // Parse the RAML file + std::shared_ptr ramlParser = std::make_shared(configPath); + RAML::RamlPtr raml = ramlParser->getRamlPtr(); + + // Get the first resource model from RAML + RAML::RamlResourcePtr ramlResource; + if (0 == raml->getResources().size() + || nullptr == (ramlResource = raml->getResources().begin()->second)) + { + OC_LOG(ERROR, TAG, "Zero resources detected from RAML!"); + return resources; + } + + while (count--) + { + std::shared_ptr resource = buildResource(ramlResource); + if (!resource) + { + OC_LOG(ERROR, TAG, "Failed to create resource!"); + return resources; + } + + resources.push_back(resource); + } + + return resources; +} + +std::shared_ptr SimulatorResourceFactory::createSingleResource( + const std::string &name, const std::string &uri, const std::string &resourceType) +{ + SimulatorSingleResourceImpl *simpleResource = new SimulatorSingleResourceImpl(); + simpleResource->setName(name); + simpleResource->setURI(uri); + simpleResource->setResourceType(resourceType); + return std::shared_ptr(simpleResource); +} + +std::shared_ptr SimulatorResourceFactory::createCollectionResource( + const std::string &name, const std::string &uri, const std::string &resourceType) +{ + SimulatorCollectionResourceImpl *collectionResource = new SimulatorCollectionResourceImpl(); + collectionResource->setName(name); + collectionResource->setURI(uri); + collectionResource->setResourceType(resourceType); + return std::shared_ptr(collectionResource); +} + +SimulatorResourceModel::Attribute SimulatorResourceFactory::buildAttribute( + std::shared_ptr propertyElement) +{ + std::string propName = propertyElement->getName(); + + // Build representation attribute + SimulatorResourceModel::Attribute attribute(propName); + switch (propertyElement->getVariantType()) + { + case RAML::VariantType::INT: + { + attribute.setValue(propertyElement->getValue()); + + // Convert suppoted values + std::vector allowedValues = propertyElement->getAllowedValuesInt(); + if (allowedValues.size() > 0) + { + SimulatorResourceModel::AttributeProperty attrProp(allowedValues); + attribute.setProperty(attrProp); + } + } + break; + + case RAML::VariantType::DOUBLE: + { + attribute.setValue(propertyElement->getValue()); + + // Convert suppoted values + std::vector allowedValues = propertyElement->getAllowedValuesDouble(); + if (allowedValues.size() > 0) + { + SimulatorResourceModel::AttributeProperty attrProp(allowedValues); + attribute.setProperty(attrProp); + } + } + break; + + case RAML::VariantType::BOOL: + { + attribute.setValue(propertyElement->getValue()); + + std::vector allowedValues = {true, false}; + SimulatorResourceModel::AttributeProperty attrProp(allowedValues); + attribute.setProperty(attrProp); + } + break; + + case RAML::VariantType::STRING: + { + attribute.setValue(propertyElement->getValue()); + + // Convert suppoted values + std::vector allowedValues = propertyElement->getAllowedValuesString(); + if (allowedValues.size() > 0) + { + SimulatorResourceModel::AttributeProperty attrProp(allowedValues); + attribute.setProperty(attrProp); + } + } + break; + } + + // Set the range property if its present + double min, max; + int multipleof; + propertyElement->getRange(min, max, multipleof); + if (min != INT_MIN && max != INT_MAX) + { + SimulatorResourceModel::AttributeProperty attrProp(min, max); + attribute.setProperty(attrProp); + } + return attribute; +} + +SimulatorResourceModel SimulatorResourceFactory::buildResourceModel( + std::shared_ptr item) +{ + SimulatorResourceModel itemModel; + for ( auto &propElement : item->getProperties()) + { + if (!propElement.second) + continue; + + std::string propName = propElement.second->getName(); + if ("p" == propName || "n" == propName || "id" == propName) + { + continue; + } + + if ("array" == propElement.second->getType()) + { + std::vector arrayResModel; + for ( auto &propertyItem : propElement.second->getItems()) + { + arrayResModel.push_back(buildResourceModel(propertyItem)); + } + itemModel.add(propName, arrayResModel); + } + else + { + itemModel.add(buildAttribute(propElement.second)); + } + } + return itemModel; +} + +RAML::RequestResponseBodyPtr SimulatorResourceFactory::getRAMLResponseBody( + std::shared_ptr ramlResource, RAML::ActionType type, std::string responseCode) +{ + // Get the resource representation schema from response body + RAML::ActionPtr action = ramlResource->getAction(type); + if (!action) + { + OC_LOG(ERROR, TAG, "Resource does not possess the request!"); + return nullptr; + } + + RAML::ResponsePtr response = action->getResponse(responseCode); + if (!response) + { + OC_LOG(ERROR, TAG, "Resource does not provide valid GET response!"); + return nullptr; + } + + RAML::RequestResponseBodyPtr responseBody = response->getResponseBody("application/json"); + if (!responseBody) + { + OC_LOG(ERROR, TAG, "GET response is not of type \"application/json\" "); + return nullptr; + } + + return responseBody; +} + +SimulatorResourceModel SimulatorResourceFactory::buildModelFromResponseBody( + RAML::RequestResponseBodyPtr responseBody, std::string &resourceType, std::vector &interfaceType) +{ + SimulatorResourceModel resModel; + + if (!responseBody) + return resModel; + + // Iterate throgh all resource property and extract information needed for simulating resource. + RAML::JsonSchemaPtr resourceProperties = responseBody->getSchema()->getProperties(); + + + for ( auto &propertyElement : resourceProperties->getProperties()) + { + if (!propertyElement.second) + continue; + + std::string propName = propertyElement.second->getName(); + + // Resource type + if ("rt" == propName || "resourceType" == propName) + { + resourceType = propertyElement.second->getValueString(); + continue; + } + + // Interface type + if ("if" == propName) + { + if ("string" == propertyElement.second->getType()) + { + interfaceType.push_back(propertyElement.second->getValueString()); + } + else if ("array" == propertyElement.second->getType()) + { + for (auto &item : propertyElement.second->getItems()) + { + if ("string" == item->getType()) + { + interfaceType = item->getAllowedValuesString(); + break; + } + } + } + continue; + } + + // Other Standard properties which should not be part of resource model + if ("p" == propName || "n" == propName || "id" == propName) + { + continue; + } + + // Add the attribute to resource model + if ("array" == propertyElement.second->getType()) + { + std::vector arrayResModel; + for ( auto &propertyItem : propertyElement.second->getItems()) + { + arrayResModel.push_back(buildResourceModel(propertyItem)); + } + resModel.add(propName, arrayResModel); + } + else + { + resModel.add(buildAttribute(propertyElement.second)); + } + } + + if ("array" == resourceProperties->getType()) + { + std::vector arrayResModel; + for ( auto &propertyItem : resourceProperties->getItems()) + { + arrayResModel.push_back(buildResourceModel(propertyItem)); + } + resModel.add("links", arrayResModel); + } + + return resModel; +} + +std::shared_ptr SimulatorResourceFactory::buildResource( + std::shared_ptr ramlResource) +{ + std::string name; + std::string uri; + std::string resourceType, rt; + std::vector interfaceType, ifType; + + name = ramlResource->getDisplayName(); + uri = ramlResource->getResourceUri(); + + RAML::RequestResponseBodyPtr successResponseBody = getRAMLResponseBody( + ramlResource, RAML::ActionType::GET, "200"); + RAML::RequestResponseBodyPtr putErrorResponseBody = getRAMLResponseBody( + ramlResource, RAML::ActionType::PUT, "403"); + RAML::RequestResponseBodyPtr postErrorResponseBody = getRAMLResponseBody( + ramlResource, RAML::ActionType::POST, "403"); + + SimulatorResourceModel successResponseModel = buildModelFromResponseBody( + successResponseBody, resourceType, interfaceType); + SimulatorResourceModel putErrorResponseModel = buildModelFromResponseBody( + putErrorResponseBody, rt, ifType); + SimulatorResourceModel postErrorResponseModel = buildModelFromResponseBody( + postErrorResponseBody, rt, ifType); + + // Create simple/collection resource + std::shared_ptr simResource; + if (successResponseModel.containsAttribute("links")) + { + try + { + std::shared_ptr collectionRes( + new SimulatorCollectionResourceImpl()); + + collectionRes->setName(name); + collectionRes->setResourceType(resourceType); + collectionRes->setInterface(interfaceType); + collectionRes->setURI(ResourceURIFactory::getInstance()->constructURI(uri)); + + collectionRes->setResourceModel(successResponseModel); + simResource = std::dynamic_pointer_cast(collectionRes); + } + catch (InvalidArgsException &e) {} + } + else + { + try + { + std::shared_ptr singleRes( + new SimulatorSingleResourceImpl()); + + singleRes->setName(name); + singleRes->setResourceType(resourceType); + singleRes->setInterface(interfaceType); + singleRes->setURI(ResourceURIFactory::getInstance()->constructURI(uri)); + + singleRes->setResourceModel(successResponseModel); + singleRes->setPutErrorResponseModel(putErrorResponseModel); + singleRes->setPostErrorResponseModel(postErrorResponseModel); + + simResource = std::dynamic_pointer_cast(singleRes); + } + catch (InvalidArgsException &e) {} + } + + return simResource; +} + +ResourceURIFactory *ResourceURIFactory::getInstance() +{ + static ResourceURIFactory s_instance; + return &s_instance; +} + +ResourceURIFactory::ResourceURIFactory() + : m_id(0) {} + +std::string ResourceURIFactory::constructURI(const std::string &uri) +{ + std::lock_guard lock(m_lock); + if (isUnique(uri)) + { + updateUri(uri); + return uri; + } + std::ostringstream os; + os << uri; + if (!uri.empty() && '/' != uri[uri.length() - 1]) + os << '/'; + os << m_id++; + updateUri(os.str()); + return os.str(); +} + +void ResourceURIFactory::updateUri(const std::string &uri) +{ + m_uriList.insert(std::pair(uri, true)); +} + +bool ResourceURIFactory::isUnique(const std::string &uri) +{ + if (m_uriList.end() == m_uriList.find(uri)) + return true; + else + return false; +} + diff --git a/service/simulator/src/server/simulator_resource_factory.h b/service/simulator/src/server/simulator_resource_factory.h new file mode 100644 index 0000000..242385e --- /dev/null +++ b/service/simulator/src/server/simulator_resource_factory.h @@ -0,0 +1,142 @@ +/****************************************************************** + * + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +#ifndef SIMULATOR_RESOURCE_FACTORY_H_ +#define SIMULATOR_RESOURCE_FACTORY_H_ + +#include "simulator_single_resource.h" +#include "simulator_collection_resource.h" +#include "RamlParser.h" + +namespace RAML +{ + class RamlResource; + class Properties; + class Items; +} + +class SimulatorResourceFactory +{ + public: + /** + * API for getting singleton instance of SimulatorClient class. + * + * @return Singleton instance of SimulatorClient class. + * + */ + static SimulatorResourceFactory *getInstance(); + + /** + * API to create resource based on the given RAML file. + * + * @param configPath - RAML file path. + * + * @return SimulatorResource shared object created using RAML file. + */ + std::shared_ptr createResource(const std::string &configPath); + + /** + * API to create resource based on the given RAML file. + * + * @param configPath - RAML file path. + * + * @return SimulatorResource shared object created using RAML file. + */ + std::vector > createResource( + const std::string &configPath, unsigned int count); + + /** + * API to create simple resource. + * + * @param name - Name of resource. + * @param uri - URI of resource. + * @param resourceType - ResourceType of resource. + * + * @return SimulatorSimpleResource. + */ + std::shared_ptr createSingleResource( + const std::string &name, const std::string &uri, const std::string &resourceType); + + /** + * API to create collection resource. + * + * @param name - Name of collection resource. + * @param uri - URI of resource. + * @param resourceType - ResourceType of collection resource. + * + * @return SimulatorCollectionResource. + */ + std::shared_ptr createCollectionResource( + const std::string &name, const std::string &uri, const std::string &resourceType); + + private: + SimulatorResourceModel::Attribute buildAttribute( + std::shared_ptr propertyElement); + SimulatorResourceModel buildResourceModel(std::shared_ptr item); + SimulatorResourceModel buildModelFromResponseBody( + RAML::RequestResponseBodyPtr responseBody, std::string &resourceType, std::vector &interfaceType); + RAML::RequestResponseBodyPtr getRAMLResponseBody( + std::shared_ptr ramlResource, RAML::ActionType type, std::string responseCode); + std::shared_ptr buildResource( + std::shared_ptr ramlResource); + + SimulatorResourceFactory() = default; + SimulatorResourceFactory(const SimulatorResourceFactory &) = delete; + SimulatorResourceFactory &operator=(const SimulatorResourceFactory &) = delete; + SimulatorResourceFactory(SimulatorResourceFactory &&) = delete; + SimulatorResourceFactory &operator=(SimulatorResourceFactory && ) = delete; +}; + +class ResourceURIFactory +{ + public: + /** + * API for getting singleton instance of SimulatorClient class. + * + * @return Singleton instance of SimulatorClient class. + * + */ + static ResourceURIFactory *getInstance(); + + /** + * API to construct unique URI from the given base @uri. + * + * @param uri - Base uri to be used to construct unique uri. + * + * @return Unique uri. + */ + std::string constructURI(const std::string &uri); + + private: + ResourceURIFactory(); + ResourceURIFactory(const ResourceURIFactory &) = delete; + ResourceURIFactory &operator=(const ResourceURIFactory &) = delete; + ResourceURIFactory(ResourceURIFactory &&) = delete; + ResourceURIFactory &operator=(ResourceURIFactory && ) = delete; + + bool isUnique(const std::string &uri); + void updateUri(const std::string &uri); + + unsigned int m_id; + std::mutex m_lock; + std::map m_uriList; +}; + +#endif diff --git a/service/simulator/src/server/simulator_single_resource_impl.cpp b/service/simulator/src/server/simulator_single_resource_impl.cpp new file mode 100644 index 0000000..5d5df1d --- /dev/null +++ b/service/simulator/src/server/simulator_single_resource_impl.cpp @@ -0,0 +1,598 @@ +/****************************************************************** + * + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +#include "simulator_single_resource_impl.h" +#include "simulator_utils.h" +#include "simulator_logger.h" +#include "logger.h" + +#define TAG "SIM_SINGLE_RESOURCE" + +SimulatorSingleResourceImpl::SimulatorSingleResourceImpl() + : m_type(SimulatorResource::Type::SINGLE_RESOURCE), + m_interfaces {OC::DEFAULT_INTERFACE}, + m_resourceHandle(NULL) +{ + m_property = static_cast(OC_DISCOVERABLE | OC_OBSERVABLE); +} + +std::string SimulatorSingleResourceImpl::getName() const +{ + return m_name; +} + +SimulatorResource::Type SimulatorSingleResourceImpl::getType() const +{ + return m_type; +} + +std::string SimulatorSingleResourceImpl::getURI() const +{ + return m_uri; +} + +std::string SimulatorSingleResourceImpl::getResourceType() const +{ + return m_resourceType; +} + +std::vector SimulatorSingleResourceImpl::getInterface() const +{ + return m_interfaces; +} + +void SimulatorSingleResourceImpl::setInterface(const std::vector &interfaces) +{ + m_interfaces = interfaces; +} + +void SimulatorSingleResourceImpl::setName(const std::string &name) +{ + VALIDATE_INPUT(name.empty(), "Name is empty!") + + std::lock_guard lock(m_objectLock); + if (m_resourceHandle) + { + throw SimulatorException(SIMULATOR_OPERATION_NOT_ALLOWED, + "Name can not be set when resource is started!"); + } + + m_name = name; +} + +void SimulatorSingleResourceImpl::setURI(const std::string &uri) +{ + VALIDATE_INPUT(uri.empty(), "Uri is empty!") + + std::lock_guard lock(m_objectLock); + if (m_resourceHandle) + { + throw SimulatorException(SIMULATOR_OPERATION_NOT_ALLOWED, + "URI can not be set when resource is started!"); + } + + m_uri = uri; +} + +void SimulatorSingleResourceImpl::setResourceType(const std::string &resourceType) +{ + VALIDATE_INPUT(resourceType.empty(), "Resource type is empty!") + + std::lock_guard lock(m_objectLock); + if (m_resourceHandle) + { + throw SimulatorException(SIMULATOR_OPERATION_NOT_ALLOWED, + "Resource type can not be set when resource is started!"); + } + + m_resourceType = resourceType; +} + +void SimulatorSingleResourceImpl::addInterface(std::string interfaceType) +{ + VALIDATE_INPUT(interfaceType.empty(), "Interface type is empty!") + + if (interfaceType == OC::LINK_INTERFACE + || interfaceType == OC::BATCH_INTERFACE + || interfaceType == OC::GROUP_INTERFACE) + { + throw NoSupportException("Single type resource does not support this interface!"); + } + + std::lock_guard lock(m_objectLock); + if (m_resourceHandle) + { + throw SimulatorException(SIMULATOR_OPERATION_NOT_ALLOWED, + "Interface type can not be set when resource is started!"); + } + + auto found = std::find(m_interfaces.begin(), m_interfaces.end(), interfaceType); + if (found != m_interfaces.end()) + m_interfaces.push_back(interfaceType); +} + +void SimulatorSingleResourceImpl::setObservable(bool state) +{ + std::lock_guard lock(m_objectLock); + if (m_resourceHandle) + { + throw SimulatorException(SIMULATOR_OPERATION_NOT_ALLOWED, + "Observation state can not be changed when resource is started!"); + } + + if (true == state) + m_property = static_cast(m_property | OC_OBSERVABLE); + else + m_property = static_cast(m_property ^ OC_OBSERVABLE); +} + +void SimulatorSingleResourceImpl::setObserverCallback(ObserverCallback callback) +{ + VALIDATE_CALLBACK(callback) + m_observeCallback = callback; +} + +bool SimulatorSingleResourceImpl::isObservable() +{ + return (m_property & OC_OBSERVABLE); +} + +bool SimulatorSingleResourceImpl::isStarted() +{ + return (nullptr != m_resourceHandle); +} + +void SimulatorSingleResourceImpl::start() +{ + std::lock_guard lock(m_objectLock); + if (m_resourceHandle) + { + SIM_LOG(ILogger::INFO, "[" << m_name << "] " << "Resource already registered!") + } + + if (m_uri.empty() || m_resourceType.empty()) + { + throw SimulatorException(SIMULATOR_ERROR, "Found incomplete data to start resource!"); + } + + typedef OCStackResult (*RegisterResource)(OCResourceHandle &, std::string &, const std::string &, + const std::string &, OC::EntityHandler, uint8_t); + + invokeocplatform(static_cast(OC::OCPlatform::registerResource), + m_resourceHandle, m_uri, m_resourceType, m_interfaces[0], + std::bind(&SimulatorSingleResourceImpl::handleRequests, + this, std::placeholders::_1), m_property); + + for (size_t index = 1; m_interfaces.size() > 1 && index < m_interfaces.size(); index++) + { + typedef OCStackResult (*bindInterfaceToResource)(const OCResourceHandle &, + const std::string &); + + try + { + invokeocplatform(static_cast( + OC::OCPlatform::bindInterfaceToResource), m_resourceHandle, + m_interfaces[index]); + } + catch (SimulatorException &e) + { + stop(); + throw; + } + } +} + +void SimulatorSingleResourceImpl::stop() +{ + std::lock_guard lock(m_objectLock); + if (!m_resourceHandle) + return; + + typedef OCStackResult (*UnregisterResource)(const OCResourceHandle &); + + invokeocplatform(static_cast(OC::OCPlatform::unregisterResource), + m_resourceHandle); + + m_resourceHandle = nullptr; +} + +std::vector SimulatorSingleResourceImpl::getObserversList() +{ + return m_observersList; +} + +void SimulatorSingleResourceImpl::notify(int id, SimulatorResourceModel &resModel) +{ + std::lock_guard lock(m_objectLock); + if (!m_resourceHandle) + return; + + std::shared_ptr resourceResponse = + {std::make_shared()}; + + resourceResponse->setErrorCode(200); + resourceResponse->setResponseResult(OC_EH_OK); + resourceResponse->setResourceRepresentation(resModel.getOCRepresentation(), + OC::DEFAULT_INTERFACE); + + OC::ObservationIds observers; + observers.push_back(id); + + typedef OCStackResult (*NotifyListOfObservers)(OCResourceHandle, OC::ObservationIds &, + const std::shared_ptr); + + invokeocplatform(static_cast(OC::OCPlatform::notifyListOfObservers), + m_resourceHandle, observers, resourceResponse); +} + +void SimulatorSingleResourceImpl::notifyAll(SimulatorResourceModel &resModel) +{ + std::lock_guard lock(m_objectLock); + if (!m_resourceHandle) + return; + + if (!m_observersList.size()) + return; + + std::shared_ptr resourceResponse = + {std::make_shared()}; + + resourceResponse->setErrorCode(200); + resourceResponse->setResponseResult(OC_EH_OK); + resourceResponse->setResourceRepresentation(resModel.getOCRepresentation(), + OC::DEFAULT_INTERFACE); + + OC::ObservationIds observers; + for (auto &observer : m_observersList) + observers.push_back(observer.id); + + typedef OCStackResult (*NotifyListOfObservers)(OCResourceHandle, OC::ObservationIds &, + const std::shared_ptr); + + invokeocplatform(static_cast(OC::OCPlatform::notifyListOfObservers), + m_resourceHandle, observers, resourceResponse); +} + +void SimulatorSingleResourceImpl::notify(int id) +{ + notify(id, m_resModel); +} + +void SimulatorSingleResourceImpl::notifyAll() +{ + notifyAll(m_resModel); +} + +bool SimulatorSingleResourceImpl::getAttribute(const std::string &attrName, + SimulatorResourceModel::Attribute &attribute) +{ + VALIDATE_INPUT(attrName.empty(), "Attribute name is empty!") + + std::lock_guard lock(m_modelLock); + return m_resModel.getAttribute(attrName, attribute); +} + +void SimulatorSingleResourceImpl::addAttribute(const SimulatorResourceModel::Attribute &attribute, + bool notify) +{ + std::lock_guard lock(m_modelLock); + if (m_resModel.containsAttribute(attribute.getName())) + throw SimulatorException(SIMULATOR_ERROR, "Attribute exist with same name!"); + + if (!m_resModel.add(attribute)) + throw SimulatorException(SIMULATOR_ERROR, "Failed to add attribute!"); + + if (notify && isStarted()) + notifyAll(); +} + +bool SimulatorSingleResourceImpl::getAttributeProperty(const std::string &attrName, + SimulatorResourceModel::AttributeProperty &property) +{ + VALIDATE_INPUT(attrName.empty(), "Attribute name is empty!") + + std::lock_guard lock(m_modelLock); + return m_resModel.getAttributeProperty(attrName, property); +} + +bool SimulatorSingleResourceImpl::setAttributeProperty(const std::string &attrName, + const SimulatorResourceModel::AttributeProperty &property) +{ + VALIDATE_INPUT(attrName.empty(), "Attribute name is empty!") + + std::lock_guard lock(m_modelLock); + return m_resModel.setAttributeProperty(attrName, property); +} + +bool SimulatorSingleResourceImpl::updateAttributeValue( + const SimulatorResourceModel::Attribute &attribute, + bool notify) +{ + std::lock_guard lock(m_modelLock); + if (m_resModel.updateValue(attribute)) + { + if (notify && isStarted()) + notifyAll(); + return true; + } + + return false; +} + +bool SimulatorSingleResourceImpl::removeAttribute(const std::string &attrName, bool notify) +{ + VALIDATE_INPUT(attrName.empty(), "Attribute name is empty!") + + std::lock_guard lock(m_modelLock); + if (m_resModel.removeAttribute(attrName)) + { + if (notify && isStarted()) + notifyAll(); + return true; + } + + return false; +} + +SimulatorResourceModel SimulatorSingleResourceImpl::getResourceModel() +{ + std::lock_guard lock(m_modelLock); + return m_resModel; +} + +void SimulatorSingleResourceImpl::setModelChangeCallback(ResourceModelChangedCallback callback) +{ + VALIDATE_CALLBACK(callback) + m_modelCallback = callback; +} + +int SimulatorSingleResourceImpl::startResourceUpdation(AutomationType type, + int updateInterval, updateCompleteCallback callback) +{ + VALIDATE_CALLBACK(callback) + + std::lock_guard lock(m_objectLock); + if (!m_resourceHandle) + throw SimulatorException(SIMULATOR_NO_RESOURCE, "Resource is not registered!"); + + return m_updateAutomationMgr.startResourceAutomation(this, type, updateInterval, callback); +} + +int SimulatorSingleResourceImpl::startAttributeUpdation(const std::string &attrName, + AutomationType type, int updateInterval, updateCompleteCallback callback) +{ + VALIDATE_CALLBACK(callback) + + std::lock_guard lock(m_objectLock); + if (!m_resourceHandle) + throw SimulatorException(SIMULATOR_NO_RESOURCE, "Resource is not registered!"); + + return m_updateAutomationMgr.startAttributeAutomation(this, attrName, type, + updateInterval, callback); +} + +std::vector SimulatorSingleResourceImpl::getResourceUpdationIds() +{ + return m_updateAutomationMgr.getResourceAutomationIds(); +} + +std::vector SimulatorSingleResourceImpl::getAttributeUpdationIds() +{ + return m_updateAutomationMgr.getAttributeAutomationIds(); +} + +void SimulatorSingleResourceImpl::stopUpdation(const int id) +{ + m_updateAutomationMgr.stop(id); +} + +void SimulatorSingleResourceImpl::setResourceModel(const SimulatorResourceModel &resModel) +{ + std::lock_guard lock(m_modelLock); + m_resModel = resModel; +} + +void SimulatorSingleResourceImpl::setPutErrorResponseModel(const SimulatorResourceModel &resModel) +{ + m_putErrorResModel = resModel; +} + +void SimulatorSingleResourceImpl::setPostErrorResponseModel(const SimulatorResourceModel &resModel) +{ + m_postErrorResModel = resModel; +} + +void SimulatorSingleResourceImpl::notifyApp(SimulatorResourceModel &resModel) +{ + if (m_modelCallback) + { + m_modelCallback(m_uri, resModel); + } +} + +void SimulatorSingleResourceImpl::notifyApp() +{ + notifyApp(m_resModel); +} + +bool SimulatorSingleResourceImpl::updateResourceModel(OC::OCRepresentation &ocRep, + SimulatorResourceModel &resModel) +{ + std::lock_guard lock(m_modelLock); + if (m_resModel.update(ocRep)) + { + resModel = m_resModel; + return true; + } + return false; +} + +OCEntityHandlerResult SimulatorSingleResourceImpl::handleRequests( + std::shared_ptr request) +{ + OCEntityHandlerResult errCode = OC_EH_ERROR; + if (!request) + return OC_EH_ERROR; + + if (OC::RequestHandlerFlag::RequestFlag & request->getRequestHandlerFlag()) + { + { + OC::OCRepresentation rep = request->getResourceRepresentation(); + std::string payload = getPayloadString(rep); + SIM_LOG(ILogger::INFO, "[" << m_name << "] " << request->getRequestType() + << " request received. \n**Payload details**\n" << payload) + } + + // Handover the request to appropriate interface handler + std::string interfaceType(OC::DEFAULT_INTERFACE); + OC::QueryParamsMap queryParams = request->getQueryParameters(); + if (queryParams.end() != queryParams.find("if")) + interfaceType = queryParams["if"]; + + std::shared_ptr response; + if (interfaceType == OC::DEFAULT_INTERFACE) + { + response = requestOnBaseLineInterface(request); + } + + // Send response if the request handled by resource + if (response) + { + if (OC_STACK_OK != OC::OCPlatform::sendResponse(response)) + return OC_EH_ERROR; + } + else + { + SIM_LOG(ILogger::ERROR, "[" << m_name << "] " << "Unsupported request received!") + return OC_EH_ERROR; + } + } + + if (OC::RequestHandlerFlag::ObserverFlag & request->getRequestHandlerFlag()) + { + if (false == isObservable()) + { + SIM_LOG(ILogger::INFO, "[" << m_uri << "] OBSERVE request received") + SIM_LOG(ILogger::INFO, "[" << m_uri << "] Sending error as resource is in unobservable state") + return OC_EH_ERROR; + } + + OC::ObservationInfo observationInfo = request->getObservationInfo(); + if (OC::ObserveAction::ObserveRegister == observationInfo.action) + { + SIM_LOG(ILogger::INFO, "[" << m_uri << "] OBSERVE REGISTER request received"); + + ObserverInfo info {observationInfo.obsId, observationInfo.address, observationInfo.port}; + m_observersList.push_back(info); + + if (m_observeCallback) + m_observeCallback(m_uri, ObservationStatus::REGISTER, info); + } + else if (OC::ObserveAction::ObserveUnregister == observationInfo.action) + { + SIM_LOG(ILogger::INFO, "[" << m_uri << "] OBSERVE UNREGISTER request received"); + + ObserverInfo info; + for (auto iter = m_observersList.begin(); iter != m_observersList.end(); iter++) + { + if ((info = *iter), info.id == observationInfo.obsId) + { + m_observersList.erase(iter); + break; + } + } + + if (m_observeCallback) + m_observeCallback(m_uri, ObservationStatus::UNREGISTER, info); + } + errCode = OC_EH_OK; + } + + return errCode; +} + +std::shared_ptr SimulatorSingleResourceImpl::requestOnBaseLineInterface( + std::shared_ptr request) +{ + std::shared_ptr response; + if ("GET" == request->getRequestType()) + { + OC::OCRepresentation ocRep = m_resModel.getOCRepresentation(); + response = std::make_shared(); + response->setErrorCode(200); + response->setResponseResult(OC_EH_OK); + response->setResourceRepresentation(ocRep); + std::string resPayload = getPayloadString(ocRep); + SIM_LOG(ILogger::INFO, "[" << m_uri << + "] Sending response for GET request. \n**Payload details**" << resPayload) + } + else if ("PUT" == request->getRequestType() + || "POST" == request->getRequestType()) + { + OC::OCRepresentation requestRep = request->getResourceRepresentation(); + SimulatorResourceModel resModel; + if (true == updateResourceModel(requestRep, resModel)) + { + notifyAll(resModel); + notifyApp(resModel); + + response = std::make_shared(); + response->setErrorCode(200); + response->setResponseResult(OC_EH_OK); + response->setResourceRepresentation(resModel.getOCRepresentation()); + std::string resPayload = getPayloadString(resModel.getOCRepresentation()); + SIM_LOG(ILogger::INFO, "[" << m_uri << + "] Sending response for " << request->getRequestType() << " request. \n**Payload details**" << + resPayload) + } + else + { + response = std::make_shared(); + response->setErrorCode(400); + response->setResponseResult(OC_EH_ERROR); + if ("PUT" == request->getRequestType()) + { + if (m_putErrorResModel.getOCRepresentation().empty()) + response->setResourceRepresentation(m_resModel.getOCRepresentation()); + else + response->setResourceRepresentation(m_putErrorResModel.getOCRepresentation()); + } + else + { + if (m_postErrorResModel.getOCRepresentation().empty()) + response->setResourceRepresentation(m_resModel.getOCRepresentation()); + else + response->setResourceRepresentation(m_postErrorResModel.getOCRepresentation()); + } + } + } + else if ("DELETE" == request->getRequestType()) + { + // TODO: Handle this request + } + + if (response) + { + response->setRequestHandle(request->getRequestHandle()); + response->setResourceHandle(request->getResourceHandle()); + } + + return response; +} diff --git a/service/simulator/src/server/simulator_single_resource_impl.h b/service/simulator/src/server/simulator_single_resource_impl.h new file mode 100644 index 0000000..6aa6a4a --- /dev/null +++ b/service/simulator/src/server/simulator_single_resource_impl.h @@ -0,0 +1,110 @@ +/****************************************************************** + * + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +#ifndef SIMULATOR_SINGLE_RESOURCE_IMPL_H_ +#define SIMULATOR_SINGLE_RESOURCE_IMPL_H_ + +#include "simulator_single_resource.h" +#include "resource_update_automation_mngr.h" + +class SimulatorResourceFactory; +class SimulatorSingleResourceImpl : public SimulatorSingleResource +{ + public: + friend class SimulatorResourceFactory; + + std::string getName() const; + SimulatorResource::Type getType() const; + std::string getURI() const; + std::string getResourceType() const; + std::vector getInterface() const; + void setInterface(const std::vector &interfaces); + void setName(const std::string &name); + void setURI(const std::string &uri); + void setResourceType(const std::string &resourceType); + void addInterface(std::string interfaceType); + void setObservable(bool state); + void setObserverCallback(ObserverCallback callback); + bool isObservable(); + bool isStarted(); + void start(); + void stop(); + std::vector getObserversList(); + void notify(int id); + void notifyAll(); + void notify(int id, SimulatorResourceModel &resModel); + void notifyAll(SimulatorResourceModel &resModel); + + bool getAttribute(const std::string &attrName, + SimulatorResourceModel::Attribute &attribute); + void addAttribute(const SimulatorResourceModel::Attribute &attribute, bool notify = true); + bool getAttributeProperty(const std::string &attrName, + SimulatorResourceModel::AttributeProperty &property); + bool setAttributeProperty(const std::string &attrName, + const SimulatorResourceModel::AttributeProperty &property); + bool updateAttributeValue(const SimulatorResourceModel::Attribute &attribute, + bool notify = true); + bool removeAttribute(const std::string &attrName, bool notify = true); + SimulatorResourceModel getResourceModel(); + void setModelChangeCallback(ResourceModelChangedCallback callback); + int startResourceUpdation(AutomationType type, int updateInterval, + updateCompleteCallback callback); + int startAttributeUpdation(const std::string &attrName, AutomationType type, + int updateInterval, updateCompleteCallback callback); + std::vector getResourceUpdationIds(); + std::vector getAttributeUpdationIds(); + void stopUpdation(const int id); + void setResourceModel(const SimulatorResourceModel &resModel); + void setPutErrorResponseModel(const SimulatorResourceModel &resModel); + void setPostErrorResponseModel(const SimulatorResourceModel &resModel); + void notifyApp(); + void notifyApp(SimulatorResourceModel &resModel); + + private: + SimulatorSingleResourceImpl(); + OCEntityHandlerResult handleRequests(std::shared_ptr request); + std::shared_ptr requestOnBaseLineInterface( + std::shared_ptr request); + void resourceModified(); + bool updateResourceModel(OC::OCRepresentation &ocRep, SimulatorResourceModel &resModel); + + SimulatorResource::Type m_type; + std::string m_name; + std::string m_uri; + std::string m_resourceType; + std::vector m_interfaces; + + std::recursive_mutex m_objectLock; + std::mutex m_modelLock; + SimulatorResourceModel m_resModel; + SimulatorResourceModel m_putErrorResModel; + SimulatorResourceModel m_postErrorResModel; + ResourceModelChangedCallback m_modelCallback; + ObserverCallback m_observeCallback; + UpdateAutomationMngr m_updateAutomationMgr; + std::vector m_observersList; + + OCResourceProperty m_property; + OCResourceHandle m_resourceHandle; +}; + +typedef std::shared_ptr SimulatorSingleResourceImplSP; + +#endif diff --git a/service/simulator/src/service-provider/resource_manager.cpp b/service/simulator/src/service-provider/resource_manager.cpp deleted file mode 100644 index 54c5e8b..0000000 --- a/service/simulator/src/service-provider/resource_manager.cpp +++ /dev/null @@ -1,215 +0,0 @@ -/****************************************************************** - * - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************/ - -#include "resource_manager.h" -#include "simulator_logger.h" -#include "logger.h" - -#define TAG "RESOURCE_MANAGER" - -ResourceManager *ResourceManager::getInstance() -{ - static ResourceManager s_instance; - return &s_instance; -} - -SimulatorResourceServerSP ResourceManager::createResource(const std::string &configPath, - SimulatorResourceServer::ResourceModelChangedCB callback) -{ - OC_LOG_V(INFO, "Create resource request : config=%s", configPath.c_str()); - - // Input validation - if (configPath.empty()) - { - OC_LOG(ERROR, TAG, "Invalid config file path!"); - throw InvalidArgsException(SIMULATOR_INVALID_PARAM, "Invalid RAML file path!"); - } - - if (!callback) - { - OC_LOG(ERROR, TAG, "Invalid callback!"); - throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!"); - } - - return buildResource(configPath, callback); -} - -std::vector 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 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 ResourceManager::getResources( - const std::string &resourceType) -{ - std::lock_guard lock(m_lock); - - std::vector 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 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(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 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(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 lock(m_lock); - SimulatorResourceServerSP resource = - std::dynamic_pointer_cast(resourceImpl); - m_resources[resourceImpl->getResourceType()].insert( - std::pair(resourceImpl->getURI(), resourceImpl)); - - SIM_LOG(ILogger::INFO, "Created an OIC resource of type [" << - resourceImpl->getResourceType() << "]"); - return resourceImpl; -} - -/** - * This method appends a unique key to the given URI to make the URI unique in simulator. - * Example: If input is "/a/light", then the output will be "/a/light/simulator/0" for the first resource - * and "/a/light/simulator/1" for the second resource and so on. - */ -std::string ResourceManager::constructURI(const std::string &uri) -{ - std::ostringstream os; - os << uri; - if (!uri.empty() && '/' != uri[uri.length() - 1]) - os << '/'; - os << "simulator/" << m_id++; - return os.str(); -} - diff --git a/service/simulator/src/service-provider/resource_manager.h b/service/simulator/src/service-provider/resource_manager.h deleted file mode 100644 index ddb63f3..0000000 --- a/service/simulator/src/service-provider/resource_manager.h +++ /dev/null @@ -1,119 +0,0 @@ -/****************************************************************** - * - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************/ - -/** - * @file resource_manager.h - * - * @brief This file provides APIs for simulated resource management. - */ - -#ifndef RESOURCE_MANAGER_H_ -#define RESOURCE_MANAGER_H_ - -#include "simulator_resource_server_impl.h" -#include "simulator_resource_creator.h" -#include "simulator_error_codes.h" - -/** - * @class ResourceManager - * @brief This class provides a set of APIs for managing the simulated resource(s). - */ -class ResourceManager -{ - public: - /** - * This method is to create/obtain the singleton instance of ResourceManager. - */ - static ResourceManager *getInstance(void); - - /** - * This method is for simulating/creating a resource based on the input data provided from - * RAML file. - * - * @param configPath - RAML configuration file path. - * @param callback - Callback method for receiving notifications when resource model changes. - * - * @return SimulatorResourceServer shared object representing simulated/created resource. - */ - SimulatorResourceServerSP createResource(const std::string &configPath, - SimulatorResourceServer::ResourceModelChangedCB callback); - - /** - * This method is for creating multiple resources of same type based on the input data - * provided from RAML file. - * - * @param configPath - RAML configuration file path. - * @param count - Number of resource to be created. - * @param callback - Callback method for receiving notifications when resource model changes. - * - * @return vector of SimulatorResourceServer shared objects representing simulated/created - * resources. - */ - std::vector 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 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> m_resources; -}; - -#endif - diff --git a/service/simulator/src/service-provider/simulator_resource_creator.cpp b/service/simulator/src/service-provider/simulator_resource_creator.cpp deleted file mode 100755 index 18bd97a..0000000 --- a/service/simulator/src/service-provider/simulator_resource_creator.cpp +++ /dev/null @@ -1,154 +0,0 @@ -/****************************************************************** - * - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************/ - -#include "simulator_resource_creator.h" -#include "simulator_logger.h" -#include -#include "logger.h" - -#define TAG "SIM_RESOURCE_CREATOR" - -unsigned int SimulatorResourceCreator::s_id; -SimulatorResourceServerImplSP SimulatorResourceCreator::createResource( - const std::string &configPath) -{ - RAML::RamlPtr raml; - - try - { - std::shared_ptr ramlParser = std::make_shared(configPath); - raml = ramlParser->getRamlPtr(); - } - catch (RAML::RamlException &e) - { - OC_LOG_V(ERROR, TAG, "RAML Exception occured! [%s]", e.what()); - throw; - } - - std::map ramlResources = raml->getResources(); - RAML::RamlResourcePtr ramlResource; - if (0 == ramlResources.size() || (ramlResource = ramlResources.begin()->second) == nullptr) - { - OC_LOG(ERROR, TAG, "Zero resources detected from RAML!"); - return nullptr; - } - - if (ramlResource) - { - SimulatorResourceServerImplSP simResource(new SimulatorResourceServerImpl()); - simResource->setName(ramlResource->getDisplayName()); - simResource->setURI(ramlResource->getResourceUri()); - - // Get the resource representation schema from GET response body - RAML::ActionPtr action = ramlResource->getAction(RAML::ActionType::GET); - if (!action) - { - OC_LOG(ERROR, TAG, "Failed to create resource representation schema as it does not" - "posess the GET request!"); - return nullptr; - } - - RAML::ResponsePtr getResponse = action->getResponse("200"); - if (!getResponse) - { - OC_LOG(ERROR, TAG, "Resource does not provide valid GET response!"); - return nullptr; - } - - RAML::RequestResponseBodyPtr responseBody = getResponse->getResponseBody("application/json"); - if (responseBody) - { - RAML::JsonSchemaPtr resourceProperties = responseBody->getSchema()->getProperties(); - for ( auto & propertyElement : resourceProperties->getProperties()) - { - if (!propertyElement.second) - continue; - - std::string propName = propertyElement.second->getName(); - if ("rt" == propName || "resourceType" == propName) - { - simResource->setResourceType(propertyElement.second->getValueString()); - continue; - } - else if ("if" == propName) - { - simResource->setInterfaceType(propertyElement.second->getValueString()); - continue; - } - else if ("p" == propName || "n" == propName || "id" == propName) - { - continue; - } - - // Build representation attribute - SimulatorResourceModel::Attribute attribute(propName); - switch (propertyElement.second->getValueType()) - { - case 0: // Integer - attribute.setValue(propertyElement.second->getValue()); - break; - - case 1: // Double - attribute.setValue(propertyElement.second->getValue()); - break; - - case 2: // Boolean - attribute.setValue(propertyElement.second->getValue()); - break; - - case 3: // String - attribute.setValue(propertyElement.second->getValue()); - break; - } - - // Set range/supported values set - int min = 0, max = 0, multipleof = 0; - propertyElement.second->getRange(min, max, multipleof); - attribute.setRange(min, max); - - if (propertyElement.second->getAllowedValuesSize() > 0) - attribute.setAllowedValues(propertyElement.second->getAllowedValues()); - - simResource->addAttribute(attribute); - } - } - - simResource->setURI(constructURI(simResource->getURI())); - return simResource; - } - - return nullptr; -} - -/** - * This method appends a unique key to the given URI to make the URI unique in simulator. - * Example: If input is "/a/light", then the output will be "/a/light/simulator/0" for the first resource - * and "/a/light/simulator/1" for the second resource and so on. - */ -std::string SimulatorResourceCreator::constructURI(const std::string &uri) -{ - std::ostringstream os; - os << uri; - if (!uri.empty() && '/' != uri[uri.length() - 1]) - os << '/'; - os << "simulator/" << s_id++; - return os.str(); -} - diff --git a/service/simulator/src/service-provider/simulator_resource_server.cpp b/service/simulator/src/service-provider/simulator_resource_server.cpp deleted file mode 100644 index a4ae6a7..0000000 --- a/service/simulator/src/service-provider/simulator_resource_server.cpp +++ /dev/null @@ -1,75 +0,0 @@ -/****************************************************************** - * - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************/ - -#include "simulator_resource_server.h" - -SimulatorResourceServer::SimulatorResourceServer() -{ -} - -std::string SimulatorResourceServer::getURI() const -{ - return m_uri; -} - -std::string SimulatorResourceServer::getResourceType() const -{ - return m_resourceType; -} - -std::string SimulatorResourceServer::getInterfaceType() const -{ - return m_interfaceType; -} - -std::string SimulatorResourceServer::getName() const -{ - return m_name; -} - -void SimulatorResourceServer::addAttribute(SimulatorResourceModel::Attribute &attribute) -{ - m_resModel.addAttribute(attribute); -} - -void SimulatorResourceServer::setRange(const std::string &attrName, const int min, const int max) -{ - m_resModel.setRange(attrName, min, max); -} - -SimulatorResourceModel SimulatorResourceServer::getModel() const -{ - return m_resModel; -} - -void SimulatorResourceServer::updateFromAllowedValues(const std::string &attrName, - unsigned int index) -{ - m_resModel.updateAttributeFromAllowedValues(attrName, index); - - // Notify all the subscribers - notifyAll(); -} - -void SimulatorResourceServer::removeAttribute(const std::string &attrName) -{ - m_resModel.removeAttribute(attrName); -} - diff --git a/service/simulator/src/service-provider/simulator_resource_server_impl.cpp b/service/simulator/src/service-provider/simulator_resource_server_impl.cpp deleted file mode 100644 index 4f3b042..0000000 --- a/service/simulator/src/service-provider/simulator_resource_server_impl.cpp +++ /dev/null @@ -1,438 +0,0 @@ -/****************************************************************** - * - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************/ - -#include "simulator_resource_server_impl.h" -#include "simulator_utils.h" -#include "simulator_logger.h" -#include "logger.h" - -#define TAG "SIM_RESOURCE_SERVER" - -SimulatorResourceServerImpl::SimulatorResourceServerImpl() - : m_resourceHandle(NULL) -{ - m_property = static_cast(OC_DISCOVERABLE | OC_OBSERVABLE); - m_interfaceType.assign(OC::DEFAULT_INTERFACE); -} - -bool SimulatorResourceServerImpl::isObservable() const -{ - return (m_property & OC_OBSERVABLE); -} - -void SimulatorResourceServerImpl::setURI(const std::string &uri) -{ - m_uri = uri; -} - -void SimulatorResourceServerImpl::setResourceType(const std::string &resourceType) -{ - m_resourceType = resourceType; -} - -void SimulatorResourceServerImpl::setInterfaceType(const std::string &interfaceType) -{ - m_interfaceType = interfaceType; -} - -void SimulatorResourceServerImpl::setName(const std::string &name) -{ - m_name = name; -} - -void SimulatorResourceServerImpl::setObservable(bool state) -{ - if (true == state) - m_property = static_cast(m_property | OC_OBSERVABLE); - else - m_property = static_cast(m_property ^ OC_OBSERVABLE); -} - -int SimulatorResourceServerImpl::startUpdateAutomation(AutomationType type, - int updateInterval, updateCompleteCallback callback) -{ - if (!callback) - { - OC_LOG(ERROR, TAG, "Invalid callback!"); - throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!"); - } - - if (!m_resourceHandle) - { - OC_LOG(ERROR, TAG, "Invalid resource!"); - throw SimulatorException(SIMULATOR_NO_RESOURCE, "Invalid resource!"); - } - - return m_updateAutomationMgr.startResourceAutomation(this, type, updateInterval, callback); -} - -int SimulatorResourceServerImpl::startUpdateAutomation(const std::string &attrName, - AutomationType type, int updateInterval, - updateCompleteCallback callback) -{ - if (!callback) - { - OC_LOG(ERROR, TAG, "Invalid callback!"); - throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!"); - } - - if (!m_resourceHandle) - { - OC_LOG(ERROR, TAG, "Invalid resource!"); - throw SimulatorException(SIMULATOR_NO_RESOURCE, "Invalid resource!"); - } - - return m_updateAutomationMgr.startAttributeAutomation(this, attrName, type, updateInterval, callback); -} - -std::vector SimulatorResourceServerImpl::getResourceAutomationIds() -{ - return m_updateAutomationMgr.getResourceAutomationIds(); -} - -std::vector 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 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 resourceResponse = - {std::make_shared()}; - - 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); - - invokeocplatform(static_cast(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 resourceResponse = - {std::make_shared()}; - - 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); - - invokeocplatform(static_cast(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(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(OC::OCPlatform::unregisterResource), - m_resourceHandle); - - m_resourceHandle = nullptr; -} - -void SimulatorResourceServerImpl::notifyApp() -{ - // Notify the application callback - if (m_callback) - { - m_callback(m_uri, m_resModel); - } -} - -OC::OCRepresentation SimulatorResourceServerImpl::getOCRepresentation() -{ - return m_resModel.getOCRepresentation(); -} - -bool SimulatorResourceServerImpl::modifyResourceModel(OC::OCRepresentation &ocRep) -{ - bool status = m_resModel.update(ocRep); - if (true == status) - { - resourceModified(); - } - return status; -} - -void SimulatorResourceServerImpl::resourceModified() -{ - if (!m_resourceHandle) - { - return; - } - - // Notify all the subscribers - notifyAll(); - - // Notify the application callback - if (m_callback) - { - m_callback(m_uri, m_resModel); - } -} - -OCEntityHandlerResult SimulatorResourceServerImpl::entityHandler( - std::shared_ptr - request) -{ - OCEntityHandlerResult errCode = OC_EH_ERROR; - if (!request) - { - return OC_EH_ERROR; - } - - if (OC::RequestHandlerFlag::RequestFlag & request->getRequestHandlerFlag()) - { - auto response = std::make_shared(); - response->setRequestHandle(request->getRequestHandle()); - response->setResourceHandle(request->getResourceHandle()); - - if ("GET" == request->getRequestType()) - { - OC::OCRepresentation rep = request->getResourceRepresentation(); - std::string payload = getPayloadString(rep); - SIM_LOG(ILogger::INFO, "[" << m_uri << - "] GET request received. \n**Payload details**" << payload) - - response->setErrorCode(200); - response->setResponseResult(OC_EH_OK); - response->setResourceRepresentation(getOCRepresentation()); - - if (OC_STACK_OK == OC::OCPlatform::sendResponse(response)) - { - errCode = OC_EH_OK; - } - } - else if ("PUT" == request->getRequestType()) - { - OC::OCRepresentation rep = request->getResourceRepresentation(); - std::string payload = getPayloadString(rep); - SIM_LOG(ILogger::INFO, "[" << m_uri << - "] PUT request received. \n**Payload details**" << payload) - - if (true == modifyResourceModel(rep)) - { - response->setErrorCode(200); - response->setResponseResult(OC_EH_OK); - response->setResourceRepresentation(getOCRepresentation()); - } - else - { - response->setErrorCode(400); - response->setResponseResult(OC_EH_ERROR); - } - - if (OC_STACK_OK == OC::OCPlatform::sendResponse(response)) - { - errCode = OC_EH_OK; - } - } - else if ("POST" == request->getRequestType()) - { - OC::OCRepresentation rep = request->getResourceRepresentation(); - std::string payload = getPayloadString(rep); - SIM_LOG(ILogger::INFO, "[" << m_uri << - "] POST request received. \n**Payload details**" << payload) - - if (true == modifyResourceModel(rep)) - { - response->setErrorCode(200); - response->setResponseResult(OC_EH_OK); - response->setResourceRepresentation(getOCRepresentation()); - } - else - { - response->setErrorCode(400); - response->setResponseResult(OC_EH_ERROR); - } - - if (OC_STACK_OK == OC::OCPlatform::sendResponse(response)) - { - errCode = OC_EH_OK; - } - } - else if ("DELETE" == request->getRequestType()) - { - OC::OCRepresentation rep = request->getResourceRepresentation(); - std::string payload = getPayloadString(rep); - SIM_LOG(ILogger::INFO, "[" << m_uri << - "] DELETE request received. \n**Payload details**" << payload) - - // DELETE request handling not supported right now - response->setErrorCode(400); - response->setResponseResult(OC_EH_ERROR); - if (OC_STACK_OK == OC::OCPlatform::sendResponse(response)) - { - errCode = OC_EH_OK; - } - } - else - { - OC::OCRepresentation rep = request->getResourceRepresentation(); - std::string payload = getPayloadString(rep); - SIM_LOG(ILogger::INFO, "[" << m_uri << - "] UNKNOWN type request received. \n**Payload details**" << payload) - - response->setResponseResult(OC_EH_ERROR); - if (OC_STACK_OK == OC::OCPlatform::sendResponse(response)) - { - errCode = OC_EH_ERROR; - } - } - } - - if (OC::RequestHandlerFlag::ObserverFlag & request->getRequestHandlerFlag()) - { - if (false == isObservable()) - { - SIM_LOG(ILogger::INFO, "[" << m_uri << "] OBSERVE request received") - SIM_LOG(ILogger::INFO, "[" << m_uri << "] Sending error as resource is in unobservable state") - return OC_EH_ERROR; - } - - OC::ObservationInfo observationInfo = request->getObservationInfo(); - if (OC::ObserveAction::ObserveRegister == observationInfo.action) - { - SIM_LOG(ILogger::INFO, "[" << m_uri << "] OBSERVE REGISTER request received"); - - ObserverInfo info {observationInfo.obsId, observationInfo.address, observationInfo.port}; - m_observersList.push_back(info); - - //Inform about addition of observer - if (m_observeCallback) - { - m_observeCallback(m_uri, ObservationStatus::OBSERVE_REGISTER, info); - } - } - else if (OC::ObserveAction::ObserveUnregister == observationInfo.action) - { - SIM_LOG(ILogger::INFO, "[" << m_uri << "] OBSERVE UNREGISTER request received"); - - ObserverInfo info; - for (auto iter = m_observersList.begin(); iter != m_observersList.end(); iter++) - { - if ((info = *iter), info.id == observationInfo.obsId) - { - m_observersList.erase(iter); - break; - } - } - - // Inform about cancellation of observer - if (m_observeCallback) - { - m_observeCallback(m_uri, ObservationStatus::OBSERVE_UNREGISTER, info); - } - } - errCode = OC_EH_OK; - } - - return errCode; -} diff --git a/service/simulator/src/service-provider/simulator_resource_server_impl.h b/service/simulator/src/service-provider/simulator_resource_server_impl.h deleted file mode 100644 index 010865c..0000000 --- a/service/simulator/src/service-provider/simulator_resource_server_impl.h +++ /dev/null @@ -1,89 +0,0 @@ -/****************************************************************** - * - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************/ - -#ifndef SIMULATOR_RESOURCE_SERVER_IMPL_H_ -#define SIMULATOR_RESOURCE_SERVER_IMPL_H_ - -#include "simulator_resource_server.h" -#include "resource_update_automation_mngr.h" - -class SimulatorResourceServerImpl : public SimulatorResourceServer -{ - public: - SimulatorResourceServerImpl(); - - void setURI(const std::string &uri); - - void setResourceType(const std::string &resourceType); - - void setInterfaceType(const std::string &interfaceType); - - void setName(const std::string &name); - - void setObservable(bool state); - - bool isObservable() const; - - int startUpdateAutomation(AutomationType type, int updateInterval, - updateCompleteCallback callback); - - int startUpdateAutomation(const std::string &attrName, AutomationType type, - int updateInterval, updateCompleteCallback callback); - - std::vector getResourceAutomationIds(); - - std::vector getAttributeAutomationIds(); - - void stopUpdateAutomation(const int id); - - void setModelChangeCallback(ResourceModelChangedCB callback); - - void setObserverCallback(ObserverCB callback); - - std::vector getObserversList(); - - void notify(uint8_t id); - - void notifyAll(); - - void start(); - - void stop(); - - void notifyApp(); - - private: - OC::OCRepresentation getOCRepresentation(); - bool modifyResourceModel(OC::OCRepresentation &ocRep); - OCEntityHandlerResult entityHandler(std::shared_ptr request); - void resourceModified(); - - ResourceModelChangedCB m_callback; - ObserverCB m_observeCallback; - UpdateAutomationMngr m_updateAutomationMgr; - std::vector m_observersList; - - OCResourceProperty m_property; - OCResourceHandle m_resourceHandle; -}; - -typedef std::shared_ptr SimulatorResourceServerImplSP; - -#endif diff --git a/service/simulator/src/simulator_manager.cpp b/service/simulator/src/simulator_manager.cpp index 38e5269..001cbb3 100644 --- a/service/simulator/src/simulator_manager.cpp +++ b/service/simulator/src/simulator_manager.cpp @@ -19,8 +19,8 @@ ******************************************************************/ #include "simulator_manager.h" -#include "resource_manager.h" -#include "simulator_client.h" +#include "simulator_resource_factory.h" +#include "simulator_remote_resource_impl.h" #include "simulator_utils.h" SimulatorManager *SimulatorManager::getInstance() @@ -43,54 +43,102 @@ SimulatorManager::SimulatorManager() OC::OCPlatform::Configure(conf); } -std::shared_ptr SimulatorManager::createResource( - const std::string &configPath, - SimulatorResourceServer::ResourceModelChangedCB callback) +std::shared_ptr SimulatorManager::createResource( + const std::string &configPath) { - return ResourceManager::getInstance()->createResource(configPath, callback); -} + VALIDATE_INPUT(configPath.empty(), "Empty path!") -std::vector> SimulatorManager::createResource( - const std::string &configPath, unsigned short count, - SimulatorResourceServer::ResourceModelChangedCB callback) -{ - return ResourceManager::getInstance()->createResource(configPath, count, callback); + std::shared_ptr resource = + SimulatorResourceFactory::getInstance()->createResource(configPath); + if (!resource) + throw SimulatorException(SIMULATOR_ERROR, "Failed to create resource!"); + return resource; } -std::vector> SimulatorManager::getResources( - const std::string &resourceType) +std::vector> SimulatorManager::createResource( + const std::string &configPath, unsigned int count) { - return ResourceManager::getInstance()->getResources(resourceType); + VALIDATE_INPUT(configPath.empty(), "Empty path!") + VALIDATE_INPUT(!count, "Count is zero!") + + std::vector> resources = + SimulatorResourceFactory::getInstance()->createResource(configPath, count); + if (!resources.size()) + throw SimulatorException(SIMULATOR_ERROR, "Failed to create resource!"); + return resources; } -void SimulatorManager::deleteResource( - const std::shared_ptr &resource) +std::shared_ptr SimulatorManager::createSingleResource( + const std::string &name, const std::string &uri, const std::string &resourceType) { - ResourceManager::getInstance()->deleteResource(resource); + VALIDATE_INPUT(name.empty(), "Empty resource name!") + VALIDATE_INPUT(resourceType.empty(), "Empty resource type!") + + return SimulatorResourceFactory::getInstance()->createSingleResource(name, uri, resourceType); } -void SimulatorManager::deleteResource(const std::string &resourceType) +std::shared_ptr SimulatorManager::createCollectionResource( + const std::string &name, const std::string &uri, const std::string &resourceType) { - ResourceManager::getInstance()->deleteResources(resourceType); + VALIDATE_INPUT(name.empty(), "Empty resource name!") + VALIDATE_INPUT(resourceType.empty(), "Empty resource type!") + + return SimulatorResourceFactory::getInstance()->createCollectionResource(name, uri, resourceType); } void SimulatorManager::findResource(ResourceFindCallback callback) { - SimulatorClient::getInstance()->findResources(callback); + VALIDATE_CALLBACK(callback) + + OC::FindCallback findCallback = std::bind( + [](std::shared_ptr ocResource, ResourceFindCallback callback) + { + if (!ocResource) + return; + + SimulatorRemoteResourceSP simulatorResource(new SimulatorRemoteResourceImpl(ocResource)); + callback(simulatorResource); + }, std::placeholders::_1, callback); + + typedef OCStackResult (*FindResource)(const std::string &, const std::string &, + OCConnectivityType, OC::FindCallback); + + invokeocplatform(static_cast(OC::OCPlatform::findResource), "", + OC_MULTICAST_DISCOVERY_URI, CT_DEFAULT, findCallback); } void SimulatorManager::findResource(const std::string &resourceType, - ResourceFindCallback callback) + ResourceFindCallback callback) { - SimulatorClient::getInstance()->findResources(resourceType, callback); + VALIDATE_INPUT(resourceType.empty(), "Empty resource type!") + VALIDATE_CALLBACK(callback) + + OC::FindCallback findCallback = std::bind( + [](std::shared_ptr ocResource, ResourceFindCallback callback) + { + if (!ocResource) + return; + + SimulatorRemoteResourceSP simulatorResource(new SimulatorRemoteResourceImpl(ocResource)); + callback(simulatorResource); + }, std::placeholders::_1, callback); + + std::ostringstream query; + query << OC_MULTICAST_DISCOVERY_URI << "?rt=" << resourceType; + + typedef OCStackResult (*FindResource)(const std::string &, const std::string &, + OCConnectivityType, OC::FindCallback); + + invokeocplatform(static_cast(OC::OCPlatform::findResource), "", query.str(), + CT_DEFAULT, findCallback); } void SimulatorManager::getDeviceInfo(DeviceInfoCallback callback) { - if (!callback) - throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!"); + VALIDATE_CALLBACK(callback) - OC::FindDeviceCallback deviceCallback = [this, callback](const OC::OCRepresentation & rep) + OC::FindDeviceCallback deviceCallback = std::bind( + [](const OC::OCRepresentation & rep, DeviceInfoCallback callback) { std::string deviceName = rep.getValue("n"); std::string deviceID = rep.getValue("di"); @@ -99,7 +147,7 @@ void SimulatorManager::getDeviceInfo(DeviceInfoCallback callback) DeviceInfo deviceInfo(deviceName, deviceID, deviceSpecVersion, deviceDMV); callback(deviceInfo); - }; + }, std::placeholders::_1, callback); std::ostringstream uri; uri << OC_MULTICAST_PREFIX << OC_RSRVD_DEVICE_URI; @@ -108,16 +156,12 @@ void SimulatorManager::getDeviceInfo(DeviceInfoCallback callback) OCConnectivityType, OC::FindDeviceCallback); invokeocplatform(static_cast(OC::OCPlatform::getDeviceInfo), "", - uri.str(), - CT_DEFAULT, - deviceCallback); + uri.str(), CT_DEFAULT, deviceCallback); } void SimulatorManager::setDeviceInfo(const std::string &deviceName) { - if (deviceName.empty()) - throw InvalidArgsException(SIMULATOR_INVALID_PARAM, "Device name is empty!"); - + VALIDATE_INPUT(deviceName.empty(), "Empty resource type!") typedef OCStackResult (*RegisterDeviceInfo)(const OCDeviceInfo); @@ -129,10 +173,10 @@ void SimulatorManager::setDeviceInfo(const std::string &deviceName) void SimulatorManager::getPlatformInfo(PlatformInfoCallback callback) { - if (!callback) - throw InvalidArgsException(SIMULATOR_INVALID_CALLBACK, "Invalid callback!"); + VALIDATE_CALLBACK(callback) - OC::FindPlatformCallback platformCallback = [this, callback](const OC::OCRepresentation & rep) + OC::FindPlatformCallback platformCallback = std::bind( + [](const OC::OCRepresentation & rep, PlatformInfoCallback callback) { PlatformInfo platformInfo; platformInfo.setPlatformID(rep.getValue("pi")); @@ -148,7 +192,7 @@ void SimulatorManager::getPlatformInfo(PlatformInfoCallback callback) platformInfo.setSystemTime(rep.getValue("st")); callback(platformInfo); - }; + }, std::placeholders::_1, callback); std::ostringstream uri; uri << OC_MULTICAST_PREFIX << OC_RSRVD_PLATFORM_URI; @@ -157,9 +201,7 @@ void SimulatorManager::getPlatformInfo(PlatformInfoCallback callback) OCConnectivityType, OC::FindPlatformCallback); invokeocplatform(static_cast(OC::OCPlatform::getPlatformInfo), "", - uri.str(), - CT_DEFAULT, - platformCallback); + uri.str(), CT_DEFAULT, platformCallback); } void SimulatorManager::setPlatformInfo(PlatformInfo &platformInfo) diff --git a/service/simulator/unittests/SimulatorTest/.gitignore b/service/simulator/unittests/SimulatorTest/.gitignore new file mode 100644 index 0000000..ae3c172 --- /dev/null +++ b/service/simulator/unittests/SimulatorTest/.gitignore @@ -0,0 +1 @@ +/bin/ diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/client/test/SimulatorRemoteResourceTest.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/client/test/SimulatorRemoteResourceTest.java new file mode 100644 index 0000000..0687158 --- /dev/null +++ b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/client/test/SimulatorRemoteResourceTest.java @@ -0,0 +1,1148 @@ +/* + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.oic.simulator.client.test; + +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import org.oic.simulator.AttributeValue; +import org.oic.simulator.InvalidArgsException; +import org.oic.simulator.SimulatorException; +import org.oic.simulator.SimulatorManager; +import org.oic.simulator.SimulatorResourceAttribute; +import org.oic.simulator.SimulatorResourceModel; +import org.oic.simulator.SimulatorResult; +import org.oic.simulator.client.FindResourceListener; +import org.oic.simulator.client.SimulatorRemoteResource; +import org.oic.simulator.server.SimulatorSingleResource; +import org.oic.simulator.test.ExceptionType; +import org.oic.simulator.utils.ObjectHolder; + +import junit.framework.TestCase; + +/** + * This class tests the APIs of SimulatorRemoteResource class. + */ +public class SimulatorRemoteResourceTest extends TestCase { + private static final String SINGLE_RES_RAML = "./ramls/oic.r.light.raml"; + private static SimulatorSingleResource singleResource = null; + private static SimulatorRemoteResource remoteResource = null; + + static { + System.loadLibrary("SimulatorManager"); + System.loadLibrary("RamlParser"); + System.loadLibrary("oc"); + System.loadLibrary("oc_logger"); + System.loadLibrary("octbstack"); + } + + protected void setUp() throws Exception { + super.setUp(); + + // Create single resource for first time + if (null == singleResource) { + singleResource = (SimulatorSingleResource) SimulatorManager + .createResource(SINGLE_RES_RAML); + singleResource.start(); + } + + // Find the created resource for first time + if (null != singleResource && null == remoteResource) { + CountDownLatch lockObject = new CountDownLatch(1); + ObjectHolder resourceHolder = new ObjectHolder<>(); + FindResourceCallbackListener listener = new FindResourceCallbackListener( + lockObject, resourceHolder); + + try { + SimulatorManager.findResource(singleResource.getResourceType(), + listener); + + try { + lockObject.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + } + + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + remoteResource = resourceHolder.get(); + } + } + + protected void tearDown() throws Exception { + super.tearDown(); + } + + public void testGetUri_P01() { + String serverURI = null; + try { + serverURI = singleResource.getURI(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertNotNull(remoteResource.getURI()); + assertEquals(serverURI, remoteResource.getURI()); + } + + public void testGetConnectivityType_P01() { + assertNotNull(remoteResource.getConnectivityType()); + } + + public void testGetResourceTypes_P01() { + assertNotNull(remoteResource.getResourceTypes()); + assertTrue(remoteResource.getResourceTypes().size() > 0); + } + + public void testGetResourceInterfaces_P01() { + assertNotNull(remoteResource.getResourceInterfaces()); + assertTrue(remoteResource.getResourceInterfaces().size() > 0); + } + + public void testGetHost_P01() { + assertNotNull(remoteResource.getHost()); + } + + public void testGetId_P01() { + assertNotNull(remoteResource.getId()); + } + + public void testIsObservable_P01() { + boolean serverObserveState = false; + try { + serverObserveState = singleResource.isObservable(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertEquals(serverObserveState, remoteResource.isObservable()); + } + + public void testGet_P01() { + CountDownLatch lockObject = new CountDownLatch(1); + boolean syncResult = false; + ObjectHolder response = new ObjectHolder<>(); + GetResponseCallbackListener listener = new GetResponseCallbackListener( + lockObject, response); + + try { + remoteResource.get(null, listener); + + try { + lockObject.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + } + + syncResult = true; + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertTrue(syncResult); + assertNotNull(response.get()); + assertEquals(remoteResource.getId(), response.get().uid()); + } + + public void testGet_P02() { + CountDownLatch lockObject = new CountDownLatch(1); + boolean syncResult = false; + ObjectHolder response = new ObjectHolder<>(); + GetResponseCallbackListener listener = new GetResponseCallbackListener( + lockObject, response); + + try { + Map queryParams = new HashMap<>(); + remoteResource.get(queryParams, listener); + + try { + lockObject.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + } + + syncResult = true; + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertTrue(syncResult); + assertNotNull(response.get()); + assertEquals(remoteResource.getId(), response.get().uid()); + } + + public void testGet_P03() { + CountDownLatch lockObject = new CountDownLatch(1); + boolean syncResult = false; + ObjectHolder response = new ObjectHolder<>(); + GetResponseCallbackListener listener = new GetResponseCallbackListener( + lockObject, response); + + try { + remoteResource.get(remoteResource.getResourceInterfaces().get(0), + null, listener); + + try { + lockObject.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + } + + syncResult = true; + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertTrue(syncResult); + assertNotNull(response.get()); + assertEquals(remoteResource.getId(), response.get().uid()); + } + + public void testGet_P04() { + CountDownLatch lockObject = new CountDownLatch(1); + boolean syncResult = false; + ObjectHolder response = new ObjectHolder<>(); + GetResponseCallbackListener listener = new GetResponseCallbackListener( + lockObject, response); + + try { + Map queryParams = new HashMap<>(); + remoteResource.get(remoteResource.getResourceInterfaces().get(0), + queryParams, listener); + + try { + lockObject.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + } + + syncResult = true; + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertTrue(syncResult); + assertNotNull(response.get()); + assertEquals(remoteResource.getId(), response.get().uid()); + } + + public void testGet_N01() { + ExceptionType exType = ExceptionType.UNKNOWN; + + try { + remoteResource.get(null, null); + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; + } + + assertTrue(exType == ExceptionType.INVALID_ARGS); + } + + public void testGet_N02() { + ExceptionType exType = ExceptionType.UNKNOWN; + + try { + remoteResource.get(remoteResource.getResourceInterfaces().get(0), + null, null); + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; + } + + assertTrue(exType == ExceptionType.INVALID_ARGS); + } + + public void testGet_N03() { + ExceptionType exType = ExceptionType.UNKNOWN; + + try { + Map queryParams = new HashMap<>(); + remoteResource.get(null, queryParams, + new SimulatorRemoteResource.GetResponseListener() { + @Override + public void onGetResponse(String uid, + SimulatorResult result, + SimulatorResourceModel resourceModel) { + } + }); + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; + } + + assertTrue(exType == ExceptionType.INVALID_ARGS); + } + + public void testPut_P01() { + CountDownLatch lockObject = new CountDownLatch(1); + boolean syncResult = false; + ObjectHolder response = new ObjectHolder<>(); + PutResponseCallbackListener listener = new PutResponseCallbackListener( + lockObject, response); + + try { + SimulatorResourceModel resModel = singleResource.getResourceModel(); + remoteResource.put(null, resModel, listener); + + try { + lockObject.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + } + + syncResult = true; + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertTrue(syncResult); + assertNotNull(response.get()); + assertNotNull(response.get().resourceModel()); + assertEquals(remoteResource.getId(), response.get().uid()); + } + + public void testPut_P02() { + CountDownLatch lockObject = new CountDownLatch(1); + boolean syncResult = false; + ObjectHolder response = new ObjectHolder<>(); + PutResponseCallbackListener listener = new PutResponseCallbackListener( + lockObject, response); + + try { + SimulatorResourceModel resModel = singleResource.getResourceModel(); + Map queryParams = new HashMap<>(); + remoteResource.put(queryParams, resModel, listener); + + try { + lockObject.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + } + + syncResult = true; + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertTrue(syncResult); + assertNotNull(response.get()); + assertNotNull(response.get().resourceModel()); + assertEquals(remoteResource.getId(), response.get().uid()); + } + + public void testPut_P03() { + CountDownLatch lockObject = new CountDownLatch(1); + boolean syncResult = false; + ObjectHolder response = new ObjectHolder<>(); + PutResponseCallbackListener listener = new PutResponseCallbackListener( + lockObject, response); + + try { + SimulatorResourceModel resModel = singleResource.getResourceModel(); + remoteResource.put(remoteResource.getResourceInterfaces().get(0), + null, resModel, listener); + + try { + lockObject.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + } + + syncResult = true; + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertTrue(syncResult); + assertNotNull(response.get()); + assertNotNull(response.get().resourceModel()); + assertEquals(remoteResource.getId(), response.get().uid()); + } + + public void testPut_P05() { + CountDownLatch lockObject = new CountDownLatch(1); + boolean syncResult = false; + ObjectHolder response = new ObjectHolder<>(); + PutResponseCallbackListener listener = new PutResponseCallbackListener( + lockObject, response); + + try { + SimulatorResourceModel resModel = singleResource.getResourceModel(); + Map queryParams = new HashMap<>(); + remoteResource.put(remoteResource.getResourceInterfaces().get(0), + queryParams, resModel, listener); + + try { + lockObject.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + } + + syncResult = true; + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertTrue(syncResult); + assertNotNull(response.get()); + assertNotNull(response.get().resourceModel()); + assertEquals(remoteResource.getId(), response.get().uid()); + } + + public void testPut_P04() { + CountDownLatch lockObject = new CountDownLatch(1); + boolean syncResult = false; + ObjectHolder response = new ObjectHolder<>(); + PutResponseCallbackListener listener = new PutResponseCallbackListener( + lockObject, response); + + try { + SimulatorResourceModel resModel = singleResource.getResourceModel(); + Map queryParams = new HashMap<>(); + remoteResource.put(queryParams, null, listener); + + try { + lockObject.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + } + + syncResult = true; + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertTrue(syncResult); + assertNotNull(response.get()); + assertNotNull(response.get().resourceModel()); + assertEquals(remoteResource.getId(), response.get().uid()); + } + + public void testPut_N01() { + ExceptionType exType = ExceptionType.UNKNOWN; + + try { + SimulatorResourceModel resModel = singleResource.getResourceModel(); + remoteResource.put(null, resModel, null); + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; + } + + assertTrue(exType == ExceptionType.INVALID_ARGS); + } + + public void testPut_N02() { + ExceptionType exType = ExceptionType.UNKNOWN; + + try { + SimulatorResourceModel resModel = singleResource.getResourceModel(); + remoteResource.put(remoteResource.getResourceInterfaces().get(0), + null, resModel, null); + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; + } + + assertTrue(exType == ExceptionType.INVALID_ARGS); + } + + public void testPut_N03() { + ExceptionType exType = ExceptionType.UNKNOWN; + + try { + SimulatorResourceModel resModel = singleResource.getResourceModel(); + Map queryParams = new HashMap<>(); + remoteResource.put(null, queryParams, resModel, + new SimulatorRemoteResource.PutResponseListener() { + @Override + public void onPutResponse(String uid, + SimulatorResult result, + SimulatorResourceModel resourceModel) { + } + }); + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; + } + + assertTrue(exType == ExceptionType.INVALID_ARGS); + } + + public void testPost_P01() { + CountDownLatch lockObject = new CountDownLatch(1); + boolean syncResult = false; + ObjectHolder response = new ObjectHolder<>(); + PostResponseCallbackListener listener = new PostResponseCallbackListener( + lockObject, response); + + try { + SimulatorResourceModel resModel = singleResource.getResourceModel(); + remoteResource.post(null, resModel, listener); + + try { + lockObject.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + } + + syncResult = true; + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertTrue(syncResult); + assertNotNull(response.get()); + assertNotNull(response.get().resourceModel()); + assertEquals(remoteResource.getId(), response.get().uid()); + } + + public void testPost_P02() { + CountDownLatch lockObject = new CountDownLatch(1); + boolean syncResult = false; + ObjectHolder response = new ObjectHolder<>(); + PostResponseCallbackListener listener = new PostResponseCallbackListener( + lockObject, response); + + try { + SimulatorResourceModel resModel = singleResource.getResourceModel(); + Map queryParams = new HashMap<>(); + remoteResource.post(queryParams, resModel, listener); + + try { + lockObject.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + } + + syncResult = true; + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertTrue(syncResult); + assertNotNull(response.get()); + assertNotNull(response.get().resourceModel()); + assertEquals(remoteResource.getId(), response.get().uid()); + } + + public void testPost_P03() { + CountDownLatch lockObject = new CountDownLatch(1); + boolean syncResult = false; + ObjectHolder response = new ObjectHolder<>(); + PostResponseCallbackListener listener = new PostResponseCallbackListener( + lockObject, response); + + try { + SimulatorResourceModel resModel = singleResource.getResourceModel(); + remoteResource.post(remoteResource.getResourceInterfaces().get(0), + null, resModel, listener); + + try { + lockObject.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + } + + syncResult = true; + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertTrue(syncResult); + assertNotNull(response.get()); + assertNotNull(response.get().resourceModel()); + assertEquals(remoteResource.getId(), response.get().uid()); + } + + public void testPost_P04() { + CountDownLatch lockObject = new CountDownLatch(1); + boolean syncResult = false; + ObjectHolder response = new ObjectHolder<>(); + PostResponseCallbackListener listener = new PostResponseCallbackListener( + lockObject, response); + + try { + SimulatorResourceModel resModel = singleResource.getResourceModel(); + Map queryParams = new HashMap<>(); + remoteResource.post(remoteResource.getResourceInterfaces().get(0), + queryParams, resModel, listener); + + try { + lockObject.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + } + + syncResult = true; + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertTrue(syncResult); + assertNotNull(response.get()); + assertNotNull(response.get().resourceModel()); + assertEquals(remoteResource.getId(), response.get().uid()); + } + + public void testPost_P05() { + CountDownLatch lockObject = new CountDownLatch(1); + boolean syncResult = false; + ObjectHolder response = new ObjectHolder<>(); + PostResponseCallbackListener listener = new PostResponseCallbackListener( + lockObject, response); + + try { + SimulatorResourceModel resModel = singleResource.getResourceModel(); + Map queryParams = new HashMap<>(); + remoteResource.post(queryParams, null, listener); + + try { + lockObject.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + } + + syncResult = true; + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertTrue(syncResult); + assertNotNull(response.get()); + assertNotNull(response.get().resourceModel()); + assertEquals(remoteResource.getId(), response.get().uid()); + } + + public void testPost_N01() { + ExceptionType exType = ExceptionType.UNKNOWN; + + try { + SimulatorResourceModel resModel = singleResource.getResourceModel(); + remoteResource.post(null, resModel, null); + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; + } + + assertTrue(exType == ExceptionType.INVALID_ARGS); + } + + public void testPost_N02() { + ExceptionType exType = ExceptionType.UNKNOWN; + + try { + SimulatorResourceModel resModel = singleResource.getResourceModel(); + remoteResource.post(remoteResource.getResourceInterfaces().get(0), + null, resModel, null); + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; + } + + assertTrue(exType == ExceptionType.INVALID_ARGS); + } + + public void testPost_N03() { + ExceptionType exType = ExceptionType.UNKNOWN; + + try { + SimulatorResourceModel resModel = singleResource.getResourceModel(); + Map queryParams = new HashMap<>(); + remoteResource.post(null, queryParams, resModel, + new SimulatorRemoteResource.PostResponseListener() { + @Override + public void onPostResponse(String uid, + SimulatorResult result, + SimulatorResourceModel resourceModel) { + } + }); + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; + } + + assertTrue(exType == ExceptionType.INVALID_ARGS); + } + + public void testStartObserve_P01() { + CountDownLatch lockObject = new CountDownLatch(1); + boolean syncResult = false; + ObjectHolder response = new ObjectHolder<>(); + ObserveNotificationCallbackListener listener = new ObserveNotificationCallbackListener( + lockObject, response); + + try { + Map queryParams = new HashMap<>(); + remoteResource.startObserve(queryParams, listener); + singleResource.addAttribute(new SimulatorResourceAttribute( + "boolean", new AttributeValue(true), null)); + singleResource.removeAttribute("boolean"); + + try { + lockObject.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + } + + remoteResource.stopObserve(); + syncResult = true; + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertTrue(syncResult); + assertNotNull(response.get()); + assertNotNull(response.get().resourceModel()); + assertEquals(remoteResource.getId(), response.get().uid()); + } + + public void testStartObserve_P02() { + CountDownLatch lockObject = new CountDownLatch(1); + boolean syncResult = false; + ObjectHolder response = new ObjectHolder<>(); + ObserveNotificationCallbackListener listener = new ObserveNotificationCallbackListener( + lockObject, response); + + try { + remoteResource.startObserve(null, listener); + singleResource.addAttribute(new SimulatorResourceAttribute( + "boolean", new AttributeValue(true), null)); + singleResource.removeAttribute("boolean"); + + try { + lockObject.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + } + + remoteResource.stopObserve(); + syncResult = true; + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertTrue(syncResult); + assertNotNull(response.get()); + assertNotNull(response.get().resourceModel()); + assertEquals(remoteResource.getId(), response.get().uid()); + } + + public void testStartObserve_N01() { + ExceptionType exType = ExceptionType.UNKNOWN; + + try { + Map queryParams = new HashMap<>(); + remoteResource.startObserve(queryParams, null); + + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; + } + + assertTrue(exType == ExceptionType.INVALID_ARGS); + } + + public void testStopObserve_P01() { + CountDownLatch lockObject = new CountDownLatch(1); + boolean syncResult = false; + ObjectHolder response = new ObjectHolder<>(); + ObserveNotificationCallbackListener listener = new ObserveNotificationCallbackListener( + lockObject, response); + + try { + Map queryParams = new HashMap<>(); + remoteResource.startObserve(queryParams, listener); + + try { + lockObject.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + } + + response.set(null); + remoteResource.stopObserve(); + singleResource.addAttribute(new SimulatorResourceAttribute( + "boolean", new AttributeValue(true), null)); + singleResource.removeAttribute("boolean"); + + try { + lockObject.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + } + + syncResult = true; + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertTrue(syncResult); + assertNull(response.get()); + } + + public void testSetConfigInfo_P01() { + boolean syncResult = false; + try { + remoteResource.setConfigInfo(SINGLE_RES_RAML); + syncResult = true; + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertTrue(syncResult); + } + + public void testSetConfigInfo_N01() { + ExceptionType exType = ExceptionType.UNKNOWN; + + try { + remoteResource.setConfigInfo(""); + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; + } + + assertTrue(exType == ExceptionType.INVALID_ARGS); + } + + public void testSetConfigInfo_N02() { + ExceptionType exType = ExceptionType.UNKNOWN; + + try { + remoteResource.setConfigInfo(null); + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; + } + + assertTrue(exType == ExceptionType.INVALID_ARGS); + } + + public void testStartVerification_P01() { + CountDownLatch lockObject = new CountDownLatch(1); + boolean syncResult = false; + ObjectHolder response = new ObjectHolder<>(); + VerificationCallbackListener listener = new VerificationCallbackListener( + lockObject, response); + + try { + remoteResource.setConfigInfo(SINGLE_RES_RAML); + remoteResource.startVerification( + SimulatorRemoteResource.VerificationType.GET, listener); + + try { + lockObject.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + } + + syncResult = true; + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertTrue(syncResult); + assertNotNull(response.get()); + assertEquals(remoteResource.getId(), response.get().uid()); + } + + public void testStartVerification_P02() { + CountDownLatch lockObject = new CountDownLatch(1); + boolean syncResult = false; + ObjectHolder response = new ObjectHolder<>(); + VerificationCallbackListener listener = new VerificationCallbackListener( + lockObject, response); + + try { + remoteResource.setConfigInfo(SINGLE_RES_RAML); + remoteResource.startVerification( + SimulatorRemoteResource.VerificationType.PUT, listener); + + try { + lockObject.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + } + + syncResult = true; + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertTrue(syncResult); + assertNotNull(response.get()); + assertEquals(remoteResource.getId(), response.get().uid()); + } + + public void testStartVerification_P03() { + CountDownLatch lockObject = new CountDownLatch(1); + boolean syncResult = false; + ObjectHolder response = new ObjectHolder<>(); + VerificationCallbackListener listener = new VerificationCallbackListener( + lockObject, response); + + try { + remoteResource.setConfigInfo(SINGLE_RES_RAML); + remoteResource.startVerification( + SimulatorRemoteResource.VerificationType.POST, listener); + + try { + lockObject.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + } + + syncResult = true; + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertTrue(syncResult); + assertNotNull(response.get()); + assertEquals(remoteResource.getId(), response.get().uid()); + } + + public void testStartVerification_N01() { + ExceptionType exType = ExceptionType.UNKNOWN; + + try { + remoteResource.setConfigInfo(SINGLE_RES_RAML); + remoteResource.startVerification( + SimulatorRemoteResource.VerificationType.GET, null); + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; + } + + assertTrue(exType == ExceptionType.INVALID_ARGS); + } + + public void testStopVerification_N01() { + CountDownLatch lockObject = new CountDownLatch(1); + boolean syncResult = false; + ObjectHolder response = new ObjectHolder<>(); + VerificationCallbackListener listener = new VerificationCallbackListener( + lockObject, response); + + try { + remoteResource.setConfigInfo(SINGLE_RES_RAML); + int id = remoteResource.startVerification( + SimulatorRemoteResource.VerificationType.POST, listener); + remoteResource.stopVerification(id); + syncResult = true; + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertTrue(syncResult); + } +} + +class ResponseDetails { + private String mUid = null; + private SimulatorResourceModel mResModel = null; + private SimulatorResult mResult = SimulatorResult.SIMULATOR_ERROR; + + ResponseDetails(String uid, SimulatorResult result, + SimulatorResourceModel resModel) { + mUid = uid; + mResModel = resModel; + mResult = result; + } + + String uid() { + return mUid; + } + + SimulatorResourceModel resourceModel() { + return mResModel; + } + + SimulatorResult errorCode() { + return mResult; + } +} + +class GetResponseCallbackListener implements + SimulatorRemoteResource.GetResponseListener { + private CountDownLatch mLockObject; + private ObjectHolder mResponse; + + public GetResponseCallbackListener(CountDownLatch lockObject, + ObjectHolder response) { + mLockObject = lockObject; + mResponse = response; + } + + @Override + public void onGetResponse(String uid, SimulatorResult result, + SimulatorResourceModel resourceModel) { + mResponse.set(new ResponseDetails(uid, result, resourceModel)); + mLockObject.countDown(); + } +} + +class PutResponseCallbackListener implements + SimulatorRemoteResource.PutResponseListener { + private CountDownLatch mLockObject; + private ObjectHolder mResponse; + + public PutResponseCallbackListener(CountDownLatch lockObject, + ObjectHolder response) { + mLockObject = lockObject; + mResponse = response; + } + + @Override + public void onPutResponse(String uid, SimulatorResult result, + SimulatorResourceModel resourceModel) { + mResponse.set(new ResponseDetails(uid, result, resourceModel)); + mLockObject.countDown(); + } +} + +class PostResponseCallbackListener implements + SimulatorRemoteResource.PostResponseListener { + private CountDownLatch mLockObject; + private ObjectHolder mResponse; + + public PostResponseCallbackListener(CountDownLatch lockObject, + ObjectHolder response) { + mLockObject = lockObject; + mResponse = response; + } + + @Override + public void onPostResponse(String uid, SimulatorResult result, + SimulatorResourceModel resourceModel) { + mResponse.set(new ResponseDetails(uid, result, resourceModel)); + mLockObject.countDown(); + } +} + +class ObserveNotificationCallbackListener implements + SimulatorRemoteResource.ObserveNotificationListener { + private CountDownLatch mLockObject; + private ObjectHolder mResponse; + + public ObserveNotificationCallbackListener(CountDownLatch lockObject, + ObjectHolder response) { + mLockObject = lockObject; + mResponse = response; + } + + @Override + public void onObserveNotification(String uid, + SimulatorResourceModel resourceModel, int sequenceNumber) { + mResponse.set(new ResponseDetails(uid, SimulatorResult.SIMULATOR_OK, + resourceModel)); + mLockObject.countDown(); + } +} + +class VerificationCallbackListener implements + SimulatorRemoteResource.VerificationListener { + private CountDownLatch mLockObject; + private ObjectHolder mResponse; + + public VerificationCallbackListener(CountDownLatch lockObject, + ObjectHolder response) { + mLockObject = lockObject; + mResponse = response; + } + + @Override + public void onVerificationStarted(String uid, int id) { + mResponse.set(new ResponseDetails(uid, SimulatorResult.SIMULATOR_OK, + null)); + mLockObject.countDown(); + } + + @Override + public void onVerificationAborted(String uid, int id) { + mResponse.set(new ResponseDetails(uid, SimulatorResult.SIMULATOR_OK, + null)); + mLockObject.countDown(); + } + + @Override + public void onVerificationCompleted(String uid, int id) { + mResponse.set(new ResponseDetails(uid, SimulatorResult.SIMULATOR_OK, + null)); + mLockObject.countDown(); + } +} + +class FindResourceCallbackListener implements FindResourceListener { + private CountDownLatch mLockObject; + private ObjectHolder mResourceHolder; + + public FindResourceCallbackListener(CountDownLatch lockObject, + ObjectHolder resourceHolder) { + mLockObject = lockObject; + mResourceHolder = resourceHolder; + } + + @Override + public void onResourceFound(SimulatorRemoteResource resource) { + mResourceHolder.set(resource); + mLockObject.countDown(); + } +} \ No newline at end of file diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/GetListener.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/GetListener.java deleted file mode 100644 index ed9fd7e..0000000 --- a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/GetListener.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.oic.simulator.clientcontroller.test; - -import java.util.concurrent.CountDownLatch; - -import org.oic.simulator.SimulatorResourceModel; -import org.oic.simulator.clientcontroller.IGetListener; - -/** - * This class implements methods for receiving notification when - * response is received for GET request. - */ -public class GetListener implements IGetListener -{ - - private CountDownLatch lockObject; - private ListenerObject getListenerObject; - - public GetListener(CountDownLatch lockObject, ListenerObject getListenerObject) - { - this.lockObject = lockObject; - this.getListenerObject = getListenerObject; - } - - @Override - public void onGetCompleted(String uId, SimulatorResourceModel representation) - { - if (null != getListenerObject) { - getListenerObject.setuId(uId); - getListenerObject.setRepresentation(representation); - } - - lockObject.countDown(); - } - - @Override - public void onGetFailed(Throwable ex) - { - if (null != getListenerObject) - getListenerObject.setEx(ex); - - lockObject.countDown(); - } -} diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/ListenerObject.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/ListenerObject.java deleted file mode 100644 index 860cf6a..0000000 --- a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/ListenerObject.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.oic.simulator.clientcontroller.test; - -import org.oic.simulator.SimulatorResourceModel; - -/** - * This class implements methods for setting/getting UID and - * resource representation. - */ -public class ListenerObject -{ - - private String uId; - private SimulatorResourceModel representation; - private Throwable ex; - - public void setuId(String uId) - { - this.uId = uId; - } - - public String getuId() - { - return uId; - } - - public void setRepresentation(SimulatorResourceModel representation) - { - this.representation = representation; - } - - public SimulatorResourceModel getRepresentation() - { - return representation; - } - - public void setEx(Throwable ex) - { - this.ex = ex; - } - - public Throwable getEx() - { - return ex; - } -} diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/ObserveListener.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/ObserveListener.java deleted file mode 100644 index ecc6c10..0000000 --- a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/ObserveListener.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.oic.simulator.clientcontroller.test; - -import java.util.concurrent.CountDownLatch; - -import org.oic.simulator.SimulatorResourceModel; -import org.oic.simulator.clientcontroller.IObserveListener; - -/** - * This class implements methods for receiving notification when - * response is received for Observe request. - */ -public class ObserveListener implements IObserveListener -{ - - private CountDownLatch lockObject; - private ObserveListenerObject observeListenerObject; - - public ObserveListener(CountDownLatch lockObject, ObserveListenerObject observeListenerObject) - { - this.lockObject = lockObject; - this.observeListenerObject = observeListenerObject; - } - - @Override - public void onObserveCompleted(String uId, SimulatorResourceModel representation, int sequenceNumber) - { - observeListenerObject.setuId(uId); - observeListenerObject.setRepresentation(representation); - observeListenerObject.setSequenceNumber(sequenceNumber); - - lockObject.countDown(); - } - - @Override - public void onObserveFailed(Throwable ex) - { - observeListenerObject.setEx(ex); - lockObject.countDown(); - } -} diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/ObserveListenerObject.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/ObserveListenerObject.java deleted file mode 100644 index 6bcca0c..0000000 --- a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/ObserveListenerObject.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.oic.simulator.clientcontroller.test; - -import org.oic.simulator.SimulatorResourceModel; - -/** - * This class implements methods for setting/getting UID, - * resource representation and sequence number for observe. - */ -public class ObserveListenerObject -{ - private String uId; - private SimulatorResourceModel representation; - private int sequenceNumber; - private Throwable ex; - - public void setuId(String uId) - { - this.uId = uId; - } - - public String getuId() - { - return uId; - } - - public void setRepresentation(SimulatorResourceModel representation) - { - this.representation = representation; - } - - public SimulatorResourceModel getRepresentation() - { - return representation; - } - - public void setSequenceNumber(int sequenceNumber) - { - this.sequenceNumber = sequenceNumber; - } - - public int getSequenceNumber() - { - return sequenceNumber; - } - - public void setEx(Throwable ex) - { - this.ex = ex; - } - - public Throwable getEx() - { - return ex; - } -} diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/PostListener.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/PostListener.java deleted file mode 100644 index 3942b51..0000000 --- a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/PostListener.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.oic.simulator.clientcontroller.test; - -import java.util.concurrent.CountDownLatch; - -import org.oic.simulator.SimulatorResourceModel; -import org.oic.simulator.clientcontroller.IPostListener; - -/** - * This class implements methods for receiving notification when - * response is received for POST request. - */ -public class PostListener implements IPostListener -{ - - private CountDownLatch lockObject; - private ListenerObject postListenerObject; - - public PostListener(CountDownLatch lockObject, ListenerObject postListenerObject) - { - this.lockObject = lockObject; - this.postListenerObject = postListenerObject; - } - - @Override - public void onPostCompleted(String uId, SimulatorResourceModel representation) - { - if (null != postListenerObject) { - postListenerObject.setuId(uId); - postListenerObject.setRepresentation(representation); - } - - lockObject.countDown(); - } - - @Override - public void onPostFailed(Throwable ex) - { - if (null != postListenerObject) - postListenerObject.setEx(ex); - - lockObject.countDown(); - } -} diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/PutListener.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/PutListener.java deleted file mode 100644 index 1dafed3..0000000 --- a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/PutListener.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.oic.simulator.clientcontroller.test; - -import java.util.concurrent.CountDownLatch; - -import org.oic.simulator.SimulatorResourceModel; -import org.oic.simulator.clientcontroller.IPutListener; - -/** - * This class implements methods for receiving notification when - * response is received for PUT request. - */ -public class PutListener implements IPutListener -{ - private CountDownLatch lockObject; - private ListenerObject putListenerObject; - - public PutListener(CountDownLatch lockObject, ListenerObject putListenerObject) - { - this.lockObject = lockObject; - this.putListenerObject = putListenerObject; - } - - @Override - public void onPutCompleted(String uId, SimulatorResourceModel representation) - { - if (null != putListenerObject) { - putListenerObject.setuId(uId); - putListenerObject.setRepresentation(representation); - } - - lockObject.countDown(); - } - - @Override - public void onPutFailed(Throwable ex) - { - if (null != putListenerObject) - putListenerObject.setEx(ex); - - lockObject.countDown(); - } -} diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/SimulatorRemoteResourceTest.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/SimulatorRemoteResourceTest.java deleted file mode 100644 index 6cc820a..0000000 --- a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/SimulatorRemoteResourceTest.java +++ /dev/null @@ -1,915 +0,0 @@ -/* - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.oic.simulator.clientcontroller.test; - -import java.util.HashMap; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -import junit.framework.TestCase; - -import org.oic.simulator.SimulatorException; -import org.oic.simulator.SimulatorManager; -import org.oic.simulator.SimulatorResourceModel; -import org.oic.simulator.clientcontroller.SimulatorObserveType; -import org.oic.simulator.clientcontroller.SimulatorRemoteResource; -import org.oic.simulator.clientcontroller.SimulatorVerificationType; -import org.oic.simulator.serviceprovider.SimulatorResourceServer; -import org.oic.simulator.test.FindResourceListener; -import org.oic.simulator.test.ResourceModelChangeListener; -import org.oic.simulator.test.ResourceModelObject; -import org.oic.simulator.test.SimulatorRemoteResourceObject; - -/** - * This class tests the functionality of Simulator Remote Resource - * class APIs. - */ -public class SimulatorRemoteResourceTest extends TestCase -{ - private static final String CONFIG_PATH = "./ramls/simple-light.raml"; - // private static final String RESOURCE_TYPE = "oic.light"; - - private CountDownLatch lockObject; - private ResourceModelObject resourceModelObject; - private ResourceModelChangeListener resourceModelChangeListener; - - private SimulatorRemoteResourceObject simulatorRemoteResourceObject; - private SimulatorRemoteResource simulatorRemoteResource; - - private SimulatorResourceServer simulatorResourceServer; - - private FindResourceListener findResourceListener; - - static - { - System.loadLibrary("SimulatorManager"); - System.loadLibrary("RamlParser"); - System.loadLibrary("oc"); - System.loadLibrary("oc_logger"); - System.loadLibrary("octbstack"); - } - - protected void setUp() throws Exception - { - super.setUp(); - - lockObject = new CountDownLatch(1); - resourceModelObject = new ResourceModelObject(); - resourceModelChangeListener = new ResourceModelChangeListener(resourceModelObject); - - simulatorResourceServer = SimulatorManager.createResource(CONFIG_PATH, resourceModelChangeListener); - - simulatorRemoteResourceObject = new SimulatorRemoteResourceObject(); - - findResourceListener = new FindResourceListener(lockObject, simulatorRemoteResourceObject); - - SimulatorManager.findResource(findResourceListener); - - try - { - lockObject.await(10, TimeUnit.SECONDS); - } - catch (InterruptedException e) - { - } - - simulatorRemoteResource = simulatorRemoteResourceObject.getSimulatorRemoteResource(); - } - - protected void tearDown() throws Exception - { - super.tearDown(); - - SimulatorManager.deleteResource(simulatorResourceServer); - - lockObject = null; - resourceModelObject = null; - resourceModelChangeListener = null; - - simulatorRemoteResourceObject = null; - findResourceListener = null; - - simulatorRemoteResource = null; - } - - public void testGetUri_P01() - { - assertNotNull(simulatorRemoteResource.getUri()); - } - - public void testGetIsObservable_P01() - { - assertTrue(simulatorRemoteResource.getIsObservable()); - } - - public void testGetConnectivityType_P01() - { - assertNotNull(simulatorRemoteResource.getConnectivityType()); - } - - public void testGetResourceTypes_P01() - { - assertTrue(simulatorRemoteResource.getResourceTypes() != null && simulatorRemoteResource.getResourceTypes().size() > 0); - } - - public void testGetResourceInterfaces_P01() - { - assertTrue(simulatorRemoteResource.getResourceInterfaces() != null && simulatorRemoteResource.getResourceInterfaces().size() > 0); - } - - public void testGetId_P01() - { - assertNotNull(simulatorRemoteResource.getId()); - } - - public void testStartObserve_P01() - { - boolean result = true; - HashMap queryParamMap = new HashMap(); - - lockObject = new CountDownLatch(1); - - ObserveListenerObject observeListenerObject = new ObserveListenerObject(); - ObserveListener observeListener = new ObserveListener(lockObject, observeListenerObject); - - try - { - simulatorRemoteResource.startObserve(SimulatorObserveType.OBSERVE, queryParamMap, observeListener); - simulatorResourceServer.addAttributeString("test", "test"); - } - catch (Exception e1) - { - result = false; - } - - try - { - lockObject.await(10, TimeUnit.SECONDS); - } - catch (InterruptedException e) - { - } - - assertTrue(observeListenerObject.getRepresentation() != null && result); - - try - { - simulatorRemoteResource.stopObserve(); - } - catch (Exception e) - { - e.printStackTrace(); - } - - observeListenerObject = null; - observeListener = null; - } - - public void testStopObserve_P01() - { - boolean result = true; - - HashMap queryParamMap = new HashMap(); - lockObject = new CountDownLatch(1); - ObserveListenerObject observeListenerObject = new ObserveListenerObject(); - ObserveListener observeListener = new ObserveListener(lockObject, observeListenerObject); - - try - { - simulatorRemoteResource.startObserve(SimulatorObserveType.OBSERVE, queryParamMap, observeListener); - simulatorResourceServer.addAttributeString("test", "test"); - } - catch (Exception e1) - { - e1.printStackTrace(); - result = false; - } - - try - { - lockObject.await(10, TimeUnit.SECONDS); - } - catch (InterruptedException e) - { - } - - result = result && observeListenerObject.getRepresentation() != null; - - try - { - simulatorRemoteResource.stopObserve(); - } - catch (Exception e) - { - result = false; - e.printStackTrace(); - } - - assertTrue(result); - - observeListenerObject = null; - observeListener = null; - } - - public void testGetQueryParamGetListener_P01() - { - boolean result = true; - lockObject = new CountDownLatch(1); - HashMap queryParamMap = new HashMap(); - - ListenerObject getListenerObject = new ListenerObject(); - GetListener getListener = new GetListener(lockObject, getListenerObject); - - try - { - simulatorRemoteResource.get(queryParamMap, getListener); - } - catch (Exception e1) - { - e1.printStackTrace(); - result = false; - } - - try - { - lockObject.await(10, TimeUnit.SECONDS); - } - catch (InterruptedException e) - { - } - - if(getListenerObject.getEx() == null) - { - try - { - result = result && getListenerObject.getRepresentation() != null && getListenerObject.getRepresentation().size() > 0; - } - catch (SimulatorException e) - { - result = false; - e.printStackTrace(); - } - } - else - result = false; - - assertTrue(result); - } - - public void testGetStringMapOfStringStringIGetListener_P01() - { - boolean result = true; - lockObject = new CountDownLatch(1); - HashMap queryParamMap = new HashMap(); - - String resourceInterface = "oic.if.baseline"; - - ListenerObject getListenerObject = new ListenerObject(); - GetListener getListener = new GetListener(lockObject, getListenerObject); - - try - { - simulatorRemoteResource.get(resourceInterface, queryParamMap, getListener); - } - catch (Exception e1) - { - e1.printStackTrace(); - result = false; - } - - try - { - lockObject.await(10, TimeUnit.SECONDS); - } - catch (InterruptedException e) - { - } - - if(getListenerObject.getEx() == null) - { - try - { - result = result && getListenerObject.getRepresentation() != null && getListenerObject.getRepresentation().size() > 0; - } - catch (SimulatorException e) - { - result = false; - e.printStackTrace(); - } - } - else - result = false; - - assertTrue(result); - } - - public void testPut_P01() - { - boolean result = true; - SimulatorResourceModel model = new SimulatorResourceModel(); - - lockObject = new CountDownLatch(1); - - ListenerObject listenerObject = null; - - try - { - listenerObject = new ListenerObject(); - PutListener putListener = new PutListener(lockObject, listenerObject); - - model.addAttributeInt("intensity", 5); - model.addAttributeString("power", "off"); - - simulatorRemoteResource.put(model, null, putListener); - } - catch(Exception e) - { - result = false; - } - - try - { - lockObject.await(10, TimeUnit.SECONDS); - } - catch (InterruptedException e) - { - } - - assertTrue(result && listenerObject != null && listenerObject.getRepresentation() != null && listenerObject.getuId() != null); - } - - /** - * model as null - */ - - public void testPut_N01() { - boolean result = true; - ListenerObject listenerObject = new ListenerObject(); - PutListener putListener = new PutListener(lockObject, listenerObject); - - try { - simulatorRemoteResource.put(null, null, putListener); - result = false; - } catch (Exception e1) { - result = true; - } - - try { - lockObject.await(10, TimeUnit.SECONDS); - } catch (InterruptedException e) { - } - - assertTrue(result && listenerObject.getRepresentation() == null && listenerObject.getuId() == null); - } - - public void testPost_P01() - { - boolean result = true; - ListenerObject listenerObject = null; - lockObject = new CountDownLatch(1); - - SimulatorResourceModel model = new SimulatorResourceModel(); - try - { - model.addAttributeInt("intensity", 8); - - listenerObject = new ListenerObject(); - PostListener postListener = new PostListener(lockObject, listenerObject); - - simulatorRemoteResource.post(model, null, postListener); - } - catch(Exception e) - { - result = false; - } - - try - { - lockObject.await(10, TimeUnit.SECONDS); - } - catch (InterruptedException e) - { - } - - assertTrue(result && listenerObject != null && listenerObject.getRepresentation() != null && listenerObject.getuId() != null); - } - - /** - * Model is set to null - */ - - public void testPost_N01() { - boolean result = true; - - lockObject = new CountDownLatch(1); - - ListenerObject listenerObject = new ListenerObject(); - PostListener postListener = new PostListener(lockObject, listenerObject); - - try { - simulatorRemoteResource.post(null, null, postListener); - result = false; - } catch (Exception e1) { - result = true; - } - - try { - lockObject.await(10, TimeUnit.SECONDS); - } catch (InterruptedException e) { - } - - assertTrue(result && listenerObject.getRepresentation() == null && listenerObject.getuId() == null); - } - - public void testGet_P01() - { - boolean result = true; - ListenerObject listenerObject = null; - lockObject = new CountDownLatch(1); - - try - { - listenerObject = new ListenerObject(); - GetListener onGetListener = new GetListener(lockObject, listenerObject); - - String resInterface = simulatorRemoteResource.getResourceInterfaces().get(0); - - if(resInterface != null) - simulatorRemoteResource.get(resInterface,null, onGetListener); - else - result = false; - } - catch(Exception e) - { - result = false; - } - - try - { - lockObject.await(10, TimeUnit.SECONDS); - } - catch (InterruptedException e) - { - } - - assertTrue(result && listenerObject != null && listenerObject.getRepresentation() != null && listenerObject.getuId() != null); - } - - /** - * null resInterface - */ - public void testGet_N01() - { - boolean result = false; - ListenerObject listenerObject = null; - lockObject = new CountDownLatch(1); - - try - { - listenerObject = new ListenerObject(); - GetListener onGetListener = new GetListener(lockObject, listenerObject); - - simulatorRemoteResource.get(null, null, onGetListener); - result = false; - } - catch(Exception e) - { - result = true; - } - - try - { - lockObject.await(10, TimeUnit.SECONDS); - } - catch (InterruptedException e) - { - } - - assertTrue(result); - } - - /** - * null listener - */ - public void testGet_N02() - { - boolean result = false; - try - { - String resInterface = simulatorRemoteResource.getResourceInterfaces().get(0); - - if(resInterface != null) - { - simulatorRemoteResource.get( resInterface,null, null); - } - - result = false; - } - catch(Exception e) - { - result = true; - } - - assertTrue(result); - } - - /** - * all params as null - */ - public void testGet_N03() - { - boolean result = false; - try - { - simulatorRemoteResource.get(null, null, null); - result = false; - } - catch(Exception e) - { - result = true; - } - - assertTrue(result); - } - - public void testGetWithoutResInterface_P01() - { - boolean result = true; - ListenerObject listenerObject = null; - lockObject = new CountDownLatch(1); - - try - { - listenerObject = new ListenerObject(); - GetListener onGetListener = new GetListener(lockObject, listenerObject); - - simulatorRemoteResource.get(null, onGetListener); - } - catch(Exception e) - { - result = false; - } - - try - { - lockObject.await(10, TimeUnit.SECONDS); - } - catch (InterruptedException e) - { - } - - assertTrue(result && listenerObject != null && listenerObject.getRepresentation() != null && listenerObject.getuId() != null); - } - - /** - * null listener - */ - public void testGetWithoutResInterface_N01() - { - boolean result = false; - try - { - simulatorRemoteResource.get(null, null); - result = false; - } - catch(Exception e) - { - result = true; - } - - assertTrue(result); - } - - public void testSetConfigInfo_P01() - { - boolean result = true; - try - { - simulatorRemoteResource.setConfigInfo(CONFIG_PATH); - } - catch (Exception e2) - { - e2.printStackTrace(); - result = false; - } - - lockObject = new CountDownLatch(1); - VerifyListenerObject verifyListenerObject = new VerifyListenerObject(); - VerifyListener verifyListener = new VerifyListener(lockObject, verifyListenerObject); - - try - { - simulatorRemoteResource.startVerification(SimulatorVerificationType.RQ_TYPE_POST, verifyListener); - } - catch (Exception e1) - { - e1.printStackTrace(); - result = false; - } - - try - { - lockObject.await(10, TimeUnit.MILLISECONDS); - } - catch (InterruptedException e) - { - } - - assertTrue(result && verifyListenerObject.getWhichOne().equals("started")&& - verifyListenerObject.getuId() != null && - verifyListenerObject.getId() != -1); - } - - /** - * Passing empty - */ - public void testSetConfigInfo_N01() - { - boolean result = true; - try - { - simulatorRemoteResource.setConfigInfo(""); - result = false; - } - catch (Exception e2) - { - result = true; - } - - assertTrue(result); - } - - public void testStartVerification_P01() - { - boolean result = true; - lockObject = new CountDownLatch(1); - try - { - simulatorRemoteResource.setConfigInfo(CONFIG_PATH); - } - catch (Exception e1) - { - e1.printStackTrace(); - result = false; - } - - VerifyListenerObject verifyListenerObject = new VerifyListenerObject(); - VerifyListener verifyListener = new VerifyListener(lockObject, verifyListenerObject); - try - { - result = result && simulatorRemoteResource.startVerification(SimulatorVerificationType.RQ_TYPE_POST, verifyListener) != -1; - } - catch (Exception e1) - { - e1.printStackTrace(); - result = false; - } - - try - { - lockObject.await(10, TimeUnit.MILLISECONDS); - } - catch (InterruptedException e) - { - } - - assertTrue(result && verifyListenerObject.getWhichOne().equals("started") && - verifyListenerObject.getuId() != null && - verifyListenerObject.getId() != -1); - } - - public void testStartVerification_P02() - { - boolean result = true; - lockObject = new CountDownLatch(1); - try - { - simulatorRemoteResource.setConfigInfo(CONFIG_PATH); - } - catch (Exception e1) - { - e1.printStackTrace(); - result = false; - } - - VerifyListenerObject verifyListenerObject = new VerifyListenerObject(); - VerifyListener verifyListener = new VerifyListener(lockObject, verifyListenerObject); - try - { - result = result && simulatorRemoteResource.startVerification(SimulatorVerificationType.RQ_TYPE_PUT, verifyListener) != -1; - } - catch (Exception e1) - { - e1.printStackTrace(); - result = false; - } - - try - { - lockObject.await(10, TimeUnit.MILLISECONDS); - } - catch (InterruptedException e) - { - } - - assertTrue(result && verifyListenerObject.getWhichOne().equals("started") && - verifyListenerObject.getuId() != null && - verifyListenerObject.getId() != -1); - } - - public void testStartVerification_P03() - { - boolean result = true; - lockObject = new CountDownLatch(1); - try - { - simulatorRemoteResource.setConfigInfo(CONFIG_PATH); - } - catch (Exception e1) - { - e1.printStackTrace(); - result = false; - } - - VerifyListenerObject verifyListenerObject = new VerifyListenerObject(); - VerifyListener verifyListener = new VerifyListener(lockObject, verifyListenerObject); - try - { - result = result && simulatorRemoteResource.startVerification(SimulatorVerificationType.RQ_TYPE_GET, verifyListener) != -1; - } - catch (Exception e1) - { - e1.printStackTrace(); - result = false; - } - - try - { - lockObject.await(10, TimeUnit.MILLISECONDS); - } - catch (InterruptedException e) - { - } - - assertTrue(result && verifyListenerObject.getWhichOne().equals("started") && - verifyListenerObject.getuId() != null && - verifyListenerObject.getId() != -1); - } - - /** - * setting listener to null - */ - public void testStartVerification_N01() - { - boolean result = true; - try - { - simulatorRemoteResource.setConfigInfo(CONFIG_PATH); - } - catch (Exception e) - { - e.printStackTrace(); - result = false; - } - - try - { - result = result && (simulatorRemoteResource.startVerification(SimulatorVerificationType.RQ_TYPE_POST, null) == -1); - result = false; - } - catch (Exception e) - { - result = true; - } - assertTrue(result); - } - - public void testStopVerification_P01() - { - boolean result = true; - lockObject = new CountDownLatch(2); - try - { - simulatorRemoteResource.setConfigInfo(CONFIG_PATH); - } - catch (Exception e1) - { - e1.printStackTrace(); - result = false; - } - - VerifyListenerObject verifyListenerObject = new VerifyListenerObject(); - VerifyListener verifyListener = new VerifyListener(lockObject, verifyListenerObject); - try - { - result = result && simulatorRemoteResource.startVerification(SimulatorVerificationType.RQ_TYPE_POST, verifyListener) != -1; - } - catch (Exception e1) - { - e1.printStackTrace(); - result = false; - } - - try - { - lockObject.await(10, TimeUnit.MILLISECONDS); - } - catch (InterruptedException e) - { - } - - result = result && verifyListenerObject.getWhichOne().equals("started") && - verifyListenerObject.getuId() != null && - verifyListenerObject.getId() != -1; - - try - { - simulatorRemoteResource.stopVerification(verifyListenerObject.getId()); - } - catch (Exception e1) - { - e1.printStackTrace(); - result = false; - } - - try - { - lockObject.await(100, TimeUnit.MILLISECONDS); - } - catch (InterruptedException e) - { - } - - assertTrue(result && verifyListenerObject.getWhichOne().equals("aborted") && - verifyListenerObject.getuId() != null && - verifyListenerObject.getId() != -1); - } - - /** - * Random id. This is just to check the crash - */ - public void testStopVerification_N01() - { - boolean result = true; - lockObject = new CountDownLatch(1); - try - { - simulatorRemoteResource.setConfigInfo(CONFIG_PATH); - } - catch (Exception e2) - { - result = false; - e2.printStackTrace(); - } - - VerifyListenerObject verifyListenerObject = new VerifyListenerObject(); - VerifyListener verifyListener = new VerifyListener(lockObject, verifyListenerObject); - try - { - result = result && simulatorRemoteResource.startVerification(SimulatorVerificationType.RQ_TYPE_POST, verifyListener) != -1; - } - catch (Exception e1) - { - e1.printStackTrace(); - result = false; - } - - try - { - lockObject.await(10, TimeUnit.SECONDS); - } - catch (InterruptedException e) - { - } - - result = result && verifyListenerObject.getWhichOne().equals("started") && - verifyListenerObject.getuId() != null && - verifyListenerObject.getId() != -1; - - try - { - simulatorRemoteResource.stopVerification(123435); - result = false; - } - catch (Exception e) - { - result = true; - } - - assertTrue(result); - } -} diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/VerifyListener.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/VerifyListener.java deleted file mode 100644 index 2e16ef5..0000000 --- a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/VerifyListener.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.oic.simulator.clientcontroller.test; - -import java.util.concurrent.CountDownLatch; - -import org.oic.simulator.clientcontroller.IVerificationListener; - -/** - * This class implements listeners for getting verification - * status callbacks. - */ -public class VerifyListener implements IVerificationListener -{ - - private CountDownLatch lockObject; - private VerifyListenerObject verifyListenerObject; - - public VerifyListener(CountDownLatch lockObject, VerifyListenerObject verifyListenerObject) - { - this.lockObject = lockObject; - this.verifyListenerObject = verifyListenerObject; - } - - @Override - public void onVerificationStarted(String uId, int id) - { - verifyListenerObject.setId(id); - verifyListenerObject.setuId(uId); - verifyListenerObject.setWhichOne("started"); - - lockObject.countDown(); - } - - @Override - public void onVerificationAborted(String uId, int id) - { - verifyListenerObject.setId(id); - verifyListenerObject.setuId(uId); - verifyListenerObject.setWhichOne("aborted"); - - lockObject.countDown(); - } - - @Override - public void onVerificationCompleted(String uId, int id) - { - verifyListenerObject.setId(id); - verifyListenerObject.setuId(uId); - verifyListenerObject.setWhichOne("completed"); - - lockObject.countDown(); - } -} diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/VerifyListenerObject.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/VerifyListenerObject.java deleted file mode 100644 index 45a2eaf..0000000 --- a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/VerifyListenerObject.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.oic.simulator.clientcontroller.test; - -/** - * This class tests the functionality of getting/setting - * verification ID. - */ -public class VerifyListenerObject -{ - - private String uId; - private int id; - private String whichOne; - - public void setuId(String uId) - { - this.uId = uId; - } - - public String getuId() - { - return uId; - } - - public void setId(int id) - { - this.id = id; - } - - public int getId() - { - return id; - } - - public void setWhichOne(String whichOne) - { - this.whichOne = whichOne; - } - - public String getWhichOne() - { - return whichOne; - } -} diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/server/test/SimulatorCollectionResourceTest.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/server/test/SimulatorCollectionResourceTest.java new file mode 100644 index 0000000..475b708 --- /dev/null +++ b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/server/test/SimulatorCollectionResourceTest.java @@ -0,0 +1,301 @@ +/* + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.oic.simulator.server.test; + +import java.util.Vector; + +import org.oic.simulator.InvalidArgsException; +import org.oic.simulator.SimulatorException; +import org.oic.simulator.SimulatorManager; +import org.oic.simulator.SimulatorResourceModel; +import org.oic.simulator.server.SimulatorCollectionResource; +import org.oic.simulator.server.SimulatorResource; +import org.oic.simulator.test.ExceptionType; + +import junit.framework.TestCase; + +public class SimulatorCollectionResourceTest extends TestCase { + static { + System.loadLibrary("SimulatorManager"); + System.loadLibrary("RamlParser"); + System.loadLibrary("oc"); + System.loadLibrary("oc_logger"); + System.loadLibrary("octbstack"); + } + + private static final String COLLECTION_RES_RAML = "./ramls/oic.d.airconditioner.raml"; + private SimulatorCollectionResource collectionResource = null; + + protected void setUp() throws Exception { + super.setUp(); + collectionResource = (SimulatorCollectionResource) SimulatorManager + .createResource(COLLECTION_RES_RAML); + } + + protected void tearDown() throws Exception { + super.tearDown(); + collectionResource = null; + } + + public void testAddChildResource_P01() { + SimulatorResource childResource = null; + + try { + String name = "child-resource"; + String uri = "/child/resource"; + String resType = "child.resource"; + + childResource = SimulatorManager.createResource( + SimulatorResource.Type.SINGLE, name, uri, resType); + } catch (InvalidArgsException e1) { + e1.printStackTrace(); + } catch (SimulatorException e1) { + e1.printStackTrace(); + } + + if (null == childResource) + return; + + Vector result = null; + try { + collectionResource.addChildResource(childResource); + result = collectionResource.getChildResource(); + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertNotNull(result); + assertEquals(1, result.size()); + } + + public void testAddChildResource_P02() { + SimulatorResource childResource = null; + + try { + String name = "child-resource"; + String uri = "/child/resource"; + String resType = "child.resource"; + + childResource = SimulatorManager.createResource( + SimulatorResource.Type.COLLECTION, name, uri, resType); + } catch (InvalidArgsException e1) { + e1.printStackTrace(); + } catch (SimulatorException e1) { + e1.printStackTrace(); + } + + if (null == childResource) + return; + + Vector result = null; + try { + collectionResource.addChildResource(childResource); + result = collectionResource.getChildResource(); + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertNotNull(result); + assertEquals(1, result.size()); + } + + public void testAddChildResource_P03() { + SimulatorResource childResource1 = null; + SimulatorResource childResource2 = null; + + try { + String name = "child-resource"; + String uri = "/child/resource"; + String resType = "child.resource"; + + childResource1 = SimulatorManager.createResource( + SimulatorResource.Type.SINGLE, name, uri, resType); + childResource2 = SimulatorManager.createResource( + SimulatorResource.Type.COLLECTION, name + "-2", uri + "/2", + resType); + } catch (InvalidArgsException e1) { + e1.printStackTrace(); + } catch (SimulatorException e1) { + e1.printStackTrace(); + } + + if (null == childResource1 || null == childResource2) + return; + + Vector result = null; + try { + collectionResource.addChildResource(childResource1); + collectionResource.addChildResource(childResource2); + result = collectionResource.getChildResource(); + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertNotNull(result); + assertEquals(2, result.size()); + } + + public void testAddChildResource_N01() { + ExceptionType exType = ExceptionType.UNKNOWN; + + try { + collectionResource.addChildResource(null); + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; + } + + assertTrue(exType == ExceptionType.INVALID_ARGS); + } + + public void testRemoveChildResource_P01() { + SimulatorResource childResource = null; + Vector result = null; + + try { + String name = "child-resource"; + String uri = "/child/resource"; + String resType = "child.resource"; + + childResource = SimulatorManager.createResource( + SimulatorResource.Type.COLLECTION, name, uri, resType); + collectionResource.addChildResource(childResource); + result = collectionResource.getChildResource(); + } catch (InvalidArgsException e1) { + e1.printStackTrace(); + } catch (SimulatorException e1) { + e1.printStackTrace(); + } + + if (null == childResource || null == result) + return; + + int count = result.size(); + try { + collectionResource.removeChildResource(childResource); + result = collectionResource.getChildResource(); + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertTrue((count == 1 && result == null) + || (count > 1 && result.size() == count - 1)); + } + + public void testRemoveChildResource_N01() { + ExceptionType exType = ExceptionType.UNKNOWN; + + try { + collectionResource.removeChildResource(null); + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; + } + + assertTrue(exType == ExceptionType.INVALID_ARGS); + } + + public void testRemoveChildResourceByUri_P01() { + SimulatorResource childResource = null; + Vector result = null; + + try { + String name = "child-resource"; + String uri = "/child/resource"; + String resType = "child.resource"; + + childResource = SimulatorManager.createResource( + SimulatorResource.Type.COLLECTION, name, uri, resType); + collectionResource.addChildResource(childResource); + result = collectionResource.getChildResource(); + } catch (InvalidArgsException e1) { + e1.printStackTrace(); + } catch (SimulatorException e1) { + e1.printStackTrace(); + } + + if (null == childResource || null == result) + return; + + int count = result.size(); + try { + collectionResource.removeChildResourceByUri(childResource.getURI()); + result = collectionResource.getChildResource(); + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertTrue((count == 1 && result == null) + || (count > 1 && result.size() == count - 1)); + } + + public void testRemoveChildResourceByUri_N01() { + ExceptionType exType = ExceptionType.UNKNOWN; + + try { + collectionResource.removeChildResourceByUri(null); + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; + } + + assertTrue(exType == ExceptionType.INVALID_ARGS); + } + + public void testRemoveChildResourceByUri_N02() { + ExceptionType exType = ExceptionType.UNKNOWN; + + try { + String uri = ""; + collectionResource.removeChildResourceByUri(uri); + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; + } + + assertTrue(exType == ExceptionType.INVALID_ARGS); + } + + public void testGetResourceModel_P01() { + SimulatorResourceModel result = null; + + try { + result = collectionResource.getResourceModel(); + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertNotNull(result); + assertTrue(result.size() > 0); + } +} diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/server/test/SimulatorResourceTest.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/server/test/SimulatorResourceTest.java new file mode 100644 index 0000000..33cde70 --- /dev/null +++ b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/server/test/SimulatorResourceTest.java @@ -0,0 +1,419 @@ +/* + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.oic.simulator.server.test; + +import java.util.Vector; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import org.oic.simulator.InvalidArgsException; +import org.oic.simulator.SimulatorException; +import org.oic.simulator.SimulatorManager; +import org.oic.simulator.client.FindResourceListener; +import org.oic.simulator.client.SimulatorRemoteResource; +import org.oic.simulator.server.SimulatorResource; +import org.oic.simulator.test.ExceptionType; +import org.oic.simulator.utils.ObjectHolder; + +import junit.framework.TestCase; + +/** + * This class tests the APIs of SimulatorResource class + */ +public class SimulatorResourceTest extends TestCase { + private static final String RES_NAME = "test-resource"; + private static final String RES_URI = "/test/resource"; + private static final String RES_TYPE = "test.resource"; + private SimulatorResource resource = null; + + static { + System.loadLibrary("SimulatorManager"); + System.loadLibrary("RamlParser"); + System.loadLibrary("oc"); + System.loadLibrary("oc_logger"); + System.loadLibrary("octbstack"); + } + + protected void setUp() throws Exception { + super.setUp(); + resource = SimulatorManager.createResource( + SimulatorResource.Type.SINGLE, RES_NAME, RES_URI, RES_TYPE); + } + + protected void tearDown() throws Exception { + super.tearDown(); + resource = null; + } + + public void testGetName_P01() { + String name = null; + + try { + name = resource.getName(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertEquals(RES_NAME, name); + } + + public void testGetType_P01() { + SimulatorResource.Type type = SimulatorResource.Type.SINGLE; + + try { + type = resource.getType(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertEquals(SimulatorResource.Type.SINGLE, type); + } + + public void testGetURI_P01() { + String uri = null; + + try { + uri = resource.getURI(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertEquals(RES_URI, uri); + } + + public void testGetResourceType_P01() { + String resType = null; + + try { + resType = resource.getResourceType(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertEquals(RES_TYPE, resType); + } + + public void testGetInterface_P01() { + Vector interfaces = null; + + try { + interfaces = resource.getInterface(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertNotNull(interfaces); + assertTrue(interfaces.size() > 0); + } + + public void testSetName_P01() { + String name = "new-name"; + String newName = null; + + try { + resource.setName(name); + newName = resource.getName(); + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertEquals(name, newName); + } + + public void testSetName_N01() { + String newName = ""; + ExceptionType exType = ExceptionType.UNKNOWN; + + try { + resource.setName(newName); + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; + } + + assertEquals(ExceptionType.INVALID_ARGS, exType); + } + + public void testSetName_N02() { + String newName = null; + ExceptionType exType = ExceptionType.UNKNOWN; + + try { + resource.setName(newName); + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; + } + + assertEquals(ExceptionType.INVALID_ARGS, exType); + } + + public void testSetURI_P01() { + String newUri = "/test/newuri/1"; + String uri = null; + + try { + resource.setURI(newUri); + uri = resource.getURI(); + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertEquals(newUri, uri); + } + + public void testSetURI_N01() { + String newUri = ""; + ExceptionType exType = ExceptionType.UNKNOWN; + + try { + resource.setURI(newUri); + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; + } + + assertEquals(ExceptionType.INVALID_ARGS, exType); + } + + public void testSetURI_N02() { + String newUri = null; + ExceptionType exType = ExceptionType.UNKNOWN; + + try { + resource.setURI(newUri); + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; + } + + assertEquals(ExceptionType.INVALID_ARGS, exType); + } + + public void testSetResourceType_P01() { + String newResType = "test.newresource"; + String resType = null; + + try { + resource.setResourceType(newResType); + resType = resource.getResourceType(); + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertEquals(newResType, resType); + } + + public void testSetResourceType_N01() { + String newResType = ""; + ExceptionType exType = ExceptionType.UNKNOWN; + + try { + resource.setResourceType(newResType); + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; + } + + assertEquals(ExceptionType.INVALID_ARGS, exType); + } + + public void testSetResourceType_N02() { + String newResType = null; + ExceptionType exType = ExceptionType.UNKNOWN; + + try { + resource.setResourceType(newResType); + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; + } + + assertEquals(ExceptionType.INVALID_ARGS, exType); + } + + public void testSetObservable_P01() { + boolean newState = true; + boolean state = false; + try { + resource.setObservable(newState); + state = resource.isObservable(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertEquals(newState, state); + } + + public void testSetObservable_P02() { + boolean newState = false; + boolean state = true; + try { + resource.setObservable(newState); + state = resource.isObservable(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertEquals(newState, state); + } + + public void testIsObservable_P01() { + boolean state = false; + + try { + state = resource.isObservable(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertEquals(true, state); + } + + public void testIsStarted_P01() { + boolean state = true; + + try { + state = resource.isStarted(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertEquals(false, state); + } + + public void testIsStarted_P02() { + boolean state = false; + + try { + resource.start(); + state = resource.isStarted(); + resource.stop(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertEquals(true, state); + } + + public void testIsStarted_P03() { + boolean state = true; + + try { + resource.start(); + resource.stop(); + state = resource.isStarted(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertEquals(false, state); + } + + public void testStart_P01() { + CountDownLatch lockObject = new CountDownLatch(1); + ObjectHolder resourceHolder = new ObjectHolder<>(); + FindResourceCallbackListener listener = new FindResourceCallbackListener( + lockObject, resourceHolder); + + try { + resource.start(); + SimulatorManager.findResource(resource.getResourceType(), listener); + + // Wait for the resource to found + try { + lockObject.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + try { + resource.stop(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertNotNull(resourceHolder.get()); + } + + public void testStop_P01() { + CountDownLatch lockObject = new CountDownLatch(1); + ObjectHolder resourceHolder = new ObjectHolder<>(); + FindResourceCallbackListener listener = new FindResourceCallbackListener( + lockObject, resourceHolder); + + try { + resource.start(); + resource.stop(); + SimulatorManager.findResource(resource.getResourceType(), listener); + + // Wait for the resource to found + try { + lockObject.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + try { + resource.stop(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertNull(resourceHolder.get()); + } +} + +class FindResourceCallbackListener implements FindResourceListener { + + private CountDownLatch mLockObject; + private ObjectHolder mResourceHolder; + + public FindResourceCallbackListener(CountDownLatch lockObject, + ObjectHolder resourceHolder) { + mLockObject = lockObject; + mResourceHolder = resourceHolder; + } + + @Override + public void onResourceFound(SimulatorRemoteResource resource) { + mResourceHolder.set(resource); + mLockObject.countDown(); + } +} \ No newline at end of file diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/server/test/SimulatorSingleResourceTest.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/server/test/SimulatorSingleResourceTest.java new file mode 100644 index 0000000..b6bcc94 --- /dev/null +++ b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/server/test/SimulatorSingleResourceTest.java @@ -0,0 +1,649 @@ +/* + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.oic.simulator.server.test; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import org.oic.simulator.AttributeProperty; +import org.oic.simulator.AttributeValue; +import org.oic.simulator.InvalidArgsException; +import org.oic.simulator.SimulatorException; +import org.oic.simulator.SimulatorManager; +import org.oic.simulator.SimulatorResourceAttribute; +import org.oic.simulator.SimulatorResourceModel; +import org.oic.simulator.server.SimulatorResource; +import org.oic.simulator.server.SimulatorResource.AutoUpdateListener; +import org.oic.simulator.server.SimulatorSingleResource; +import org.oic.simulator.test.ExceptionType; +import org.oic.simulator.utils.ObjectHolder; + +import junit.framework.TestCase; + +public class SimulatorSingleResourceTest extends TestCase { + static { + System.loadLibrary("SimulatorManager"); + System.loadLibrary("RamlParser"); + System.loadLibrary("oc"); + System.loadLibrary("oc_logger"); + System.loadLibrary("octbstack"); + } + + private static final String SINGLE_RES_RAML = "./ramls/oic.r.light.raml"; + private static final String INT_KEY = "Interger"; + private static final String DOUBLE_KEY = "Double"; + private static final String BOOL_KEY = "Boolean"; + private static final String STRING_KEY = "String"; + private SimulatorSingleResource singleResource = null; + + protected void setUp() throws Exception { + super.setUp(); + singleResource = (SimulatorSingleResource) SimulatorManager + .createResource(SimulatorResource.Type.SINGLE, "test-resource", + "/test/resource", "test.resource"); + } + + protected void tearDown() throws Exception { + super.tearDown(); + singleResource = null; + } + + SimulatorSingleResource createResourceFromRAML() { + try { + return (SimulatorSingleResource) SimulatorManager + .createResource(SINGLE_RES_RAML); + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + return null; + } + + public void testGetResourceModel_P01() { + SimulatorResourceModel resModel = null; + + try { + SimulatorSingleResource resource = createResourceFromRAML(); + resModel = resource.getResourceModel(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertNotNull(resModel); + assertTrue(resModel.size() > 0); + } + + public void testAddAttributeInteger_P01() { + int result = -1; + + try { + SimulatorResourceAttribute attribute = new SimulatorResourceAttribute( + INT_KEY, new AttributeValue(2), null); + singleResource.addAttribute(attribute); + result = ((Integer) singleResource.getAttribute(INT_KEY).value() + .get()).intValue(); + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertEquals(2, result); + } + + public void testAddAttributeDouble_P01() { + double result = 0.0; + + try { + SimulatorResourceAttribute attribute = new SimulatorResourceAttribute( + DOUBLE_KEY, new AttributeValue(4.0), null); + singleResource.addAttribute(attribute); + result = ((Double) singleResource.getAttribute(DOUBLE_KEY).value() + .get()).doubleValue(); + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertEquals(4.0, result); + } + + public void testAddAttributeBoolean_P01() { + boolean result = false; + + try { + SimulatorResourceAttribute attribute = new SimulatorResourceAttribute( + BOOL_KEY, new AttributeValue(true), null); + singleResource.addAttribute(attribute); + result = ((Boolean) singleResource.getAttribute(BOOL_KEY).value() + .get()).booleanValue(); + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertEquals(true, result); + } + + public void testaddAttributeString_P01() { + String result = null; + + try { + SimulatorResourceAttribute attribute = new SimulatorResourceAttribute( + STRING_KEY, new AttributeValue("string-value"), null); + singleResource.addAttribute(attribute); + result = (String) singleResource.getAttribute(STRING_KEY).value() + .get(); + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertEquals("string-value", result); + } + + public void testUpdateAttributeInteger_P01() { + int result = -1; + + try { + SimulatorResourceAttribute attribute = new SimulatorResourceAttribute( + INT_KEY, new AttributeValue(10), null); + singleResource.addAttribute(attribute); + singleResource.updateAttribute(INT_KEY, new AttributeValue(12)); + result = ((Integer) singleResource.getAttribute(INT_KEY).value() + .get()).intValue(); + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertEquals(12, result); + } + + public void testUpdateAttributeDouble_P01() { + double result = 0.0; + + try { + SimulatorResourceAttribute attribute = new SimulatorResourceAttribute( + DOUBLE_KEY, new AttributeValue(22.0), null); + singleResource.addAttribute(attribute); + singleResource + .updateAttribute(DOUBLE_KEY, new AttributeValue(25.3)); + result = ((Double) singleResource.getAttribute(DOUBLE_KEY).value() + .get()).doubleValue(); + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertEquals(25.3, result); + } + + public void testUpdateAttributeBoolean_P01() { + boolean result = true; + + try { + SimulatorResourceAttribute attribute = new SimulatorResourceAttribute( + BOOL_KEY, new AttributeValue(true), null); + singleResource.addAttribute(attribute); + singleResource.updateAttribute(BOOL_KEY, new AttributeValue(false)); + result = ((Boolean) singleResource.getAttribute(BOOL_KEY).value() + .get()).booleanValue(); + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertEquals(false, result); + } + + public void testupdateAttributeString_P01() { + String result = null; + + try { + SimulatorResourceAttribute attribute = new SimulatorResourceAttribute( + STRING_KEY, new AttributeValue("old-value"), null); + singleResource.addAttribute(attribute); + singleResource.updateAttribute(STRING_KEY, new AttributeValue( + "new-value")); + result = (String) singleResource.getAttribute(STRING_KEY).value() + .get(); + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertEquals("new-value", result); + } + + public void testSetRange_P01() { + int result = -1; + + try { + SimulatorResourceAttribute attribute = new SimulatorResourceAttribute( + INT_KEY, new AttributeValue(10), new AttributeProperty(1, + 12)); + singleResource.addAttribute(attribute); + singleResource.updateAttribute(INT_KEY, new AttributeValue(3)); + result = ((Integer) singleResource.getAttribute(INT_KEY).value() + .get()).intValue(); + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertEquals(3, result); + } + + public void testSetRange_N01() { + int result = -1; + + try { + SimulatorResourceAttribute attribute = new SimulatorResourceAttribute( + INT_KEY, new AttributeValue(10), new AttributeProperty(1, + 12)); + singleResource.addAttribute(attribute); + singleResource.updateAttribute(INT_KEY, new AttributeValue(13)); + result = ((Integer) singleResource.getAttribute(INT_KEY).value() + .get()).intValue(); + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertEquals(10, result); + } + + public void testSetAllowedValuesInteger_P01() { + int result = -1; + + try { + int[] values = { 1, 10, 20, 50 }; + SimulatorResourceAttribute attribute = new SimulatorResourceAttribute( + INT_KEY, new AttributeValue(10), new AttributeProperty( + values)); + singleResource.addAttribute(attribute); + singleResource.updateAttribute(INT_KEY, new AttributeValue(20)); + result = ((Integer) singleResource.getAttribute(INT_KEY).value() + .get()).intValue(); + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertEquals(20, result); + } + + public void testSetAllowedValuesInteger_N01() { + int result = -1; + + try { + int[] values = { 1, 10, 20, 50 }; + SimulatorResourceAttribute attribute = new SimulatorResourceAttribute( + INT_KEY, new AttributeValue(10), new AttributeProperty( + values)); + singleResource.addAttribute(attribute); + singleResource.updateAttribute(INT_KEY, new AttributeValue(15)); + result = ((Integer) singleResource.getAttribute(INT_KEY).value() + .get()).intValue(); + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertEquals(10, result); + } + + public void testSetAllowedValuesDouble_P01() { + double result = 0.0; + + try { + double[] values = { 11.5, 10.5, 20.5, 50.5 }; + SimulatorResourceAttribute attribute = new SimulatorResourceAttribute( + DOUBLE_KEY, new AttributeValue(11.5), + new AttributeProperty(values)); + singleResource.addAttribute(attribute); + singleResource + .updateAttribute(DOUBLE_KEY, new AttributeValue(10.5)); + result = ((Double) singleResource.getAttribute(DOUBLE_KEY).value() + .get()).doubleValue(); + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertEquals(10.5, result); + } + + public void testSetAllowedValuesDouble_N01() { + double result = 0.0; + + try { + double[] values = { 11.5, 10.5, 20.5, 50.5 }; + SimulatorResourceAttribute attribute = new SimulatorResourceAttribute( + DOUBLE_KEY, new AttributeValue(11.5), + new AttributeProperty(values)); + singleResource.addAttribute(attribute); + singleResource.updateAttribute(DOUBLE_KEY, new AttributeValue(2.2)); + result = ((Double) singleResource.getAttribute(DOUBLE_KEY).value() + .get()).doubleValue(); + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertEquals(11.5, result); + } + + public void testsetAllowedValuesString_P01() { + String result = null; + + try { + String[] values = { "monday", "tuesday", "wednesday" }; + SimulatorResourceAttribute attribute = new SimulatorResourceAttribute( + STRING_KEY, new AttributeValue("monday"), + new AttributeProperty(values)); + singleResource.addAttribute(attribute); + singleResource.updateAttribute(STRING_KEY, new AttributeValue( + "tuesday")); + result = (String) singleResource.getAttribute(STRING_KEY).value() + .get(); + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertEquals("tuesday", result); + } + + public void testsetAllowedValuesString_N01() { + String result = null; + + try { + String[] values = { "monday", "tuesday", "wednesday" }; + SimulatorResourceAttribute attribute = new SimulatorResourceAttribute( + STRING_KEY, new AttributeValue("monday"), + new AttributeProperty(values)); + singleResource.addAttribute(attribute); + singleResource.updateAttribute(STRING_KEY, new AttributeValue( + "friday")); + result = (String) singleResource.getAttribute(STRING_KEY).value() + .get(); + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertEquals("monday", result); + } + + public void testRemoveAttribute_P01() { + SimulatorResourceAttribute result = null; + + try { + SimulatorResourceAttribute attribute = new SimulatorResourceAttribute( + STRING_KEY, new AttributeValue("friday"), null); + singleResource.addAttribute(attribute); + singleResource.removeAttribute(STRING_KEY); + result = singleResource.getAttribute(STRING_KEY); + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertNull(result); + } + + public void testRemoveAttribute_N02() { + ExceptionType exType = ExceptionType.UNKNOWN; + + try { + SimulatorResourceAttribute attribute = new SimulatorResourceAttribute( + STRING_KEY, new AttributeValue("friday"), null); + singleResource.addAttribute(attribute); + singleResource.removeAttribute(null); + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; + } + + assertEquals(ExceptionType.INVALID_ARGS, exType); + } + + public void testRemoveAttribute_N03() { + ExceptionType exType = ExceptionType.UNKNOWN; + + try { + singleResource.removeAttribute(""); + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; + } + + assertEquals(ExceptionType.INVALID_ARGS, exType); + } + + public void testStartResourceAutomation_P01() { + SimulatorSingleResource resource = createResourceFromRAML(); + if (null == resource) + return; + + CountDownLatch lockObject = new CountDownLatch(1); + ObjectHolder autoUpdateHolder = new ObjectHolder<>(); + AutoUpdateCompleteListener automationListener = new AutoUpdateCompleteListener( + lockObject, autoUpdateHolder); + int id = -1; + + try { + resource.start(); + id = resource.startResourceUpdation( + SimulatorResource.AutoUpdateType.REPEAT, 1000, + automationListener); + + try { + lockObject.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + resource.stopUpdation(id); + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + try { + resource.stop(); + resource.stopUpdation(id); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertNotNull(autoUpdateHolder.get()); + assertEquals(id, autoUpdateHolder.get().getId()); + } + + public void testStartResourceAutomation_N01() { + ExceptionType exType = ExceptionType.UNKNOWN; + + try { + singleResource.startResourceUpdation( + SimulatorResource.AutoUpdateType.ONE_TIME, 500, null); + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; + } + + assertEquals(ExceptionType.INVALID_ARGS, exType); + } + + public void testStartAttributeAutomation_P01() { + SimulatorSingleResource resource = createResourceFromRAML(); + if (null == resource) + return; + + String attributeName = null; + try { + for (SimulatorResourceAttribute resAttribute : resource + .getResourceModel().getAttributes().values()) + attributeName = resAttribute.name(); + } catch (SimulatorException e1) { + e1.printStackTrace(); + } + + if (null == attributeName) + return; + + CountDownLatch lockObject = new CountDownLatch(1); + ObjectHolder autoUpdateHolder = new ObjectHolder<>(); + AutoUpdateCompleteListener automationListener = new AutoUpdateCompleteListener( + lockObject, autoUpdateHolder); + int id = -1; + + try { + resource.start(); + id = resource.startAttributeUpdation(attributeName, + SimulatorResource.AutoUpdateType.REPEAT, 100, + automationListener); + + try { + lockObject.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + resource.stopUpdation(id); + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + try { + resource.stop(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertNotNull(autoUpdateHolder.get()); + assertEquals(id, autoUpdateHolder.get().getId()); + } + + public void testStartAttributeAutomation_N01() { + ExceptionType exType = ExceptionType.UNKNOWN; + + try { + singleResource.startAttributeUpdation("intensity", + SimulatorResource.AutoUpdateType.ONE_TIME, 1000, null); + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; + } + + assertEquals(ExceptionType.INVALID_ARGS, exType); + } + + public void testStopUpdation_P01() { + SimulatorSingleResource resource = createResourceFromRAML(); + if (null == resource) + return; + + CountDownLatch lockObject = new CountDownLatch(1); + ObjectHolder autoUpdateHolder = new ObjectHolder<>(); + AutoUpdateCompleteListener automationListener = new AutoUpdateCompleteListener( + lockObject, autoUpdateHolder); + boolean result = false; + try { + resource.start(); + int id = resource.startResourceUpdation( + SimulatorResource.AutoUpdateType.REPEAT, 1000, + automationListener); + resource.stopUpdation(id); + result = true; + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + try { + resource.stop(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertTrue(result); + } +} + +class AutoUpdateInfo { + private String uri = null; + private int id = -1; + + AutoUpdateInfo(String uri, int id) { + this.uri = uri; + this.id = id; + } + + public String getUri() { + return uri; + } + + public int getId() { + return id; + } +} + +class AutoUpdateCompleteListener implements AutoUpdateListener { + private CountDownLatch lock; + private ObjectHolder autoUpdateHolder; + + public AutoUpdateCompleteListener(CountDownLatch lock, + ObjectHolder autoUpdateHolder) { + this.lock = lock; + this.autoUpdateHolder = autoUpdateHolder; + } + + @Override + public void onUpdateComplete(String uri, int id) { + autoUpdateHolder.set(new AutoUpdateInfo(uri, id)); + lock.countDown(); + } +} \ No newline at end of file diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/serviceprovider/test/AutomationListener.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/serviceprovider/test/AutomationListener.java deleted file mode 100644 index cb545db..0000000 --- a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/serviceprovider/test/AutomationListener.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.oic.simulator.serviceprovider.test; - -import java.util.concurrent.CountDownLatch; -import org.oic.simulator.IAutomation; - -/** - * This class implements methods for receiving notifications on - * completion of automation. - */ -public class AutomationListener implements IAutomation -{ - - private CountDownLatch lockObject; - private AutomationObject automationObject; - - public AutomationListener(CountDownLatch lockObject, AutomationObject automationObject) - { - this.lockObject = lockObject; - this.automationObject = automationObject; - } - - @Override - public void onAutomationComplete(String resourceURI, int automationId) - { - automationObject.setAutomationId(automationId); - automationObject.setResourceURI(resourceURI); - - lockObject.countDown(); - } -} diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/serviceprovider/test/Observer.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/serviceprovider/test/Observer.java deleted file mode 100644 index ca69964..0000000 --- a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/serviceprovider/test/Observer.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.oic.simulator.serviceprovider.test; - -import java.util.concurrent.CountDownLatch; - -import org.oic.simulator.serviceprovider.IObserver; -import org.oic.simulator.serviceprovider.ObserverInfo; - -/** - * This class implements methods for receiving observer - * change callbacks. - */ -public class Observer implements IObserver -{ - private CountDownLatch lockObject; - private ObserverObject observerObject; - - public Observer(CountDownLatch lockObject, ObserverObject observerObject) - { - this.lockObject = lockObject; - this.observerObject = observerObject; - } - - @Override - public void onObserverChanged(String resourceURI, int state, ObserverInfo observer) - { - observerObject.setState(state); - observerObject.setResourceURI(resourceURI); - observerObject.setObserver(observer); - - lockObject.countDown(); - } -} diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/serviceprovider/test/ObserverObject.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/serviceprovider/test/ObserverObject.java deleted file mode 100644 index 14bd6a1..0000000 --- a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/serviceprovider/test/ObserverObject.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.oic.simulator.serviceprovider.test; - -import org.oic.simulator.serviceprovider.ObserverInfo; - -/** - * This class provides methods to set/get observers and state - * information. - */ -public class ObserverObject -{ - private String resourceURI; - private int state; - private ObserverInfo observer; - - public void setResourceURI(String resourceURI) - { - this.resourceURI = resourceURI; - } - - public String getResourceURI() - { - return resourceURI; - } - - public void setState(int state) - { - this.state = state; - } - - public int getState() - { - return state; - } - - public void setObserver(ObserverInfo observer) - { - this.observer = observer; - } - - public ObserverInfo getObserver() - { - return observer; - } -} diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/serviceprovider/test/SimlatorResourceServerTest.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/serviceprovider/test/SimlatorResourceServerTest.java deleted file mode 100644 index cfbe5d2..0000000 --- a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/serviceprovider/test/SimlatorResourceServerTest.java +++ /dev/null @@ -1,936 +0,0 @@ -/* - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.oic.simulator.serviceprovider.test; - -import java.util.Vector; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -import junit.framework.TestCase; - -import org.oic.simulator.InvalidArgsException; -import org.oic.simulator.ResourceAttribute; -import org.oic.simulator.SimulatorException; -import org.oic.simulator.SimulatorManager; -import org.oic.simulator.SimulatorResourceModel; -import org.oic.simulator.serviceprovider.AutomationType; -import org.oic.simulator.serviceprovider.SimulatorResourceServer; -import org.oic.simulator.test.ResourceModelChangeListener; -import org.oic.simulator.test.ResourceModelObject; - -/** - * This class tests the functionality of Simulator Resource Server - * class APIs. - */ -public class SimlatorResourceServerTest extends TestCase -{ - - private static final String CONFIG_PATH = "./ramls/simple-light.raml"; - - private static final String KEY = "testkey"; - - private CountDownLatch lockObject; - private ResourceModelObject resourceModelObject; - private ResourceModelChangeListener resourceModelChangeListener; - - private SimulatorResourceServer simulatorResourceServer; - - static - { - System.loadLibrary("SimulatorManager"); - System.loadLibrary("RamlParser"); - System.loadLibrary("oc"); - System.loadLibrary("oc_logger"); - System.loadLibrary("octbstack"); - } - - protected void setUp() throws Exception - { - super.setUp(); - lockObject= new CountDownLatch(1); - resourceModelObject = new ResourceModelObject(); - resourceModelChangeListener = new ResourceModelChangeListener(resourceModelObject); - simulatorResourceServer = SimulatorManager.createResource(CONFIG_PATH, resourceModelChangeListener); - } - - protected void tearDown() throws Exception - { - super.tearDown(); - - SimulatorManager.deleteResource(simulatorResourceServer); - - lockObject = null; - resourceModelObject = null; - resourceModelChangeListener = null; - - simulatorResourceServer = null; - } - - public void testGetURI_P01() - { - assertNotNull(simulatorResourceServer.getURI()); - } - - public void testGetResourceType_P01() - { - assertNotNull(simulatorResourceServer.getResourceType()); - } - - public void testGetInterfaceType_P01() - { - assertNotNull(simulatorResourceServer.getInterfaceType()); - } - - public void testGetModel_P01() - { - boolean result = false; - - try - { - if(simulatorResourceServer.getModel() != null && simulatorResourceServer.getModel().size() > 0) - result = true; - } - catch (InvalidArgsException e) - { - e.printStackTrace(); - } - catch (SimulatorException e) - { - e.printStackTrace(); - } - - assertTrue(result); - } - - public void testAddAttributeInteger_P01() - { - try - { - simulatorResourceServer.addAttributeInteger(KEY, 2); - } - catch (Exception e) - { - e.printStackTrace(); - } - assertEquals(Integer.parseInt(getValue(KEY) + ""), 2); - } - - public void testAddAttributeDouble_P01() - { - try - { - simulatorResourceServer.addAttributeDouble(KEY, 4.0); - } - catch (Exception e) - { - e.printStackTrace(); - } - assertEquals(Double.parseDouble(getValue(KEY) + ""), 4.0); - } - - public void testAddAttributeBoolean_P01() - { - try - { - simulatorResourceServer.addAttributeBoolean(KEY, Boolean.parseBoolean("true")); - } - catch (Exception e) - { - e.printStackTrace(); - } - assertEquals(Boolean.parseBoolean(getValue(KEY).toString() + ""), true); - } - - public void testaddAttributeString_P01() - { - try - { - simulatorResourceServer.addAttributeString(KEY, "test"); - } - catch (Exception e) - { - e.printStackTrace(); - } - assertEquals(getValue(KEY) + "", "test"); - } - - public void testUpdateAttributeInteger_P01() - { - boolean result = true; - - try - { - simulatorResourceServer.addAttributeInteger(KEY, 10); - } - catch (Exception e) - { - result = false; - e.printStackTrace(); - } - - result = result && Integer.parseInt(getValue(KEY) + "") == 10; - - try - { - simulatorResourceServer.updateAttributeInteger(KEY, 12); - } - catch (Exception e) - { - result = false; - e.printStackTrace(); - } - result = result && Integer.parseInt(getValue(KEY) + "") == 12; - - assertTrue(result); - } - - public void testUpdateAttributeDouble_P01() - { - boolean result = true; - - try - { - simulatorResourceServer.addAttributeDouble(KEY, 22.0); - } - catch (Exception e) - { - result = false; - e.printStackTrace(); - } - - result = result && Double.parseDouble(getValue(KEY) + "") == 22.0; - - try - { - simulatorResourceServer.updateAttributeDouble(KEY, 25.3); - } - catch (Exception e) - { - result = false; - e.printStackTrace(); - } - - result = result && Double.parseDouble(getValue(KEY) + "") == 25.3; - - assertTrue(result); - } - - public void testUpdateAttributeBoolean_P01() - { - boolean result = true; - - try - { - simulatorResourceServer.addAttributeBoolean(KEY, Boolean.parseBoolean("true")); - } - catch (Exception e) - { - result = false; - e.printStackTrace(); - } - - result = result && Boolean.parseBoolean(getValue(KEY) + "")==true; - - try - { - simulatorResourceServer.updateAttributeBoolean(KEY, Boolean.parseBoolean("false")); - } - catch (Exception e) - { - result = false; - e.printStackTrace(); - } - - result = result && !Boolean.parseBoolean(getValue(KEY) + ""); - - assertTrue(result); - } - - public void testupdateAttributeString_P01() - { - boolean result = true; - - try - { - simulatorResourceServer.addAttributeString(KEY, "old"); - } - catch (Exception e) - { - result = false; - e.printStackTrace(); - } - - result = result && getValue(KEY).equals("old"); - - try - { - simulatorResourceServer.updateAttributeString(KEY, "new"); - } - catch (Exception e) - { - result = false; - e.printStackTrace(); - } - - result = result && getValue(KEY).equals("new"); - - assertTrue(result); - } - - public void testSetRange_P01() - { - boolean result = true; - - try - { - simulatorResourceServer.addAttributeInteger(KEY, 10); - simulatorResourceServer.setRange(KEY, 1, 12); - } - catch (Exception e) - { - result = false; - e.printStackTrace(); - } - - result = result && Integer.parseInt(getValue(KEY) + "") == 10; - - try - { - simulatorResourceServer.updateAttributeInteger(KEY, 3); - } - catch (Exception e) - { - result = false; - e.printStackTrace(); - } - - result = result && Integer.parseInt(getValue(KEY) + "") == 3; - - assertTrue(result); - } - - /** - * Try to set the value out of range - */ - public void testSetRange_N01() - { - boolean result = true; - - try - { - simulatorResourceServer.addAttributeInteger(KEY, 10); - simulatorResourceServer.setRange(KEY, 1, 12); - } - catch (Exception e) - { - result = false; - e.printStackTrace(); - } - - result = result && Integer.parseInt(getValue(KEY) + "") == 10; - - try - { - simulatorResourceServer.updateAttributeInteger(KEY, 13); - result = false; - } - catch (Exception e) - { - result = true; - } - - result = result && Integer.parseInt(getValue(KEY) + "") == 10; - - assertTrue(result); - } - - public void testSetAllowedValuesInteger_P01() - { - boolean result = true; - - try - { - simulatorResourceServer.addAttributeInteger(KEY, 10); - } - catch (Exception e) - { - result = false; - e.printStackTrace(); - } - - Vector values = new Vector(); - values.add(1); - values.add(10); - values.add(20); - values.add(50); - - try - { - simulatorResourceServer.setAllowedValuesInteger(KEY, values); - } - catch (Exception e) - { - result = false; - e.printStackTrace(); - } - - result = result && Integer.parseInt(getValue(KEY) + "") == 10; - - try - { - simulatorResourceServer.updateAttributeInteger(KEY, 20); - } - catch (Exception e) - { - result = false; - e.printStackTrace(); - } - - result = result && Integer.parseInt(getValue(KEY) + "") == 20; - - assertTrue(result); - } - - /** - * Try setting with out of range - */ - public void testSetAllowedValuesInteger_N01() - { - boolean result = true; - - try - { - simulatorResourceServer.addAttributeInteger(KEY, 10); - } - catch (Exception e) - { - result = false; - e.printStackTrace(); - } - - Vector values = new Vector(); - values.add(1); - values.add(10); - values.add(20); - values.add(50); - - try - { - simulatorResourceServer.setAllowedValuesInteger(KEY, values); - } - catch (Exception e) - { - result = false; - e.printStackTrace(); - } - - result = result && Integer.parseInt(getValue(KEY) + "") == 10; - - try - { - simulatorResourceServer.updateAttributeInteger(KEY, 2); - result = false; - } - catch (Exception e) - { - result = true; - } - - result = result && Integer.parseInt(getValue(KEY) + "") == 10; - - assertTrue(result); - } - - /** - * Try setting values multiple times - */ - public void testSetAllowedValuesDouble_P01() - { - boolean result = true; - - try - { - simulatorResourceServer.addAttributeDouble(KEY, 11.5); - } - catch (Exception e) - { - result = false; - e.printStackTrace(); - } - - Vector values = new Vector(); - values.add(11.5); - values.add(10.5); - values.add(20.5); - values.add(50.5); - - try - { - simulatorResourceServer.setAllowedValuesDouble(KEY, values); - } - catch (Exception e) - { - result = false; - e.printStackTrace(); - } - - result = result && Double.parseDouble(getValue(KEY) + "") == 11.5; - - try - { - simulatorResourceServer.updateAttributeDouble(KEY, 10.5); - } - catch (Exception e) - { - result = false; - e.printStackTrace(); - } - - result = result && Double.parseDouble(getValue(KEY) + "") == 10.5; - - assertTrue(result); - } - - /** - * Try setting with out of range - */ - public void testSetAllowedValuesDouble_N01() - { - boolean result = true; - - try - { - simulatorResourceServer.addAttributeDouble(KEY, 10.5); - } - catch (Exception e) - { - result = false; - e.printStackTrace(); - } - - Vector values = new Vector(); - values.add(11.5); - values.add(10.5); - values.add(20.5); - values.add(50.5); - - try - { - simulatorResourceServer.setAllowedValuesDouble(KEY, values); - } - catch (Exception e) - { - result = false; - e.printStackTrace(); - } - - result = result && Double.parseDouble(getValue(KEY) + "") == 10.5; - - try - { - simulatorResourceServer.updateAttributeDouble(KEY, 2.2); - result = false; - } - catch (Exception e) - { - result = true; - } - - result = result && Double.parseDouble(getValue(KEY) + "") == 10.5; - - assertTrue(result); - } - - public void testsetAllowedValuesString_P01() - { - boolean result = true; - - try - { - simulatorResourceServer.addAttributeString(KEY, "mon"); - } - catch (Exception e) - { - result = false; - e.printStackTrace(); - } - - Vector values = new Vector(); - values.add("mon"); - values.add("tue"); - values.add("wed"); - - try - { - simulatorResourceServer.setAllowedValuesString(KEY, values); - } - catch (Exception e) - { - result = false; - e.printStackTrace(); - } - - result = result && getValue(KEY).equals("mon"); - - try - { - simulatorResourceServer.updateAttributeString(KEY, "tue"); - } - catch (Exception e) - { - result = false; - e.printStackTrace(); - } - - result = result && getValue(KEY).equals("tue"); - - assertTrue(result); - } - - /** - * Set the value that is not in allowed values - */ - public void testsetAllowedValuesString_N01() - { - boolean result = true; - - try - { - simulatorResourceServer.addAttributeString(KEY, "mon"); - } - catch (Exception e) - { - result = false; - e.printStackTrace(); - } - - Vector values = new Vector(); - values.add("mon"); - values.add("tue"); - values.add("wed"); - - try - { - simulatorResourceServer.setAllowedValuesString(KEY, values); - } - catch (Exception e) - { - result = false; - e.printStackTrace(); - } - - result = result && getValue(KEY).equals("mon"); - - try - { - simulatorResourceServer.updateAttributeString(KEY, "thu"); - result = false; - } - catch (Exception e) - { - result = true; - } - - result = result && getValue(KEY).equals("mon"); - - assertTrue(result); - } - - public void testRemoveAttribute_P01() - { - boolean result = true; - - try - { - simulatorResourceServer.addAttributeString(KEY, "fri"); - } - catch (Exception e) - { - result = false; - e.printStackTrace(); - } - - result = result && getValue(KEY).equals("fri"); - - try - { - simulatorResourceServer.removeAttribute(KEY); - result = result && !simulatorResourceServer.getModel().getAttributes().containsKey(KEY); - } - catch (Exception e) - { - result = false; - e.printStackTrace(); - } - - assertTrue(result); - } - - /** - * Try removing the attribute thats not present - */ - public void testRemoveAttribute_N01() - { - boolean result = false; - - try - { - simulatorResourceServer.removeAttribute("something"); - } - catch (Exception e) - { - result = true; - } - - assertTrue(result); - } - - /** - * Try removing when null is passed - */ - public void testRemoveAttribute_N02() - { - boolean result = false; - - try - { - simulatorResourceServer.removeAttribute(null); - } - catch (Exception e) - { - result = true; - } - - assertTrue(result); - } - - /** - * Try removing when attribute is empty - */ - public void testRemoveAttribute_N03() - { - boolean result = false; - - try - { - simulatorResourceServer.removeAttribute(""); - } - catch (Exception e) - { - result = true; - } - - assertTrue(result); - } - - public void testStartResourceAutomation_P01() - { - boolean result = true; - lockObject = new CountDownLatch(1); - AutomationObject automationObject = new AutomationObject(); - AutomationListener automationListener = new AutomationListener(lockObject, automationObject); - int id = 0; - try - { - id = simulatorResourceServer.startResourceAutomation(AutomationType.NORMAL, automationListener); - } - catch (Exception e) - { - result = false; - e.printStackTrace(); - } - - try - { - lockObject.await(15,TimeUnit.SECONDS); - } - catch (InterruptedException e) - { - e.printStackTrace(); - } - - assertTrue(result && automationObject.getResourceURI() != null && automationObject.getAutomationId() != -1 && id != -1); - - try - { - simulatorResourceServer.stopAutomation(id); - } - catch (Exception e) - { - e.printStackTrace(); - } - } - - /** - * null listener - */ - public void testStartResourceAutomation_N01() - { - boolean result = true; - int id = 0; - try - { - id = simulatorResourceServer.startResourceAutomation(AutomationType.NORMAL, null); - } - catch (Exception e) - { - result = false; - } - assertTrue(!result && id == 0); - } - - public void testStartAttributeAutomation_P01() - { - boolean result = true; - lockObject = new CountDownLatch(1); - AutomationObject automationObject = new AutomationObject(); - AutomationListener automationListener = new AutomationListener(lockObject, automationObject); - int id = 0; - try - { - simulatorResourceServer.addAttributeInteger(KEY, 10); - id = simulatorResourceServer.startAttributeAutomation(KEY, - AutomationType.NORMAL, automationListener); - } - catch (Exception e) - { - result = false; - } - - try - { - lockObject.await(10, TimeUnit.SECONDS); - } - catch (InterruptedException e) - { - } - - assertTrue(result && automationObject.getResourceURI() != null && automationObject.getAutomationId() != -1 && id != -1); - - try - { - simulatorResourceServer.stopAutomation(id); - } - catch (Exception e) - { - e.printStackTrace(); - } - } - - /** - * null listener - */ - public void testStartAttributeAutomation_N01() - { - boolean result = false; - int id = 0; - try - { - id = simulatorResourceServer.startAttributeAutomation(simulatorResourceServer.getModel().getAttributes().get(0).getName(), - AutomationType.NORMAL, null); - result = false; - } - catch (Exception e) - { - result = true; - } - - assertTrue(result && id != -1); - } - - public void testStopAutomation_P01() - { - boolean result = true; - - lockObject = new CountDownLatch(1); - - AutomationObject automationObject = new AutomationObject(); - AutomationListener automationListener = new AutomationListener(lockObject, automationObject); - - int id = 0; - try - { - id = simulatorResourceServer.startResourceAutomation(AutomationType.NORMAL, automationListener); - } - catch(Exception e) - { - result = false; - } - - try - { - lockObject.await(05, TimeUnit.SECONDS); - } - catch (InterruptedException e) - { - } - - try - { - simulatorResourceServer.stopAutomation(id); - } - catch(Exception e) - { - result = false; - } - - assertTrue(result); - } - - /** - * checking for crash - * random id - */ - public void testStopAutomation_N01() - { - boolean result = false; - try - { - simulatorResourceServer.stopAutomation(144353544); - } - catch (Exception e) - { - result = true; - e.printStackTrace(); - } - assertTrue(result); - } - - private Object getValue(Object key) - { - SimulatorResourceModel simulatorResourceModel = null; - try - { - simulatorResourceModel = simulatorResourceServer.getModel(); - } - catch (Exception e) - { - e.printStackTrace(); - } - - ResourceAttribute resourceAttribute = null; - try - { - resourceAttribute = simulatorResourceModel.getAttributes().get(key); - } - catch (SimulatorException e) - { - e.printStackTrace(); - } - return resourceAttribute.getValue(); - } -} diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/AttributeValueTest.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/AttributeValueTest.java new file mode 100644 index 0000000..f382716 --- /dev/null +++ b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/AttributeValueTest.java @@ -0,0 +1,478 @@ +/* + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.oic.simulator.test; + +import org.oic.simulator.AttributeValue; +import org.oic.simulator.InvalidArgsException; +import org.oic.simulator.SimulatorResourceModel; + +import junit.framework.TestCase; + +public class AttributeValueTest extends TestCase { + private static final String INT_KEY = "Interger"; + private static final String DOUBLE_KEY = "Double"; + private static final String BOOL_KEY = "Boolean"; + private static final String STRING_KEY = "String"; + + protected void setUp() throws Exception { + super.setUp(); + } + + protected void tearDown() throws Exception { + super.tearDown(); + } + + public void testAttributeValueInt_P01() { + AttributeValue value = new AttributeValue(5); + + assertNotNull(value); + assertTrue(value.typeInfo() != null + && value.typeInfo().mType == AttributeValue.ValueType.INTEGER + && value.typeInfo().mBaseType == AttributeValue.ValueType.INTEGER + && value.typeInfo().mDepth == 0); + } + + public void testAttributeValueInt_P02() { + AttributeValue attribute = new AttributeValue(new Integer(5)); + assertNotNull(attribute); + assertTrue(attribute.typeInfo() != null + && attribute.typeInfo().mType == AttributeValue.ValueType.INTEGER + && attribute.typeInfo().mBaseType == AttributeValue.ValueType.INTEGER + && attribute.typeInfo().mDepth == 0); + } + + public void testAttributeValueDouble_P01() { + AttributeValue value = new AttributeValue(5.00); + + assertNotNull(value); + assertTrue(value.typeInfo() != null + && value.typeInfo().mType == AttributeValue.ValueType.DOUBLE + && value.typeInfo().mBaseType == AttributeValue.ValueType.DOUBLE + && value.typeInfo().mDepth == 0); + } + + public void testAttributeValueDouble_P02() { + AttributeValue value = new AttributeValue(new Double(5.00)); + + assertNotNull(value); + assertTrue(value.typeInfo() != null + && value.typeInfo().mType == AttributeValue.ValueType.DOUBLE + && value.typeInfo().mBaseType == AttributeValue.ValueType.DOUBLE + && value.typeInfo().mDepth == 0); + } + + public void testAttributeValueBoolean_P01() { + AttributeValue value = new AttributeValue(true); + + assertNotNull(value); + assertTrue(value.typeInfo() != null + && value.typeInfo().mType == AttributeValue.ValueType.BOOLEAN + && value.typeInfo().mBaseType == AttributeValue.ValueType.BOOLEAN + && value.typeInfo().mDepth == 0); + } + + public void testAttributeValueBoolean_P02() { + AttributeValue value = new AttributeValue(new Boolean(true)); + + assertNotNull(value); + assertTrue(value.typeInfo() != null + && value.typeInfo().mType == AttributeValue.ValueType.BOOLEAN + && value.typeInfo().mBaseType == AttributeValue.ValueType.BOOLEAN + && value.typeInfo().mDepth == 0); + } + + public void testAttributeValueString_P01() { + AttributeValue value = new AttributeValue("String"); + + assertNotNull(value); + assertTrue(value.typeInfo() != null + && value.typeInfo().mType == AttributeValue.ValueType.STRING + && value.typeInfo().mBaseType == AttributeValue.ValueType.STRING + && value.typeInfo().mDepth == 0); + } + + public void testAttributeValueString_P02() { + AttributeValue value = new AttributeValue(new String("String")); + + assertNotNull(value); + assertTrue(value.typeInfo() != null + && value.typeInfo().mType == AttributeValue.ValueType.STRING + && value.typeInfo().mBaseType == AttributeValue.ValueType.STRING + && value.typeInfo().mDepth == 0); + } + + public void testAttributeValueSimulatorResourceModel() { + SimulatorResourceModel model = new SimulatorResourceModel(); + try { + model.addAttribute(INT_KEY, new AttributeValue(1)); + model.addAttribute(DOUBLE_KEY, new AttributeValue(1.00)); + model.addAttribute(BOOL_KEY, new AttributeValue(true)); + model.addAttribute(STRING_KEY, new AttributeValue("string")); + } catch (InvalidArgsException e) { + e.printStackTrace(); + } + + if (model.size() != 4) + fail("Failed to construct model for continuing test!"); + + AttributeValue value = new AttributeValue(model); + assertNotNull(value); + assertTrue(value.typeInfo() != null + && value.typeInfo().mType == AttributeValue.ValueType.RESOURCEMODEL + && value.typeInfo().mBaseType == AttributeValue.ValueType.RESOURCEMODEL + && value.typeInfo().mDepth == 0); + } + + public void testAttributeValueIntArray_P01() { + int[] array = { 1, 2, 3 }; + AttributeValue value = new AttributeValue(array); + + assertNotNull(value); + assertTrue(value.typeInfo() != null + && value.typeInfo().mType == AttributeValue.ValueType.ARRAY + && value.typeInfo().mBaseType == AttributeValue.ValueType.INTEGER + && value.typeInfo().mDepth == 1); + } + + public void testAttributeValueIntArray_P02() { + Integer[] array = { new Integer(1), new Integer(2), new Integer(3) }; + AttributeValue value = new AttributeValue(array); + + assertNotNull(value); + assertTrue(value.typeInfo() != null + && value.typeInfo().mType == AttributeValue.ValueType.ARRAY + && value.typeInfo().mBaseType == AttributeValue.ValueType.INTEGER + && value.typeInfo().mDepth == 1); + } + + public void testAttributeValueDoubleArray_P01() { + double[] array = { 1.00, 2.00, 3.00 }; + AttributeValue value = new AttributeValue(array); + + assertNotNull(value); + assertTrue(value.typeInfo() != null + && value.typeInfo().mType == AttributeValue.ValueType.ARRAY + && value.typeInfo().mBaseType == AttributeValue.ValueType.DOUBLE + && value.typeInfo().mDepth == 1); + } + + public void testAttributeValueDoubleArray_P02() { + Double[] array = { new Double(1.00), new Double(2.00), new Double(3.00) }; + AttributeValue value = new AttributeValue(array); + + assertNotNull(value); + assertTrue(value.typeInfo() != null + && value.typeInfo().mType == AttributeValue.ValueType.ARRAY + && value.typeInfo().mBaseType == AttributeValue.ValueType.DOUBLE + && value.typeInfo().mDepth == 1); + } + + public void testAttributeValueBooleanArray_P01() { + boolean[] array = { true }; + AttributeValue value = new AttributeValue(array); + + assertNotNull(value); + assertTrue(value.typeInfo() != null + && value.typeInfo().mType == AttributeValue.ValueType.ARRAY + && value.typeInfo().mBaseType == AttributeValue.ValueType.BOOLEAN + && value.typeInfo().mDepth == 1); + } + + public void testAttributeValueBooleanArray_P02() { + boolean[] array = { new Boolean(true) }; + AttributeValue value = new AttributeValue(array); + + assertNotNull(value); + assertTrue(value.typeInfo() != null + && value.typeInfo().mType == AttributeValue.ValueType.ARRAY + && value.typeInfo().mBaseType == AttributeValue.ValueType.BOOLEAN + && value.typeInfo().mDepth == 1); + } + + public void testAttributeValueStringArray_P01() { + String[] array = { "string1", "string2" }; + AttributeValue value = new AttributeValue(array); + + assertNotNull(value); + assertTrue(value.typeInfo() != null + && value.typeInfo().mType == AttributeValue.ValueType.ARRAY + && value.typeInfo().mBaseType == AttributeValue.ValueType.STRING + && value.typeInfo().mDepth == 1); + } + + public void testAttributeValueStringArray_P02() { + String[] array = { new String("string1"), new String("string2") }; + AttributeValue value = new AttributeValue(array); + + assertNotNull(value); + assertTrue(value.typeInfo() != null + && value.typeInfo().mType == AttributeValue.ValueType.ARRAY + && value.typeInfo().mBaseType == AttributeValue.ValueType.STRING + && value.typeInfo().mDepth == 1); + } + + public void testAttributeValueSimulatorResourceModelArray() { + SimulatorResourceModel childModel = new SimulatorResourceModel(); + try { + childModel.addAttribute(INT_KEY, new AttributeValue(1)); + childModel.addAttribute(DOUBLE_KEY, new AttributeValue(1.00)); + childModel.addAttribute(BOOL_KEY, new AttributeValue(true)); + childModel.addAttribute(STRING_KEY, new AttributeValue("string")); + } catch (InvalidArgsException e) { + e.printStackTrace(); + } + + if (childModel.size() != 4) + fail("Failed to construct model for continuing test!"); + + SimulatorResourceModel[] array = { childModel }; + + AttributeValue value = new AttributeValue(array); + assertNotNull(value); + assertTrue(value.typeInfo() != null + && value.typeInfo().mType == AttributeValue.ValueType.ARRAY + && value.typeInfo().mBaseType == AttributeValue.ValueType.RESOURCEMODEL + && value.typeInfo().mDepth == 1); + } + + public void testAttributeValueIntArrayArray_P01() { + int[][] array = { { 1, 2, 3 } }; + AttributeValue value = new AttributeValue(array); + + assertNotNull(value); + assertTrue(value.typeInfo() != null + && value.typeInfo().mType == AttributeValue.ValueType.ARRAY + && value.typeInfo().mBaseType == AttributeValue.ValueType.INTEGER + && value.typeInfo().mDepth == 2); + } + + public void testAttributeValueIntArrayArray_P02() { + Integer[][] array = { { new Integer(1), new Integer(2), new Integer(3) } }; + AttributeValue value = new AttributeValue(array); + + assertNotNull(value); + assertTrue(value.typeInfo() != null + && value.typeInfo().mType == AttributeValue.ValueType.ARRAY + && value.typeInfo().mBaseType == AttributeValue.ValueType.INTEGER + && value.typeInfo().mDepth == 2); + } + + public void testAttributeValueDoubleArrayArray_P01() { + double[][] array = { { 1.00, 2.00, 3.00 } }; + AttributeValue value = new AttributeValue(array); + + assertNotNull(value); + assertTrue(value.typeInfo() != null + && value.typeInfo().mType == AttributeValue.ValueType.ARRAY + && value.typeInfo().mBaseType == AttributeValue.ValueType.DOUBLE + && value.typeInfo().mDepth == 2); + } + + public void testAttributeValueDoubleArrayArray_P02() { + Double[][] array = { { new Double(1.00), new Double(2.00), + new Double(3.00) } }; + AttributeValue value = new AttributeValue(array); + + assertNotNull(value); + assertTrue(value.typeInfo() != null + && value.typeInfo().mType == AttributeValue.ValueType.ARRAY + && value.typeInfo().mBaseType == AttributeValue.ValueType.DOUBLE + && value.typeInfo().mDepth == 2); + } + + public void testAttributeValueBooleanArrayArray_P01() { + boolean[][] array = { { true } }; + AttributeValue value = new AttributeValue(array); + + assertNotNull(value); + assertTrue(value.typeInfo() != null + && value.typeInfo().mType == AttributeValue.ValueType.ARRAY + && value.typeInfo().mBaseType == AttributeValue.ValueType.BOOLEAN + && value.typeInfo().mDepth == 2); + } + + public void testAttributeValueBooleanArrayArray_P02() { + Boolean[][] array = { { new Boolean(true) } }; + AttributeValue value = new AttributeValue(array); + + assertNotNull(value); + assertTrue(value.typeInfo() != null + && value.typeInfo().mType == AttributeValue.ValueType.ARRAY + && value.typeInfo().mBaseType == AttributeValue.ValueType.BOOLEAN + && value.typeInfo().mDepth == 2); + } + + public void testAttributeValueStringArrayArray_P01() { + String[][] array = { { "string" } }; + AttributeValue value = new AttributeValue(array); + + assertNotNull(value); + assertTrue(value.typeInfo() != null + && value.typeInfo().mType == AttributeValue.ValueType.ARRAY + && value.typeInfo().mBaseType == AttributeValue.ValueType.STRING + && value.typeInfo().mDepth == 2); + } + + public void testAttributeValueStringArrayArray_P02() { + String[][] array = { { new String("string") } }; + AttributeValue value = new AttributeValue(array); + + assertNotNull(value); + assertTrue(value.typeInfo() != null + && value.typeInfo().mType == AttributeValue.ValueType.ARRAY + && value.typeInfo().mBaseType == AttributeValue.ValueType.STRING + && value.typeInfo().mDepth == 2); + } + + public void testAttributeValueSimulatorResourceModelArrayArray() { + SimulatorResourceModel childModel = new SimulatorResourceModel(); + try { + childModel.addAttribute(INT_KEY, new AttributeValue(1)); + childModel.addAttribute(DOUBLE_KEY, new AttributeValue(1.00)); + childModel.addAttribute(BOOL_KEY, new AttributeValue(true)); + childModel.addAttribute(STRING_KEY, new AttributeValue("string")); + } catch (InvalidArgsException e) { + e.printStackTrace(); + } + + if (childModel.size() != 4) + fail("Failed to construct model for continuing test!"); + + SimulatorResourceModel[][] array = { { childModel } }; + + AttributeValue value = new AttributeValue(array); + assertNotNull(value); + assertTrue(value.typeInfo() != null + && value.typeInfo().mType == AttributeValue.ValueType.ARRAY + && value.typeInfo().mBaseType == AttributeValue.ValueType.RESOURCEMODEL + && value.typeInfo().mDepth == 2); + } + + public void testAttributeValueIntArrayArrayArray_P01() { + int[][][] array = { { { 1, 2, 3 } } }; + AttributeValue value = new AttributeValue(array); + + assertNotNull(value); + assertTrue(value.typeInfo() != null + && value.typeInfo().mType == AttributeValue.ValueType.ARRAY + && value.typeInfo().mBaseType == AttributeValue.ValueType.INTEGER + && value.typeInfo().mDepth == 3); + } + + public void testAttributeValueIntArrayArrayArray_P02() { + Integer[][][] array = { { { new Integer(1), new Integer(2), + new Integer(3) } } }; + AttributeValue value = new AttributeValue(array); + + assertNotNull(value); + assertTrue(value.typeInfo() != null + && value.typeInfo().mType == AttributeValue.ValueType.ARRAY + && value.typeInfo().mBaseType == AttributeValue.ValueType.INTEGER + && value.typeInfo().mDepth == 3); + } + + public void testAttributeValueDoubleArrayArrayArray_P01() { + double[][][] array = { { { 1.00, 2.00, 3.00 } } }; + AttributeValue value = new AttributeValue(array); + + assertNotNull(value); + assertTrue(value.typeInfo() != null + && value.typeInfo().mType == AttributeValue.ValueType.ARRAY + && value.typeInfo().mBaseType == AttributeValue.ValueType.DOUBLE + && value.typeInfo().mDepth == 3); + } + + public void testAttributeValueDoubleArrayArrayArray_P02() { + Double[][][] array = { { { new Double(1.00), new Double(2.00), + new Double(3.00) } } }; + AttributeValue value = new AttributeValue(array); + + assertNotNull(value); + assertTrue(value.typeInfo() != null + && value.typeInfo().mType == AttributeValue.ValueType.ARRAY + && value.typeInfo().mBaseType == AttributeValue.ValueType.DOUBLE + && value.typeInfo().mDepth == 3); + } + + public void testAttributeValueBooleanArrayArrayArray_P01() { + boolean[][][] array = { { { true } } }; + AttributeValue value = new AttributeValue(array); + + assertNotNull(value); + assertTrue(value.typeInfo() != null + && value.typeInfo().mType == AttributeValue.ValueType.ARRAY + && value.typeInfo().mBaseType == AttributeValue.ValueType.BOOLEAN + && value.typeInfo().mDepth == 3); + } + + public void testAttributeValueBooleanArrayArrayArray_P02() { + Boolean[][][] array = { { { new Boolean(true) } } }; + AttributeValue value = new AttributeValue(array); + + assertNotNull(value); + assertTrue(value.typeInfo() != null + && value.typeInfo().mType == AttributeValue.ValueType.ARRAY + && value.typeInfo().mBaseType == AttributeValue.ValueType.BOOLEAN + && value.typeInfo().mDepth == 3); + } + + public void testAttributeValueStringArrayArrayArray_P01() { + String[][][] array = { { { "string" } } }; + AttributeValue value = new AttributeValue(array); + + assertNotNull(value); + assertTrue(value.typeInfo() != null + && value.typeInfo().mType == AttributeValue.ValueType.ARRAY + && value.typeInfo().mBaseType == AttributeValue.ValueType.STRING + && value.typeInfo().mDepth == 3); + } + + public void testAttributeValueStringArrayArrayArray_P02() { + String[][][] array = { { { new String("string") } } }; + AttributeValue value = new AttributeValue(array); + + assertNotNull(value); + assertTrue(value.typeInfo() != null + && value.typeInfo().mType == AttributeValue.ValueType.ARRAY + && value.typeInfo().mBaseType == AttributeValue.ValueType.STRING + && value.typeInfo().mDepth == 3); + } + + public void testAttributeValueSimulatorResourceModelArrayArrayArray() { + SimulatorResourceModel childModel = new SimulatorResourceModel(); + try { + childModel.addAttribute(INT_KEY, new AttributeValue(1)); + childModel.addAttribute(DOUBLE_KEY, new AttributeValue(1.00)); + childModel.addAttribute(BOOL_KEY, new AttributeValue(true)); + childModel.addAttribute(STRING_KEY, new AttributeValue("string")); + } catch (InvalidArgsException e) { + e.printStackTrace(); + } + + if (childModel.size() != 4) + fail("Failed to construct model for continuing test!"); + + SimulatorResourceModel[][][] array = { { { childModel } } }; + + AttributeValue value = new AttributeValue(array); + assertNotNull(value); + assertTrue(value.typeInfo() != null + && value.typeInfo().mType == AttributeValue.ValueType.ARRAY + && value.typeInfo().mBaseType == AttributeValue.ValueType.RESOURCEMODEL + && value.typeInfo().mDepth == 3); + } +} diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/AttributeValueValidationTest.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/AttributeValueValidationTest.java new file mode 100644 index 0000000..96618f4 --- /dev/null +++ b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/AttributeValueValidationTest.java @@ -0,0 +1,253 @@ +package org.oic.simulator.test; + +import org.oic.simulator.AttributeProperty; +import org.oic.simulator.AttributeValue; +import org.oic.simulator.AttributeValueValidation; + +import junit.framework.TestCase; + +public class AttributeValueValidationTest extends TestCase { + protected void setUp() throws Exception { + super.setUp(); + } + + protected void tearDown() throws Exception { + super.tearDown(); + } + + public void testValidateInt_P01() { + AttributeProperty property = new AttributeProperty(1, 10); + AttributeValueValidation validation = new AttributeValueValidation( + property); + assertTrue(validation.validate(new AttributeValue(5))); + } + + public void testValidateInt_P02() { + int[] valueSet = { 1, 5, 7 }; + AttributeProperty property = new AttributeProperty(valueSet); + AttributeValueValidation validation = new AttributeValueValidation( + property); + assertTrue(validation.validate(new AttributeValue(5))); + } + + public void testValidateInt_N01() { + AttributeProperty property = new AttributeProperty(1, 10); + AttributeValueValidation validation = new AttributeValueValidation( + property); + assertFalse(validation.validate(new AttributeValue(15))); + } + + public void testValidateInt_N02() { + int[] valueSet = { 1, 5, 7 }; + AttributeProperty property = new AttributeProperty(valueSet); + AttributeValueValidation validation = new AttributeValueValidation( + property); + assertFalse(validation.validate(new AttributeValue(6))); + } + + public void testValidateInt_N03() { + AttributeValueValidation validation = new AttributeValueValidation( + null); + assertFalse(validation.validate(new AttributeValue(6))); + } + + public void testValidateInt1DArray_P01() { + AttributeProperty arrayProp = new AttributeProperty(1, 2); + arrayProp.setChildProperty(new AttributeProperty(1, 10)); + + int[] value = { 1, 5 }; + AttributeValueValidation validation = new AttributeValueValidation( + arrayProp); + assertTrue(validation.validate(new AttributeValue(value))); + } + + public void testValidateInt1DArray_N01() { + AttributeProperty arrayProp = new AttributeProperty(1, 2); + arrayProp.setChildProperty(new AttributeProperty(1, 10)); + + int[] value = { 1, 5, 7 }; + AttributeValueValidation validation = new AttributeValueValidation( + arrayProp); + assertFalse(validation.validate(new AttributeValue(value))); + } + + public void testValidateInt1DArray_N02() { + AttributeProperty arrayProp = new AttributeProperty(1, 2); + arrayProp.setChildProperty(new AttributeProperty(1, 10)); + + int[] value = { 1, 15 }; + AttributeValueValidation validation = new AttributeValueValidation( + arrayProp); + assertFalse(validation.validate(new AttributeValue(value))); + } + + public void testValidateInt2DArray_P01() { + AttributeProperty array1Prop = new AttributeProperty(1, 1); + AttributeProperty array2Prop = new AttributeProperty(1, 1); + AttributeProperty valueProp = new AttributeProperty(1, 10); + array1Prop.setChildProperty(array2Prop); + array2Prop.setChildProperty(valueProp); + + int[][] value = { { 1 } }; + AttributeValueValidation validation = new AttributeValueValidation( + array1Prop); + assertTrue(validation.validate(new AttributeValue(value))); + } + + public void testValidateInt2DArray_N01() { + AttributeProperty array1Prop = new AttributeProperty(1, 1); + AttributeProperty array2Prop = new AttributeProperty(1, 1); + AttributeProperty valueProp = new AttributeProperty(1, 10); + array1Prop.setChildProperty(array2Prop); + array2Prop.setChildProperty(valueProp); + + int[][] value = { { 1 }, { 2 } }; + AttributeValueValidation validation = new AttributeValueValidation( + array1Prop); + assertFalse(validation.validate(new AttributeValue(value))); + } + + public void testValidateInt2DArray_N02() { + AttributeProperty array1Prop = new AttributeProperty(1, 1); + AttributeProperty array2Prop = new AttributeProperty(1, 1); + AttributeProperty valueProp = new AttributeProperty(1, 10); + array1Prop.setChildProperty(array2Prop); + array2Prop.setChildProperty(valueProp); + + int[][] value = { { 1, 2 } }; + AttributeValueValidation validation = new AttributeValueValidation( + array1Prop); + assertFalse(validation.validate(new AttributeValue(value))); + } + + public void testValidateInt2DArray_N03() { + AttributeProperty array1Prop = new AttributeProperty(1, 1); + AttributeProperty array2Prop = new AttributeProperty(1, 1); + AttributeProperty valueProp = new AttributeProperty(1, 10); + array1Prop.setChildProperty(array2Prop); + array2Prop.setChildProperty(valueProp); + + int[][] value = { { 15 } }; + AttributeValueValidation validation = new AttributeValueValidation( + array1Prop); + assertFalse(validation.validate(new AttributeValue(value))); + } + + public void testValidateDouble_P01() { + AttributeProperty property = new AttributeProperty(1, 10); + AttributeValueValidation validation = new AttributeValueValidation( + property); + assertTrue(validation.validate(new AttributeValue(5.12))); + } + + public void testValidateDouble_P02() { + double[] valueSet = { 1.0, 5.12, 7.0 }; + AttributeProperty property = new AttributeProperty(valueSet); + AttributeValueValidation validation = new AttributeValueValidation( + property); + assertTrue(validation.validate(new AttributeValue(5.12))); + } + + public void testValidateDouble_N01() { + AttributeProperty property = new AttributeProperty(1, 10); + AttributeValueValidation validation = new AttributeValueValidation( + property); + assertFalse(validation.validate(new AttributeValue(15.23))); + } + + public void testValidateDouble_N02() { + double[] valueSet = { 1.0, 5.12, 7.0 }; + AttributeProperty property = new AttributeProperty(valueSet); + AttributeValueValidation validation = new AttributeValueValidation( + property); + assertFalse(validation.validate(new AttributeValue(6.0))); + } + + public void testValidateDouble_N03() { + AttributeValueValidation validation = new AttributeValueValidation( + null); + assertFalse(validation.validate(new AttributeValue(6.0))); + } + + public void testValidateDouble1DArray_P01() { + AttributeProperty arrayProp = new AttributeProperty(1, 2); + arrayProp.setChildProperty(new AttributeProperty(1, 10)); + + double[] value = { 1.2, 5.2 }; + AttributeValueValidation validation = new AttributeValueValidation( + arrayProp); + assertTrue(validation.validate(new AttributeValue(value))); + } + + public void testValidateDouble1DArray_N01() { + AttributeProperty arrayProp = new AttributeProperty(1, 2); + arrayProp.setChildProperty(new AttributeProperty(1, 10)); + + double[] value = { 1.2, 5.2, 7.2 }; + AttributeValueValidation validation = new AttributeValueValidation( + arrayProp); + assertFalse(validation.validate(new AttributeValue(value))); + } + + public void testValidateDouble1DArray_N02() { + AttributeProperty arrayProp = new AttributeProperty(1, 2); + arrayProp.setChildProperty(new AttributeProperty(1, 10)); + + double[] value = { 1.2, 15.2 }; + AttributeValueValidation validation = new AttributeValueValidation( + arrayProp); + assertFalse(validation.validate(new AttributeValue(value))); + } + + public void testValidateDouble2DArray_P01() { + AttributeProperty array1Prop = new AttributeProperty(1, 1); + AttributeProperty array2Prop = new AttributeProperty(1, 1); + AttributeProperty valueProp = new AttributeProperty(1, 10); + array1Prop.setChildProperty(array2Prop); + array2Prop.setChildProperty(valueProp); + + double[][] value = { { 1.2 } }; + AttributeValueValidation validation = new AttributeValueValidation( + array1Prop); + assertTrue(validation.validate(new AttributeValue(value))); + } + + public void testValidateDouble2DArray_N01() { + AttributeProperty array1Prop = new AttributeProperty(1, 1); + AttributeProperty array2Prop = new AttributeProperty(1, 1); + AttributeProperty valueProp = new AttributeProperty(1, 10); + array1Prop.setChildProperty(array2Prop); + array2Prop.setChildProperty(valueProp); + + double[][] value = { { 1.2 }, { 2.2 } }; + AttributeValueValidation validation = new AttributeValueValidation( + array1Prop); + assertFalse(validation.validate(new AttributeValue(value))); + } + + public void testValidateDouble2DArray_N02() { + AttributeProperty array1Prop = new AttributeProperty(1, 1); + AttributeProperty array2Prop = new AttributeProperty(1, 1); + AttributeProperty valueProp = new AttributeProperty(1, 10); + array1Prop.setChildProperty(array2Prop); + array2Prop.setChildProperty(valueProp); + + double[][] value = { { 1.2, 2.2 } }; + AttributeValueValidation validation = new AttributeValueValidation( + array1Prop); + assertFalse(validation.validate(new AttributeValue(value))); + } + + public void testValidateDouble2DArray_N03() { + AttributeProperty array1Prop = new AttributeProperty(1, 1); + AttributeProperty array2Prop = new AttributeProperty(1, 1); + AttributeProperty valueProp = new AttributeProperty(1, 10); + array1Prop.setChildProperty(array2Prop); + array2Prop.setChildProperty(valueProp); + + double[][] value = { { 15.2 } }; + AttributeValueValidation validation = new AttributeValueValidation( + array1Prop); + assertFalse(validation.validate(new AttributeValue(value))); + } +} diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/ExceptionType.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/ExceptionType.java new file mode 100644 index 0000000..3429ea5 --- /dev/null +++ b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/ExceptionType.java @@ -0,0 +1,21 @@ +/* + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.oic.simulator.test; + +public enum ExceptionType { + UNKNOWN, INVALID_ARGS, NOT_SUPPORTED, OPERATION_IN_PROGRESS, SIMULATOR +} diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/FindResourceListener.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/FindResourceListener.java deleted file mode 100644 index a8469aa..0000000 --- a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/FindResourceListener.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.oic.simulator.test; - -import java.util.concurrent.CountDownLatch; - -import org.oic.simulator.clientcontroller.IFindResourceListener; -import org.oic.simulator.clientcontroller.SimulatorRemoteResource; - -/** - * This class implements methods for receiving notification when - * resources are discovered in network. - */ -public class FindResourceListener implements IFindResourceListener -{ - - private CountDownLatch lockObject; - private SimulatorRemoteResourceObject simulatorRemoteResource; - - public FindResourceListener(CountDownLatch lockObject, SimulatorRemoteResourceObject simulatorRemoteResource) - { - this.lockObject = lockObject; - this.simulatorRemoteResource = simulatorRemoteResource; - } - - @Override - public void onResourceCallback(SimulatorRemoteResource resource) - { - simulatorRemoteResource.setSimulatorRemoteResource(resource); - - lockObject.countDown(); - } -} diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/ResourceModelChangeListener.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/ResourceModelChangeListener.java deleted file mode 100644 index 9c199b8..0000000 --- a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/ResourceModelChangeListener.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.oic.simulator.test; - -import org.oic.simulator.SimulatorResourceModel; -import org.oic.simulator.serviceprovider.IResourceModelChangedListener; - -/** - * This class implements methods for receiving notification when - * resource model is changed. - */ -public class ResourceModelChangeListener implements IResourceModelChangedListener -{ - - private ResourceModelObject toReturn; - - public ResourceModelChangeListener(Object toReturn) - { - this.toReturn = (ResourceModelObject)toReturn; - } - - @Override - public void onResourceModelChanged(String resourceURI, SimulatorResourceModel resourceModel) - { - toReturn.setResourceURI(resourceURI); - toReturn.setResourceModel(resourceModel); - } -} diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/SimulatorManagerTest.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/SimulatorManagerTest.java index 7fb25db..c63170a 100644 --- a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/SimulatorManagerTest.java +++ b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/SimulatorManagerTest.java @@ -16,475 +16,724 @@ package org.oic.simulator.test; +import java.util.Vector; import java.util.concurrent.CountDownLatch; -import junit.framework.TestCase; +import java.util.concurrent.TimeUnit; +import org.oic.simulator.DeviceInfo; +import org.oic.simulator.DeviceListener; +import org.oic.simulator.InvalidArgsException; import org.oic.simulator.PlatformInfo; +import org.oic.simulator.PlatformListener; +import org.oic.simulator.SimulatorException; import org.oic.simulator.SimulatorManager; -import org.oic.simulator.serviceprovider.SimulatorResourceServer; +import org.oic.simulator.client.FindResourceListener; +import org.oic.simulator.client.SimulatorRemoteResource; +import org.oic.simulator.server.SimulatorResource; +import org.oic.simulator.utils.ObjectHolder; +import org.oic.simulator.utils.SampleSingleResource; + +import junit.framework.TestCase; /** - * This class tests the functionality of Simulator Manager - * class APIs. + * This class tests the functionality of Simulator Manager class APIs. */ -public class SimulatorManagerTest extends TestCase -{ - - private static final String CONFIG_PATH = "./ramls/simple-light.raml"; - private static final String RESOURCE_TYPE = "oic.r.light"; - - private CountDownLatch lockObject; - private ResourceModelObject resourceModelObject; - private ResourceModelChangeListener resourceModelChangeListener; +public class SimulatorManagerTest extends TestCase { + private static final String SINGLE_RES_RAML = "./ramls/oic.r.light.raml"; + private static final String COLLECTION_RES_RAML = "./ramls/oic.d.airconditioner.raml"; - - static - { + static { System.loadLibrary("SimulatorManager"); + System.loadLibrary("RamlParser"); + System.loadLibrary("oc"); + System.loadLibrary("oc_logger"); + System.loadLibrary("octbstack"); } @Override - protected void setUp() throws Exception - { + protected void setUp() throws Exception { super.setUp(); - - lockObject = new CountDownLatch(1); } @Override - protected void tearDown() throws Exception - { + protected void tearDown() throws Exception { super.tearDown(); - - resourceModelObject = null; - resourceModelChangeListener = null; - lockObject = null; } - private SimulatorResourceServer createResource() - { - resourceModelObject = new ResourceModelObject(); - resourceModelChangeListener = new ResourceModelChangeListener(resourceModelObject); + public void testCreateResource_P01() { + SimulatorResource resource = null; + SimulatorResource.Type resType = SimulatorResource.Type.SINGLE; - SimulatorResourceServer simulatorResourceServer = null; - try - { - simulatorResourceServer = SimulatorManager.createResource(CONFIG_PATH, resourceModelChangeListener); - } - catch (Exception e) - { + try { + resource = SimulatorManager.createResource(SINGLE_RES_RAML); + resType = resource.getType(); + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { e.printStackTrace(); } - return simulatorResourceServer; + assertNotNull(resource); + assertTrue(resType == SimulatorResource.Type.SINGLE); } - private SimulatorResourceServer[] createResources(int n) - { - resourceModelObject = new ResourceModelObject(); - resourceModelChangeListener = new ResourceModelChangeListener(resourceModelObject); + public void testCreateResource_P02() { + SimulatorResource resource = null; + SimulatorResource.Type resType = SimulatorResource.Type.COLLECTION; - SimulatorResourceServer[] simulatorResourceServers = null; - try - { - simulatorResourceServers = SimulatorManager.createResource(CONFIG_PATH, n, resourceModelChangeListener); - } - catch (Exception e) - { + try { + resource = SimulatorManager.createResource(COLLECTION_RES_RAML); + resType = resource.getType(); + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { e.printStackTrace(); } - return simulatorResourceServers; + assertNotNull(resource); + assertTrue(resType == SimulatorResource.Type.COLLECTION); } - private void deleteResource(SimulatorResourceServer sim) - { - try - { - SimulatorManager.deleteResource(sim); - } - catch (Exception e) - { - e.printStackTrace(); + public void testCreateResource_N01() { + ExceptionType exType = ExceptionType.UNKNOWN; + + try { + String configPath = ""; + SimulatorResource resource = SimulatorManager + .createResource(configPath); + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; } + + assertTrue(exType == ExceptionType.INVALID_ARGS); } - public void testCreateResource_P01() - { - SimulatorResourceServer simulatorResourceServer = createResource(); + public void testCreateResource_N02() { + ExceptionType exType = ExceptionType.UNKNOWN; - assertNotNull(simulatorResourceServer); + try { + SimulatorResource resource = SimulatorManager.createResource(null); + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; + } - deleteResource(simulatorResourceServer); + assertTrue(exType == ExceptionType.INVALID_ARGS); } - /** - * When config path is empty - */ - public void testCreateResource_N01() - { - String configPath = ""; - boolean result = false; + public void testCreateResourceWithCount_P01() { + Vector resources = null; + SimulatorResource.Type resType = SimulatorResource.Type.SINGLE; - resourceModelObject = new ResourceModelObject(); - resourceModelChangeListener = new ResourceModelChangeListener(resourceModelObject); - - SimulatorResourceServer simulatorResourceServer = null; - try - { - simulatorResourceServer = SimulatorManager.createResource(configPath, resourceModelChangeListener); + try { + resources = SimulatorManager.createResource(SINGLE_RES_RAML, 1); + resType = resources.elementAt(0).getType(); + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); } - catch (Exception e) - { - result = true; + + assertNotNull(resources); + assertTrue(resources.size() == 1); + assertTrue(resType == SimulatorResource.Type.SINGLE); + } + + public void testCreateResourceWithCount_P02() { + Vector resources = null; + SimulatorResource.Type resType = SimulatorResource.Type.COLLECTION; + + try { + resources = SimulatorManager.createResource(COLLECTION_RES_RAML, 1); + resType = resources.elementAt(0).getType(); + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); } - assertTrue(simulatorResourceServer == null && result); + assertNotNull(resources); + assertTrue(resources.size() == 1); + assertTrue(resType == SimulatorResource.Type.COLLECTION); } - /** - * When listener is not set. Passed null - */ - public void testCreateResource_N02() - { - boolean result = false; - SimulatorResourceServer simulatorResourceServer = null; - try - { - simulatorResourceServer = SimulatorManager.createResource(CONFIG_PATH, null); + public void testCreateResourceWithCount_N01() { + ExceptionType exType = ExceptionType.UNKNOWN; + + try { + String configPath = ""; + Vector resource = SimulatorManager + .createResource(configPath, 1); + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; } - catch (Exception e) - { - result = true; + + assertTrue(exType == ExceptionType.INVALID_ARGS); + } + + public void testCreateResourceWithCount_N02() { + ExceptionType exType = ExceptionType.UNKNOWN; + + try { + Vector resource = SimulatorManager + .createResource(null, 1); + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; } - assertTrue(simulatorResourceServer == null && result); + + assertTrue(exType == ExceptionType.INVALID_ARGS); } - /** - * When listener and config path are set to null - */ - public void testCreateResource_N03() - { - boolean result = false; - SimulatorResourceServer simulatorResourceServer = null; - try - { - simulatorResourceServer = SimulatorManager.createResource(null, null); + public void testCreateResourceWithCount_N03() { + ExceptionType exType = ExceptionType.UNKNOWN; + + try { + Vector resource = SimulatorManager + .createResource(SINGLE_RES_RAML, 0); + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; } - catch (Exception e) - { - result = true; + + assertTrue(exType == ExceptionType.INVALID_ARGS); + } + + public void testCreateResourceWithCount_N04() { + ExceptionType exType = ExceptionType.UNKNOWN; + + try { + Vector resource = SimulatorManager + .createResource(SINGLE_RES_RAML, -1); + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; } - assertTrue(simulatorResourceServer == null && result); + + assertTrue(exType == ExceptionType.INVALID_ARGS); } - public void testCreateResourceCount_P01() - { - int count = 5; + public void testCreateResourceByType_P01() { + SimulatorResource resource = null; + SimulatorResource.Type resType = SimulatorResource.Type.SINGLE; - SimulatorResourceServer[] simulatorResourceServers = createResources(count); + try { + String name = "test-singleresource"; + String uri = "/test/singleresource"; + String resourceType = "test.singleresource"; - assertTrue(simulatorResourceServers != null && simulatorResourceServers.length == 5); + resource = SimulatorManager.createResource( + SimulatorResource.Type.SINGLE, name, uri, resourceType); + resType = resource.getType(); + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } - for(SimulatorResourceServer srs : simulatorResourceServers) - deleteResource(srs); + assertNotNull(resource); + assertTrue(resType == SimulatorResource.Type.SINGLE); } - /** - * When config path is empty - */ - public void testCreateResourceCount_N01() - { - int count = 5; - String configPath = ""; - boolean result = false; + public void testCreateResourceByType_P02() { + SimulatorResource resource = null; + SimulatorResource.Type resType = SimulatorResource.Type.COLLECTION; - resourceModelObject = new ResourceModelObject(); - resourceModelChangeListener = new ResourceModelChangeListener(resourceModelObject); + try { + String name = "test-collectionresource"; + String uri = "/test/collectionresource"; + String resourceType = "test.collectionresource"; - SimulatorResourceServer[] simulatorResourceServers = null; - try - { - SimulatorManager.setDeviceInfo("test"); - simulatorResourceServers = SimulatorManager.createResource(configPath, count, resourceModelChangeListener); - } - catch (Exception e) - { - result = true; + resource = SimulatorManager.createResource( + SimulatorResource.Type.COLLECTION, name, uri, resourceType); + resType = resource.getType(); + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); } - assertTrue(simulatorResourceServers == null && result); + assertNotNull(resource); + assertTrue(resType == SimulatorResource.Type.COLLECTION); } - /** - * When listener is not set - */ - public void testCreateResourceCount_N02() - { - int count = 5; - boolean result = false; + public void testCreateResourceByType_N01() { + ExceptionType exType = ExceptionType.INVALID_ARGS; - SimulatorResourceServer[] simulatorResourceServers = null; - try - { - simulatorResourceServers = SimulatorManager.createResource(CONFIG_PATH, count, null); - } - catch (Exception e) - { - result = true; + try { + String name = ""; + String uri = "/test/resource"; + String resourceType = "test.resource"; + + SimulatorResource resource = SimulatorManager.createResource( + SimulatorResource.Type.SINGLE, name, uri, resourceType); + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; } - assertTrue(simulatorResourceServers == null && result); + assertTrue(exType == ExceptionType.INVALID_ARGS); } - /** - * When configPath and listener are set to null - */ - public void testCreateResourceCount_N03() - { - int count = 5; - boolean result = false; + public void testCreateResourceByType_N02() { + ExceptionType exType = ExceptionType.INVALID_ARGS; - SimulatorResourceServer[] simulatorResourceServers = null; - try - { - simulatorResourceServers = SimulatorManager.createResource(null, count, null); - } - catch (Exception e) - { - result = true; + try { + String name = null; + String uri = "/test/resource"; + String resourceType = "test.resource"; + + SimulatorResource resource = SimulatorManager.createResource( + SimulatorResource.Type.SINGLE, name, uri, resourceType); + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; } - assertTrue(simulatorResourceServers == null && result); + assertTrue(exType == ExceptionType.INVALID_ARGS); } - /** - * When count is set to 0 - */ - public void testCreateResourceCount_N04() - { - int count = 0; + public void testCreateResourceByType_N03() { + ExceptionType exType = ExceptionType.INVALID_ARGS; + + try { + String name = "test-resource"; + String uri = ""; + String resourceType = "test.resource"; - SimulatorResourceServer[] simulatorResourceServers = createResources(count); + SimulatorResource resource = SimulatorManager.createResource( + SimulatorResource.Type.SINGLE, name, uri, resourceType); + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; + } - assertTrue(simulatorResourceServers == null); + assertTrue(exType == ExceptionType.INVALID_ARGS); } - /** - * When count is set to -ve - */ + public void testCreateResourceByType_N04() { + ExceptionType exType = ExceptionType.INVALID_ARGS; - public void testCreateResourceCount_N05() - { - int count = -10; + try { + String name = "test-resource"; + String uri = null; + String resourceType = "test.resource"; - SimulatorResourceServer[] simulatorResourceServers = createResources(count); + SimulatorResource resource = SimulatorManager.createResource( + SimulatorResource.Type.SINGLE, name, uri, resourceType); + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; + } - assertTrue(simulatorResourceServers == null ); + assertTrue(exType == ExceptionType.INVALID_ARGS); } - public void testDeleteResource_P01() - { - boolean result = true; + public void testCreateResourceByType_N05() { + ExceptionType exType = ExceptionType.INVALID_ARGS; - SimulatorResourceServer simRes = createResource(); + try { + String name = "test-resource"; + String uri = "/test/resource";; + String resourceType = ""; - try - { - SimulatorManager.deleteResource(simRes); - } - catch (Exception e) - { - result = false; + SimulatorResource resource = SimulatorManager.createResource( + SimulatorResource.Type.SINGLE, name, uri, resourceType); + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; } - assertTrue(result); + assertTrue(exType == ExceptionType.INVALID_ARGS); } - public void testDeleteResource_P02() - { - boolean result = true; + public void testCreateResourceByType_N06() { + ExceptionType exType = ExceptionType.INVALID_ARGS; - SimulatorResourceServer[] simResoruces = createResources(4); + try { + String name = "test-resource"; + String uri = "/test/resource";; + String resourceType = null; - try - { - SimulatorManager.deleteResource(simResoruces[0]); - } - catch (Exception e) - { - result = false; + SimulatorResource resource = SimulatorManager.createResource( + SimulatorResource.Type.SINGLE, name, uri, resourceType); + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; } - for(SimulatorResourceServer simResServer : simResoruces) - deleteResource(simResServer); - - assertTrue(result); + assertTrue(exType == ExceptionType.INVALID_ARGS); } - public void testDeleteResources_P01() - { - boolean result = true; + public void testFindResource_P01() { + // Creating sample single resource to test this API + SampleSingleResource testResource = new SampleSingleResource(); + if (false == testResource.start()) + return; + + CountDownLatch lockObject = new CountDownLatch(1); + boolean syncResult = false; + ObjectHolder resourceHolder = new ObjectHolder<>(); + FindResourceCallbackListener listener = new FindResourceCallbackListener( + lockObject, resourceHolder); + + try { + String resourceType = testResource.mResourceType; + SimulatorManager.findResource(resourceType, listener); + syncResult = true; + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + if (false == syncResult) + testResource.stop(); - createResources(4); + assertTrue(syncResult); - try - { - SimulatorManager.deleteResources(RESOURCE_TYPE); - } - catch (Exception e) - { - result = false; + // Wait for the resource to found + try { + lockObject.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { } - assertTrue(result); + testResource.stop(); + assertNotNull(resourceHolder.get()); } - public void testFindResouce_P01() - { - boolean result = true; + public void testFindResource_N01() { + ExceptionType exType = ExceptionType.UNKNOWN; + + try { + String resourceType = "test.singleresource"; + SimulatorManager.findResource(resourceType, null); + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; + } - SimulatorResourceServer simulatorResourceServer = createResource(); + assertTrue(exType == ExceptionType.INVALID_ARGS); + } - SimulatorRemoteResourceObject simulatorRemoteResource = new SimulatorRemoteResourceObject(); + public void testFindResource_N02() { + ExceptionType exType = ExceptionType.UNKNOWN; + + try { + String resourceType = ""; + SimulatorManager.findResource(resourceType, + new FindResourceListener() { + @Override + public void onResourceFound( + SimulatorRemoteResource resource) { + } + }); + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; + } + + assertTrue(exType == ExceptionType.INVALID_ARGS); + } - FindResourceListener findResourceListener = new FindResourceListener(lockObject, simulatorRemoteResource); + public void testFindResource_N03() { + ExceptionType exType = ExceptionType.UNKNOWN; + + try { + String resourceType = null; + SimulatorManager.findResource(resourceType, + new FindResourceListener() { + @Override + public void onResourceFound( + SimulatorRemoteResource resource) { + } + }); + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; + } + + assertTrue(exType == ExceptionType.INVALID_ARGS); + } - try - { - SimulatorManager.findResource(findResourceListener); - } - catch (Exception e) - { - result = false; + public void testFindResourceAll_P01() { + // Creating sample single resource to test this API + SampleSingleResource testResource = new SampleSingleResource(); + if (false == testResource.start()) + return; + + CountDownLatch lockObject = new CountDownLatch(1); + boolean syncResult = false; + ObjectHolder resourceHolder = new ObjectHolder<>(); + FindResourceCallbackListener listener = new FindResourceCallbackListener( + lockObject, resourceHolder); + + try { + SimulatorManager.findResource(listener); + syncResult = true; + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); } - assertTrue(result); + if (false == syncResult) + testResource.stop(); - deleteResource(simulatorResourceServer); - } + assertTrue(syncResult); - /** - * Pass null to listener - */ - public void testFindResouce_N01() - { - boolean result = true; + // Wait for the resource to found + try { + lockObject.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + } - SimulatorResourceServer simulatorResourceServer = createResource(); + testResource.stop(); + assertNotNull(resourceHolder.get()); + } - try - { + public void testFindResourceAll_N01() { + ExceptionType exType = ExceptionType.UNKNOWN; + + try { SimulatorManager.findResource(null); - result = false; - } - catch (Exception e) - { - result = true; + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; } - assertTrue(result); - - deleteResource(simulatorResourceServer); + assertTrue(exType == ExceptionType.INVALID_ARGS); } - /** - * checking for crash - */ - public void testSetDeviceInfo_P01() - { - SimulatorManager.setDeviceInfo("test"); + public void testregisterDeviceInfo_P01() { + boolean syncResult = false; + + try { + String deviceName = "test-device"; + SimulatorManager.setDeviceInfo(deviceName); + syncResult = true; + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + assertTrue(syncResult); } - /** - * checking for crash - * Pass empty - */ - public void testSetDeviceInfo_N01() - { - try - { - SimulatorManager.setDeviceInfo(""); + public void testregisterDeviceInfo_N01() { + ExceptionType exType = ExceptionType.UNKNOWN; + + try { + String deviceName = ""; + SimulatorManager.setDeviceInfo(deviceName); + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; } - catch(Exception e) - { - System.out.println("Exception hit"); + + assertTrue(exType == ExceptionType.INVALID_ARGS); + } + + public void testregisterDeviceInfo_N02() { + ExceptionType exType = ExceptionType.UNKNOWN; + + try { + String deviceName = null; + SimulatorManager.setDeviceInfo(deviceName); + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; } + + assertTrue(exType == ExceptionType.INVALID_ARGS); } - /** - * checking for crash - * pass null - */ - public void testSetDeviceInfo_N02() - { - try - { - SimulatorManager.setDeviceInfo(null); + public void testregisterPlatformInfo_P01() { + boolean syncResult = false; + + try { + PlatformInfo platformInfo = new PlatformInfo(); + platformInfo.setManufacturerName("Samsung"); + + SimulatorManager.setPlatformInfo(platformInfo); + syncResult = true; + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); } - catch(Exception e) - { - System.out.println("Exception hit"); + + assertTrue(syncResult); + } + + public void testregisterPlatformInfo_N01() { + ExceptionType exType = ExceptionType.UNKNOWN; + + try { + PlatformInfo platformInfo = null; + SimulatorManager.setPlatformInfo(platformInfo); + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; } + + assertTrue(exType == ExceptionType.INVALID_ARGS); } - public void testGetDeviceInfo_N01() - { - try - { - SimulatorManager.getDeviceInfo(null); + public void testFindDevices_P01() { + CountDownLatch lockObject = new CountDownLatch(1); + boolean syncResult = false; + ObjectHolder infoHolder = new ObjectHolder<>(); + DeviceInfoListener listener = new DeviceInfoListener(lockObject, + infoHolder); + + try { + SimulatorManager.setDeviceInfo("Samsung"); + SimulatorManager.findDevices(listener); + syncResult = true; + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); } - catch(Exception e) - { - System.out.println(" Exception hit"); + + assertTrue(syncResult); + + // Wait for the asynchronous response + try { + lockObject.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { } + + assertNotNull(infoHolder.get()); } - /** - * Checking for crash - */ - public void testSetPlatformInfo_P01() - { - PlatformInfo platformInfo = new PlatformInfo(); - platformInfo.setDateOfManufacture("asdf"); - platformInfo.setFirmwareVersion("asdf"); - platformInfo.setHardwareVersion("asdf"); - platformInfo.setManufacturerName("asdfdfg"); - platformInfo.setManufacturerUrl("asdffdg"); - platformInfo.setModelNumber("fddfg"); - platformInfo.setOperationSystemVersion("sadfg"); - platformInfo.setPlatformID("asdf"); - platformInfo.setPlatformVersion("asdfgfdg"); - platformInfo.setSupportUrl("adfgg"); - platformInfo.setSystemTime("adsfgfg"); + public void testFindDevices_N01() { + ExceptionType exType = ExceptionType.UNKNOWN; - SimulatorManager.setPlatformInfo(platformInfo); + try { + SimulatorManager.findDevices(null); + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; + } + + assertTrue(exType == ExceptionType.INVALID_ARGS); } - /** - * Checking for crash - */ - public void testSetPlatformInfo_N01() - { - try - { - SimulatorManager.setPlatformInfo(null); + public void testGetPlatformInfo_P01() { + CountDownLatch lockObject = new CountDownLatch(1); + boolean syncResult = false; + ObjectHolder infoHolder = new ObjectHolder<>(); + PlatformInfoListener listener = new PlatformInfoListener(lockObject, + infoHolder); + + try { + SimulatorManager.getPlatformInformation(listener); + syncResult = true; + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); } - catch(Exception e) - { - System.out.println("Exception Hit"); + + assertTrue(syncResult); + + // Wait for the asynchronous response + try { + lockObject.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { } + + assertNotNull(infoHolder.get()); } - public void testGetPlatformInfo_N01() - { - try - { - SimulatorManager.getPlatformInfo(null); - } - catch (Exception e) - { - System.out.println("Exception Hit"); + public void testGetPlatformInfo_N01() { + ExceptionType exType = ExceptionType.UNKNOWN; + + try { + SimulatorManager.getPlatformInformation(null); + } catch (InvalidArgsException e) { + exType = ExceptionType.INVALID_ARGS; + } catch (SimulatorException e) { + exType = ExceptionType.SIMULATOR; } + + assertTrue(exType == ExceptionType.INVALID_ARGS); + } +} + +class FindResourceCallbackListener implements FindResourceListener { + private CountDownLatch mLockObject; + private ObjectHolder mResourceHolder; + + public FindResourceCallbackListener(CountDownLatch lockObject, + ObjectHolder resourceHolder) { + mLockObject = lockObject; + mResourceHolder = resourceHolder; + } + + @Override + public void onResourceFound(SimulatorRemoteResource resource) { + mResourceHolder.set(resource); + mLockObject.countDown(); + } +} + +class DeviceInfoListener implements DeviceListener { + private CountDownLatch mLockObject; + private ObjectHolder mInfoHolder; + + public DeviceInfoListener(CountDownLatch lockObject, + ObjectHolder infoHolder) { + mLockObject = lockObject; + mInfoHolder = infoHolder; + } + + @Override + public void onDeviceFound(DeviceInfo devInfo) { + mInfoHolder.set(devInfo); + mLockObject.countDown(); + } +} + +class PlatformInfoListener implements PlatformListener { + + private CountDownLatch mLockObject; + private ObjectHolder mInfoHolder; + + public PlatformInfoListener(CountDownLatch lockObject, + ObjectHolder infoHolder) { + mLockObject = lockObject; + mInfoHolder = infoHolder; + } + + @Override + public void onPlatformFound(PlatformInfo platformInfo) { + mInfoHolder.set(platformInfo); + mLockObject.countDown(); } } diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/SimulatorRemoteResourceObject.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/SimulatorRemoteResourceObject.java deleted file mode 100644 index 17c5196..0000000 --- a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/SimulatorRemoteResourceObject.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2015 Samsung Electronics All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.oic.simulator.test; - -import org.oic.simulator.clientcontroller.SimulatorRemoteResource; - -/** - * This class provides methods to set/get remote resource objects. - */ -public class SimulatorRemoteResourceObject -{ - - private SimulatorRemoteResource simulatorRemoteResource; - - public void setSimulatorRemoteResource(SimulatorRemoteResource simulatorRemoteResource) - { - this.simulatorRemoteResource = simulatorRemoteResource; - } - - public SimulatorRemoteResource getSimulatorRemoteResource() - { - return simulatorRemoteResource; - } -} diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/SimulatorResourceModelTest.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/SimulatorResourceModelTest.java index 2748e09..76ae00e 100644 --- a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/SimulatorResourceModelTest.java +++ b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/SimulatorResourceModelTest.java @@ -18,317 +18,234 @@ package org.oic.simulator.test; import java.util.Map; -import junit.framework.TestCase; - -import org.oic.simulator.ResourceAttribute; +import org.oic.simulator.AttributeValue; +import org.oic.simulator.InvalidArgsException; +import org.oic.simulator.SimulatorResourceAttribute; import org.oic.simulator.SimulatorResourceModel; +import junit.framework.TestCase; + /** - * This class tests the functionality of Simulator Resource Model - * class APIs. + * This class tests the APIs of SimulatorResourceModel class. */ -public class SimulatorResourceModelTest extends TestCase -{ - - private SimulatorResourceModel simulatorResourceModel; - - private static final String KEY = "test"; - - static - { - System.loadLibrary("SimulatorManager"); - System.loadLibrary("RamlParser"); - System.loadLibrary("oc"); - System.loadLibrary("oc_logger"); - System.loadLibrary("octbstack"); - } +public class SimulatorResourceModelTest extends TestCase { + private static final String INT_KEY = "Interger"; + private static final String DOUBLE_KEY = "Double"; + private static final String BOOL_KEY = "Boolean"; + private static final String STRING_KEY = "String"; @Override - protected void setUp() throws Exception - { + protected void setUp() throws Exception { super.setUp(); - - simulatorResourceModel = new SimulatorResourceModel(); } @Override - protected void tearDown() throws Exception - { + protected void tearDown() throws Exception { super.tearDown(); - - simulatorResourceModel = null; } - public void testAddAttributeInt_P01() - { - int val = 100; - - boolean result = true; - try - { - simulatorResourceModel.addAttributeInt(KEY, val); - result = result && Integer.parseInt(simulatorResourceModel.getAttribute(KEY).getValue().toString()) == val; - } - catch(Exception e) - { - result = false; - } - - assertTrue(result); + public void testSimulatorResourceModel_P01() { + SimulatorResourceModel resModel = new SimulatorResourceModel(); + assertNotNull(resModel); } - public void testAddAttributeInt_N01() - { - int val = -10; + public void testAddAttributeInt_P01() { + int result = -1; - boolean result = true; - try - { - simulatorResourceModel.addAttributeInt(KEY, val); - result = result && Integer.parseInt(simulatorResourceModel.getAttribute(KEY).getValue().toString()) == val; - } - catch(Exception e) - { - result = false; + SimulatorResourceModel resModel = new SimulatorResourceModel(); + SimulatorResourceAttribute attribute = new SimulatorResourceAttribute( + INT_KEY, new AttributeValue(10), null); + try { + resModel.addAttribute(attribute); + result = ((Integer) resModel.getAttribute(INT_KEY).value().get()) + .intValue(); + } catch (InvalidArgsException e) { + e.printStackTrace(); } - assertTrue(result); + assertEquals(10, result); } - public void testAddAttributeInt_N02() - { - int val = 666666; + public void testAddAttributeInt_P02() { + int result = -1; - boolean result = true; - try - { - simulatorResourceModel.addAttributeInt(KEY, val); - result = result && Integer.parseInt(simulatorResourceModel.getAttribute(KEY).getValue().toString()) == val; - } - catch(Exception e) - { - result = false; + SimulatorResourceModel resModel = new SimulatorResourceModel(); + SimulatorResourceAttribute attribute = new SimulatorResourceAttribute( + INT_KEY, new AttributeValue(-10), null); + try { + resModel.addAttribute(attribute); + result = ((Integer) resModel.getAttribute(INT_KEY).value().get()) + .intValue(); + } catch (InvalidArgsException e) { + e.printStackTrace(); } - assertTrue(result); + assertEquals(-10, result); } - public void testAddAttributeDouble_P01() - { - double val = 10.11; + public void testAddAttributeDouble_P01() { + double result = 0.0; - boolean result = true; - try - { - simulatorResourceModel.addAttributeDouble(KEY, val); - result = result && Double.parseDouble(simulatorResourceModel.getAttribute(KEY).getValue().toString()) == val; - } - catch(Exception e) - { - result = false; + SimulatorResourceModel resModel = new SimulatorResourceModel(); + SimulatorResourceAttribute attribute = new SimulatorResourceAttribute( + DOUBLE_KEY, new AttributeValue(4.0), null); + try { + resModel.addAttribute(attribute); + result = ((Double) resModel.getAttribute(DOUBLE_KEY).value().get()) + .doubleValue(); + } catch (InvalidArgsException e) { + e.printStackTrace(); } - assertTrue(result); + assertEquals(4.0, result); } - public void testAddAttributeDouble_N01() - { - double val = -11.12; + public void testAddAttributeDouble_P02() { + double result = 0.0; - boolean result = true; - try - { - simulatorResourceModel.addAttributeDouble(KEY, val); - result = result && Double.parseDouble(simulatorResourceModel.getAttribute(KEY).getValue().toString()) == val; - } - catch(Exception e) - { - result = false; + SimulatorResourceModel resModel = new SimulatorResourceModel(); + SimulatorResourceAttribute attribute = new SimulatorResourceAttribute( + DOUBLE_KEY, new AttributeValue(-4.0), null); + try { + resModel.addAttribute(attribute); + result = ((Double) resModel.getAttribute(DOUBLE_KEY).value().get()) + .doubleValue(); + } catch (InvalidArgsException e) { + e.printStackTrace(); } - assertTrue(result); + assertEquals(-4.0, result); } - public void testAddAttributeDouble_N02() - { - double val = 0.0044444444444; + public void testAddAttributeBoolean_P01() { + boolean result = false; - boolean result = true; - try - { - simulatorResourceModel.addAttributeDouble(KEY, val); - result = result && Double.parseDouble(simulatorResourceModel.getAttribute(KEY).getValue().toString()) == val; - } - catch(Exception e) - { - result = false; + SimulatorResourceModel resModel = new SimulatorResourceModel(); + SimulatorResourceAttribute attribute = new SimulatorResourceAttribute( + BOOL_KEY, new AttributeValue(true), null); + try { + resModel.addAttribute(attribute); + result = ((Boolean) resModel.getAttribute(BOOL_KEY).value().get()) + .booleanValue(); + } catch (InvalidArgsException e) { + e.printStackTrace(); } - assertTrue(result); + assertEquals(true, result); } - public void testAddAttributeString_P01() - { - String val = "asdf"; + public void testAddAttributeString_P01() { + String result = null; - boolean result = true; - try - { - simulatorResourceModel.addAttributeString(KEY, val); - result = result && simulatorResourceModel.getAttribute(KEY).getValue().toString().equals(val); - } - catch(Exception e) - { - result = false; + SimulatorResourceModel resModel = new SimulatorResourceModel(); + SimulatorResourceAttribute attribute = new SimulatorResourceAttribute( + STRING_KEY, new AttributeValue("string-value"), null); + try { + resModel.addAttribute(attribute); + result = (String) resModel.getAttribute(STRING_KEY).value().get(); + } catch (InvalidArgsException e) { + e.printStackTrace(); } - assertTrue(result); + assertEquals("string-value", result); } - public void testAddAttributeString_N01() - { - String val = ""; + public void testAddAttributeString_P02() { + String result = null; - boolean result = true; - try - { - simulatorResourceModel.addAttributeString(KEY, val); - result = result && simulatorResourceModel.getAttribute(KEY).getValue().toString().equals(val); - } - catch(Exception e) - { - result = false; + SimulatorResourceModel resModel = new SimulatorResourceModel(); + SimulatorResourceAttribute attribute = new SimulatorResourceAttribute( + STRING_KEY, new AttributeValue(""), null); + try { + resModel.addAttribute(attribute); + result = (String) resModel.getAttribute(STRING_KEY).value().get(); + } catch (InvalidArgsException e) { + e.printStackTrace(); } - assertTrue(result); + assertEquals("", result); } - public void testAddAttributeString_N02() { - String val = null; + public void testAddAttributeString_P03() { + String result = null; - boolean result = false; + SimulatorResourceModel resModel = new SimulatorResourceModel(); + SimulatorResourceAttribute attribute = new SimulatorResourceAttribute( + STRING_KEY, new AttributeValue("@#$$&^*^(*^&"), null); try { - - simulatorResourceModel.addAttributeString(KEY, val); - - result = result && simulatorResourceModel.getAttribute(KEY).getValue().toString().equals(val); - - } catch(Exception e) { - result = true; + resModel.addAttribute(attribute); + result = (String) resModel.getAttribute(STRING_KEY).value().get(); + } catch (InvalidArgsException e) { + e.printStackTrace(); } - assertTrue(result); + assertEquals("@#$$&^*^(*^&", result); } - public void testAddAttributeString_N03() - { - String val = "@#$$&^*^(*^&"; + public void testSize_P01() { + int result = -1; - boolean result = true; - try - { - simulatorResourceModel.addAttributeString(KEY, val); - result = result && simulatorResourceModel.getAttribute(KEY).getValue().toString().equals(val); - } - catch(Exception e) - { - result = false; - } + SimulatorResourceModel resModel = new SimulatorResourceModel(); + result = resModel.size(); - assertTrue(result); + assertEquals(0, result); } - public void testAddAttributeBoolean_P01() - { - boolean result = true; - - boolean val; - - try - { - val=Boolean.parseBoolean("true"); - simulatorResourceModel.addAttributeBoolean(KEY, val); + public void testSize_P02() { + int result = -1; - result = result && ((Boolean.parseBoolean(simulatorResourceModel.getAttribute(KEY).getValue().toString()+""))); - - val = Boolean.parseBoolean("false"); - - simulatorResourceModel.addAttributeBoolean(KEY, val); - - result = result && !((Boolean.parseBoolean(simulatorResourceModel.getAttribute(KEY).getValue().toString()+""))); - } - catch (Exception e) - { - result = false; + SimulatorResourceModel resModel = new SimulatorResourceModel(); + try { + resModel.addAttribute(new SimulatorResourceAttribute(INT_KEY, + new AttributeValue(1234), null)); + resModel.addAttribute(new SimulatorResourceAttribute(DOUBLE_KEY, + new AttributeValue(1.234), null)); + resModel.addAttribute(new SimulatorResourceAttribute(BOOL_KEY, + new AttributeValue(true), null)); + resModel.addAttribute(new SimulatorResourceAttribute(STRING_KEY, + new AttributeValue("string-value"), null)); + result = resModel.size(); + } catch (InvalidArgsException e) { + e.printStackTrace(); } - assertTrue(result); + assertEquals(4, result); } - public void testSize_P01() - { - boolean result = true; - - try - { - simulatorResourceModel.addAttributeInt("test1", 1234); - - result = result && (simulatorResourceModel.size() == 1); + public void testGetAttribute_P01() { + SimulatorResourceAttribute result = null; - simulatorResourceModel.addAttributeString("test2", "asdf"); - simulatorResourceModel.addAttributeBoolean("test3", Boolean.parseBoolean("true")); - simulatorResourceModel.addAttributeDouble("test4", 22.435234); - - result = result && (simulatorResourceModel.size() == 4); - } - catch(Exception e) - { - result = false; + SimulatorResourceModel resModel = new SimulatorResourceModel(); + try { + resModel.addAttribute(new SimulatorResourceAttribute(INT_KEY, + new AttributeValue(10), null)); + result = resModel.getAttribute(INT_KEY); + } catch (InvalidArgsException e) { + e.printStackTrace(); } - assertTrue(result); - } - - public void testGetAttributes_P01() - { - boolean result = true; - - try - { - simulatorResourceModel.addAttributeInt("test1", 1234); - simulatorResourceModel.addAttributeString("test2", "asdf"); - simulatorResourceModel.addAttributeBoolean("test3", Boolean.parseBoolean("true")); - simulatorResourceModel.addAttributeDouble("test4", 22.435234); - - Map attributes = simulatorResourceModel.getAttributes(); - result = result && (((Integer)attributes.get("test1").getValue()) == 1234) && - (((String)attributes.get("test2").getValue()).equals("asdf")) && - ((Boolean.parseBoolean(attributes.get("test3").getValue().toString() + "")==true)) && - (((Double)attributes.get("test4").getValue()) == 22.435234); - } - catch(Exception e) - { - result = false; - } - assertTrue(result); + assertNotNull(result); } - public void testGetAttribute_P01() - { - int val = 100; - - boolean result = true; - - try - { - simulatorResourceModel.addAttributeInt(KEY, val); + public void testGetAttributes_P01() { + Map result = null; - result = result && Integer.parseInt(simulatorResourceModel.getAttribute(KEY).getValue().toString()) == val; - } - catch(Exception e) - { - result = false; - } - assertTrue(result); + SimulatorResourceModel resModel = new SimulatorResourceModel(); + try { + resModel.addAttribute(new SimulatorResourceAttribute(INT_KEY, + new AttributeValue(1234), null)); + resModel.addAttribute(new SimulatorResourceAttribute(DOUBLE_KEY, + new AttributeValue(1.234), null)); + resModel.addAttribute(new SimulatorResourceAttribute(BOOL_KEY, + new AttributeValue(true), null)); + resModel.addAttribute(new SimulatorResourceAttribute(STRING_KEY, + new AttributeValue("string-value"), null)); + result = resModel.getAttributes(); + } catch (InvalidArgsException e) { + e.printStackTrace(); + } + + assertNotNull(result); + assertEquals(4, result.size()); } } diff --git a/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/SimulatorObserveType.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/utils/ObjectHolder.java similarity index 68% rename from service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/SimulatorObserveType.java rename to service/simulator/unittests/SimulatorTest/src/org/oic/simulator/utils/ObjectHolder.java index 9f32d1c..b0d3fe2 100644 --- a/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/SimulatorObserveType.java +++ b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/utils/ObjectHolder.java @@ -14,21 +14,16 @@ * limitations under the License. */ -package org.oic.simulator.clientcontroller; +package org.oic.simulator.utils; -/** - * Enum for observe types. - */ -public enum SimulatorObserveType { - OBSERVE(0), OBSERVE_ALL(1); - - private int value; +public class ObjectHolder { + private T mObject; - private SimulatorObserveType(int value) { - this.value = value; + public void set(T object) { + mObject = object; } - public int getValue() { - return this.value; + public T get() { + return mObject; } } diff --git a/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/utils/SampleSingleResource.java b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/utils/SampleSingleResource.java new file mode 100644 index 0000000..fd88189 --- /dev/null +++ b/service/simulator/unittests/SimulatorTest/src/org/oic/simulator/utils/SampleSingleResource.java @@ -0,0 +1,59 @@ +/* + * Copyright 2015 Samsung Electronics All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.oic.simulator.utils; + +import org.oic.simulator.InvalidArgsException; +import org.oic.simulator.SimulatorException; +import org.oic.simulator.SimulatorManager; +import org.oic.simulator.server.SimulatorResource; +import org.oic.simulator.server.SimulatorSingleResource; + +public class SampleSingleResource { + + private SimulatorSingleResource mResource; + public String mName = "test-singleresource"; + public String mUri = "/test/singleresource"; + public String mResourceType = "test.singleresource"; + + public boolean start() { + try { + mResource = (SimulatorSingleResource) SimulatorManager + .createResource(SimulatorResource.Type.SINGLE, mName, mUri, + mResourceType); + mResource.start(); + return true; + } catch (InvalidArgsException e) { + e.printStackTrace(); + } catch (SimulatorException e) { + e.printStackTrace(); + } + + return false; + } + + public boolean stop() { + try { + mResource.stop(); + mResource = null; + return true; + } catch (SimulatorException e) { + e.printStackTrace(); + } + + return false; + } +} -- 2.7.4