Merge branch 'master' into simulator
authorG S Senthil Kumar <senthil.gs@samsung.com>
Tue, 1 Sep 2015 06:46:09 +0000 (12:16 +0530)
committerG S Senthil Kumar <senthil.gs@samsung.com>
Tue, 1 Sep 2015 06:46:09 +0000 (12:16 +0530)
Change-Id: I991a4d46eaa2cf073cdad357bc11b373971837be
Signed-off-by: G S Senthil Kumar <senthil.gs@samsung.com>
157 files changed:
extlibs/yaml/SConscript [new file with mode: 0755]
service/SConscript
service/simulator/SConscript [new file with mode: 0644]
service/simulator/examples/README.txt [new file with mode: 0755]
service/simulator/examples/client-controller/SConscript [new file with mode: 0644]
service/simulator/examples/client-controller/client_controller.cpp [new file with mode: 0644]
service/simulator/examples/resources/light.raml [new file with mode: 0755]
service/simulator/examples/resources/oic.light.json [new file with mode: 0755]
service/simulator/examples/server/SConscript [new file with mode: 0644]
service/simulator/examples/server/service_provider.cpp [new file with mode: 0644]
service/simulator/inc/simulator_manager.h [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/.classpath [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/.project [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/META-INF/MANIFEST.MF [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/README.txt [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/build.properties [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/clear_d.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/clear_e.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/debug_log.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/delete_d.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/delete_e.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/error_log.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/export_log_d.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/export_log_e.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/filter_d.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/filter_e.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/info_log.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/lock_d.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/lock_e.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/log_details_e.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/oic_logo_16x16.png [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/oic_logo_32x32.png [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/oic_logo_64x64.png [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/prop_d.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/prop_e.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/sample.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/trash_e.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/tree_mode_d.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/tree_mode_e.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/unknown_log.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/warning_log.gif [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/libs/Simulator.jar [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/plugin.xml [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/logger/LogContentProvider.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/logger/LogEntry.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/logger/LogLabelProvider.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/logger/LoggerCallback.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/Activator.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IAutomationUIListener.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/ILogUIListener.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IResourceListChangedUIListener.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IResourceModelChangedUIListener.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IResourceSelectionChangedUIListener.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/manager/LogManager.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/manager/ResourceManager.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/perspective/PerspectiveFactory.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/AttributeValueType.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/AutomationSettingHelper.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/MetaProperty.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/ModelChangeNotificationType.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/ResourceAttribute.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/SimulatorResource.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/StandardConfiguration.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/utils/Constants.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/utils/Utility.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/AttributeView.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/LogDetailsDialog.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/LogView.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/MetaPropertiesView.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/MultiResourceOrchestrationView.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/ResourceManagerView.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/CreateResourcePage.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/CreateResourceWizard.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/DeleteCategory.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/DeleteResourcePage.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/DeleteResourceWizard.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/FilterDialog.java [new file with mode: 0644]
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/ResourceWizardDialog.java [new file with mode: 0644]
service/simulator/java/jni/simulator_common_jni.h [new file with mode: 0644]
service/simulator/java/jni/simulator_manager_jni.cpp [new file with mode: 0644]
service/simulator/java/jni/simulator_manager_jni.h [new file with mode: 0644]
service/simulator/java/jni/simulator_remote_resource_jni.cpp [new file with mode: 0644]
service/simulator/java/jni/simulator_remote_resource_jni.h [new file with mode: 0644]
service/simulator/java/jni/simulator_resource_attributes_jni.cpp [new file with mode: 0644]
service/simulator/java/jni/simulator_resource_attributes_jni.h [new file with mode: 0644]
service/simulator/java/jni/simulator_resource_jni_util.cpp [new file with mode: 0644]
service/simulator/java/jni/simulator_resource_jni_util.h [new file with mode: 0644]
service/simulator/java/jni/simulator_resource_model_jni.cpp [new file with mode: 0644]
service/simulator/java/jni/simulator_resource_model_jni.h [new file with mode: 0644]
service/simulator/java/jni/simulator_resource_server_jni.cpp [new file with mode: 0644]
service/simulator/java/jni/simulator_resource_server_jni.h [new file with mode: 0644]
service/simulator/java/sdk/.classpath [new file with mode: 0644]
service/simulator/java/sdk/.project [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/AutomationType.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/IAutomation.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/ILogger.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/OCSimulatorResult.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/SimulatorManager.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/SimulatorManagerNativeInterface.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/SimulatorResourceAttribute.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IFindResourceListener.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IGetListener.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IObserveListener.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IPostListener.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IPutListener.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/SimulatorObserveType.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/SimulatorRemoteResource.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/serviceprovider/IResourceModelChangedListener.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/serviceprovider/SimulatorResourceModel.java [new file with mode: 0644]
service/simulator/java/sdk/src/org/oic/simulator/serviceprovider/SimulatorResourceServer.java [new file with mode: 0644]
service/simulator/ramlparser/SConscript [new file with mode: 0755]
service/simulator/ramlparser/raml/IncludeResolver.cpp [new file with mode: 0755]
service/simulator/ramlparser/raml/IncludeResolver.h [new file with mode: 0755]
service/simulator/ramlparser/raml/RamlParser.cpp [new file with mode: 0755]
service/simulator/ramlparser/raml/RamlParser.h [new file with mode: 0755]
service/simulator/ramlparser/raml/Utils.h [new file with mode: 0755]
service/simulator/ramlparser/raml/model/AbstractParam.cpp [new file with mode: 0755]
service/simulator/ramlparser/raml/model/AbstractParam.h [new file with mode: 0755]
service/simulator/ramlparser/raml/model/Action.cpp [new file with mode: 0755]
service/simulator/ramlparser/raml/model/Action.h [new file with mode: 0755]
service/simulator/ramlparser/raml/model/ActionType.h [new file with mode: 0755]
service/simulator/ramlparser/raml/model/DocumentationItem.cpp [new file with mode: 0755]
service/simulator/ramlparser/raml/model/DocumentationItem.h [new file with mode: 0755]
service/simulator/ramlparser/raml/model/FormParameter.h [new file with mode: 0755]
service/simulator/ramlparser/raml/model/Header.h [new file with mode: 0755]
service/simulator/ramlparser/raml/model/QueryParameter.h [new file with mode: 0755]
service/simulator/ramlparser/raml/model/Raml.cpp [new file with mode: 0755]
service/simulator/ramlparser/raml/model/Raml.h [new file with mode: 0755]
service/simulator/ramlparser/raml/model/RamlResource.cpp [new file with mode: 0755]
service/simulator/ramlparser/raml/model/RamlResource.h [new file with mode: 0755]
service/simulator/ramlparser/raml/model/RequestResponseBody.cpp [new file with mode: 0755]
service/simulator/ramlparser/raml/model/RequestResponseBody.h [new file with mode: 0755]
service/simulator/ramlparser/raml/model/ResourceProperties.cpp [new file with mode: 0755]
service/simulator/ramlparser/raml/model/ResourceProperties.h [new file with mode: 0755]
service/simulator/ramlparser/raml/model/Response.cpp [new file with mode: 0755]
service/simulator/ramlparser/raml/model/Response.h [new file with mode: 0755]
service/simulator/ramlparser/raml/model/Schema.cpp [new file with mode: 0755]
service/simulator/ramlparser/raml/model/Schema.h [new file with mode: 0755]
service/simulator/ramlparser/raml/model/UriParameter.h [new file with mode: 0755]
service/simulator/src/resource_manager.cpp [new file with mode: 0644]
service/simulator/src/resource_manager.h [new file with mode: 0644]
service/simulator/src/simulator_attribute_automation.cpp [new file with mode: 0644]
service/simulator/src/simulator_attribute_automation.h [new file with mode: 0644]
service/simulator/src/simulator_client.cpp [new file with mode: 0644]
service/simulator/src/simulator_client.h [new file with mode: 0644]
service/simulator/src/simulator_error_codes.h [new file with mode: 0644]
service/simulator/src/simulator_logger.cpp [new file with mode: 0644]
service/simulator/src/simulator_logger.h [new file with mode: 0644]
service/simulator/src/simulator_manager.cpp [new file with mode: 0644]
service/simulator/src/simulator_remote_resource.cpp [new file with mode: 0644]
service/simulator/src/simulator_remote_resource.h [new file with mode: 0644]
service/simulator/src/simulator_resource_creator.cpp [new file with mode: 0644]
service/simulator/src/simulator_resource_creator.h [new file with mode: 0644]
service/simulator/src/simulator_resource_model.cpp [new file with mode: 0644]
service/simulator/src/simulator_resource_model.h [new file with mode: 0644]
service/simulator/src/simulator_resource_server.cpp [new file with mode: 0644]
service/simulator/src/simulator_resource_server.h [new file with mode: 0644]

diff --git a/extlibs/yaml/SConscript b/extlibs/yaml/SConscript
new file mode 100755 (executable)
index 0000000..4cd8948
--- /dev/null
@@ -0,0 +1,54 @@
+#******************************************************************\r
+#\r
+# Copyright 2014 Samsung Electronics All Rights Reserved.\r
+#\r
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+#\r
+# Licensed under the Apache License, Version 2.0 (the "License");\r
+# you may not use this file except in compliance with the License.\r
+# You may obtain a copy of the License at\r
+#\r
+#      http://www.apache.org/licenses/LICENSE-2.0\r
+#\r
+# Unless required by applicable law or agreed to in writing, software\r
+# distributed under the License is distributed on an "AS IS" BASIS,\r
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+# See the License for the specific language governing permissions and\r
+# limitations under the License.\r
+#\r
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+\r
+import os\r
+Import('env')\r
+\r
+yaml_env = env.Clone()\r
+src_dir = env.get('SRC_DIR')\r
+\r
+yamlDir = os.path.join(src_dir, 'extlibs','yaml','yaml')\r
+\r
+if not os.path.exists(yamlDir):\r
+    print '''\r
+*********************************** Error: ****************************************\r
+* Please download yaml using the following command:                               *\r
+*     $ git clone https://github.com/jbeder/yaml-cpp.git extlibs/yaml/yaml *\r
+***********************************************************************************\r
+'''\r
+    Exit(1)\r
+\r
+######################################################################\r
+# Build flags\r
+######################################################################\r
+yaml_env.AppendUnique(CPPPATH = ['yaml/src' , 'yaml/include'])\r
+yaml_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])\r
+yaml_env.AppendUnique(CPPDEFINES = ['LINUX'])\r
+yaml_env.AppendUnique(LIBS = ['pthread'])\r
+\r
+yaml_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x'])\r
+\r
+######################################################################\r
+# Source files and Targets\r
+######################################################################\r
+yaml_src = [env.Glob('yaml/src/*.cpp'), env.Glob('yaml/src/contrib/*.cpp')]\r
+yamlsdk = yaml_env.StaticLibrary('YamlParser', yaml_src)\r
+\r
+yaml_env.InstallTarget(yamlsdk, 'libYaml')\r
index 75270d7..d6d8a5b 100644 (file)
@@ -44,6 +44,11 @@ if target_os not in ['arduino','darwin','ios']:
 
        # Build resource-encapsulation project
        SConscript('resource-encapsulation/SConscript')
+
+       # Build simulator module
+       if target_os in ['linux']:
+               SConscript('simulator/SConscript')
 #else:
 #      SConscript('notification-manager/SampleApp/arduino/SConscript')
 
+
diff --git a/service/simulator/SConscript b/service/simulator/SConscript
new file mode 100644 (file)
index 0000000..ce9a46c
--- /dev/null
@@ -0,0 +1,84 @@
+#******************************************************************
+#
+# Copyright 2014 Samsung Electronics All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+##
+# Simulator build script
+##
+
+import os
+Import('env')
+
+lib_env = env.Clone()
+SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env')
+simulator_env = lib_env.Clone()
+
+target_os = env.get('TARGET_OS')
+######################################################################
+# Build flags
+######################################################################
+simulator_env.AppendUnique(CPPPATH = ['inc', 'src'])
+simulator_env.AppendUnique(CPPPATH = [
+               '../../resource/include/',
+               '../../resource/csdk/stack/include',
+               '../../resource/csdk/ocrandom/include',
+               '../../resource/csdk/logger/include',
+               '../../resource/oc_logger/include',
+               './ramlparser/raml',
+               './ramlparser/raml/model',              
+               '../../extlibs/yaml/yaml/include'
+               ])
+
+# Including Java path for building JNI files
+try:
+       os.environ['JAVA_HOME']
+except KeyError:
+       print '''
+*************************************** Error *********************************
+* JAVA_HOME environment variable not set                                      
+* Simulator has dependency on java, Please set environment variable JAVA_HOME
+*******************************************************************************
+       '''
+       sys.exit(1)
+       
+java_headers = [os.path.join(os.environ['JAVA_HOME'], 'include')]
+java_headers.append(os.path.join(java_headers[0], 'win32'))
+java_headers.append(os.path.join(java_headers[0], 'linux'))
+java_headers.append(os.path.join(java_headers[0], 'solaris'))
+simulator_env.AppendUnique(CPPPATH = java_headers)
+
+simulator_env.AppendUnique(CPPPATH = ['../../extlibs/cjson'])
+simulator_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'libcoap','RamlParser','YamlParser'])
+simulator_env.AppendUnique(LIBS = ['pthread'])
+
+simulator_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x'])
+
+######################################################################
+# Source files and Targets
+######################################################################
+simulator_src = [env.Glob('src/*.cpp'), env.Glob('java/jni/*.cpp')]
+simulatorsdk = simulator_env.SharedLibrary('SimulatorManager', simulator_src)
+
+simulator_env.InstallTarget(simulatorsdk, 'libSimulator')
+
+#Build sample application
+SConscript('examples/server/SConscript')
+SConscript('examples/client-controller/SConscript')
+#Raml Parser
+SConscript('ramlparser/SConscript')
diff --git a/service/simulator/examples/README.txt b/service/simulator/examples/README.txt
new file mode 100755 (executable)
index 0000000..1bec229
--- /dev/null
@@ -0,0 +1,3 @@
+Command to run Service Provider with Resource definitions provided throught RAML file :\r
+./simulator-server  ../../../../../../../../service/simulator/examples/resources/light.raml\r
+\r
diff --git a/service/simulator/examples/client-controller/SConscript b/service/simulator/examples/client-controller/SConscript
new file mode 100644 (file)
index 0000000..ade7410
--- /dev/null
@@ -0,0 +1,29 @@
+Import('env')
+lib_env = env.Clone()
+SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env')
+sim_env = lib_env.Clone()
+
+######################################################################
+# Build flags
+######################################################################
+sim_env.AppendUnique(CPPPATH = ['../../../../extlibs/timer'])
+sim_env.AppendUnique(CPPPATH = ['../../inc'])
+sim_env.AppendUnique(CPPPATH = ['../../src'])
+sim_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
+sim_env.AppendUnique(CPPDEFINES = ['LINUX'])
+sim_env.AppendUnique(LIBS = ['SimulatorManager'])
+
+sim_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+sim_env.AppendUnique(RPATH = [env.get('BUILD_DIR')])
+sim_env.PrependUnique(LIBS = ['SimulatorManager'])
+
+if sim_env.get('SECURED') == '1':
+    sim_env.AppendUnique(LIBS = ['tinydtls'])
+
+######################################################################
+# Source files and Targets
+######################################################################
+clientcontroller = sim_env.Program('client-controller', 'client_controller.cpp')
+
+Alias("clientcontroller", clientcontroller)
+env.AppendTarget('clientcontroller')
diff --git a/service/simulator/examples/client-controller/client_controller.cpp b/service/simulator/examples/client-controller/client_controller.cpp
new file mode 100644 (file)
index 0000000..f48a2a4
--- /dev/null
@@ -0,0 +1,388 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "simulator_manager.h"
+
+class AppLogger : public ILogger
+{
+    public:
+        void write(std::string time, ILogger::Level level, std::string message)
+        {
+            std::cout << "[APPLogger] " << time << " " << ILogger::getString(level) << " " << message;
+        }
+};
+std::shared_ptr<AppLogger> gAppLogger(new AppLogger());
+
+class ClientController
+{
+    public:
+        void startTest()
+        {
+            printMenu();
+            bool cont = true;
+            while (cont)
+            {
+                int choice = -1;
+                std::cout << "Enter your choice: ";
+                std::cin >> choice;
+                if (choice < 0 || choice > 8)
+                {
+                    std::cout << "Invaild choice !" << std::endl; continue;
+                }
+
+                switch (choice)
+                {
+                    case 1: findResource(); break;
+                    case 2: displayResource(); break;
+                    case 3: observeResource(); break;
+                    case 4: cancelObserving(); break;
+                    case 5: sendGet(); break;
+                    case 6: sendPut(); break;
+                    case 7: sendPost(); break;
+                    case 8: printMenu(); break;
+                    case 0: cont = false;
+                }
+            }
+        }
+
+    private:
+        void printMenu()
+        {
+            std::cout << "########### SIMULATOR CLIENT CONTROLLER ###########" << std::endl;
+            std::cout << "1. Find resource" << std::endl;
+            std::cout << "2. Display resource information" << std::endl;
+            std::cout << "3. Observe for resource change" << std::endl;
+            std::cout << "4. Cancel observation" << std::endl;
+            std::cout << "5. Send GET message" << std::endl;
+            std::cout << "6. Send PUT message" << std::endl;
+            std::cout << "7. Send POST message" << std::endl;
+            std::cout << "8: Help" << std::endl;
+            std::cout << "0. Exit" << std::endl;
+            std::cout << "###################################################" << std::endl;
+        }
+
+        int selectResource(std::vector<SimulatorRemoteResourcePtr> resourceList)
+        {
+            if (0 == resourceList.size())
+            {
+                std::cout << "No resouces!" << std::endl;
+                return -1;
+            }
+
+            int index = 1;
+            for (auto & resource : resourceList)
+            {
+                std::cout << index++ << ": " << resource->getURI() << "[" << resource->getHost()  << "]" << 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 findResource()
+        {
+            std::string resourceType;
+            std::cout << "Enter resource type : ";
+            std::cin >> resourceType;
+
+            ResourceFindCallback callback = [this](std::shared_ptr<SimulatorRemoteResource> resource)
+            {
+                std::cout << "Resource found ######" << std::endl;
+                displayResource(resource);
+            };
+
+            SimulatorResult result = SimulatorManager::getInstance()->findResource
+                                          (resourceType, callback);
+            if (SIMULATOR_SUCCESS != result)
+                std::cout << "SimulatorManager::findResource returned error : " << result << std::endl;
+        }
+
+        void displayResource()
+        {
+            std::vector<SimulatorRemoteResourcePtr> resourceList =
+                SimulatorManager::getInstance()->getFoundResources();
+
+            int index = selectResource(resourceList);
+            if (-1 == index)
+                return;
+
+            displayResource(resourceList[index - 1]);
+        }
+
+        void displayResource(SimulatorRemoteResourcePtr resource)
+        {
+            std::cout << "#############################" << std::endl;
+            std::cout << "URI: " << resource->getURI().c_str() << std::endl;
+            std::cout << "Host: " << resource->getHost().c_str() << std::endl;
+            std::cout << "Resource Types: ";
+            for (auto &type : resource->getResourceTypes())
+                std::cout << type << " ";
+            std::cout << "\nInterface Types: ";
+            for (auto &type : resource->getResourceInterfaces())
+                std::cout << type << " ";
+            std::cout << std::boolalpha << "\nisObservable : " << resource->isObservable() << std::endl;
+            std::cout << "#############################" << std::endl;
+        }
+
+        void observeResource()
+        {
+            std::vector<SimulatorRemoteResourcePtr> resourceList =
+                SimulatorManager::getInstance()->getFoundResources();
+
+            int index = selectResource(resourceList);
+            if (-1 == index)
+                return;
+
+            SimulatorRemoteResourcePtr resource = resourceList[index - 1];
+
+            // callback implementaion
+            SimulatorRemoteResource::RepresentationChangeCallback callback =
+            [](int errorCode, const SimulatorResourceModel &rep, int seq)
+            {
+                std::cout << "\nObserve notificatoin received ###[errorcode:  " << errorCode << " seq:  " << seq << "]" << std::endl;
+                std::map<std::string, SimulatorResourceModel::Attribute> attributes = rep.getAttributes();
+                for (auto & attribute : attributes)
+                {
+                    std::cout << (attribute.second).getName() << " :  {" << std::endl;
+                    std::cout << "value: " << (attribute.second).valueToString().c_str() << std::endl;
+                    std::cout << "}" << std::endl;
+                }
+                std::cout << std::endl;
+            };
+
+            std::map <std::string, std::string> queryParams;
+            SimulatorResult result = resource->observe(SimulatorRemoteResource::OBSERVE, queryParams, callback);
+            if ( SIMULATOR_SUCCESS == result)
+                std::cout << "Observe is successfull!" << std::endl;
+            else
+                std::cout << "Observe is failed!error: " << result << std::endl;
+        }
+
+        void cancelObserving()
+        {
+            std::vector<SimulatorRemoteResourcePtr> resourceList =
+                SimulatorManager::getInstance()->getFoundResources();
+
+            int index = selectResource(resourceList);
+            if (-1 == index)
+                return;
+
+            SimulatorRemoteResourcePtr resource = resourceList[index - 1];
+            SimulatorResult result = resource->cancelObserve();
+            if ( SIMULATOR_SUCCESS == result)
+                std::cout << "Cancelling observe is successfull!" << std::endl;
+            else
+                std::cout << "Cancelling observe is failed!error: " << result << std::endl;
+        }
+
+        void sendGet()
+        {
+            std::vector<SimulatorRemoteResourcePtr> resourceList =
+                SimulatorManager::getInstance()->getFoundResources();
+
+            int index = selectResource(resourceList);
+            if (-1 == index)
+                return;
+
+            SimulatorRemoteResourcePtr resource = resourceList[index - 1];
+
+            // callback implementaion
+            SimulatorRemoteResource::ResponseCallback callback =
+            [](int errorCode, const SimulatorResourceModel & rep)
+            {
+                std::cout << "\nGET Response received ### [errorcode:  " << errorCode << "]" << std::endl;
+                std::cout << "Representation is: " << std::endl;
+                std::map<std::string, SimulatorResourceModel::Attribute> attributes = rep.getAttributes();
+                for (auto & attribute : attributes)
+                {
+                    std::cout << (attribute.second).getName() << " :  {" << std::endl;
+                    std::cout << "value: " << (attribute.second).valueToString().c_str() << std::endl;
+                    std::cout << "}" << std::endl;
+                }
+                std::cout << std::endl;
+            };
+
+            std::map <std::string, std::string> queryParams;
+            SimulatorResult result = resource->get(queryParams, callback);
+            if ( SIMULATOR_SUCCESS == result)
+                std::cout << "GET is successfull!" << std::endl;
+            else
+                std::cout << "GET is failed!error: " << result << std::endl;
+        }
+
+        void sendPut()
+        {
+            std::vector<SimulatorRemoteResourcePtr> resourceList =
+                SimulatorManager::getInstance()->getFoundResources();
+
+            int index = selectResource(resourceList);
+            if (-1 == index)
+                return;
+
+            SimulatorRemoteResourcePtr resource = resourceList[index - 1];
+
+            // callback implementaion
+            SimulatorRemoteResource::ResponseCallback callback =
+            [](int errorCode, const SimulatorResourceModel & rep)
+            {
+                std::cout << "\nPUT Response received ![errorcode:  " << errorCode << "]" << std::endl;
+                std::cout << "Representation is: " << std::endl;
+                std::map<std::string, SimulatorResourceModel::Attribute> attributes = rep.getAttributes();
+                for (auto & attribute : attributes)
+                {
+                    std::cout << (attribute.second).getName() << " :  {" << std::endl;
+                    std::cout << "value: " << (attribute.second).valueToString().c_str() << std::endl;
+                    std::cout << "}" << std::endl;
+                }
+                std::cout << std::endl;
+            };
+
+            std::map <std::string, std::string> queryParams;
+            SimulatorResourceModel rep;
+            rep.addAttribute("power", "off");
+            rep.addAttribute("intensity", 5);
+
+            SimulatorResult result = resource->put(rep, queryParams, callback);
+            if ( SIMULATOR_SUCCESS == result)
+                std::cout << "PUT is successfull!" << std::endl;
+            else
+                std::cout << "PUT is failed!error: " << result << std::endl;
+        }
+
+        void sendPost()
+        {
+            std::vector<SimulatorRemoteResourcePtr> resourceList =
+                SimulatorManager::getInstance()->getFoundResources();
+
+            int index = selectResource(resourceList);
+            if (-1 == index)
+                return;
+
+            SimulatorRemoteResourcePtr resource = resourceList[index - 1];
+
+            // callback implementaion
+            SimulatorRemoteResource::ResponseCallback callback =
+            [](int errorCode, const SimulatorResourceModel & rep)
+            {
+                std::cout << "\nPOST Response received ![errorcode:  " << errorCode << "]" << std::endl;
+                std::cout << "Representation is: " << std::endl;
+                std::map<std::string, SimulatorResourceModel::Attribute> attributes = rep.getAttributes();
+                for (auto & attribute : attributes)
+                {
+                    std::cout << (attribute.second).getName() << " :  {" << std::endl;
+                    std::cout << "value: " << (attribute.second).valueToString().c_str() << std::endl;
+                    std::cout << "}" << std::endl;
+                }
+                std::cout << std::endl;
+            };
+
+            std::map <std::string, std::string> queryParams;
+            SimulatorResourceModel rep;
+            rep.addAttribute("power", "on");
+            rep.addAttribute("intensity", 7);
+
+            SimulatorResult result = resource->post(rep, queryParams, callback);
+            if ( SIMULATOR_SUCCESS == result)
+                std::cout << "POST is successfull!" << std::endl;
+            else
+                std::cout << "POST is failed!error: " << result << std::endl;
+        }
+};
+
+void printMainMenu()
+{
+    std::cout << "############### MAIN MENU###############" << std::endl;
+    std::cout << "1. Client Controller Test" << std::endl;
+    std::cout << "2. Set Logger" << std::endl;
+    std::cout << "3. Help" << std::endl;
+    std::cout << "0. Exit" << std::endl;
+    std::cout << "######################################" << std::endl;
+}
+
+void setLogger()
+{
+    std::cout << "1. Default console logger" << std::endl;
+    std::cout << "2. Default file logger" << std::endl;
+    std::cout << "3. custom logger" << std::endl;
+
+    int choice = -1;
+    std::cin >> choice;
+    if (choice <= 0 || choice > 3)
+    {
+        std::cout << "Invalid selection !" << std::endl;
+        return;
+    }
+
+    switch (choice)
+    {
+        case 1:
+            {
+                if (false == SimulatorManager::getInstance()->setDefaultConsoleLogger())
+                    std::cout << "Failed to set the default console logger" << std::endl;
+            } break;
+        case 2:
+            {
+                std::string filePath;
+                std::cout << "Enter the file path (without file name) : ";
+                std::cin >> filePath;
+                if (false == SimulatorManager::getInstance()->setDefaultFileLogger(filePath))
+                    std::cout << "Failed to set default file logger" << std::endl;
+            } break;
+        case 3: SimulatorManager::getInstance()->setLogger(gAppLogger);
+    }
+}
+
+int main(void)
+{
+    ClientController clientController;
+    printMainMenu();
+    bool cont = true;
+    while (cont == true)
+    {
+        int choice = -1;
+        std::cout << "Enter your choice: ";
+        std::cin >> choice;
+        if (choice < 0 || choice > 3)
+        {
+            std::cout << "Invaild choice !" << std::endl; continue;
+        }
+
+        switch (choice)
+        {
+            case 1: clientController.startTest();
+                std::cout << "Welcome back to main menu !" << std::endl;
+                break;
+            case 2: setLogger(); break;
+            case 3: printMainMenu(); break;
+            case 0: cont = false;
+        }
+    }
+
+    std::cout << "Terminating test !!!" << std::endl;
+}
diff --git a/service/simulator/examples/resources/light.raml b/service/simulator/examples/resources/light.raml
new file mode 100755 (executable)
index 0000000..db3e037
--- /dev/null
@@ -0,0 +1,27 @@
+#%RAML 0.8
+#RAML for Light Resource
+title: Resource Light
+version: 1.0
+mediaType : application/json
+schemas:
+- 
+  lightPublish: !include oic.light.json
+
+/oic/light:
+  displayName: Resource Light
+  description: |
+    Resource to be exposed by any OIC Device that can act as Light
+  get:
+    description: |
+      Get the attributes of light
+    responses:
+      200:
+        description: |
+          Respond with the selector criteria
+        body:
+          application/json:
+            schema: !include oic.light.json
+            example: |
+              {
+              
+              }
\ No newline at end of file
diff --git a/service/simulator/examples/resources/oic.light.json b/service/simulator/examples/resources/oic.light.json
new file mode 100755 (executable)
index 0000000..fd27af8
--- /dev/null
@@ -0,0 +1,21 @@
+{\r
+  "title": "light",\r
+  "rt": "oic.light",\r
+  "if": "oic.if.baseline",\r
+  "properties": {\r
+    "power": {\r
+      "type": "string",\r
+      "description": "Light status",\r
+      "values": ["on","off"],\r
+      "default": "on",\r
+      "update_frequency": 1000\r
+    },\r
+    "intensity": {\r
+      "type": "integer",\r
+      "description": "brightness of the light",\r
+      "range": [1,9],\r
+      "default": 1,\r
+      "update_frequency": 1001\r
+    }\r
+  }\r
+}
\ No newline at end of file
diff --git a/service/simulator/examples/server/SConscript b/service/simulator/examples/server/SConscript
new file mode 100644 (file)
index 0000000..417ca75
--- /dev/null
@@ -0,0 +1,29 @@
+Import('env')
+lib_env = env.Clone()
+SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env')
+sim_env = lib_env.Clone()
+
+######################################################################
+# Build flags
+######################################################################
+sim_env.AppendUnique(CPPPATH = ['../../../../extlibs/timer'])
+sim_env.AppendUnique(CPPPATH = ['../../inc'])
+sim_env.AppendUnique(CPPPATH = ['../../src'])
+sim_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
+sim_env.AppendUnique(CPPDEFINES = ['LINUX'])
+sim_env.AppendUnique(LIBS = ['SimulatorManager'])
+
+sim_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+sim_env.AppendUnique(RPATH = [env.get('BUILD_DIR')])
+sim_env.PrependUnique(LIBS = ['SimulatorManager'])
+
+if sim_env.get('SECURED') == '1':
+    sim_env.AppendUnique(LIBS = ['tinydtls'])
+
+######################################################################
+# Source files and Targets
+######################################################################
+simulatorserver = sim_env.Program('simulator-server', 'service_provider.cpp')
+
+Alias("simulatorserver", simulatorserver)
+env.AppendTarget('simulatorserver')
diff --git a/service/simulator/examples/server/service_provider.cpp b/service/simulator/examples/server/service_provider.cpp
new file mode 100644 (file)
index 0000000..6413b12
--- /dev/null
@@ -0,0 +1,554 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "simulator_manager.h"
+
+class AppLogger : public ILogger
+{
+    public:
+        void write(std::string time, ILogger::Level level, std::string message)
+        {
+            std::cout << "[APPLogger] " << time << " " << ILogger::getString(level) << " " << message;
+        }
+};
+std::shared_ptr<AppLogger> gAppLogger(new AppLogger());
+
+class SimLightResource
+{
+    public:
+        void startTest(std::string &configPath)
+        {
+            printMenu();
+            bool cont = true;
+            while (cont)
+            {
+                int choice = -1;
+                std::cout << "Enter your choice: ";
+                std::cin >> choice;
+                if (choice < 0 || choice > 9)
+                {
+                    std::cout << "Invaild choice !" << std::endl; continue;
+                }
+
+                switch (choice)
+                {
+                    case 1 : simulateResource(configPath); break;
+                    case 2: displayResource(); break;
+                    case 3: deleteResource(); break;
+                    case 4: updateAttributePower(); break;
+                    case 5: updateAttributeIntensity(); break;
+                    case 6: automateResourceUpdate(); break;
+                    case 7: automateAttributeUpdate(); break;
+                    case 8: stopAutomation(); break;
+                    case 9: 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: Help" << std::endl;
+            std::cout << "0. Exit" << std::endl;
+            std::cout << "#######################################" << std::endl;
+        }
+
+        int selectResource()
+        {
+            if (0 == m_resources.size())
+            {
+                std::cout << "No resouces!" << std::endl;
+                return -1;
+            }
+
+            int index = 1;
+            for (auto & resource : m_resources)
+            {
+                std::cout << index++ << ": " << resource->getURI().c_str() << std::endl;
+            }
+
+            int choice = -1;
+            std::cout << "Choose the resource: ";
+            std::cin >> choice;
+
+            if (choice < 1 || choice > index - 1)
+            {
+                std::cout << "Invalid choice !" << std::endl;
+                choice = -1;
+            }
+
+            return choice;
+        }
+
+        void onResourceModelChanged(const std::string &uri,
+                                    const SimulatorResourceModel &resModel)
+        {
+            std::cout << "[callback] Resource model is changed URI: " << uri.c_str() << " Count : " <<
+                      resModel.size() << std::endl;
+            std::cout << "#### Modified attributes are ####" << std::endl;
+            for (auto & attribute : resModel.getAttributes())
+            {
+                std::cout << attribute.second.getName() << " :  " << attribute.second.valueToString().c_str() <<
+                          std::endl;
+            }
+            std::cout << "########################" << std::endl;
+        }
+
+        void simulateResource(std::string &configPath)
+        {
+            SimulatorResourceServer::ResourceModelChangedCB callback = std::bind(
+                        &SimLightResource::onResourceModelChanged, this, std::placeholders::_1, std::placeholders::_2);
+            SimulatorResourceServerPtr resource = SimulatorManager::getInstance()->createResource(configPath,
+                                                  callback);
+            if (NULL == resource.get())
+                std::cout << "Failed to create resource" << std::endl;
+
+            m_resources.push_back(resource);
+            std::cout << "Resource created successfully! URI= " << resource->getURI().c_str() << std::endl;
+        }
+
+        void deleteResource()
+        {
+            int choice = -1;
+            std::cout << "1. Delete single resource" << std::endl;
+            std::cout << "2. Delete resources on resource types" << std::endl;
+            std::cout << "3. Delete all resources" << std::endl;
+
+            std::cout << "Enter your choice: ";
+            std::cin >> choice;
+            if (choice < 1 || choice > 3)
+            {
+                std::cout << "Invalid choice !" << std::endl;
+                return;
+            }
+
+            switch (choice)
+            {
+                case 1:
+                    {
+                        int index = selectResource();
+                        if (-1 == index)
+                            return;
+
+                        if (SIMULATOR_SUCCESS == SimulatorManager::getInstance()->deleteResource(m_resources[index - 1]))
+                        {
+                            std::cout << "Resource deleted successfully! " << std::endl;
+                            m_resources.erase(m_resources.begin() + (index - 1));
+                        }
+                        else
+                        {
+                            std::cout << "Failed to delete resource!" << std::endl;
+                        }
+                    } 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;
+                        }
+
+                        if (SIMULATOR_SUCCESS == SimulatorManager::getInstance()->deleteResources(resourceType))
+                        {
+                            std::cout << "Resources of type \"" << resourceType << "\"" << " deleted successfully! " <<
+                                      std::endl;
+                            std::vector<SimulatorResourceServerPtr>::iterator ite = m_resources.begin();
+                            while (ite != m_resources.end())
+                            {
+                                if (!resourceType.compare((*ite)->getResourceType()))
+                                {
+                                    ite = m_resources.erase(ite);
+                                    continue;
+                                }
+                                ite++;
+                            }
+                        }
+                        else
+                        {
+                            std::cout << "Failed to delete resources of type \"" << resourceType << "\"!" << std::endl;
+                        }
+                    } break;
+                case 3:
+                    {
+                        if (SIMULATOR_SUCCESS == SimulatorManager::getInstance()->deleteResources())
+                        {
+                            std::cout << "All resources deleted successfully! " << std::endl;
+                            m_resources.clear();
+                        }
+                        else
+                        {
+                            std::cout << "Failed to delete all resources!" << std::endl;
+                        }
+                    } break;
+            }
+
+        }
+
+        void updateAttributePower()
+        {
+            int index = selectResource();
+            if (-1 == index)
+                return;
+
+            SimulatorResourceServerPtr 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->updateAttributeFromAllowedValues("power", index);
+                std::cout << "Attribute value is modified ####" << std::endl;
+
+                // Display the resource to user to verify the changed attribute value
+                displayResource(resource);
+                std::cout << std::endl << std::endl;
+
+                // Get user input for continuing this operation
+                if ((index + 1) < allowedValuesSize)
+                {
+                    int choice;
+                    std::cout << "Would you like to continue the attribute values changing process? (1/0): ";
+                    std::cin >> choice;
+                    if (0 == choice)
+                        break;
+                }
+            }
+
+            std::cout << "All the allowed values are tried!" << std::endl;
+        }
+
+        void updateAttributeIntensity()
+        {
+            int index = selectResource();
+            if (-1 == index)
+                return;
+
+            SimulatorResourceServerPtr resource = m_resources[index - 1];
+            SimulatorResourceModel resModel = resource->getModel();
+            SimulatorResourceModel::Attribute intensityAttribute;
+            resModel.getAttribute("intensity", intensityAttribute);
+
+            int allowedValuesSize = intensityAttribute.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 intensity 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->updateAttributeFromAllowedValues("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) < allowedValuesSize)
+                {
+                    int choice;
+                    std::cout << "Would you like to continue the attribute values changing process? (1/0): ";
+                    std::cin >> choice;
+                    if (0 == choice)
+                        break;
+                }
+            }
+
+            std::cout << "All the allowed values are tried!" << std::endl;
+        }
+
+        void displayResource()
+        {
+            int index = selectResource();
+            if (-1 == index)
+                return;
+
+            SimulatorResourceServerPtr resource = m_resources[index - 1];
+            displayResource(resource);
+        }
+
+        void displayResource(SimulatorResourceServerPtr resource)
+        {
+            std::cout << "#############################" << std::endl;
+            std::cout << "Name: " << resource->getName().c_str() << std::endl;
+            std::cout << "URI: " << resource->getURI().c_str() << std::endl;
+            std::cout << "R. Type: " << resource->getResourceType().c_str() << std::endl;
+            std::cout << "I. Type: " << resource->getInterfaceType().c_str() << std::endl;
+
+            // Attributes
+            SimulatorResourceModel resModel = resource->getModel();
+            std::map<std::string, SimulatorResourceModel::Attribute> attributes = resModel.getAttributes();
+            std::cout << "##### Attributes [" << attributes.size() << "]" << std::endl;
+            for (auto & attribute : attributes)
+            {
+                std::cout << (attribute.second).getName() << " :  {" << std::endl;
+                std::cout << "value: " << (attribute.second).valueToString().c_str() << std::endl;
+                int min, max;
+                (attribute.second).getRange(min, max);
+                std::cout << "min: " << min << std::endl;
+                std::cout << "max: " << max << std::endl;
+                std::cout << "allowed values : " << (attribute.second).allowedValuesToString() << 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;
+
+            int id;
+            if (SIMULATOR_SUCCESS != m_resources[index - 1]->startUpdateAutomation(type,
+                    std::bind(&SimLightResource::onUpdateAutomationCompleted, this, std::placeholders::_1,
+                              std::placeholders::_2),
+                    id))
+                std::cout << "startUpdateAutomation() returned error!" << std::endl;
+            else
+                std::cout << "startUpdateAutomation() returned succces : " << id << std::endl;
+        }
+
+        void automateAttributeUpdate()
+        {
+            int index = selectResource();
+            if (-1 == index)
+                return;
+
+            SimulatorResourceServerPtr resource = m_resources[index - 1];
+            SimulatorResourceModel resModel = resource->getModel();
+            std::map<std::string, SimulatorResourceModel::Attribute> attributes = resModel.getAttributes();
+            int size = 0;
+            for (auto & attribute : attributes)
+            {
+                std::cout << ++size << ": " << attribute.first.c_str() << std::endl;
+            }
+
+            if (0 == size)
+            {
+                std::cout << "This resource doest not contain any attributes!" << std::endl;
+                return;
+            }
+
+            int choice = -1;
+            std::cout << "Select the attribute which you want to automate for updation: " << std::endl;
+            std::cin >> choice;
+            if (choice < 0 || choice > size)
+            {
+                std::cout << "Invalid selection!" << std::endl;
+                return;
+            }
+
+            int count = 0;
+            std::string attributeName;
+            for (auto & attribute : attributes)
+            {
+                if (count == choice - 1)
+                {
+                    attributeName = attribute.first;
+                    break;
+                }
+
+                count++;
+            }
+
+            AutomationType type = AutomationType::NORMAL;
+            std::cout << "Press 1 if you want recurrent automation: ";
+            std::cin >> choice;
+            if (1 == choice)
+                type = AutomationType::RECURRENT;
+
+            std::cout << "Requesting attribute automation for " << attributeName.c_str() << std::endl;
+            int id;
+            if (SIMULATOR_SUCCESS != resource->startUpdateAutomation(attributeName, type,
+                    std::bind(&SimLightResource::onUpdateAutomationCompleted, this, std::placeholders::_1,
+                              std::placeholders::_2),
+                    id))
+                std::cout << "startUpdateAutomation() returned error!" << std::endl;
+            else
+                std::cout << "startUpdateAutomation() returned succces : " << id << std::endl;
+        }
+
+        void stopAutomation()
+        {
+            int index = selectResource();
+            if (-1 == index)
+                return;
+
+            SimulatorResourceServerPtr resource = m_resources[index - 1];
+
+            // Select the automation to stop
+            std::vector<int> ids;
+            {
+                std::vector<int> rids = resource->getResourceAutomationIds();
+                std::vector<int> aids = resource->getAttributeAutomationIds();
+                ids.insert(ids.end(), rids.begin(), rids.end());
+                ids.insert(ids.end(), aids.begin(), aids.end());
+            }
+
+            if (!ids.size())
+            {
+                std::cout << "No automation operation is going on this resource right now!" << std::endl;
+                return;
+            }
+
+            for (auto & id : ids)
+                std::cout <<  id  << " ";
+
+            int automationid;
+            std::cout << "\nEnter automation id: " << std::endl;
+            std::cin >> automationid;
+            resource->stopUpdateAutomation(automationid);
+        }
+
+    private:
+        std::vector<SimulatorResourceServerPtr> m_resources;
+};
+
+void printMainMenu()
+{
+    std::cout << "############### MAIN MENU###############" << std::endl;
+    std::cout << "1. Test simulation of resource" << std::endl;
+    std::cout << "2. Set Logger" << std::endl;
+    std::cout << "3. Help" << std::endl;
+    std::cout << "0. Exit" << std::endl;
+    std::cout <<
+              "To set the Resource from RAML file, run the service provider with argument of Path of Raml File."
+              << std::endl;
+    std::cout <<
+              "Example: ./simulator-server  ../../../../../../../../service/simulator/examples/resources/light.raml"
+              << std::endl;
+    std::cout << "######################################" << std::endl;
+}
+
+void setLogger()
+{
+    std::cout << "1. Default console logger" << std::endl;
+    std::cout << "2. Default file logger" << std::endl;
+    std::cout << "3. custom logger" << std::endl;
+
+    int choice = -1;
+    std::cin >> choice;
+    if (choice <= 0 || choice > 3)
+    {
+        std::cout << "Invalid selection !" << std::endl;
+        return;
+    }
+
+    switch (choice)
+    {
+        case 1:
+            {
+                if (false == SimulatorManager::getInstance()->setDefaultConsoleLogger())
+                    std::cout << "Failed to set the default console logger" << std::endl;
+            } break;
+        case 2:
+            {
+                std::string filePath;
+                std::cout << "Enter the file path (without file name) : ";
+                std::cin >> filePath;
+                if (false == SimulatorManager::getInstance()->setDefaultFileLogger(filePath))
+                    std::cout << "Failed to set default file logger" << std::endl;
+            } break;
+        case 3: SimulatorManager::getInstance()->setLogger(gAppLogger);
+    }
+}
+
+int main(int argc, char *argv[])
+{
+    std::string configPath = "";
+    if (argc == 2)
+    {
+        char *value = argv[1];
+        configPath.append(value);
+    }
+    else
+    {
+        configPath = "";
+    }
+    SimLightResource lightResource;
+
+    printMainMenu();
+    bool cont = true;
+    while (cont == true)
+    {
+        int choice = -1;
+        std::cout << "Enter your choice: ";
+        std::cin >> choice;
+        if (choice < 0 || choice > 3)
+        {
+            std::cout << "Invaild choice !" << std::endl; continue;
+        }
+
+        switch (choice)
+        {
+            case 1: lightResource.startTest(configPath);
+                std::cout << "Welcome back to main menu !" << std::endl;
+                break;
+            case 2: setLogger(); break;
+            case 3: printMainMenu(); break;
+            case 0: cont = false;
+        }
+    }
+
+    std::cout << "Terminating test !!!" << std::endl;
+}
diff --git a/service/simulator/inc/simulator_manager.h b/service/simulator/inc/simulator_manager.h
new file mode 100644 (file)
index 0000000..f63a6c7
--- /dev/null
@@ -0,0 +1,159 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+  * @file   simulator_manager.h
+  *
+  * @brief   This file contains the declaration of SimulatorManager class which has the methods
+  *              for configuring the platform and creation/deletion of resources.
+  */
+
+#ifndef SIMULATOR_MANAGER_H_
+#define SIMULATOR_MANAGER_H_
+
+#include <vector>
+#include "simulator_resource_server.h"
+#include "simulator_remote_resource.h"
+#include "simulator_error_codes.h"
+#include "simulator_logger.h"
+
+/**
+ * @class   SimulatorManager
+ *
+ * @brief   This class provides a set of methods for platform configuration,
+ *              and creation/deletion of resources.
+ *
+ */
+class SimulatorManager
+{
+    public:
+        static SimulatorManager *getInstance();
+
+        /**
+         * This method is called for creating a single resource from RAML configuration file.
+         *
+         * @param configPath - RAML configuration file path.
+         * @param callback - Callback method for receive notifications when resource model changes.
+         *
+         * @return SimulatorResourceServerPtr - Shared pointer of SimulatorResourceServer on success, otherwise NULL.
+         */
+        SimulatorResourceServerPtr createResource(const std::string &configPath,
+                SimulatorResourceServer::ResourceModelChangedCB callback);
+
+        /**
+         * This method is called for creating a collection of resources from RAML configuration file.
+         *
+         * @param configPath - RAML configuration file path.
+         * @param count - Number of resource to be created.
+         * @param callback - Callback method for receive notifications when resource model changes.
+         *
+         * @return SimulatorResourceServerPtr - A vector of Shared pointers of SimulatorResourceServer Objects.
+         */
+        std::vector<SimulatorResourceServerPtr> createResource(const std::string &configPath,
+                const int count,
+                SimulatorResourceServer::ResourceModelChangedCB callback);
+
+        /**
+         * This method is called for obtaining a list of created resources.
+         *
+         * @return SimulatorResourceServerPtr - A vector of Shared pointers of SimulatorResourceServer Objects.
+         */
+        std::vector<SimulatorResourceServerPtr> getResources(const std::string &resourceType = "");
+
+        /**
+          * This method is called for deleting a single resource.
+          *
+          * @param resource - Shared pointer of the SimulatorResourceServer to be deleted.
+          *
+          * @return SimulatorResult
+          */
+        SimulatorResult deleteResource(SimulatorResourceServerPtr &resource);
+
+        /**
+          * This method is called for deleting multiple resources.
+          * If this method is called without any parameter, then all resources will be deleted.
+          * If thie method is called with a specific resourcetype as a parameter, then all the resources
+          * of that particular type will be deleted.
+          *
+          * @param resourceType - Resource type of the resource
+          *
+          * @return SimulatorResult
+          */
+        SimulatorResult deleteResources(const std::string &resourceType = "");
+
+        /**
+         * API for discovering resources of a particular resource type.
+         * Callback is called when a resource is found.
+         *
+         * @param resourceType - required resource type
+         * @param callback - Returns SimulatorRemoteResource.
+         *
+         * @return SimulatorResult - return value of this API.
+         *                         It returns SIMULATOR_SUCCESS if success.
+         *
+         * NOTE: SimulatorResult is defined in simulator_error_codes.h.
+         */
+        SimulatorResult findResource(const std::string &resourceType, ResourceFindCallback callback);
+
+        /**
+         * API for getting list of already found resources.
+         *
+         * @param resourceType - resource type
+         *
+         * @return List of SimulatorRemoteResource
+         *
+         */
+        std::vector<SimulatorRemoteResourcePtr> getFoundResources(
+            const std::string resourceType = "");
+
+        /**
+         * API for setting logger target for receiving the log messages.
+         *
+         * @param logger - ILogger interface for handling the log messages.
+         *
+         */
+        void setLogger(std::shared_ptr<ILogger> logger);
+
+        /**
+         * API for setting console as logger target.
+         *
+         * @return true if console set as logger target,
+         *         otherwise false.
+         *
+         */
+        bool setDefaultConsoleLogger();
+
+        /**
+         * API for setting file as logger target.
+         *
+         * @param path - File to which log messages to be saved.
+         *
+         * @return true if console set as logger target,
+         *         otherwise false.
+         *
+         */
+        bool setDefaultFileLogger(std::string &path);
+
+    private:
+        SimulatorManager();
+        ~SimulatorManager() = default;
+};
+
+#endif
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/.classpath b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/.classpath
new file mode 100644 (file)
index 0000000..61b8255
--- /dev/null
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+    <classpathentry kind="lib" path="libs/Simulator.jar"/>
+    <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7"/>
+    <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
+    <classpathentry kind="src" path="src"/>
+    <classpathentry kind="output" path="bin"/>
+</classpath>
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/.project b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/.project
new file mode 100644 (file)
index 0000000..65d5304
--- /dev/null
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+    <name>ServiceProviderPlugin</name>
+    <comment></comment>
+    <projects>
+    </projects>
+    <buildSpec>
+        <buildCommand>
+            <name>org.eclipse.jdt.core.javabuilder</name>
+            <arguments>
+            </arguments>
+        </buildCommand>
+        <buildCommand>
+            <name>org.eclipse.pde.ManifestBuilder</name>
+            <arguments>
+            </arguments>
+        </buildCommand>
+        <buildCommand>
+            <name>org.eclipse.pde.SchemaBuilder</name>
+            <arguments>
+            </arguments>
+        </buildCommand>
+    </buildSpec>
+    <natures>
+        <nature>org.eclipse.pde.PluginNature</nature>
+        <nature>org.eclipse.jdt.core.javanature</nature>
+    </natures>
+</projectDescription>
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/META-INF/MANIFEST.MF b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/META-INF/MANIFEST.MF
new file mode 100644 (file)
index 0000000..08798e4
--- /dev/null
@@ -0,0 +1,13 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: ServiceProviderPlugin
+Bundle-SymbolicName: ServiceProviderPlugin;singleton:=true
+Bundle-Version: 1.0.0.qualifier
+Bundle-Activator: oic.simulator.serviceprovider.Activator
+Require-Bundle: org.eclipse.ui,
+ org.eclipse.core.runtime
+Bundle-RequiredExecutionEnvironment: JavaSE-1.7
+Bundle-ActivationPolicy: lazy
+Bundle-NativeCode: libs/libSimulatorManager.so
+Bundle-ClassPath: libs/Simulator.jar,
+ .
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/README.txt b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/README.txt
new file mode 100644 (file)
index 0000000..bb5b937
--- /dev/null
@@ -0,0 +1,20 @@
+Service Provider eclipse plug-in
+
+Pre-requisites
+--------------
+    1.Build the IoTivity project for linux:
+        Run the "scons" command in iotivity home directory.
+        It generates the libraries in ~/iotivity/out/linux/<arch>/release directory.
+    2.Copy the libraries mentioned below into the libs folder of the plug-in project.
+        Required libraries: libSimulatorManager.so, liboc.so, liboctbstack.so, and liboc_logger.so
+
+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.
+    2.Right click the project -> Run As Eclipse Application.
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/build.properties b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/build.properties
new file mode 100644 (file)
index 0000000..0a482ed
--- /dev/null
@@ -0,0 +1,9 @@
+source.. = src/
+output.. = bin/
+bin.includes = META-INF/,\
+               .,\
+               libs/,\
+               icons/,\
+               plugin.xml,\
+               ,\
+               libs/Simulator.jar
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/clear_d.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/clear_d.gif
new file mode 100644 (file)
index 0000000..6775edf
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/clear_d.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/clear_e.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/clear_e.gif
new file mode 100644 (file)
index 0000000..af30a42
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/clear_e.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/debug_log.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/debug_log.gif
new file mode 100644 (file)
index 0000000..d90a29f
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/debug_log.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/delete_d.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/delete_d.gif
new file mode 100644 (file)
index 0000000..9e14298
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/delete_d.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/delete_e.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/delete_e.gif
new file mode 100644 (file)
index 0000000..b6922ac
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/delete_e.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/error_log.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/error_log.gif
new file mode 100644 (file)
index 0000000..9b048d6
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/error_log.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/export_log_d.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/export_log_d.gif
new file mode 100644 (file)
index 0000000..030b93e
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/export_log_d.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/export_log_e.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/export_log_e.gif
new file mode 100644 (file)
index 0000000..5a0837d
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/export_log_e.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/filter_d.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/filter_d.gif
new file mode 100644 (file)
index 0000000..ba6d891
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/filter_d.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/filter_e.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/filter_e.gif
new file mode 100644 (file)
index 0000000..1492b4e
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/filter_e.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/info_log.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/info_log.gif
new file mode 100644 (file)
index 0000000..3679f84
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/info_log.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/lock_d.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/lock_d.gif
new file mode 100644 (file)
index 0000000..b776478
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/lock_d.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/lock_e.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/lock_e.gif
new file mode 100644 (file)
index 0000000..68fd6cf
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/lock_e.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/log_details_e.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/log_details_e.gif
new file mode 100644 (file)
index 0000000..7ccc6a7
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/log_details_e.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/oic_logo_16x16.png b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/oic_logo_16x16.png
new file mode 100644 (file)
index 0000000..e6bbc36
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/oic_logo_16x16.png differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/oic_logo_32x32.png b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/oic_logo_32x32.png
new file mode 100644 (file)
index 0000000..d02a216
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/oic_logo_32x32.png differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/oic_logo_64x64.png b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/oic_logo_64x64.png
new file mode 100644 (file)
index 0000000..4fe3cbb
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/oic_logo_64x64.png differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/prop_d.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/prop_d.gif
new file mode 100644 (file)
index 0000000..ec394d6
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/prop_d.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/prop_e.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/prop_e.gif
new file mode 100644 (file)
index 0000000..d11c996
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/prop_e.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/sample.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/sample.gif
new file mode 100644 (file)
index 0000000..34fb3c9
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/sample.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/trash_e.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/trash_e.gif
new file mode 100644 (file)
index 0000000..bf961b3
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/trash_e.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/tree_mode_d.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/tree_mode_d.gif
new file mode 100644 (file)
index 0000000..62bdbe2
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/tree_mode_d.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/tree_mode_e.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/tree_mode_e.gif
new file mode 100644 (file)
index 0000000..dda8bae
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/tree_mode_e.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/unknown_log.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/unknown_log.gif
new file mode 100644 (file)
index 0000000..a54ccfe
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/unknown_log.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/warning_log.gif b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/warning_log.gif
new file mode 100644 (file)
index 0000000..14009e9
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/icons/warning_log.gif differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/libs/Simulator.jar b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/libs/Simulator.jar
new file mode 100644 (file)
index 0000000..612bc7a
Binary files /dev/null and b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/libs/Simulator.jar differ
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/plugin.xml b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/plugin.xml
new file mode 100644 (file)
index 0000000..d1fd34e
--- /dev/null
@@ -0,0 +1,82 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<?eclipse version="3.4"?>
+<plugin>
+   <extension
+         point="org.eclipse.ui.perspectives">
+      <perspective
+            class="oic.simulator.serviceprovider.perspective.PerspectiveFactory"
+            icon="icons/oic_logo_16x16.png"
+            id="oic.simulator.serviceprovider.perspective"
+            name="Service Provider">
+      </perspective>
+   </extension>
+   <extension
+         point="org.eclipse.ui.views">
+         <category
+            id="oic.simulator.serviceprovider.category"
+            name="Service Provider">
+         </category>
+         <view category="oic.simulator.serviceprovider.category"
+            class="oic.simulator.serviceprovider.view.ResourceManagerView"
+            icon="icons/oic_logo_16x16.png"
+            id="oic.simulator.serviceprovider.view.resourcemanager"
+            name="Resource Manager"
+            restorable="true">
+         </view>
+         <view category="oic.simulator.serviceprovider.category"
+            class="oic.simulator.serviceprovider.view.AttributeView"
+            icon="icons/oic_logo_16x16.png"
+            id="oic.simulator.serviceprovider.view.attribute"
+            name="Attribute Manager"
+            restorable="true">
+         </view>
+         <view category="oic.simulator.serviceprovider.category"
+            class="oic.simulator.serviceprovider.view.MultiResourceOrchestrationView"
+            icon="icons/oic_logo_16x16.png"
+            id="oic.simulator.serviceprovider.view.orchestration"
+            name="Multi-Resource Automation"
+            restorable="true">
+         </view>
+         <view category="oic.simulator.serviceprovider.category"
+            class="oic.simulator.serviceprovider.view.LogView"
+            icon="icons/oic_logo_16x16.png"
+            id="oic.simulator.serviceprovider.view.log"
+            name="Simulator Log"
+            restorable="true">
+         </view>
+         <view category="oic.simulator.serviceprovider.category"
+            class="oic.simulator.serviceprovider.view.MetaPropertiesView"
+            icon="icons/oic_logo_16x16.png"
+            id="oic.simulator.serviceprovider.view.metaproperties"
+            name="Properties"
+            restorable="true">
+         </view>
+   </extension>
+   <extension
+         point="org.eclipse.ui.perspectiveExtensions">
+      <perspectiveExtension
+            targetID="*">
+         <perspectiveShortcut
+               id="oic.simulator.serviceprovider.perspective">
+         </perspectiveShortcut>
+      </perspectiveExtension>
+      <perspectiveExtension
+            targetID="oic.simulator.serviceprovider.perspective">
+         <viewShortcut
+               id="oic.simulator.serviceprovider.view.resourcemanager">
+         </viewShortcut>
+         <viewShortcut
+               id="oic.simulator.serviceprovider.view.attribute">
+         </viewShortcut>
+         <viewShortcut
+               id="oic.simulator.serviceprovider.view.orchestration">
+         </viewShortcut>
+         <viewShortcut
+               id="oic.simulator.serviceprovider.view.log">
+         </viewShortcut>
+         <viewShortcut
+               id="oic.simulator.serviceprovider.view.metaproperties">
+         </viewShortcut>
+      </perspectiveExtension>
+   </extension>
+</plugin>
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/logger/LogContentProvider.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/logger/LogContentProvider.java
new file mode 100644 (file)
index 0000000..5d70e68
--- /dev/null
@@ -0,0 +1,46 @@
+package oic.simulator.logger;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.jface.viewers.ITreeContentProvider;
+import org.eclipse.jface.viewers.Viewer;
+
+public class LogContentProvider implements ITreeContentProvider {
+
+    List<LogEntry> logEntryList = new ArrayList<LogEntry>();
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+        logEntryList = (List<LogEntry>) newInput;
+    }
+
+    @Override
+    public Object[] getChildren(Object element) {
+        return new Object[0];
+    }
+
+    @Override
+    public Object[] getElements(Object input) {
+        return logEntryList.toArray();
+    }
+
+    @Override
+    public Object getParent(Object element) {
+        return null;
+    }
+
+    @Override
+    public boolean hasChildren(Object element) {
+        return false;
+    }
+
+    @Override
+    public void dispose() {
+    }
+
+    public synchronized void addLog(LogEntry newElement) {
+        logEntryList.add(newElement);
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/logger/LogEntry.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/logger/LogEntry.java
new file mode 100644 (file)
index 0000000..989a273
--- /dev/null
@@ -0,0 +1,39 @@
+package oic.simulator.logger;
+
+import java.util.Date;
+
+import oic.simulator.serviceprovider.manager.LogManager;
+
+public class LogEntry {
+    private final int    severity;
+    private final Date   date;
+    private final String message;
+
+    public LogEntry(int severity, Date date, String message) {
+        this.severity = severity;
+        this.date = date;
+        this.message = message;
+    }
+
+    public String getMessage() {
+        return message;
+    }
+
+    public Date getDate() {
+        return date;
+    }
+
+    public int getSeverity() {
+        return severity;
+    }
+
+    @Override
+    public String toString() {
+        String newline = System.getProperty("line.separator");
+        String out = date.toString() + newline;
+        out += "Severity: " + LogManager.getSeverityName(severity) + newline;
+        out += "Message: " + message + newline;
+        out += "===============================" + newline + newline;
+        return out;
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/logger/LogLabelProvider.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/logger/LogLabelProvider.java
new file mode 100644 (file)
index 0000000..7ec2759
--- /dev/null
@@ -0,0 +1,38 @@
+package oic.simulator.logger;
+
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+
+import oic.simulator.serviceprovider.manager.LogManager;
+
+import org.eclipse.jface.viewers.ITableLabelProvider;
+import org.eclipse.jface.viewers.LabelProvider;
+import org.eclipse.swt.graphics.Image;
+
+public class LogLabelProvider extends LabelProvider implements
+        ITableLabelProvider {
+
+    DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss.SSS");
+
+    @Override
+    public Image getColumnImage(Object element, int columnIndex) {
+        if (columnIndex == 0) {
+            LogEntry entry = (LogEntry) element;
+            return LogManager.getSeverityIcon(entry.getSeverity());
+        }
+        return null;
+    }
+
+    @Override
+    public String getColumnText(Object element, int columnIndex) {
+        LogEntry entry = (LogEntry) element;
+        if (columnIndex == 0) {
+            return LogManager.getSeverityName(entry.getSeverity());
+        } else if (columnIndex == 1) {
+            return dateFormat.format(entry.getDate());
+        } else {
+            return entry.getMessage();
+        }
+    }
+
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/logger/LoggerCallback.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/logger/LoggerCallback.java
new file mode 100644 (file)
index 0000000..94168e0
--- /dev/null
@@ -0,0 +1,55 @@
+package oic.simulator.logger;
+
+import java.util.Calendar;
+import java.util.Date;
+
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.utils.Constants;
+
+import org.oic.simulator.ILogger;
+
+public class LoggerCallback implements ILogger {
+
+    @Override
+    public void write(String time, int level, String message) {
+        if (null == time || level < 0 || null == message) {
+            return;
+        }
+        // Parse the time
+        Date date = parseTime(time);
+        if (null == date) {
+            return;
+        }
+        Activator activator = Activator.getDefault();
+        if (null == activator) {
+            return;
+        }
+        activator.getLogManager().log(level, date, message);
+    }
+
+    private Date parseTime(String time) {
+        Date date;
+        String[] token = time.split("\\.");
+        int h, m, s;
+        try {
+            if (token.length == Constants.PROPER_LOG_TIME_TOKEN_LENGTH) {
+                h = Integer.parseInt(token[0]);
+                m = Integer.parseInt(token[1]);
+                s = Integer.parseInt(token[2]);
+
+                Calendar calendar;
+                calendar = Calendar.getInstance();
+                calendar.set(Calendar.HOUR, h);
+                calendar.set(Calendar.MINUTE, m);
+                calendar.set(Calendar.SECOND, s);
+
+                date = calendar.getTime();
+            } else {
+                date = null;
+            }
+        } catch (NumberFormatException nfe) {
+            date = null;
+        }
+        return date;
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/Activator.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/Activator.java
new file mode 100644 (file)
index 0000000..c358680
--- /dev/null
@@ -0,0 +1,69 @@
+package oic.simulator.serviceprovider;
+
+import oic.simulator.serviceprovider.manager.LogManager;
+import oic.simulator.serviceprovider.manager.ResourceManager;
+
+import org.eclipse.ui.plugin.AbstractUIPlugin;
+import org.osgi.framework.BundleContext;
+
+/**
+ * The activator class controls the plug-in life cycle
+ */
+public class Activator extends AbstractUIPlugin {
+
+    // The plug-in ID
+    public static final String     PLUGIN_ID = "ServiceProviderPlugin"; //$NON-NLS-1$
+
+    // The shared instance
+    private static Activator       plugin;
+
+    private static ResourceManager resourceManager;
+
+    private static LogManager      logManager;
+
+    public Activator() {
+    }
+
+    public void start(BundleContext context) throws Exception {
+        super.start(context);
+        plugin = this;
+        setResourceManager(new ResourceManager());
+        setLogManager(new LogManager());
+    }
+
+    public void stop(BundleContext context) throws Exception {
+        plugin = null;
+
+        // Stopping Resource Manager
+        if (null != resourceManager) {
+            resourceManager.shutdown();
+            resourceManager = null;
+        }
+        // Stopping Log Manager
+        if (null != logManager) {
+            logManager.shutdown();
+            logManager = null;
+        }
+        super.stop(context);
+    }
+
+    public static Activator getDefault() {
+        return plugin;
+    }
+
+    public ResourceManager getResourceManager() {
+        return resourceManager;
+    }
+
+    private static void setResourceManager(ResourceManager manager) {
+        Activator.resourceManager = manager;
+    }
+
+    public LogManager getLogManager() {
+        return logManager;
+    }
+
+    private static void setLogManager(LogManager logManager) {
+        Activator.logManager = logManager;
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IAutomationUIListener.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IAutomationUIListener.java
new file mode 100644 (file)
index 0000000..ecc2ee7
--- /dev/null
@@ -0,0 +1,7 @@
+package oic.simulator.serviceprovider.listener;
+
+public interface IAutomationUIListener {
+    public void onResourceAutomationStart(String resourceURI);
+
+    public void onAutomationComplete(String resourceURI, String attName);
+}
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/ILogUIListener.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/ILogUIListener.java
new file mode 100644 (file)
index 0000000..dc539cd
--- /dev/null
@@ -0,0 +1,11 @@
+package oic.simulator.serviceprovider.listener;
+
+import java.util.List;
+
+import oic.simulator.logger.LogEntry;
+
+public interface ILogUIListener {
+    public void logAdded(LogEntry added);
+
+    public void logChanged(List<LogEntry> entry);
+}
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IResourceListChangedUIListener.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IResourceListChangedUIListener.java
new file mode 100644 (file)
index 0000000..17ed87f
--- /dev/null
@@ -0,0 +1,7 @@
+package oic.simulator.serviceprovider.listener;
+
+public interface IResourceListChangedUIListener {
+    public void onResourceCreation();
+
+    public void onResourceDeletion();
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IResourceModelChangedUIListener.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IResourceModelChangedUIListener.java
new file mode 100644 (file)
index 0000000..7016df5
--- /dev/null
@@ -0,0 +1,8 @@
+package oic.simulator.serviceprovider.listener;
+
+import oic.simulator.serviceprovider.resource.ModelChangeNotificationType;
+
+public interface IResourceModelChangedUIListener {
+    public void onResourceModelChange(
+            ModelChangeNotificationType notificationType, String resourceURI);
+}
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IResourceSelectionChangedUIListener.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/listener/IResourceSelectionChangedUIListener.java
new file mode 100644 (file)
index 0000000..4c844d6
--- /dev/null
@@ -0,0 +1,5 @@
+package oic.simulator.serviceprovider.listener;
+
+public interface IResourceSelectionChangedUIListener {
+    public void onResourceSelectionChange();
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/manager/LogManager.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/manager/LogManager.java
new file mode 100644 (file)
index 0000000..8563ff0
--- /dev/null
@@ -0,0 +1,253 @@
+package oic.simulator.serviceprovider.manager;
+
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.LinkedList;
+
+import oic.simulator.logger.LogEntry;
+import oic.simulator.logger.LoggerCallback;
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.listener.ILogUIListener;
+import oic.simulator.serviceprovider.utils.Constants;
+
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.jface.resource.ImageRegistry;
+import org.eclipse.swt.graphics.Image;
+import org.oic.simulator.ILogger;
+import org.oic.simulator.ILogger.Level;
+import org.oic.simulator.SimulatorManager;
+import org.osgi.framework.Bundle;
+
+public class LogManager {
+    private LinkedList<LogEntry>         entries           = new LinkedList<LogEntry>();
+    private ArrayList<ILogUIListener>    listeners         = new ArrayList<ILogUIListener>();
+    private LinkedList<LogEntry>         visibleEntries    = new LinkedList<LogEntry>();
+    private HashMap<Integer, Boolean>    visibleSeverities = new HashMap<Integer, Boolean>();
+
+    private ILogger                      logger;
+    private LogManagerSynchronizerThread synchronizerThread;
+    private Thread                       threadHandle;
+
+    static {
+        ImageRegistry r = Activator.getDefault().getImageRegistry();
+        Bundle bundle = Activator.getDefault().getBundle();
+        r.put(Constants.DEBUG_LOG, ImageDescriptor.createFromURL(bundle
+                .getEntry("/icons/debug_log.gif")));
+        r.put(Constants.INFO_LOG, ImageDescriptor.createFromURL(bundle
+                .getEntry("/icons/info_log.gif")));
+        r.put(Constants.WARNING_LOG, ImageDescriptor.createFromURL(bundle
+                .getEntry("/icons/warning_log.gif")));
+        r.put(Constants.ERROR_LOG, ImageDescriptor.createFromURL(bundle
+                .getEntry("/icons/error_log.gif")));
+        r.put(Constants.UNKNOWN_LOG, ImageDescriptor.createFromURL(bundle
+                .getEntry("/icons/unknown_log.gif")));
+    }
+
+    public LogManager() {
+        synchronizerThread = new LogManagerSynchronizerThread();
+        threadHandle = new Thread(synchronizerThread);
+        threadHandle.setName("OIC Simulator event queue");
+        threadHandle.start();
+
+        // Set the logger callback with the native layer
+        logger = new LoggerCallback();
+        SimulatorManager.setLogger(logger);
+    }
+
+    private static class LogManagerSynchronizerThread implements Runnable {
+
+        LinkedList<Runnable> eventQueue = new LinkedList<Runnable>();
+
+        @Override
+        public void run() {
+            while (!Thread.interrupted()) {
+
+                synchronized (this) {
+                    try {
+                        while (eventQueue.isEmpty()) {
+                            this.wait();
+                            break;
+                        }
+                    } catch (InterruptedException e) {
+                        return;
+                    }
+                }
+
+                Runnable pop;
+                synchronized (this) {
+                    pop = eventQueue.pop();
+                }
+                try {
+                    pop.run();
+                } catch (Exception e) {
+                    if (e instanceof InterruptedException) {
+                        return;
+                    }
+                    e.printStackTrace();
+                }
+            }
+        }
+
+        public void addToQueue(Runnable event) {
+            synchronized (this) {
+                eventQueue.add(event);
+                this.notify();
+            }
+        }
+    }
+
+    public void log(int severity, Date date, String msg) {
+        final LogEntry logEntry = new LogEntry(severity, date, msg);
+        synchronizerThread.addToQueue(new Runnable() {
+            @Override
+            public void run() {
+                boolean notify = false;
+                synchronized (entries) {
+                    entries.add(logEntry);
+                    Boolean showEntry = LogManager.this.visibleSeverities
+                            .get(logEntry.getSeverity());
+                    if (showEntry != null) {
+                        if (showEntry) {
+                            visibleEntries.add(logEntry);
+                            notify = true;
+                        }
+                    }
+                    if (entries.size() > Constants.LOG_SIZE) {
+                        entries.pop();
+                    }
+                    if (visibleEntries.size() > Constants.LOG_SIZE) {
+                        visibleEntries.pop();
+                        notify = true;
+                    }
+                }
+                if (notify) {
+                    notifyListeners(logEntry);
+                }
+            }
+        });
+    }
+
+    public void applyFilter(final HashMap<Integer, Boolean> visibleSeverities) {
+        synchronizerThread.addToQueue(new Runnable() {
+
+            @Override
+            public void run() {
+                LinkedList<LogEntry> newLogs = new LinkedList<LogEntry>();
+                synchronized (entries) {
+                    LogManager.this.visibleSeverities = visibleSeverities;
+                    for (LogEntry logEntry : entries) {
+                        if (LogManager.this.visibleSeverities.get(logEntry
+                                .getSeverity())) {
+                            newLogs.add(logEntry);
+                        }
+                    }
+                }
+                visibleEntries = newLogs;
+                notifyListeners();
+            }
+        });
+
+    }
+
+    private void notifyListeners() {
+        for (ILogUIListener l : listeners) {
+            l.logChanged(new ArrayList<LogEntry>(visibleEntries));
+        }
+    }
+
+    private void notifyListeners(LogEntry added) {
+        for (ILogUIListener l : listeners) {
+            l.logAdded(added);
+        }
+    }
+
+    public void clearLog() {
+        synchronizerThread.addToQueue(new Runnable() {
+
+            @Override
+            public void run() {
+                synchronized (entries) {
+                    entries = new LinkedList<LogEntry>();
+                    visibleEntries = new LinkedList<LogEntry>();
+                }
+                notifyListeners();
+            }
+        });
+    }
+
+    public void removeEntry(final LogEntry element) {
+        synchronizerThread.addToQueue(new Runnable() {
+
+            @Override
+            public void run() {
+                synchronized (entries) {
+                    entries.remove(element);
+                    visibleEntries.remove(element);
+                }
+                notifyListeners();
+            }
+        });
+    }
+
+    public ArrayList<LogEntry> getLogEntries() {
+        synchronized (entries) {
+            return new ArrayList<LogEntry>(entries);
+        }
+    }
+
+    public void addLogListener(final ILogUIListener listener) {
+        synchronizerThread.addToQueue(new Runnable() {
+            @Override
+            public void run() {
+                if (!listeners.contains(listener)) {
+                    listeners.add(listener);
+                }
+            }
+        });
+    }
+
+    public void removeLogListener(final ILogUIListener listener) {
+        synchronizerThread.addToQueue(new Runnable() {
+            @Override
+            public void run() {
+                if (!listeners.contains(listener)) {
+                    listeners.remove(listener);
+                }
+            }
+        });
+    }
+
+    public void shutdown() {
+        threadHandle.interrupt();
+    }
+
+    public static String getSeverityName(int severity) {
+        if (severity == Level.INFO.ordinal()) {
+            return Constants.INFO;
+        } else if (severity == Level.WARNING.ordinal()) {
+            return Constants.WARNING;
+        } else if (severity == Level.ERROR.ordinal()) {
+            return Constants.ERROR;
+        } else if (severity == Level.DEBUG.ordinal()) {
+            return Constants.DEBUG;
+        } else {
+            return Constants.UNKNOWN;
+        }
+    }
+
+    public static Image getSeverityIcon(int severity) {
+        ImageRegistry r = Activator.getDefault().getImageRegistry();
+        if (severity == Level.INFO.ordinal()) {
+            return r.get(Constants.INFO_LOG);
+        } else if (severity == Level.WARNING.ordinal()) {
+            return r.get(Constants.WARNING_LOG);
+        } else if (severity == Level.ERROR.ordinal()) {
+            return r.get(Constants.ERROR_LOG);
+        } else if (severity == Level.DEBUG.ordinal()) {
+            return r.get(Constants.DEBUG_LOG);
+        } else {
+            return r.get(Constants.UNKNOWN_LOG);
+        }
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/manager/ResourceManager.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/manager/ResourceManager.java
new file mode 100644 (file)
index 0000000..9f4c4e5
--- /dev/null
@@ -0,0 +1,1147 @@
+package oic.simulator.serviceprovider.manager;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import oic.simulator.serviceprovider.listener.IAutomationUIListener;
+import oic.simulator.serviceprovider.listener.IResourceListChangedUIListener;
+import oic.simulator.serviceprovider.listener.IResourceModelChangedUIListener;
+import oic.simulator.serviceprovider.listener.IResourceSelectionChangedUIListener;
+import oic.simulator.serviceprovider.resource.MetaProperty;
+import oic.simulator.serviceprovider.resource.ModelChangeNotificationType;
+import oic.simulator.serviceprovider.resource.ResourceAttribute;
+import oic.simulator.serviceprovider.resource.SimulatorResource;
+import oic.simulator.serviceprovider.resource.StandardConfiguration;
+import oic.simulator.serviceprovider.utils.Constants;
+
+import org.oic.simulator.AutomationType;
+import org.oic.simulator.IAutomation;
+import org.oic.simulator.SimulatorManager;
+import org.oic.simulator.SimulatorResourceAttribute;
+import org.oic.simulator.serviceprovider.IResourceModelChangedListener;
+import org.oic.simulator.serviceprovider.SimulatorResourceModel;
+import org.oic.simulator.serviceprovider.SimulatorResourceServer;
+
+public class ResourceManager {
+
+    private Map<String, Map<String, SimulatorResource>> resourceMap;
+
+    private StandardConfiguration                       stdConfig;
+
+    private SimulatorResource                           currentResourceInSelection;
+
+    private List<IResourceListChangedUIListener>        resourceListChangedUIListeners;
+
+    private List<IResourceSelectionChangedUIListener>   resourceSelectionChangedUIListeners;
+
+    private List<IResourceModelChangedUIListener>       resourceModelChangedUIListeners;
+
+    private List<IAutomationUIListener>                 automationUIListeners;
+
+    private IResourceModelChangedListener               resourceModelChangeListener;
+
+    private IAutomation                                 automationListener;
+
+    private NotificationSynchronizerThread              synchronizerThread;
+
+    private Thread                                      threadHandle;
+
+    static {
+        System.loadLibrary("SimulatorManager");
+    }
+
+    public ResourceManager() {
+        resourceMap = new HashMap<String, Map<String, SimulatorResource>>();
+        stdConfig = new StandardConfiguration();
+
+        resourceListChangedUIListeners = new ArrayList<IResourceListChangedUIListener>();
+        resourceSelectionChangedUIListeners = new ArrayList<IResourceSelectionChangedUIListener>();
+        resourceModelChangedUIListeners = new ArrayList<IResourceModelChangedUIListener>();
+        automationUIListeners = new ArrayList<IAutomationUIListener>();
+
+        // Populate standard configuration file list
+        populateStandardConfigurationList();
+
+        resourceModelChangeListener = new IResourceModelChangedListener() {
+
+            @Override
+            public void onResourceModelChanged(final String resourceURI,
+                    final SimulatorResourceModel resourceModelN) {
+                synchronizerThread.addToQueue(new Runnable() {
+
+                    @Override
+                    public void run() {
+                        if (null == resourceURI || null == resourceModelN) {
+                            return;
+                        }
+                        SimulatorResource resource = getSimulatorResourceByURI(resourceURI);
+                        if (null == resource) {
+                            return;
+                        }
+                        // Fetch the resource attributes
+                        Map<String, ResourceAttribute> resourceAttributeMapNew;
+                        resourceAttributeMapNew = fetchResourceAttributesFromModel(resourceModelN);
+                        if (null == resourceAttributeMapNew) {
+                            return;
+                        }
+                        // Update the resource with new model data
+                        Map<String, ResourceAttribute> resourceAttributeMapOld;
+                        resourceAttributeMapOld = resource
+                                .getResourceAttributesMap();
+                        if (null == resourceAttributeMapOld) {
+                            return;
+                        }
+                        ModelChangeNotificationType notificationType;
+                        notificationType = compareAndUpdateLocalAttributes(
+                                resourceAttributeMapOld,
+                                resourceAttributeMapNew);
+                        if (notificationType != ModelChangeNotificationType.NONE) {
+                            // Update the UI listeners
+                            resourceModelChangedUINotification(
+                                    notificationType, resourceURI);
+                        }
+                    }
+                });
+            }
+        };
+
+        automationListener = new IAutomation() {
+
+            @Override
+            public void onAutomationComplete(final String resourceURI,
+                    final int automationId) {
+                synchronizerThread.addToQueue(new Runnable() {
+
+                    @Override
+                    public void run() {
+                        SimulatorResource resource = getSimulatorResourceByURI(resourceURI);
+                        if (null == resource) {
+                            return;
+                        }
+                        // Checking whether this notification is for an
+                        // attribute or a resource
+                        if (resource.isResourceAutomationInProgress()) {
+                            changeResourceLevelAutomationStatus(resource, false);
+                            // Notify the UI listeners
+                            automationCompleteUINotification(resourceURI, null);
+                        } else if (resource.isAttributeAutomationInProgress()) {
+                            // Find the attribute with the given automation id
+                            ResourceAttribute attribute;
+                            attribute = getAttributeWithGivenAutomationId(
+                                    resource, automationId);
+                            if (null != attribute) {
+                                attribute.setAutomationInProgress(false);
+                                resource.setAttributeAutomationInProgress(false);
+                                // Notify the UI listeners
+                                automationCompleteUINotification(resourceURI,
+                                        attribute.getAttributeName());
+                            }
+                        } else {
+                            // Ignoring the notification as there are no
+                            // known automation for the current resource.
+                        }
+                    }
+                });
+            }
+        };
+
+        synchronizerThread = new NotificationSynchronizerThread();
+        threadHandle = new Thread(synchronizerThread);
+        threadHandle.setName("Simulator service provider event queue");
+        threadHandle.start();
+    }
+
+    private static class NotificationSynchronizerThread implements Runnable {
+
+        LinkedList<Runnable> notificationQueue = new LinkedList<Runnable>();
+
+        @Override
+        public void run() {
+            while (!Thread.interrupted()) {
+                synchronized (this) {
+                    try {
+                        while (notificationQueue.isEmpty()) {
+                            this.wait();
+                            break;
+                        }
+                    } catch (InterruptedException e) {
+                        return;
+                    }
+                }
+
+                Runnable thread;
+                synchronized (this) {
+                    thread = notificationQueue.pop();
+                }
+                try {
+                    thread.run();
+                } catch (Exception e) {
+                    if (e instanceof InterruptedException) {
+                        return;
+                    }
+                    e.printStackTrace();
+                }
+            }
+        }
+
+        public void addToQueue(Runnable event) {
+            synchronized (this) {
+                notificationQueue.add(event);
+                this.notify();
+            }
+        }
+    }
+
+    private void populateStandardConfigurationList() {
+        // TODO: Add all the standard configuration files
+        // Ex: stdConfig.addResourceConfiguration(LIGHT, LIGHT_FILE);
+    }
+
+    // This method gives a list of RAML resource configurations available.
+    public List<String> getResourceConfigurationList() {
+        List<String> resourceConfigurationList = new ArrayList<String>();
+        synchronized (stdConfig) {
+            Map<String, String> configMap = stdConfig
+                    .getStandardResourceConfigurationList();
+            if (null != configMap) {
+                Set<String> keySet = configMap.keySet();
+                Iterator<String> keyItr = keySet.iterator();
+                while (keyItr.hasNext()) {
+                    resourceConfigurationList.add(keyItr.next());
+                }
+            }
+        }
+        return resourceConfigurationList;
+    }
+
+    public String getConfigFilePath(String resourceType) {
+        String path = null;
+        if (null != resourceType) {
+            synchronized (stdConfig) {
+                path = stdConfig.getResourceConfigFilePath(resourceType);
+            }
+        }
+        return path;
+    }
+
+    public void addResourceListChangedUIListener(
+            IResourceListChangedUIListener resourceListChangedUIListener) {
+        synchronized (resourceListChangedUIListeners) {
+            resourceListChangedUIListeners.add(resourceListChangedUIListener);
+        }
+    }
+
+    public void addResourceSelectionChangedUIListener(
+            IResourceSelectionChangedUIListener resourceSelectionChangedUIListener) {
+        synchronized (resourceSelectionChangedUIListeners) {
+            resourceSelectionChangedUIListeners
+                    .add(resourceSelectionChangedUIListener);
+        }
+    }
+
+    public void addResourceModelChangedUIListener(
+            IResourceModelChangedUIListener resourceModelChangedUIListener) {
+        synchronized (resourceModelChangedUIListeners) {
+            resourceModelChangedUIListeners.add(resourceModelChangedUIListener);
+        }
+    }
+
+    public void addAutomationUIListener(
+            IAutomationUIListener automationUIListener) {
+        synchronized (automationUIListeners) {
+            automationUIListeners.add(automationUIListener);
+        }
+    }
+
+    public void removeResourceListChangedUIListener(
+            IResourceListChangedUIListener listener) {
+        synchronized (resourceListChangedUIListeners) {
+            if (null != listener && resourceListChangedUIListeners.size() > 0) {
+                resourceListChangedUIListeners.remove(listener);
+            }
+        }
+    }
+
+    public void removeResourceSelectionChangedUIListener(
+            IResourceSelectionChangedUIListener listener) {
+        synchronized (resourceSelectionChangedUIListeners) {
+            if (null != listener
+                    && resourceSelectionChangedUIListeners.size() > 0) {
+                resourceSelectionChangedUIListeners.remove(listener);
+            }
+        }
+    }
+
+    public void removeResourceModelChangedUIListener(
+            IResourceModelChangedUIListener listener) {
+        synchronized (resourceModelChangedUIListeners) {
+            if (null != listener && resourceModelChangedUIListeners.size() > 0) {
+                resourceModelChangedUIListeners.remove(listener);
+            }
+        }
+    }
+
+    public void removeAutomationUIListener(IAutomationUIListener listener) {
+        synchronized (automationUIListeners) {
+            if (null != listener && automationUIListeners.size() > 0) {
+                automationUIListeners.remove(listener);
+            }
+        }
+    }
+
+    public synchronized SimulatorResource getCurrentResourceInSelection() {
+        return currentResourceInSelection;
+    }
+
+    public synchronized void setCurrentResourceInSelection(
+            SimulatorResource resource) {
+        this.currentResourceInSelection = resource;
+    }
+
+    private void addResourceToMap(SimulatorResource simulatorResource) {
+        if (null != simulatorResource) {
+            synchronized (resourceMap) {
+                Map<String, SimulatorResource> resourceTypeMap;
+                resourceTypeMap = resourceMap.get(simulatorResource
+                        .getResourceType());
+                if (null == resourceTypeMap) {
+                    resourceTypeMap = new HashMap<String, SimulatorResource>();
+                    resourceMap.put(simulatorResource.getResourceType(),
+                            resourceTypeMap);
+                }
+                resourceTypeMap.put(simulatorResource.getResourceURI(),
+                        simulatorResource);
+            }
+        }
+    }
+
+    private void addResourceToMap(String resourceType,
+            Map<String, SimulatorResource> newResourceTypeMap) {
+        if (null != resourceType && null != newResourceTypeMap) {
+            synchronized (resourceMap) {
+                Map<String, SimulatorResource> resourceTypeMap = resourceMap
+                        .get(resourceType);
+                if (null != resourceTypeMap) {
+                    resourceTypeMap.putAll(newResourceTypeMap);
+                } else {
+                    resourceMap.put(resourceType, newResourceTypeMap);
+                }
+            }
+        }
+    }
+
+    private void removeResourceFromMap(String resourceType, String resourceURI) {
+        if (null != resourceURI && null != resourceType) {
+            synchronized (resourceMap) {
+                Map<String, SimulatorResource> resourceTypeMap = resourceMap
+                        .get(resourceType);
+                if (null != resourceTypeMap) {
+                    resourceTypeMap.remove(resourceURI);
+                    if (resourceTypeMap.size() < 1) {
+                        resourceMap.remove(resourceType);
+                    }
+                }
+            }
+        }
+    }
+
+    public boolean isResourceExist(String resourceURI) {
+        boolean result = false;
+        if (null != resourceURI) {
+            SimulatorResource resource = getSimulatorResourceByURI(resourceURI);
+            if (null != resource) {
+                result = true;
+            }
+        }
+        return result;
+    }
+
+    public void createResource(final String configFilePath) {
+        new Thread() {
+            @Override
+            public void run() {
+                SimulatorResourceServer resourceServerN;
+                resourceServerN = SimulatorManager.createResource(
+                        configFilePath, resourceModelChangeListener);
+
+                SimulatorResource simulatorResource;
+                simulatorResource = fetchResourceData(resourceServerN);
+                if (null != simulatorResource) {
+                    addResourceToMap(simulatorResource);
+
+                    resourceCreatedUINotification();
+                }
+            }
+        }.start();
+    }
+
+    public void createResource(final String configFilePath,
+            final int noOfInstances) {
+        new Thread() {
+            @Override
+            public void run() {
+                Map<String, SimulatorResource> resourceTypeMap;
+                SimulatorResourceServer[] simulatorResourceServers = null;
+                simulatorResourceServers = SimulatorManager.createResource(
+                        configFilePath, noOfInstances,
+                        resourceModelChangeListener);
+                if (null == simulatorResourceServers) {
+                    return;
+                }
+                resourceTypeMap = new HashMap<String, SimulatorResource>();
+                SimulatorResource resource;
+                String uri;
+                for (SimulatorResourceServer resourceServerN : simulatorResourceServers) {
+                    resource = fetchResourceData(resourceServerN);
+                    if (null != resource) {
+                        uri = resource.getResourceURI();
+                        resourceTypeMap.put(uri, resource);
+                    }
+                }
+
+                // Find the resourceType and add it to the local data
+                // structure and notify UI Listeners
+                if (resourceTypeMap.size() > 0) {
+                    String resourceType;
+                    Set<String> uriSet = resourceTypeMap.keySet();
+                    Iterator<String> itr = uriSet.iterator();
+                    if (itr.hasNext()) {
+                        SimulatorResource simResource = resourceTypeMap.get(itr
+                                .next());
+                        if (null != simResource) {
+                            resourceType = simResource.getResourceType();
+
+                            addResourceToMap(resourceType, resourceTypeMap);
+                            resourceCreatedUINotification();
+                        }
+                    }
+                }
+            }
+        }.start();
+    }
+
+    private SimulatorResource fetchResourceData(
+            SimulatorResourceServer resourceServerN) {
+        SimulatorResource simulatorResource = null;
+        if (null != resourceServerN) {
+            simulatorResource = new SimulatorResource();
+            simulatorResource.setResourceServer(resourceServerN);
+            simulatorResource.setResourceURI(resourceServerN.getURI());
+            simulatorResource
+                    .setResourceType(resourceServerN.getResourceType());
+            simulatorResource.setResourceName(resourceServerN.getName());
+            simulatorResource.setResourceInterface(resourceServerN
+                    .getInterfaceType());
+
+            SimulatorResourceModel resourceModelN = resourceServerN.getModel();
+            if (null != resourceModelN) {
+                simulatorResource.setResourceModel(resourceModelN);
+
+                // Fetch the resource attributes
+                Map<String, ResourceAttribute> resourceAttributeMap;
+                resourceAttributeMap = fetchResourceAttributesFromModel(resourceModelN);
+                if (null != resourceAttributeMap) {
+                    simulatorResource
+                            .setResourceAttributesMap(resourceAttributeMap);
+                }
+            }
+        }
+        return simulatorResource;
+    }
+
+    private Map<String, ResourceAttribute> fetchResourceAttributesFromModel(
+            SimulatorResourceModel resourceModelN) {
+        Map<String, ResourceAttribute> resourceAttributeMap = null;
+        if (null != resourceModelN) {
+            Map<String, SimulatorResourceAttribute> attributeMapN;
+            attributeMapN = resourceModelN.getAttributes();
+            if (null != attributeMapN) {
+                resourceAttributeMap = new HashMap<String, ResourceAttribute>();
+
+                Set<String> attNameSet = attributeMapN.keySet();
+                String attName;
+                Object attValueObj;
+                SimulatorResourceAttribute attributeN;
+                ResourceAttribute attribute;
+                Iterator<String> attNameItr = attNameSet.iterator();
+                while (attNameItr.hasNext()) {
+                    attName = attNameItr.next();
+                    attributeN = attributeMapN.get(attName);
+                    if (null != attributeN) {
+                        attribute = new ResourceAttribute();
+                        attribute.setResourceAttribute(attributeN);
+                        attribute.setAttributeName(attName);
+
+                        attValueObj = attributeN.getValue();
+                        if (null != attValueObj) {
+                            attribute.setAttributeValue(attValueObj);
+                        }
+
+                        // Read allowed values or min-max values of the
+                        // attribute
+                        // TODO: Temporarily reading the allowed values
+                        // as string
+                        // If attribute type is known, then appropriate
+                        // get method for that type will be called.
+                        String[] allowedValues = resourceModelN
+                                .getAllowedValues(attName);
+                        attribute.setAllowedValues(allowedValues);
+                        if (null == allowedValues || allowedValues.length < 1) {
+                            // TODO: Get the range(min-max) of the attribute
+                            // Implementation of GetRange is in progress
+                        }
+
+                        // Initially disabling the automation
+                        attribute.setAutomationInProgress(false);
+
+                        // TODO: Temporarily setting the interval to 500.
+                        // This value should come from the native layer.
+                        // Native implementation is in progress.
+                        attribute
+                                .setAutomationUpdateInterval(Constants.DEFAULT_AUTOMATION_INTERVAL);
+
+                        // Setting the default automation type
+                        attribute
+                                .setAutomationType(Constants.DEFAULT_AUTOMATION_TYPE);
+
+                        resourceAttributeMap.put(attName, attribute);
+                    }
+                }
+            }
+        }
+        return resourceAttributeMap;
+    }
+
+    public void deleteResourceByURI(final String resourceURI) {
+        if (null != resourceURI) {
+            new Thread() {
+                @Override
+                public void run() {
+                    SimulatorResource resource = getSimulatorResourceByURI(resourceURI);
+                    if (null != resource) {
+                        String resourceType = resource.getResourceType();
+
+                        // Unregister the resource from the platform
+                        deleteResource(resource);
+
+                        // Delete from the local data structure
+                        deleteLocalResourceDetails(resourceType, resourceURI);
+
+                        // Notify the UI listener for removing this resource
+                        // from UI
+                        resourceDeletedUINotification();
+
+                        if (null != currentResourceInSelection
+                                && resource == currentResourceInSelection) {
+                            // Listeners might query the resource being deleted
+                            // if exists. So set the currently selection to
+                            // null.
+                            setCurrentResourceInSelection(null);
+
+                            // Notify all observers for resource selection
+                            // change event
+                            resourceSelectionChangedUINotification();
+                        }
+                    }
+                }
+            }.start();
+        }
+    }
+
+    private SimulatorResource getSimulatorResourceByURI(String resourceURI) {
+        SimulatorResource resource = null;
+        if (null != resourceURI) {
+            synchronized (resourceMap) {
+                Set<String> typeSet = resourceMap.keySet();
+                Iterator<String> typeItr = typeSet.iterator();
+                String resourceType;
+                Map<String, SimulatorResource> resourceTypeMap;
+                while (typeItr.hasNext()) {
+                    resourceType = typeItr.next();
+                    resourceTypeMap = resourceMap.get(resourceType);
+                    if (null != resourceTypeMap) {
+                        resource = resourceTypeMap.get(resourceURI);
+                        if (null != resource) {
+                            break;
+                        }
+                    }
+                }
+            }
+        }
+        return resource;
+    }
+
+    private void deleteResource(SimulatorResource resource) {
+        if (null != resource) {
+            SimulatorResourceServer resourceServerN = resource
+                    .getResourceServer();
+            if (null != resourceServerN) {
+                SimulatorManager.deleteResource(resourceServerN);
+            }
+        }
+    }
+
+    public void deleteResourceByType(final String resourceType) {
+        if (null != resourceType) {
+            new Thread() {
+                @Override
+                public void run() {
+                    // Unregister the resources from the platform
+                    deleteResource(resourceType);
+
+                    // Delete from the local data structure
+                    deleteLocalResourceDetails(resourceType, null);
+
+                    // Notify the UI listener for removing this resource from UI
+                    resourceDeletedUINotification();
+
+                    if (null != currentResourceInSelection
+                            && resourceType.equals(currentResourceInSelection
+                                    .getResourceType())) {
+                        // Listeners might query the resource being deleted if
+                        // exists. So set the currently selection to null.
+                        setCurrentResourceInSelection(null);
+
+                        // Notify all observers for resource selection change
+                        // event
+                        resourceSelectionChangedUINotification();
+                    }
+                }
+            }.start();
+        }
+    }
+
+    private void deleteResource(String resourceType) {
+        if (null != resourceType) {
+            SimulatorManager.deleteResources(resourceType);
+        }
+    }
+
+    public void deleteAllResources() {
+        new Thread() {
+            @Override
+            public void run() {
+                // Unregister the resources from the platform
+                deleteResource();
+
+                // Delete from the local data structure
+                deleteLocalResourceDetails(null, null);
+
+                // Notify the UI listener for removing this resource from UI
+                resourceDeletedUINotification();
+
+                // Listeners might query the resource being deleted if exists.
+                // So set the currently selection to null.
+                setCurrentResourceInSelection(null);
+
+                // Notify all observers for resource selection change event
+                resourceSelectionChangedUINotification();
+            }
+        }.start();
+    }
+
+    private void deleteResource() {
+        SimulatorManager.deleteResources(null);
+    }
+
+    private void deleteLocalResourceDetails(String resourceType,
+            String resourceURI) {
+        if (null != resourceType && null != resourceURI) {
+            removeResourceFromMap(resourceType, resourceURI);
+        } else {
+            synchronized (resourceMap) {
+                if (null != resourceType) {
+                    resourceMap.remove(resourceType);
+                } else {
+                    resourceMap.clear();
+                }
+            }
+        }
+    }
+
+    private void resourceCreatedUINotification() {
+        synchronized (resourceListChangedUIListeners) {
+            if (resourceListChangedUIListeners.size() > 0) {
+                IResourceListChangedUIListener listener;
+                Iterator<IResourceListChangedUIListener> listenerItr = resourceListChangedUIListeners
+                        .iterator();
+                while (listenerItr.hasNext()) {
+                    listener = listenerItr.next();
+                    if (null != listener) {
+                        listener.onResourceCreation();
+                    }
+                }
+            }
+        }
+    }
+
+    private void resourceDeletedUINotification() {
+        synchronized (resourceListChangedUIListeners) {
+            if (resourceListChangedUIListeners.size() > 0) {
+                IResourceListChangedUIListener listener;
+                Iterator<IResourceListChangedUIListener> listenerItr = resourceListChangedUIListeners
+                        .iterator();
+                while (listenerItr.hasNext()) {
+                    listener = listenerItr.next();
+                    if (null != listener) {
+                        listener.onResourceDeletion();
+                    }
+                }
+            }
+        }
+    }
+
+    private void resourceSelectionChangedUINotification() {
+        synchronized (resourceSelectionChangedUIListeners) {
+            if (resourceSelectionChangedUIListeners.size() > 0) {
+                IResourceSelectionChangedUIListener listener;
+                Iterator<IResourceSelectionChangedUIListener> listenerItr = resourceSelectionChangedUIListeners
+                        .iterator();
+                while (listenerItr.hasNext()) {
+                    listener = listenerItr.next();
+                    if (null != listener) {
+                        listener.onResourceSelectionChange();
+                    }
+                }
+            }
+        }
+    }
+
+    private void resourceModelChangedUINotification(
+            ModelChangeNotificationType notificationType, String resourceURI) {
+        synchronized (resourceModelChangedUIListeners) {
+            if (resourceModelChangedUIListeners.size() > 0
+                    && notificationType != ModelChangeNotificationType.NONE
+                    && null != resourceURI) {
+                IResourceModelChangedUIListener listener;
+                Iterator<IResourceModelChangedUIListener> listenerItr = resourceModelChangedUIListeners
+                        .iterator();
+                while (listenerItr.hasNext()) {
+                    listener = listenerItr.next();
+                    if (null != listener) {
+                        listener.onResourceModelChange(notificationType,
+                                resourceURI);
+                    }
+                }
+            }
+        }
+    }
+
+    private void resourceAutomationStartedUINotification(String resourceURI) {
+        synchronized (automationUIListeners) {
+            if (automationUIListeners.size() > 0 && null != resourceURI) {
+                IAutomationUIListener listener;
+                Iterator<IAutomationUIListener> listenerItr = automationUIListeners
+                        .iterator();
+                while (listenerItr.hasNext()) {
+                    listener = listenerItr.next();
+                    if (null != listener) {
+                        listener.onResourceAutomationStart(resourceURI);
+                    }
+                }
+            }
+        }
+    }
+
+    private void automationCompleteUINotification(String resourceURI,
+            String attName) {
+        synchronized (automationUIListeners) {
+            if (automationUIListeners.size() > 0 && null != resourceURI) {
+                IAutomationUIListener listener;
+                Iterator<IAutomationUIListener> listenerItr = automationUIListeners
+                        .iterator();
+                while (listenerItr.hasNext()) {
+                    listener = listenerItr.next();
+                    if (null != listener) {
+                        listener.onAutomationComplete(resourceURI, attName);
+                    }
+                }
+            }
+        }
+    }
+
+    public List<String> getResourceTypeList() {
+        List<String> typeList = null;
+        synchronized (resourceMap) {
+            if (resourceMap.size() > 0) {
+                typeList = new ArrayList<String>();
+                Set<String> typeSet = resourceMap.keySet();
+                Iterator<String> typeItr = typeSet.iterator();
+                while (typeItr.hasNext()) {
+                    typeList.add(typeItr.next());
+                }
+            }
+        }
+        return typeList;
+    }
+
+    public boolean isTypeExist(String resType) {
+        synchronized (resourceMap) {
+            if (resourceMap.containsKey(resType)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    public List<String> getURIListOfResourceType(String type) {
+        List<String> uriList = null;
+        synchronized (resourceMap) {
+            if (null != type) {
+                Map<String, SimulatorResource> typeMap = resourceMap.get(type);
+                if (null != typeMap) {
+                    Set<String> keySet = typeMap.keySet();
+                    uriList = new ArrayList<String>();
+                    Iterator<String> keyItr = keySet.iterator();
+                    while (keyItr.hasNext()) {
+                        uriList.add(keyItr.next());
+                    }
+                }
+            }
+        }
+        return uriList;
+    }
+
+    public void resourceSelectionChanged(final String selectedItem) {
+        new Thread() {
+            @Override
+            public void run() {
+                // Check whether the item selected is a resource or resource
+                // category
+                if (isTypeExist(selectedItem)) {
+                    // Given item is a resource Type
+                    setCurrentResourceInSelection(null);
+                } else {
+                    // Given item is a resource URI
+                    SimulatorResource resource = getSimulatorResourceByURI(selectedItem);
+                    if (null != resource) {
+                        setCurrentResourceInSelection(resource);
+                    } else {
+                        setCurrentResourceInSelection(null);
+                    }
+                }
+                // Notify all observers for resource selection change event
+                resourceSelectionChangedUINotification();
+            }
+        }.start();
+    }
+
+    public List<MetaProperty> getMetaProperties(SimulatorResource resource) {
+        if (null != resource) {
+            String propName;
+            String propValue;
+
+            List<MetaProperty> metaPropertyList = new ArrayList<MetaProperty>();
+
+            for (int index = 0; index < Constants.META_PROPERTY_COUNT; index++) {
+                propName = Constants.META_PROPERTIES[index];
+                if (propName.equals(Constants.RESOURCE_URI)) {
+                    propValue = resource.getResourceURI();
+                } else if (propName.equals(Constants.RESOURCE_TYPE)) {
+                    propValue = resource.getResourceType();
+                } else if (propName.equals(Constants.RESOURCE_UID)) {
+                    // propValue = resource.getResourceUID();
+                    propValue = "Dummy123"; // Temporarily adding dummy value to
+                    // see in UI
+                } else if (propName.equals(Constants.CONNECTIVITY_TYPE)) {
+                    // propValue = resource.getConnectivityType();
+                    propValue = "IP"; // Temporarily adding dummy value to see
+                    // in UI
+                } else {
+                    propValue = null;
+                }
+                if (null != propValue) {
+                    metaPropertyList.add(new MetaProperty(propName, propValue));
+                }
+            }
+
+            return metaPropertyList;
+        }
+        return null;
+    }
+
+    public List<ResourceAttribute> getAttributes(SimulatorResource resource) {
+        List<ResourceAttribute> attList = null;
+        if (null != resource) {
+            Map<String, ResourceAttribute> attMap = resource
+                    .getResourceAttributesMap();
+            if (null != attMap && attMap.size() > 0) {
+                attList = new ArrayList<ResourceAttribute>();
+                Set<String> attNameSet = attMap.keySet();
+                String attName;
+                ResourceAttribute attribute;
+                // ResourceAttribute attributeClone;
+                Iterator<String> attNameItr = attNameSet.iterator();
+                while (attNameItr.hasNext()) {
+                    attName = attNameItr.next();
+                    attribute = attMap.get(attName);
+                    if (null != attribute) {
+                        // attributeClone =
+                        // ResourceAttribute.clone(attribute);
+                        attList.add(attribute);
+                    }
+                }
+            }
+        }
+        return attList;
+    }
+
+    public void attributeValueUpdated(SimulatorResource resource,
+            String attributeName, String value) {
+        if (null != resource && null != attributeName && null != value) {
+            SimulatorResourceServer server = resource.getResourceServer();
+            if (null != server) {
+                server.updateAttributeStringN(attributeName, value);
+            }
+        }
+    }
+
+    private ModelChangeNotificationType compareAndUpdateLocalAttributes(
+            Map<String, ResourceAttribute> resourceAttributeMapOld,
+            Map<String, ResourceAttribute> resourceAttributeMapNew) {
+        ModelChangeNotificationType notificationType = ModelChangeNotificationType.NONE;
+        if (null != resourceAttributeMapOld && null != resourceAttributeMapNew) {
+            Set<String> oldMapKeySet = resourceAttributeMapOld.keySet();
+            Iterator<String> attributeMapOldItr = oldMapKeySet.iterator();
+            String attName;
+            ResourceAttribute attributeOld;
+            ResourceAttribute 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;
+                            }
+                        }
+                    }
+                    resourceAttributeMapNew.remove(attName);
+                } else {
+                    // Attribute doesn't exist in the new model. Hence
+                    // removing it from the model.
+                    resourceAttributeMapOld.remove(attName);
+                    notificationType = ModelChangeNotificationType.ATTRIBUTE_REMOVED;
+                }
+            }
+            // Check for new attributes in the new model
+            if (resourceAttributeMapNew.size() > 0) {
+                Set<String> remainingAttSet = resourceAttributeMapNew.keySet();
+                Iterator<String> remainingAttItr = remainingAttSet.iterator();
+                ResourceAttribute attribute;
+                while (remainingAttItr.hasNext()) {
+                    attName = remainingAttItr.next();
+                    if (null != attName) {
+                        attribute = resourceAttributeMapNew.get(attName);
+                        if (null != attribute) {
+                            resourceAttributeMapOld.put(attName, attribute);
+                        }
+                    }
+                }
+                notificationType = ModelChangeNotificationType.ATTRIBUTE_ADDED;
+            }
+        }
+        return notificationType;
+    }
+
+    public int startAutomation(SimulatorResource resource,
+            ResourceAttribute attribute, AutomationType autoType,
+            int autoUpdateInterval) {
+        int autoId = -1;
+        if (null != resource && null != attribute) {
+            SimulatorResourceServer resourceServerN = resource
+                    .getResourceServer();
+            if (null != resourceServerN) {
+                String attrName = attribute.getAttributeName();
+                autoId = resourceServerN.startAttributeAutomation(attrName,
+                        autoType.ordinal(), automationListener);
+                if (-1 != autoId) {
+                    attribute.setAutomationId(autoId);
+                } else {
+                    attribute.setAutomationInProgress(false);
+                    resource.setAttributeAutomationInProgress(false);
+                }
+            }
+        }
+        return autoId;
+    }
+
+    public void stopAutomation(SimulatorResource resource, int autoId) {
+        if (null != resource) {
+            SimulatorResourceServer resourceServerN = resource
+                    .getResourceServer();
+            if (null != resourceServerN) {
+                resourceServerN.stopAutomation(autoId);
+            }
+        }
+    }
+
+    private ResourceAttribute getAttributeWithGivenAutomationId(
+            SimulatorResource resource, int automationId) {
+        ResourceAttribute targetAttribute = null;
+        if (null != resource) {
+            Map<String, ResourceAttribute> attributeMap = resource
+                    .getResourceAttributesMap();
+            if (null != attributeMap) {
+                Set<String> attNameSet = attributeMap.keySet();
+                Iterator<String> attNameItr = attNameSet.iterator();
+                String attName;
+                ResourceAttribute attribute;
+                while (attNameItr.hasNext()) {
+                    attName = attNameItr.next();
+                    if (null != attName) {
+                        attribute = attributeMap.get(attName);
+                        if (null != attribute) {
+                            if (attribute.isAutomationInProgress()
+                                    && (attribute.getAutomationId() == automationId)) {
+                                targetAttribute = attribute;
+                                break;
+                            }
+                        }
+                    }
+                }
+            }
+        }
+        return targetAttribute;
+    }
+
+    public boolean startResourceAutomationUIRequest(final String resourceURI) {
+        if (null == resourceURI) {
+            return false;
+        }
+        boolean status = false;
+        SimulatorResource resource = getSimulatorResourceByURI(resourceURI);
+        if (null != resource) {
+            changeResourceLevelAutomationStatus(resource, true);
+
+            // Invoke the native automation method
+            SimulatorResourceServer resourceServer = resource
+                    .getResourceServer();
+            if (null != resourceServer) {
+                // TODO: Temporarily handling the normal one-time automation for
+                // resources
+                int autoId = resourceServer.startResourceAutomation(
+                        AutomationType.NORMAL.ordinal(), automationListener);
+                if (-1 == autoId) {
+                    // Automation request failed and hence status is being
+                    // rolled back
+                    changeResourceLevelAutomationStatus(resource, false);
+                } else {
+                    // Automation request accepted.
+                    resource.setAutomationId(autoId);
+
+                    // Notify the UI listeners in a different thread.
+                    Thread notifyThread = new Thread() {
+                        public void run() {
+                            resourceAutomationStartedUINotification(resourceURI);
+                        };
+                    };
+                    notifyThread.setPriority(Thread.MAX_PRIORITY);
+                    notifyThread.start();
+
+                    status = true;
+                }
+            }
+        }
+        return status;
+    }
+
+    public void stopResourceAutomationUIRequest(final String resourceURI) {
+        Thread stopThread = new Thread() {
+            public void run() {
+                SimulatorResource resource = getSimulatorResourceByURI(resourceURI);
+                if (null == resource) {
+                    return;
+                }
+                int autoId = resource.getAutomationId();
+                if (-1 == autoId) {
+                    return;
+                }
+                SimulatorResourceServer resourceServer = resource
+                        .getResourceServer();
+                if (null == resourceServer) {
+                    return;
+                }
+                // Call native method
+                resourceServer.stopAutomation(autoId);
+
+                // Invoke the automation complete callback
+                automationListener.onAutomationComplete(resourceURI, autoId);
+            }
+        };
+        stopThread.start();
+    }
+
+    // Changes the automation state of the resource and its attributes
+    private void changeResourceLevelAutomationStatus(
+            SimulatorResource resource, boolean status) {
+
+        Map<String, ResourceAttribute> attributeMap = resource
+                .getResourceAttributesMap();
+        if (null != attributeMap) {
+            Set<String> attrNameSet = attributeMap.keySet();
+            Iterator<String> attrNameItr = attrNameSet.iterator();
+            String attrName;
+            ResourceAttribute attribute;
+            while (attrNameItr.hasNext()) {
+                attrName = attrNameItr.next();
+                attribute = attributeMap.get(attrName);
+                if (null != attribute) {
+                    attribute.setAutomationInProgress(status);
+                }
+            }
+        }
+        resource.setResourceAutomationInProgress(status);
+    }
+
+    public boolean isResourceAutomationStarted(String resourceURI) {
+        boolean status = false;
+        if (null == resourceURI) {
+            return status;
+        }
+
+        SimulatorResource resource = getSimulatorResourceByURI(resourceURI);
+        if (null != resource) {
+            status = resource.isResourceAutomationInProgress();
+        }
+        return status;
+    }
+
+    public boolean isAttributeAutomationStarted(String resourceURI) {
+        boolean status = false;
+        if (null == resourceURI) {
+            return status;
+        }
+        SimulatorResource resource = getSimulatorResourceByURI(resourceURI);
+        if (null != resource) {
+            status = resource.isAttributeAutomationInProgress();
+        }
+        return status;
+    }
+
+    public void shutdown() {
+        threadHandle.interrupt();
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/perspective/PerspectiveFactory.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/perspective/PerspectiveFactory.java
new file mode 100644 (file)
index 0000000..cb8954e
--- /dev/null
@@ -0,0 +1,37 @@
+package oic.simulator.serviceprovider.perspective;
+
+import oic.simulator.serviceprovider.view.AttributeView;
+import oic.simulator.serviceprovider.view.LogView;
+import oic.simulator.serviceprovider.view.MetaPropertiesView;
+import oic.simulator.serviceprovider.view.MultiResourceOrchestrationView;
+import oic.simulator.serviceprovider.view.ResourceManagerView;
+
+import org.eclipse.ui.IPageLayout;
+import org.eclipse.ui.IPerspectiveFactory;
+
+public class PerspectiveFactory implements IPerspectiveFactory {
+
+    public static final String PERSPECTIVE_ID = "oic.simulator.serviceprovider.perspective";
+    private IPageLayout        factory;
+
+    @Override
+    public void createInitialLayout(IPageLayout factory) {
+        this.factory = factory;
+        factory.setEditorAreaVisible(false);
+        addViews();
+        factory.setFixed(false);
+    }
+
+    private void addViews() {
+        factory.addView(ResourceManagerView.VIEW_ID, IPageLayout.LEFT, 0.3f,
+                factory.getEditorArea());
+        factory.addView(MetaPropertiesView.VIEW_ID, IPageLayout.BOTTOM, 0.65f,
+                ResourceManagerView.VIEW_ID);
+        factory.addView(AttributeView.VIEW_ID, IPageLayout.LEFT, 0.7f,
+                factory.getEditorArea());
+        factory.addView(LogView.VIEW_ID, IPageLayout.BOTTOM, 0.65f,
+                AttributeView.VIEW_ID);
+        factory.addView(MultiResourceOrchestrationView.VIEW_ID,
+                IPageLayout.RIGHT, 0.6f, AttributeView.VIEW_ID);
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/AttributeValueType.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/AttributeValueType.java
new file mode 100644 (file)
index 0000000..5798035
--- /dev/null
@@ -0,0 +1,6 @@
+package oic.simulator.serviceprovider.resource;
+
+// TODO: Temporarily adding this enum in plug-in. It will be removed once it is added to the java api sdk 
+public enum AttributeValueType {
+    INTEGER, DOUBLE, STRING, BOOLEAN
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/AutomationSettingHelper.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/AutomationSettingHelper.java
new file mode 100644 (file)
index 0000000..0d0d9eb
--- /dev/null
@@ -0,0 +1,111 @@
+package oic.simulator.serviceprovider.resource;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+import oic.simulator.serviceprovider.utils.Constants;
+
+import org.oic.simulator.AutomationType;
+
+public class AutomationSettingHelper {
+    private String       settingID;
+    private String       settingValue;
+    private List<String> allowedValues;
+
+    public String getSettingID() {
+        return settingID;
+    }
+
+    public void setSettingID(String settingID) {
+        this.settingID = settingID;
+    }
+
+    public String getSettingValue() {
+        return settingValue;
+    }
+
+    public void setSettingValue(String settingValue) {
+        this.settingValue = settingValue;
+    }
+
+    public List<String> getAllowedValues() {
+        return allowedValues;
+    }
+
+    public void setAllowedValues(List<String> allowedValues) {
+        this.allowedValues = allowedValues;
+    }
+
+    public void addAllowedValue(String newText) {
+        if (null != allowedValues) {
+            allowedValues.add(newText);
+        }
+    }
+
+    public static List<AutomationSettingHelper> getAutomationSettings(
+            ResourceAttribute attribute) {
+        List<AutomationSettingHelper> settingList = null;
+        boolean invalidSetting;
+        if (null != attribute) {
+            settingList = new ArrayList<AutomationSettingHelper>();
+            for (int count = 0; count < Constants.AUTOMATION_SETTINGS_COUNT; count++) {
+                invalidSetting = false;
+                AutomationSettingHelper setting = new AutomationSettingHelper();
+                if (Constants.AUTOMATION_SETTINGS[count]
+                        .equals(Constants.AUTOMATION)) {
+                    setting.setSettingID(Constants.AUTOMATION);
+                    setting.setSettingValue(attribute.isAutomationInProgress() ? Constants.ENABLE
+                            : Constants.DISABLE);
+                    List<String> valueList = new ArrayList<String>();
+                    valueList.add(Constants.ENABLE);
+                    valueList.add(Constants.DISABLE);
+                    setting.setAllowedValues(valueList);
+                } else if (Constants.AUTOMATION_SETTINGS[count]
+                        .equals(Constants.AUTOMATION_TYPE)) {
+                    setting.setSettingID(Constants.AUTOMATION_TYPE);
+                    setting.setSettingValue(attribute.getAutomationType()
+                            .toString());
+                    List<String> valueList = new ArrayList<String>();
+                    valueList.add(AutomationType.NORMAL.toString());
+                    valueList.add(AutomationType.RECURRENT.toString());
+                    setting.setAllowedValues(valueList);
+                } else if (Constants.AUTOMATION_SETTINGS[count]
+                        .equals(Constants.UPDATE_INTERVAL_IN_MS)) {
+                    setting.setSettingID(Constants.UPDATE_INTERVAL_IN_MS);
+                    setting.setSettingValue(String.valueOf(attribute
+                            .getAutomationUpdateInterval()));
+                    List<String> valueList = new ArrayList<String>();
+                    for (int index = 1; index <= 10; index++) {
+                        valueList.add(String.valueOf(index * 500));
+                    }
+                    setting.setAllowedValues(valueList);
+                } else {
+                    invalidSetting = true;
+                }
+                if (!invalidSetting) {
+                    settingList.add(setting);
+                }
+            }
+        }
+        return settingList;
+    }
+
+    public static void updateAutomationStatus(
+            List<AutomationSettingHelper> localSettingList, String status) {
+        if (null != localSettingList && null != status) {
+            Iterator<AutomationSettingHelper> settingItr = localSettingList
+                    .iterator();
+            AutomationSettingHelper setting;
+            while (settingItr.hasNext()) {
+                setting = settingItr.next();
+                if (null != setting) {
+                    if (setting.getSettingID().equals(Constants.AUTOMATION)) {
+                        setting.setSettingValue(status);
+                        break;
+                    }
+                }
+            }
+        }
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/MetaProperty.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/MetaProperty.java
new file mode 100644 (file)
index 0000000..bff71e7
--- /dev/null
@@ -0,0 +1,27 @@
+package oic.simulator.serviceprovider.resource;
+
+public class MetaProperty {
+    private String propName;
+    private String propValue;
+
+    public MetaProperty(String propName, String propValue) {
+        this.propName = propName;
+        this.propValue = propValue;
+    }
+
+    public String getPropValue() {
+        return propValue;
+    }
+
+    public void setPropValue(String propValue) {
+        this.propValue = propValue;
+    }
+
+    public String getPropName() {
+        return propName;
+    }
+
+    public void setPropName(String propName) {
+        this.propName = propName;
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/ModelChangeNotificationType.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/ModelChangeNotificationType.java
new file mode 100644 (file)
index 0000000..64deda9
--- /dev/null
@@ -0,0 +1,5 @@
+package oic.simulator.serviceprovider.resource;
+
+public enum ModelChangeNotificationType {
+    ATTRIBUTE_ADDED, ATTRIBUTE_REMOVED, ATTRIBUTE_VALUE_CHANGED, NONE
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/ResourceAttribute.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/ResourceAttribute.java
new file mode 100644 (file)
index 0000000..02b0fab
--- /dev/null
@@ -0,0 +1,181 @@
+package oic.simulator.serviceprovider.resource;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+
+import org.oic.simulator.AutomationType;
+import org.oic.simulator.SimulatorResourceAttribute;
+
+public class ResourceAttribute {
+
+    // Native object reference
+    private SimulatorResourceAttribute resourceAttribute;
+
+    private String                     attributeName;
+    private Object                     attributeValue;
+    private AttributeValueType         attributeType;
+    private List<Object>               allowedValues;
+
+    private Object                     minValue;
+    private Object                     maxValue;
+
+    private int                        automationId;
+
+    private boolean                    automationInProgress;
+
+    private int                        automationUpdateInterval;
+
+    private AutomationType             automationType;
+
+    public SimulatorResourceAttribute getResourceAttribute() {
+        return resourceAttribute;
+    }
+
+    public void setResourceAttribute(
+            SimulatorResourceAttribute resourceAttribute) {
+        this.resourceAttribute = resourceAttribute;
+    }
+
+    public String getAttributeName() {
+        return attributeName;
+    }
+
+    public void setAttributeName(String attributeName) {
+        this.attributeName = attributeName;
+    }
+
+    public Object getAttributeValue() {
+        return attributeValue;
+    }
+
+    public void setAttributeValue(Object attributeValue) {
+        this.attributeValue = attributeValue;
+    }
+
+    public AttributeValueType getAttributeType() {
+        return attributeType;
+    }
+
+    public void setAttributeType(AttributeValueType attributeType) {
+        this.attributeType = attributeType;
+    }
+
+    public List<Object> getAllowedValues() {
+        return allowedValues;
+    }
+
+    public void setAllowedValues(List<Object> allowedValues) {
+        this.allowedValues = allowedValues;
+    }
+
+    public void setAllowedValues(String[] allowedValues) {
+        List<Object> allowedValueList = null;
+        if (null != allowedValues && allowedValues.length > 0) {
+            allowedValueList = new ArrayList<Object>();
+            for (String value : allowedValues) {
+                allowedValueList.add(value);
+            }
+        }
+        this.allowedValues = allowedValueList;
+    }
+
+    public Object getMinValue() {
+        return minValue;
+    }
+
+    public void setMinValue(Object minValue) {
+        this.minValue = minValue;
+    }
+
+    public Object getMaxValue() {
+        return maxValue;
+    }
+
+    public void setMaxValue(Object maxValue) {
+        this.maxValue = maxValue;
+    }
+
+    public 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 static ResourceAttribute clone(ResourceAttribute attribute) {
+        ResourceAttribute clone = null;
+        if (null != attribute) {
+            clone = new ResourceAttribute();
+            clone.setAttributeName(attribute.getAttributeName());
+            clone.setAttributeValue(attribute.getAttributeValue());
+            clone.setAllowedValues(attribute.getAllowedValues());
+            clone.setAttributeType(attribute.getAttributeType());
+            clone.setMinValue(attribute.getMinValue());
+            clone.setMaxValue(attribute.getMaxValue());
+            clone.setAutomationInProgress(attribute.isAutomationInProgress());
+            clone.setAutomationType(attribute.getAutomationType());
+            clone.setAutomationUpdateInterval(attribute
+                    .getAutomationUpdateInterval());
+            clone.setResourceAttribute(null);
+        }
+        return clone;
+    }
+
+    // This method gives all known possible values of the attribute
+    // It takes allowed values or range of values whichever is available
+    public Set<Object> getValues() {
+        Set<Object> valueList = new HashSet<Object>();
+        if (null != allowedValues) {
+            Iterator<Object> values = allowedValues.iterator();
+            while (values.hasNext()) {
+                valueList.add(values.next());
+            }
+        } 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(value);
+                }
+            } else if (attributeValue.getClass() == Double.class) {
+                double min = (Double) minValue;
+                double max = (Double) maxValue;
+                for (double value = min; value <= max; value++) {
+                    valueList.add(value);
+                }
+            }
+        }
+        if (valueList.size() < 1) {
+            valueList.add(attributeValue);
+        }
+        return valueList;
+    }
+}
\ 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
new file mode 100644 (file)
index 0000000..f1f5171
--- /dev/null
@@ -0,0 +1,129 @@
+package oic.simulator.serviceprovider.resource;
+
+import java.util.Map;
+
+import org.oic.simulator.AutomationType;
+import org.oic.simulator.serviceprovider.SimulatorResourceModel;
+import org.oic.simulator.serviceprovider.SimulatorResourceServer;
+
+public class SimulatorResource {
+    private String                         resourceURI;
+    private String                         resourceName;
+    private String                         resourceType;
+    private String                         resourceInterface;
+
+    // Native Object references
+    private SimulatorResourceServer        resourceServer;
+    private SimulatorResourceModel         resourceModel;
+
+    private int                            automationId;
+
+    private boolean                        resourceAutomationInProgress;
+
+    private boolean                        attributeAutomationInProgress;
+
+    private int                            automationUpdateInterval;
+
+    private AutomationType                 automationType;
+
+    private Map<String, ResourceAttribute> resourceAttributesMap;
+
+    public String getResourceURI() {
+        return resourceURI;
+    }
+
+    public void setResourceURI(String resourceURI) {
+        this.resourceURI = resourceURI;
+    }
+
+    public String getResourceName() {
+        return resourceName;
+    }
+
+    public void setResourceName(String resourceName) {
+        this.resourceName = resourceName;
+    }
+
+    public String getResourceType() {
+        return resourceType;
+    }
+
+    public void setResourceType(String resourceType) {
+        this.resourceType = resourceType;
+    }
+
+    public String getResourceInterface() {
+        return resourceInterface;
+    }
+
+    public void setResourceInterface(String resourceInterface) {
+        this.resourceInterface = resourceInterface;
+    }
+
+    public SimulatorResourceServer getResourceServer() {
+        return resourceServer;
+    }
+
+    public void setResourceServer(SimulatorResourceServer resourceServer) {
+        this.resourceServer = resourceServer;
+    }
+
+    public SimulatorResourceModel getResourceModel() {
+        return resourceModel;
+    }
+
+    public void setResourceModel(SimulatorResourceModel resourceModel) {
+        this.resourceModel = resourceModel;
+    }
+
+    public Map<String, ResourceAttribute> getResourceAttributesMap() {
+        return resourceAttributesMap;
+    }
+
+    public void setResourceAttributesMap(
+            Map<String, ResourceAttribute> 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;
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/StandardConfiguration.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/resource/StandardConfiguration.java
new file mode 100644 (file)
index 0000000..2695713
--- /dev/null
@@ -0,0 +1,57 @@
+package oic.simulator.serviceprovider.resource;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public class StandardConfiguration {
+
+    private String      configuration_directory_path;
+
+    // A map of resourceType of standard resources as the key and the complete
+    // location of the file as the value
+    Map<String, String> standardResourceConfigurationMap;
+
+    public StandardConfiguration() {
+        standardResourceConfigurationMap = new HashMap<String, String>();
+    }
+
+    public String getConfiguration_directory_path() {
+        return configuration_directory_path;
+    }
+
+    public void setConfiguration_directory_path(
+            String configuration_directory_path) {
+        this.configuration_directory_path = configuration_directory_path;
+    }
+
+    public Map<String, String> getStandardResourceConfigurationList() {
+        return standardResourceConfigurationMap;
+    }
+
+    public void setStandardResourceConfigurationList(
+            Map<String, String> standardResourceConfigurationList) {
+        this.standardResourceConfigurationMap = standardResourceConfigurationList;
+    }
+
+    public void addResourceConfiguration(String resourceType,
+            String absolutePath) {
+        if (null != resourceType && resourceType.length() > 0
+                && null != absolutePath && absolutePath.length() > 0) {
+            standardResourceConfigurationMap.put(resourceType, absolutePath);
+        }
+    }
+
+    public String getResourceConfigFilePath(String resourceType) {
+        String path = null;
+        if (null != resourceType && resourceType.length() > 0) {
+            path = standardResourceConfigurationMap.get(resourceType);
+        }
+        return path;
+    }
+
+    public void removeResourceFromConfiguration(String resourceType) {
+        if (null != resourceType && resourceType.length() > 0) {
+            standardResourceConfigurationMap.remove(resourceType);
+        }
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/utils/Constants.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/utils/Constants.java
new file mode 100644 (file)
index 0000000..14d0b5a
--- /dev/null
@@ -0,0 +1,72 @@
+package oic.simulator.serviceprovider.utils;
+
+import org.oic.simulator.AutomationType;
+
+public class Constants {
+    public static final String         UNDERSCORE                       = "_";
+    public static final String         FORWARD_SLASH                    = "/";
+
+    public static final String         OIC                              = "oic";
+    public static final String         SIMULATOR                        = "simulator";
+
+    public static final String         RESOURCE_URI                     = "Resource URI";
+    public static final String         RESOURCE_TYPE                    = "Resource Type";
+    public static final String         RESOURCE_UID                     = "Resource ID";
+    public static final String         CONNECTIVITY_TYPE                = "Connectivity Type";
+
+    public static final String[]       META_PROPERTIES                  = {
+            RESOURCE_URI, RESOURCE_TYPE, RESOURCE_UID, CONNECTIVITY_TYPE };
+
+    public static final int            META_PROPERTY_COUNT              = META_PROPERTIES.length;
+
+    public static final String         ENABLE                           = "Enable";
+    public static final String         DISABLE                          = "Disable";
+    public static final String         ENABLED                          = "Enabled";
+    public static final String         DISABLED                         = "Disabled";
+
+    public static final String         AUTOMATION                       = "Automation";
+    public static final String         AUTOMATION_TYPE                  = "Automation Type";
+    public static final String         UPDATE_INTERVAL_IN_MS            = "Update Interval(ms)";
+
+    public static final String[]       AUTOMATION_SETTINGS              = {
+            AUTOMATION, AUTOMATION_TYPE, UPDATE_INTERVAL_IN_MS         };
+
+    public static final int            AUTOMATION_SETTINGS_COUNT        = AUTOMATION_SETTINGS.length;
+
+    public static final String         START_RESOURCE_AUTOMATION        = "Start Automation";
+    public static final String         STOP_RESOURCE_AUTOMATION         = "Stop Automation";
+
+    public static final int            PROPER_RESOURCE_URI_TOKEN_COUNT  = 5;
+    public static final int            DISPLAY_RESOURCE_URI_TOKEN_COUNT = 2;
+
+    public static final AutomationType DEFAULT_AUTOMATION_TYPE          = AutomationType.NORMAL;
+
+    public static final int            DEFAULT_AUTOMATION_INTERVAL      = 500;
+
+    public static final int            PROPER_LOG_TIME_TOKEN_LENGTH     = 3;
+
+    public static final String[]       BROWSE_RAML_FILTER_EXTENSIONS    = new String[] {
+            "*.raml", "*"                                              };
+    public static final String[]       SAVE_LOG_FILTER_EXTENSIONS       = new String[] {
+            "*.log", "*"                                               };
+
+    public static final int            LOG_SIZE                         = 1000;
+
+    public static final String         INFO_LOG                         = "info_log";
+    public static final String         WARNING_LOG                      = "warning_log";
+    public static final String         ERROR_LOG                        = "error_log";
+    public static final String         DEBUG_LOG                        = "debug_log";
+    public static final String         UNKNOWN_LOG                      = "unknown_log";
+
+    public static final String         INFO                             = "Info";
+    public static final String         WARNING                          = "Warning";
+    public static final String         ERROR                            = "Error";
+    public static final String         DEBUG                            = "Debug";
+    public static final String         UNKNOWN                          = "Unknown";
+
+    public static final String         CREATE_PAGE_TITLE                = "Create Resource";
+    public static final String         CREATE_PAGE_MESSAGE              = "Select a standard resource or custom resource to be created";
+
+    public static final String         DELETE_PAGE_TITLE                = "Delete Resource";
+    public static final String         DELETE_PAGE_MESSAGE              = "Select the resource(s) to be deleted";
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/utils/Utility.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/utils/Utility.java
new file mode 100644 (file)
index 0000000..481028a
--- /dev/null
@@ -0,0 +1,79 @@
+package oic.simulator.serviceprovider.utils;
+
+public class Utility {
+
+    public static String uriToDisplayName(String uri) {
+        String result = null;
+        if (null != uri) {
+            String tokens[] = uri.split(Constants.FORWARD_SLASH);
+            if (Constants.PROPER_RESOURCE_URI_TOKEN_COUNT == tokens.length) {
+                // Proper URI
+                result = tokens[2] + Constants.UNDERSCORE + tokens[4];
+            }
+        }
+        return result;
+    }
+
+    public static String displayNameToUri(String displayName) {
+        String result = null;
+        if (null != displayName) {
+            String tokens[] = displayName.split(Constants.UNDERSCORE);
+            if (Constants.DISPLAY_RESOURCE_URI_TOKEN_COUNT == tokens.length) {
+                // Proper Display Name
+                result = Constants.FORWARD_SLASH + Constants.OIC
+                        + Constants.FORWARD_SLASH + tokens[0]
+                        + Constants.FORWARD_SLASH + Constants.SIMULATOR
+                        + Constants.FORWARD_SLASH + tokens[1];
+            }
+        }
+        return result;
+    }
+
+    public static boolean isUriComplete(String uri) {
+        boolean uriComplete = false;
+        if (null != uri) {
+            String tokens[] = uri.split(Constants.FORWARD_SLASH);
+            if (Constants.PROPER_RESOURCE_URI_TOKEN_COUNT == tokens.length) {
+                uriComplete = true;
+            }
+        }
+        return uriComplete;
+    }
+
+    public static String getAutomationStatus(boolean status) {
+        if (status) {
+            return Constants.ENABLED;
+        } else {
+            return Constants.DISABLED;
+        }
+    }
+
+    public static String getAutomationString(boolean status) {
+        if (status) {
+            return Constants.ENABLE;
+        } else {
+            return Constants.DISABLE;
+        }
+    }
+
+    public static boolean getAutomationBoolean(String status) {
+        if (null != status) {
+            if (status.equals(Constants.ENABLE)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    public static int getUpdateIntervalFromString(String value) {
+        int result = Constants.DEFAULT_AUTOMATION_INTERVAL;
+        if (null != value) {
+            try {
+                result = Integer.parseInt(value);
+            } catch (NumberFormatException nfe) {
+                // Do nothing
+            }
+        }
+        return result;
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/AttributeView.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/AttributeView.java
new file mode 100644 (file)
index 0000000..ec47066
--- /dev/null
@@ -0,0 +1,1030 @@
+package oic.simulator.serviceprovider.view;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.listener.IAutomationUIListener;
+import oic.simulator.serviceprovider.listener.IResourceModelChangedUIListener;
+import oic.simulator.serviceprovider.listener.IResourceSelectionChangedUIListener;
+import oic.simulator.serviceprovider.manager.ResourceManager;
+import oic.simulator.serviceprovider.resource.AutomationSettingHelper;
+import oic.simulator.serviceprovider.resource.ModelChangeNotificationType;
+import oic.simulator.serviceprovider.resource.ResourceAttribute;
+import oic.simulator.serviceprovider.resource.SimulatorResource;
+import oic.simulator.serviceprovider.utils.Constants;
+import oic.simulator.serviceprovider.utils.Utility;
+
+import org.eclipse.jface.viewers.CellEditor;
+import org.eclipse.jface.viewers.CellLabelProvider;
+import org.eclipse.jface.viewers.ColumnLabelProvider;
+import org.eclipse.jface.viewers.ComboBoxCellEditor;
+import org.eclipse.jface.viewers.EditingSupport;
+import org.eclipse.jface.viewers.ISelectionChangedListener;
+import org.eclipse.jface.viewers.IStructuredContentProvider;
+import org.eclipse.jface.viewers.IStructuredSelection;
+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.swt.SWT;
+import org.eclipse.swt.custom.CCombo;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.TraverseEvent;
+import org.eclipse.swt.events.TraverseListener;
+import org.eclipse.swt.events.VerifyEvent;
+import org.eclipse.swt.events.VerifyListener;
+import org.eclipse.swt.graphics.Color;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Group;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Table;
+import org.eclipse.ui.part.ViewPart;
+import org.oic.simulator.AutomationType;
+
+public class AttributeView extends ViewPart {
+
+    public static final String                  VIEW_ID            = "oic.simulator.serviceprovider.view.attribute";
+
+    private TableViewer                         attTblViewer;
+    private TableViewer                         automtnSettingsTblViewer;
+
+    private IResourceSelectionChangedUIListener resourceSelectionChangedListener;
+    private IResourceModelChangedUIListener     resourceModelChangedUIListener;
+    private IAutomationUIListener               automationUIListener;
+
+    private Label                               newValueLbl;
+    private CCombo                              valueCmb;
+    private Button                              submitButton;
+    private Button                              clearButton;
+
+    private ResourceAttribute                   attributeInSelection;
+    private AttributeAutomationSettingEditor    automationSettingEditor;
+    private List<AutomationSettingHelper>       localSettingList;
+
+    private final String[]                      attTblHeaders      = { "Name",
+            "Value", "Automation Status"                          };
+    private final String[]                      settingTblHeaders  = {
+            "Setting", "Value"                                    };
+    private final Integer[]                     attTblColWidth     = { 150,
+            190, 150                                              };
+    private final Integer[]                     settingTblColWidth = { 140, 85 };
+
+    private ResourceManager                     resourceManager;
+
+    public AttributeView() {
+
+        resourceManager = Activator.getDefault().getResourceManager();
+
+        resourceSelectionChangedListener = new IResourceSelectionChangedUIListener() {
+
+            @Override
+            public void onResourceSelectionChange() {
+                Display.getDefault().asyncExec(new Runnable() {
+
+                    @Override
+                    public void run() {
+                        if (null != attTblViewer) {
+                            updateViewer(checkSelection());
+                        }
+                    }
+                });
+            }
+        };
+
+        resourceModelChangedUIListener = new IResourceModelChangedUIListener() {
+
+            @Override
+            public void onResourceModelChange(
+                    final ModelChangeNotificationType notificationType,
+                    final String resourceURI) {
+                Display.getDefault().asyncExec(new Runnable() {
+                    @Override
+                    public void run() {
+                        // Handle the notification only if it is for the current
+                        // resource in selection
+                        SimulatorResource resource = resourceManager
+                                .getCurrentResourceInSelection();
+                        if (null == resource) {
+                            return;
+                        }
+                        if (!resourceURI.equals(resource.getResourceURI())) {
+                            return;
+                        }
+                        // Refresh the table viewers which will display
+                        // the updated values
+                        if (null != attTblViewer) {
+                            attTblViewer.refresh();
+                        }
+                        // If this call has a new value for the current
+                        // attribute
+                        // in selection, then update it in the combo box
+                        if (notificationType != ModelChangeNotificationType.ATTRIBUTE_VALUE_CHANGED) {
+                            return;
+                        }
+                        if (null != valueCmb && !valueCmb.isDisposed()
+                                && null != attributeInSelection) {
+                            Map<String, ResourceAttribute> attributeMap = resource
+                                    .getResourceAttributesMap();
+                            if (null != attributeMap) {
+                                ResourceAttribute attribute = attributeMap
+                                        .get(attributeInSelection
+                                                .getAttributeName());
+                                if (null != attribute) {
+                                    Object valueObj = attribute
+                                            .getAttributeValue();
+                                    if (null != valueObj) {
+                                        String valueStr = String
+                                                .valueOf(valueObj);
+                                        int index = valueCmb.indexOf(valueStr);
+                                        if (index != -1) {
+                                            valueCmb.select(index);
+                                        } else {
+                                            valueCmb.add(valueStr);
+                                            valueCmb.select(valueCmb
+                                                    .indexOf(valueStr));
+                                        }
+                                    }
+                                }
+                            }
+                        }
+                    }
+                });
+            }
+        };
+
+        automationUIListener = new IAutomationUIListener() {
+
+            @Override
+            public void onResourceAutomationStart(final String resourceURI) {
+                Display.getDefault().asyncExec(new Runnable() {
+
+                    @Override
+                    public void run() {
+                        if (null == resourceURI) {
+                            return;
+                        }
+                        SimulatorResource resource = resourceManager
+                                .getCurrentResourceInSelection();
+                        if (null == resource) {
+                            return;
+                        }
+                        String uri = resource.getResourceURI();
+                        // Checking whether attributes view is currently
+                        // displaying the attributes of the
+                        // resource whose automation has just started
+                        if (null != uri && uri.equals(resourceURI)) {
+                            Table tbl;
+                            tbl = attTblViewer.getTable();
+                            if (!tbl.isDisposed()) {
+                                attTblViewer.refresh();
+                            }
+
+                            // If any attribute is in selection, then update
+                            // the automation setting to enable.
+                            if (null != attributeInSelection) {
+                                tbl = automtnSettingsTblViewer.getTable();
+                                if (!tbl.isDisposed()) {
+                                    // Change the local automation settings
+                                    AutomationSettingHelper
+                                            .updateAutomationStatus(
+                                                    localSettingList,
+                                                    Constants.ENABLE);
+                                    automtnSettingsTblViewer.refresh();
+                                }
+                            }
+
+                            // Disable the manual change UI controls
+                            setVisibilityForManualValueChange(false);
+                        }
+                    }
+                });
+            }
+
+            @Override
+            public void onAutomationComplete(final String resourceURI,
+                    final String attName) {
+                // This method notifies the completion of attribute level
+                // automation.
+                Display.getDefault().asyncExec(new Runnable() {
+
+                    @Override
+                    public void run() {
+                        if (null == resourceURI) {
+                            return;
+                        }
+                        // Check if the given resourceURI is the uri of the
+                        // resource whose attributes are currently being
+                        // displayed by this view.
+                        SimulatorResource resource = resourceManager
+                                .getCurrentResourceInSelection();
+                        if (null == resource) {
+                            return;
+                        }
+                        String uri = resource.getResourceURI();
+                        if (null != uri && uri.equals(resourceURI)) {
+                            Table tbl;
+                            tbl = attTblViewer.getTable();
+                            if (!tbl.isDisposed()) {
+                                attTblViewer.refresh();
+                            }
+
+                            if (null != attributeInSelection) {
+                                if (null == attName
+                                        || attributeInSelection
+                                                .getAttributeName().equals(
+                                                        attName)) {
+                                    tbl = automtnSettingsTblViewer.getTable();
+                                    if (!tbl.isDisposed()) {
+                                        // Change the local automation settings
+                                        AutomationSettingHelper
+                                                .updateAutomationStatus(
+                                                        localSettingList,
+                                                        Constants.DISABLE);
+                                        automtnSettingsTblViewer.refresh();
+                                    }
+                                    setVisibilityForManualValueChange(true);
+                                }
+                            }
+                        }
+                    }
+                });
+            }
+        };
+    }
+
+    @Override
+    public void createPartControl(Composite parent) {
+        Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE);
+
+        parent.setLayout(new GridLayout(2, false));
+        GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        parent.setLayoutData(gd);
+
+        Group attGroup = new Group(parent, SWT.NONE);
+        attGroup.setLayout(new GridLayout(1, false));
+        gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        gd.horizontalSpan = 2;
+        gd.minimumHeight = 175;
+        attGroup.setLayoutData(gd);
+        attGroup.setText("Attributes");
+        attGroup.setBackground(color);
+
+        attTblViewer = new TableViewer(attGroup, 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());
+
+        Group automationSettingsTableGrp = new Group(parent, SWT.NONE);
+        automationSettingsTableGrp.setLayout(new GridLayout(1, false));
+        gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        automationSettingsTableGrp.setLayoutData(gd);
+        automationSettingsTableGrp.setText("Automation Settings");
+        automationSettingsTableGrp.setBackground(color);
+
+        automtnSettingsTblViewer = new TableViewer(automationSettingsTableGrp,
+                SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION
+                        | SWT.BORDER);
+
+        createSettingColumns(automtnSettingsTblViewer);
+
+        // make lines visible
+        table = automtnSettingsTblViewer.getTable();
+        gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        table.setLayoutData(gd);
+        table.setHeaderVisible(true);
+        table.setLinesVisible(true);
+
+        automtnSettingsTblViewer
+                .setContentProvider(new AttributeContentProvider());
+
+        Composite rightViewComp = new Composite(parent, SWT.NONE);
+        rightViewComp.setLayout(new GridLayout(1, false));
+
+        Group valueUpdateGroup = new Group(rightViewComp, SWT.NONE);
+        valueUpdateGroup.setLayout(new GridLayout(2, false));
+        gd = new GridData();
+        gd.horizontalAlignment = SWT.FILL;
+        gd.grabExcessHorizontalSpace = true;
+        gd.horizontalSpan = 2;
+        valueUpdateGroup.setLayoutData(gd);
+        valueUpdateGroup.setText("Change Attribute Value");
+        valueUpdateGroup.setBackground(color);
+
+        newValueLbl = new Label(valueUpdateGroup, SWT.NONE);
+        newValueLbl.setText("Select New Value");
+
+        valueCmb = new CCombo(valueUpdateGroup, SWT.BORDER);
+        gd = new GridData();
+        gd.widthHint = 100;
+        valueCmb.setLayoutData(gd);
+
+        submitButton = new Button(rightViewComp, SWT.PUSH);
+        gd = new GridData();
+        gd.widthHint = 150;
+        gd.verticalIndent = 10;
+        gd.horizontalSpan = 2;
+        gd.horizontalAlignment = SWT.CENTER;
+        submitButton.setLayoutData(gd);
+        submitButton.setText("Apply Changes");
+
+        clearButton = new Button(rightViewComp, SWT.PUSH);
+        gd = new GridData();
+        gd.widthHint = 150;
+        gd.verticalIndent = 10;
+        gd.horizontalSpan = 2;
+        gd.horizontalAlignment = SWT.CENTER;
+        clearButton.setLayoutData(gd);
+        clearButton.setText("Reset Changes");
+
+        addUIListeners();
+
+        addManagerListeners();
+
+        // Check whether there is any resource selected already
+        List<ResourceAttribute> propertyList = checkSelection();
+        if (null != propertyList) {
+            updateViewer(propertyList);
+        }
+
+        setSettingSubmitVisibility(false);
+    }
+
+    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 ColumnLabelProvider() {
+            @Override
+            public String getText(Object element) {
+                if (element instanceof ResourceAttribute) {
+                    ResourceAttribute attribute = (ResourceAttribute) element;
+                    if (null != attribute) {
+                        return attribute.getAttributeName();
+                    }
+                }
+                return "";
+            }
+        });
+
+        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 ResourceAttribute) {
+                    ResourceAttribute attribute = (ResourceAttribute) element;
+                    if (null != attribute) {
+                        Object val = attribute.getAttributeValue();
+                        if (null != val) {
+                            return String.valueOf(val);
+                        }
+                    }
+                }
+                return "";
+            }
+        });
+
+        TableViewerColumn automationStatus = new TableViewerColumn(tableViewer,
+                SWT.NONE);
+        automationStatus.getColumn().setWidth(attTblColWidth[2]);
+        automationStatus.getColumn().setText(attTblHeaders[2]);
+        automationStatus.setLabelProvider(new ColumnLabelProvider() {
+            @Override
+            public String getText(Object element) {
+                if (element instanceof ResourceAttribute) {
+                    ResourceAttribute attribute = (ResourceAttribute) element;
+                    if (null != attribute) {
+                        boolean progress = attribute.isAutomationInProgress();
+                        return Utility.getAutomationStatus(progress);
+                    }
+                }
+                return "";
+            }
+        });
+    }
+
+    public void createSettingColumns(TableViewer tableViewer) {
+        TableViewerColumn key = new TableViewerColumn(tableViewer, SWT.NONE);
+        key.getColumn().setWidth(settingTblColWidth[0]);
+        key.getColumn().setText(settingTblHeaders[0]);
+        key.setLabelProvider(new StyledCellLabelProvider() {
+            @Override
+            public void update(ViewerCell cell) {
+                Object element = cell.getElement();
+                if (element instanceof AutomationSettingHelper) {
+                    AutomationSettingHelper setting = (AutomationSettingHelper) element;
+                    cell.setText(setting.getSettingID());
+                }
+            }
+        });
+
+        TableViewerColumn value = new TableViewerColumn(tableViewer, SWT.NONE);
+        value.getColumn().setWidth(settingTblColWidth[1]);
+        value.getColumn().setText(settingTblHeaders[1]);
+        value.setLabelProvider(new CellLabelProvider() {
+            @Override
+            public void update(ViewerCell cell) {
+                Object element = cell.getElement();
+                if (element instanceof AutomationSettingHelper) {
+                    AutomationSettingHelper setting = (AutomationSettingHelper) element;
+                    if (null != setting) {
+                        cell.setText(String.valueOf(setting.getSettingValue()));
+                    }
+                }
+            }
+        });
+        automationSettingEditor = new AttributeAutomationSettingEditor(
+                tableViewer);
+        value.setEditingSupport(automationSettingEditor);
+    }
+
+    private void addUIListeners() {
+        attTblViewer
+                .addSelectionChangedListener(new ISelectionChangedListener() {
+
+                    @Override
+                    public void selectionChanged(SelectionChangedEvent e) {
+                        IStructuredSelection selection = (IStructuredSelection) attTblViewer
+                                .getSelection();
+                        Object firstElement = selection.getFirstElement();
+                        if (firstElement instanceof ResourceAttribute) {
+                            ResourceAttribute attribute = (ResourceAttribute) firstElement;
+
+                            // Store the attribute selection
+                            attributeInSelection = attribute;
+
+                            // Change the visibility of the manual change
+                            // controls according to the automation status
+                            if (attribute.isAutomationInProgress()) {
+                                setVisibilityForManualValueChange(false);
+                            } else {
+                                setVisibilityForManualValueChange(true);
+                            }
+
+                            // Hide the visibility of submit and clear buttons
+                            setSettingSubmitVisibility(false);
+
+                            if (null != attribute) {
+                                if (null != automtnSettingsTblViewer) {
+                                    localSettingList = AutomationSettingHelper
+                                            .getAutomationSettings(attribute);
+                                    if (null != localSettingList) {
+                                        automtnSettingsTblViewer.getTable()
+                                                .setLinesVisible(true);
+                                        automtnSettingsTblViewer
+                                                .setInput(localSettingList
+                                                        .toArray());
+                                    }
+                                }
+                                // Populate the attribute value combo
+                                if (null != valueCmb && !valueCmb.isDisposed()) {
+                                    // Clear the existing combo list contents
+                                    valueCmb.removeAll();
+                                    Set<Object> valueList = attribute
+                                            .getValues();
+                                    Object value;
+                                    if (null != valueList) {
+                                        Iterator<Object> valueItr = valueList
+                                                .iterator();
+                                        while (valueItr.hasNext()) {
+                                            value = valueItr.next();
+                                            if (null != value) {
+                                                // Casting the value to String
+                                                // for showing in combo
+                                                valueCmb.add(String
+                                                        .valueOf(value));
+                                            }
+                                        }
+                                        // Setting the selection to the current
+                                        // value of the attribute
+                                        String attValue = String
+                                                .valueOf(attribute
+                                                        .getAttributeValue());
+                                        int index = valueCmb.indexOf(attValue);
+                                        if (index != -1) {
+                                            valueCmb.select(index);
+                                        }
+                                    }
+                                }
+                            }
+                        }
+                    }
+                });
+
+        valueCmb.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                if (null != attributeInSelection) {
+                    // attributeInSelection.setAttributeValue(valueCmb.getText());
+                    if (!valueCmb.getText().equals(
+                            String.valueOf(attributeInSelection
+                                    .getAttributeValue()))) {
+                        // Enable the submit and clear button controls
+                        setSettingSubmitVisibility(true);
+                    } else {
+                        setSettingSubmitVisibility(false);
+                    }
+                }
+            }
+        });
+
+        submitButton.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+
+                if (null != attributeInSelection && null != localSettingList) {
+                    if (attributeInSelection.isAutomationInProgress()
+                            || valueCmb.getText().equals(
+                                    String.valueOf(attributeInSelection
+                                            .getAttributeValue()))) {
+                        // Change in automation settings
+                        Iterator<AutomationSettingHelper> settingItr = localSettingList
+                                .iterator();
+
+                        // These variables will hold the new automation
+                        // settings.
+                        boolean autoEnable = false;
+                        AutomationType autoType = AutomationType.NORMAL;
+                        int autoUpdateInterval = Constants.DEFAULT_AUTOMATION_INTERVAL;
+
+                        // These variables will hold the old automation settings
+                        // and are used to roll-back the settings
+                        // if automation fails.
+                        boolean autoEnablePrev = false;
+                        AutomationType autoTypePrev = AutomationType.NORMAL;
+                        int autoUpdateIntervalPrev = Constants.DEFAULT_AUTOMATION_INTERVAL;
+
+                        String id;
+                        String value;
+                        AutomationSettingHelper setting;
+                        while (settingItr.hasNext()) {
+                            setting = settingItr.next();
+                            id = setting.getSettingID();
+                            value = setting.getSettingValue();
+                            if (id.equals(Constants.AUTOMATION)) {
+                                autoEnable = Utility
+                                        .getAutomationBoolean(value);
+                                autoEnablePrev = attributeInSelection
+                                        .isAutomationInProgress();
+
+                                attributeInSelection
+                                        .setAutomationInProgress(autoEnable);
+                                // Automation is disabled and hence the manual
+                                // controls should be enabled
+                                if (!autoEnable) {
+                                    setVisibilityForManualValueChange(true);
+                                }
+                            } else if (id.equals(Constants.AUTOMATION_TYPE)) {
+                                autoType = AutomationType.valueOf(value);
+                                autoTypePrev = attributeInSelection
+                                        .getAutomationType();
+
+                                attributeInSelection
+                                        .setAutomationType(autoType);
+                            } else if (id
+                                    .equals(Constants.UPDATE_INTERVAL_IN_MS)) {
+                                autoUpdateInterval = Utility
+                                        .getUpdateIntervalFromString(value);
+                                autoUpdateIntervalPrev = attributeInSelection
+                                        .getAutomationUpdateInterval();
+
+                                attributeInSelection
+                                        .setAutomationUpdateInterval(autoUpdateInterval);
+                            }
+                        }
+
+                        // Updating the automation status in the resource
+                        SimulatorResource resource = resourceManager
+                                .getCurrentResourceInSelection();
+                        resource.setAttributeAutomationInProgress(autoEnable);
+
+                        if (autoEnable) {
+                            // Send automation enable request
+                            int autoId = resourceManager.startAutomation(
+                                    resource, attributeInSelection, autoType,
+                                    autoUpdateInterval);
+                            if (-1 == autoId) {
+                                // Automation failed
+                                // Roll-back the attribute model and automation
+                                // settings
+                                settingItr = localSettingList.iterator();
+                                while (settingItr.hasNext()) {
+                                    setting = settingItr.next();
+                                    id = setting.getSettingID();
+                                    value = setting.getSettingValue();
+                                    if (id.equals(Constants.AUTOMATION)) {
+                                        setting.setSettingValue(Utility
+                                                .getAutomationString(autoEnablePrev));
+                                    } else if (id
+                                            .equals(Constants.AUTOMATION_TYPE)) {
+                                        setting.setSettingValue(autoTypePrev
+                                                .toString());
+                                    } else if (id
+                                            .equals(Constants.UPDATE_INTERVAL_IN_MS)) {
+                                        setting.setSettingValue(String
+                                                .valueOf(autoUpdateIntervalPrev));
+                                    }
+                                }
+
+                                attributeInSelection
+                                        .setAutomationInProgress(autoEnablePrev);
+                                attributeInSelection
+                                        .setAutomationType(autoTypePrev);
+                                attributeInSelection
+                                        .setAutomationUpdateInterval(autoUpdateIntervalPrev);
+
+                                automtnSettingsTblViewer.refresh();
+
+                                // Automation is disabled and hence the manual
+                                // controls should be enabled
+                                setVisibilityForManualValueChange(true);
+                            }
+                        } else {
+                            // Send automation disable request
+                            int autoId = attributeInSelection.getAutomationId();
+                            resourceManager.stopAutomation(resource, autoId);
+                        }
+                    } else {
+                        // Change in attribute value manually
+                        String input = valueCmb.getText();
+                        if (null != input && input.length() > 0) {
+                            attributeInSelection.setAttributeValue(input);
+
+                            SimulatorResource resource = resourceManager
+                                    .getCurrentResourceInSelection();
+                            resourceManager.attributeValueUpdated(resource,
+                                    attributeInSelection.getAttributeName(),
+                                    input);
+                        }
+                    }
+                }
+
+                attTblViewer.refresh();
+
+                setSettingSubmitVisibility(false);
+            }
+        });
+
+        clearButton.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                if (null != attributeInSelection) {
+                    // Update the settings table
+                    List<AutomationSettingHelper> settingList = AutomationSettingHelper
+                            .getAutomationSettings(attributeInSelection);
+                    if (null != settingList) {
+                        // clear the existing table contents
+                        Table tbl = automtnSettingsTblViewer.getTable();
+                        if (!tbl.isDisposed()) {
+                            tbl.removeAll();
+                            localSettingList = settingList;
+                            automtnSettingsTblViewer.setInput(localSettingList
+                                    .toArray());
+                        }
+                    }
+                    // Update the allowed values combo
+                    if (!valueCmb.isDisposed()) {
+                        valueCmb.setText(String.valueOf(attributeInSelection
+                                .getAttributeValue()));
+                        setVisibilityForManualValueChange(!attributeInSelection
+                                .isAutomationInProgress());
+                    }
+                }
+                setSettingSubmitVisibility(false);
+            }
+        });
+    }
+
+    private void addManagerListeners() {
+        resourceManager
+                .addResourceSelectionChangedUIListener(resourceSelectionChangedListener);
+        resourceManager
+                .addResourceModelChangedUIListener(resourceModelChangedUIListener);
+        resourceManager.addAutomationUIListener(automationUIListener);
+    }
+
+    private void setSettingSubmitVisibility(boolean visible) {
+        if (!submitButton.isDisposed())
+            submitButton.setEnabled(visible);
+        if (!clearButton.isDisposed())
+            clearButton.setEnabled(visible);
+    }
+
+    private List<ResourceAttribute> checkSelection() {
+        SimulatorResource resourceInSelection = resourceManager
+                .getCurrentResourceInSelection();
+        if (null != resourceInSelection) {
+            List<ResourceAttribute> attList = resourceManager
+                    .getAttributes(resourceInSelection);
+            return attList;
+        } else {
+            return null;
+        }
+    }
+
+    private void updateViewer(List<ResourceAttribute> attList) {
+        Table tbl;
+        if (null != attList) {
+            tbl = attTblViewer.getTable();
+            if (null != tbl && !tbl.isDisposed()) {
+                tbl.setLinesVisible(true);
+                attTblViewer.setInput(attList.toArray());
+            }
+        } else {
+            // Clear the attributes table viewer
+            if (null != attTblViewer) {
+                tbl = attTblViewer.getTable();
+                if (null != tbl && !tbl.isDisposed()) {
+                    // tbl.deselectAll();
+                    tbl.removeAll();
+                    tbl.setLinesVisible(false);
+                }
+            }
+        }
+
+        attributeInSelection = null;
+
+        // Clear the Settings table viewer
+        if (null != automtnSettingsTblViewer) {
+            tbl = automtnSettingsTblViewer.getTable();
+            if (null != tbl && !tbl.isDisposed()) {
+                // tbl.deselectAll();
+                tbl.removeAll();
+                tbl.setLinesVisible(false);
+            }
+        }
+        // Clear the value list combo
+        if (!valueCmb.isDisposed()) {
+            valueCmb.removeAll();
+            valueCmb.setEnabled(false);
+        }
+
+        // Hide the visibility of submit and clear buttons
+        setSettingSubmitVisibility(false);
+    }
+
+    class AttributeContentProvider implements IStructuredContentProvider {
+
+        @Override
+        public void dispose() {
+        }
+
+        @Override
+        public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
+        }
+
+        @Override
+        public Object[] getElements(Object element) {
+            return (Object[]) element;
+        }
+
+    }
+
+    class AttributeAutomationSettingEditor extends EditingSupport {
+
+        private final TableViewer       viewer;
+
+        private AutomationSettingHelper currentSettingInSelection;
+
+        public AttributeAutomationSettingEditor(TableViewer viewer) {
+            super(viewer);
+            this.viewer = viewer;
+        }
+
+        @Override
+        protected boolean canEdit(Object element) {
+            return true;
+        }
+
+        @Override
+        protected CellEditor getCellEditor(Object element) {
+            ComboBoxCellEditor combo = null;
+            if (null != element) {
+                List<String> valueList;
+                boolean readOnly = true;
+                AutomationSettingHelper setting = (AutomationSettingHelper) element;
+
+                currentSettingInSelection = setting;
+
+                String settingID = setting.getSettingID();
+                if (settingID.equals(Constants.UPDATE_INTERVAL_IN_MS)) {
+                    readOnly = false;
+                }
+                valueList = setting.getAllowedValues();
+                if (null == valueList) {
+                    valueList = new ArrayList<String>();
+                }
+                // Convert list to String[] for passing it to ComboBoxCellEditor
+                String[] values;
+                values = valueList.toArray(new String[1]);
+                if (readOnly) {
+                    combo = new ComboBoxCellEditor(viewer.getTable(), values,
+                            SWT.READ_ONLY);
+                } else {
+                    combo = new ComboBoxCellEditor(viewer.getTable(), values);
+                }
+
+                // If resource level automation is enabled, then all setting
+                // should be disabled
+                SimulatorResource resourceInSelection;
+                resourceInSelection = resourceManager
+                        .getCurrentResourceInSelection();
+                if (null != resourceInSelection
+                        && resourceInSelection.isResourceAutomationInProgress()) {
+                    CCombo c = (CCombo) combo.getControl();
+                    c.setEnabled(false);
+                } else {
+                    // Enable the automation type and update interval combo
+                    // boxes only if the current value of automation is 'enable'
+                    if (settingID.equals(Constants.AUTOMATION_TYPE)
+                            || settingID
+                                    .equals(Constants.UPDATE_INTERVAL_IN_MS)) {
+                        if (!showSettings()) {
+                            // Disable the combo box
+                            CCombo c = (CCombo) combo.getControl();
+                            c.setEnabled(false);
+                        }
+                    }
+                }
+                // Enabling editing support in update interval combo box
+                if (settingID.equals(Constants.UPDATE_INTERVAL_IN_MS)) {
+                    final CCombo c = (CCombo) combo.getControl();
+                    c.addVerifyListener(new VerifyListener() {
+                        @Override
+                        public void verifyText(VerifyEvent e) {
+                            String text = c.getText();
+                            String newText = text.substring(0, e.start)
+                                    + e.text + text.substring(e.end);
+                            try {
+                                if (newText.length() != 0) {
+                                    Integer.parseInt(newText);
+                                }
+                            } catch (NumberFormatException ex) {
+                                e.doit = false;
+                            }
+                        }
+                    });
+                    c.addTraverseListener(new TraverseListener() {
+                        @Override
+                        public void keyTraversed(TraverseEvent e) {
+                            if (e.detail == SWT.TRAVERSE_RETURN) {
+                                e.doit = false;
+                                e.detail = SWT.TRAVERSE_NONE;
+                                String newText = c.getText();
+                                try {
+                                    Integer.parseInt(newText);
+                                    if (null != currentSettingInSelection
+                                            && currentSettingInSelection
+                                                    .getSettingID()
+                                                    .equals(Constants.UPDATE_INTERVAL_IN_MS)) {
+                                        currentSettingInSelection
+                                                .addAllowedValue(newText);
+                                    }
+                                    c.add(newText);
+                                    c.setSelection(new Point(0, newText
+                                            .length()));
+                                    currentSettingInSelection
+                                            .setSettingValue(newText);
+                                } catch (NumberFormatException ex) {
+                                }
+                            }
+                        }
+                    });
+                }
+            }
+
+            return combo;
+        }
+
+        @Override
+        protected Object getValue(Object element) {
+            // This method returns the index of the item selected in the combo
+            // box
+            int index;
+            AutomationSettingHelper setting = (AutomationSettingHelper) element;
+            List<String> itemList = setting.getAllowedValues();
+            String currentValue = setting.getSettingValue();
+            index = itemList.indexOf(currentValue);
+            return index;
+        }
+
+        @Override
+        protected void setValue(Object element, Object value) {
+            AutomationSettingHelper setting = (AutomationSettingHelper) element;
+            int index = (Integer) value;
+            List<String> valueList = setting.getAllowedValues();
+            if (null != valueList) {
+                String targetValue;
+                if (index != -1) {
+                    targetValue = valueList.get(index);
+                    setting.setSettingValue(targetValue);
+
+                    if (setting.getSettingID().equals(Constants.AUTOMATION)) {
+
+                        if (attributeInSelection.isAutomationInProgress()) {
+                            // settingsVisibility = false;
+                            setVisibilityForManualValueChange(false);
+                        } else {
+                            if (targetValue.equals(Constants.ENABLE)) {
+                                // settingsVisibility = true;
+                                setVisibilityForManualValueChange(false);
+                            } else {
+                                // settingsVisibility = false;
+                                setVisibilityForManualValueChange(true);
+                            }
+                        }
+
+                        // If status is changed, then enable the submit and
+                        // clear buttons
+                        if (!targetValue.equals(Utility
+                                .getAutomationString(attributeInSelection
+                                        .isAutomationInProgress()))) {
+                            setSettingSubmitVisibility(true);
+                        } else {
+                            setSettingSubmitVisibility(false);
+                        }
+                    }
+                }
+            }
+            viewer.refresh();
+        }
+    }
+
+    private boolean showSettings() {
+        boolean show = false;
+        if (!attributeInSelection.isAutomationInProgress()) {
+            AutomationSettingHelper setting;
+            Iterator<AutomationSettingHelper> list = localSettingList
+                    .iterator();
+            while (list.hasNext()) {
+                setting = list.next();
+                if (setting.getSettingID().equals(Constants.AUTOMATION)) {
+                    if (setting.getSettingValue().equals(Constants.ENABLE)) {
+                        show = true;
+                    }
+                    break;
+                }
+            }
+        }
+        return show;
+    }
+
+    // Disable the appropriate controls which are used for manual value change
+    private void setVisibilityForManualValueChange(boolean visibility) {
+        if (null != valueCmb && !valueCmb.isDisposed()) {
+            valueCmb.setEnabled(visibility);
+        }
+        if (null != newValueLbl && !newValueLbl.isDisposed()) {
+            newValueLbl.setEnabled(visibility);
+        }
+    }
+
+    @Override
+    public void dispose() {
+        // Unregister the selection listener
+        if (null != resourceSelectionChangedListener) {
+            resourceManager
+                    .removeResourceSelectionChangedUIListener(resourceSelectionChangedListener);
+        }
+
+        // Unregister the model change listener
+        if (null != resourceModelChangedUIListener) {
+            resourceManager
+                    .removeResourceModelChangedUIListener(resourceModelChangedUIListener);
+        }
+
+        // Unregister the automation complete listener
+        if (null != automationUIListener) {
+            resourceManager.removeAutomationUIListener(automationUIListener);
+        }
+
+        super.dispose();
+    }
+
+    @Override
+    public void setFocus() {
+
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/LogDetailsDialog.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/LogDetailsDialog.java
new file mode 100644 (file)
index 0000000..c5d4e49
--- /dev/null
@@ -0,0 +1,123 @@
+package oic.simulator.serviceprovider.view;
+
+import java.text.DateFormat;
+import java.util.Date;
+
+import org.eclipse.jface.dialogs.Dialog;
+import org.eclipse.jface.dialogs.IDialogConstants;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.layout.RowData;
+import org.eclipse.swt.layout.RowLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.swt.widgets.Text;
+
+public class LogDetailsDialog extends Dialog {
+    private final String severity;
+    private final Date   date;
+    private final String message;
+    private final Image  severityIcon;
+
+    public LogDetailsDialog(Shell parentShell, String severity,
+            Image severityIcon, Date date, String message) {
+        super(parentShell);
+        this.severity = severity;
+        this.severityIcon = severityIcon;
+        this.message = message;
+        this.date = date;
+    }
+
+    @Override
+    protected boolean isResizable() {
+        return true;
+    }
+
+    @Override
+    protected void configureShell(Shell shell) {
+        super.configureShell(shell);
+    }
+
+    @Override
+    protected Control createDialogArea(Composite parent) {
+        getShell().setText("Logged event details");
+
+        Composite container = (Composite) super.createDialogArea(parent);
+
+        GridData layoutData = new GridData(SWT.FILL, SWT.FILL, true, true);
+        container.setLayoutData(layoutData);
+        container.setLayout(new GridLayout(2, false));
+
+        GridData gd;
+
+        Label l1 = new Label(container, SWT.NONE);
+        l1.setText("Severity:");
+        gd = new GridData();
+        gd.widthHint = 100;
+        l1.setLayoutData(gd);
+
+        Composite y = new Composite(container, SWT.NONE);
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        y.setLayoutData(gd);
+        y.setLayout(new RowLayout(SWT.HORIZONTAL));
+
+        Label l2 = new Label(y, SWT.NONE);
+        l2.setImage(severityIcon);
+        l2.setLayoutData(new RowData());
+        Label l3 = new Label(y, SWT.NONE);
+        l3.setText(severity);
+        l3.setLayoutData(new RowData());
+
+        Label l4 = new Label(container, SWT.NONE);
+        l4.setText("Date:");
+        gd = new GridData();
+        gd.widthHint = 100;
+        l4.setLayoutData(gd);
+
+        Label l5 = new Label(container, SWT.NONE);
+        DateFormat dateFormat = DateFormat.getDateTimeInstance(
+                DateFormat.SHORT, DateFormat.SHORT);
+        l5.setText(dateFormat.format(date));
+        gd = new GridData();
+        gd.grabExcessHorizontalSpace = true;
+        l5.setLayoutData(gd);
+
+        new Label(container, SWT.NONE); // separator
+
+        Label l6 = new Label(container, SWT.NONE);
+        l6.setText("Message details");
+        gd = new GridData();
+        gd.horizontalSpan = 2;
+        l6.setLayoutData(gd);
+
+        Text text = new Text(container, SWT.MULTI | SWT.READ_ONLY
+                | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
+        if (message != null) {
+            text.setText(message);
+        } else {
+            text.setText("No description available");
+        }
+        gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        gd.horizontalSpan = 2;
+        gd.heightHint = 350;
+        gd.widthHint = 500;
+        text.setLayoutData(gd);
+
+        return container;
+    }
+
+    @Override
+    protected Button createButton(Composite parent, int id, String label,
+            boolean defaultButton) {
+        if (id == IDialogConstants.CANCEL_ID) {
+            return null;
+        }
+        return super.createButton(parent, id, label, defaultButton);
+    }
+}
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/LogView.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/LogView.java
new file mode 100644 (file)
index 0000000..99af2ee
--- /dev/null
@@ -0,0 +1,702 @@
+package oic.simulator.serviceprovider.view;
+
+import java.io.BufferedWriter;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+import java.util.HashMap;
+import java.util.List;
+
+import oic.simulator.logger.LogContentProvider;
+import oic.simulator.logger.LogEntry;
+import oic.simulator.logger.LogLabelProvider;
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.listener.ILogUIListener;
+import oic.simulator.serviceprovider.manager.LogManager;
+import oic.simulator.serviceprovider.utils.Constants;
+import oic.simulator.serviceprovider.view.dialogs.FilterDialog;
+
+import org.eclipse.jface.action.Action;
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.action.IContributionItem;
+import org.eclipse.jface.action.IMenuManager;
+import org.eclipse.jface.action.IToolBarManager;
+import org.eclipse.jface.action.MenuManager;
+import org.eclipse.jface.action.Separator;
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.jface.viewers.DoubleClickEvent;
+import org.eclipse.jface.viewers.IDoubleClickListener;
+import org.eclipse.jface.viewers.ISelectionChangedListener;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.SelectionChangedEvent;
+import org.eclipse.jface.viewers.StructuredSelection;
+import org.eclipse.jface.viewers.TreeViewer;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.jface.viewers.ViewerComparator;
+import org.eclipse.jface.window.Window;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.KeyEvent;
+import org.eclipse.swt.events.KeyListener;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.FileDialog;
+import org.eclipse.swt.widgets.Text;
+import org.eclipse.swt.widgets.Tree;
+import org.eclipse.swt.widgets.TreeColumn;
+import org.eclipse.swt.widgets.TreeItem;
+import org.eclipse.ui.IActionBars;
+import org.eclipse.ui.IWorkbenchActionConstants;
+import org.eclipse.ui.IWorkbenchPage;
+import org.eclipse.ui.dialogs.FilteredTree;
+import org.eclipse.ui.dialogs.PatternFilter;
+import org.eclipse.ui.part.ViewPart;
+import org.oic.simulator.ILogger.Level;
+
+public class LogView extends ViewPart {
+
+    public static final String        VIEW_ID              = "oic.simulator.serviceprovider.view.log";
+
+    private LogManager                logManager;
+    private ILogUIListener            logListener;
+
+    private LogContentProvider        treeContentProvider;
+
+    private FilteredTree              tree;
+    private TreeColumn                severityColumn;
+    private TreeColumn                dateColumn;
+    private TreeColumn                messageColumn;
+
+    private IAction                   exportLogAction;
+    private IAction                   clearLogAction;
+    private IAction                   deleteLogAction;
+    private IAction                   scrollLockAction;
+    private IAction                   logDetailsAction;
+    private IAction                   filterAction;
+    private IAction                   activateViewAction;
+    private IAction                   showTextFilter;
+    private IContributionItem         groupByAction;
+
+    private HashMap<Integer, Boolean> shownSeverities      = new HashMap<Integer, Boolean>();
+
+    private boolean                   activateOnChange     = false;
+
+    private boolean                   hideTextFilter       = false;
+
+    private boolean                   scrollLockDisabled;
+
+    public static final int           ORDER_BY_TIME        = 0;
+    public static final int           ORDER_BY_SEVERITY    = 1;
+    public static final int           ORDER_BY_MESSAGE     = 2;
+
+    int                               sortCandidate        = ORDER_BY_TIME;
+
+    SortAction                        sortByTimeAction     = new SortAction(
+                                                                   "Order by Time",
+                                                                   ORDER_BY_TIME);
+    SortAction                        sortBySeverityAction = new SortAction(
+                                                                   "Order by Severity",
+                                                                   ORDER_BY_SEVERITY);
+    SortAction                        sortByMessageAction  = new SortAction(
+                                                                   "Order by Message",
+                                                                   ORDER_BY_MESSAGE);
+
+    private ViewerComparator          dateComparator;
+    private ViewerComparator          severityComparator;
+    private ViewerComparator          messageComparator;
+
+    private TreeColumn                sortColumn           = null;
+    private static int                DOWN                 = 1;
+    private static int                UP                   = -1;
+    private int                       sortDirection        = DOWN;
+
+    public LogView() {
+
+        logListener = new ILogUIListener() {
+
+            @Override
+            public void logChanged(final List<LogEntry> entry) {
+                Display.getDefault().asyncExec(new Runnable() {
+
+                    @Override
+                    public void run() {
+                        TreeViewer viewer = tree.getViewer();
+                        if (viewer.getControl().isDisposed()) {
+                            return;
+                        }
+                        viewer.setInput(entry);
+                        updateTree(false);
+                    }
+                });
+            }
+
+            @Override
+            public void logAdded(final LogEntry added) {
+                Display.getDefault().asyncExec(new Runnable() {
+
+                    @Override
+                    public void run() {
+                        TreeViewer viewer = tree.getViewer();
+                        if (viewer.getControl().isDisposed()) {
+                            return;
+                        }
+                        LogContentProvider provider = (LogContentProvider) viewer
+                                .getContentProvider();
+                        provider.addLog(added);
+                        tree.getViewer().add(viewer.getInput(), added);
+                        @SuppressWarnings("unchecked")
+                        List<LogEntry> input = (List<LogEntry>) viewer
+                                .getInput();
+                        if (input.size() > Constants.LOG_SIZE) {
+                            viewer.remove(viewer.getInput(), 0);
+                        }
+                        updateTree(true);
+                    }
+                });
+            }
+
+            private void updateTree(boolean needscroll) {
+                if (activateOnChange) {
+                    IWorkbenchPage page = Activator.getDefault().getWorkbench()
+                            .getActiveWorkbenchWindow().getActivePage();
+                    if (page != null) {
+                        page.bringToTop(LogView.this);
+                    }
+                }
+                if (scrollLockDisabled && needscroll) {
+                    Tree tree2 = tree.getViewer().getTree();
+                    if (tree2.getItemCount() > 0) {
+                        TreeItem item = tree2.getItem(tree2.getItemCount() - 1);
+                        tree2.setTopItem(item);
+                        deleteLogAction.setEnabled(true);
+                    }
+                }
+            }
+        };
+
+        logManager = Activator.getDefault().getLogManager();
+
+        // Initially state of scroll lock
+        scrollLockDisabled = true;
+    }
+
+    @Override
+    public void createPartControl(Composite parent) {
+        PatternFilter filter = new PatternFilter() {
+
+            DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss.SSS");
+
+            @Override
+            protected boolean isLeafMatch(Viewer viewer, Object element) {
+                if (element instanceof LogEntry) {
+                    LogEntry logEntry = (LogEntry) element;
+                    String severity = LogManager.getSeverityName(logEntry
+                            .getSeverity());
+                    String date = dateFormat.format(logEntry.getDate());
+                    String message = logEntry.getMessage();
+                    return wordMatches(severity) || wordMatches(date)
+                            || wordMatches(message);
+                }
+                return false;
+            }
+        };
+        filter.setIncludeLeadingWildcard(true);
+        tree = new FilteredTree(parent, SWT.SINGLE | SWT.H_SCROLL
+                | SWT.V_SCROLL | SWT.FULL_SELECTION, filter, true);
+
+        setupFilteredTree();
+
+        createColumnComparators();
+
+        createActions();
+
+        setDefaultShownSeverities();
+
+        IActionBars actionBars = getViewSite().getActionBars();
+        IToolBarManager toolBarManager = actionBars.getToolBarManager();
+        toolBarManager.add(exportLogAction);
+        toolBarManager.add(clearLogAction);
+        toolBarManager.add(deleteLogAction);
+        toolBarManager.add(scrollLockAction);
+        toolBarManager
+                .add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
+
+        IMenuManager mgr = actionBars.getMenuManager();
+        mgr.add(groupByAction);
+        mgr.add(new Separator());
+        mgr.add(filterAction);
+        mgr.add(new Separator());
+        mgr.add(activateViewAction);
+        mgr.add(showTextFilter);
+
+        addManagerListeners();
+
+        if (sortCandidate == ORDER_BY_TIME) {
+            sortByTimeAction.run();
+        } else if (sortCandidate == ORDER_BY_SEVERITY) {
+            sortBySeverityAction.run();
+        } else { // order_selected == ORDER_BY_NONE
+            sortByMessageAction.run();
+        }
+
+    }
+
+    private void setupFilteredTree() {
+        tree.setLayoutData(new GridData(GridData.FILL_BOTH));
+        final Tree innerTree = tree.getViewer().getTree();
+        innerTree.setLinesVisible(true);
+
+        severityColumn = new TreeColumn(innerTree, SWT.LEFT);
+        severityColumn.setText("Severity");
+        severityColumn.setWidth(110);
+        severityColumn.addSelectionListener(new SelectionAdapter() {
+
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                sortBySeverityAction.run();
+            }
+        });
+        dateColumn = new TreeColumn(innerTree, SWT.LEFT);
+        dateColumn.setText("Time");
+        dateColumn.setWidth(110);
+        dateColumn.addSelectionListener(new SelectionAdapter() {
+
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                sortByTimeAction.run();
+            }
+        });
+        messageColumn = new TreeColumn(innerTree, SWT.LEFT);
+        messageColumn.setText("Message");
+        messageColumn.setWidth(180);
+        messageColumn.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                sortByMessageAction.run();
+            }
+        });
+
+        innerTree.setHeaderVisible(true);
+
+        treeContentProvider = new LogContentProvider();
+
+        tree.getViewer().setContentProvider(treeContentProvider);
+        tree.getViewer().setLabelProvider(new LogLabelProvider());
+
+        tree.getViewer().setInput(logManager.getLogEntries());
+
+        tree.getViewer().addSelectionChangedListener(
+                new ISelectionChangedListener() {
+
+                    @Override
+                    public void selectionChanged(SelectionChangedEvent event) {
+                        deleteLogAction.setEnabled(!tree.getViewer()
+                                .getSelection().isEmpty());
+                        logDetailsAction.setEnabled(!tree.getViewer()
+                                .getSelection().isEmpty());
+                    }
+                });
+
+        tree.getViewer().getTree().addKeyListener(new KeyListener() {
+
+            @Override
+            public void keyReleased(KeyEvent e) {
+            }
+
+            @Override
+            public void keyPressed(KeyEvent e) {
+                if (e.character == (char) 127) { // If delete key is pressed
+                    if (deleteLogAction.isEnabled()) {
+                        deleteLogAction.run();
+                    }
+                }
+            }
+        });
+
+        tree.getViewer().addDoubleClickListener(new IDoubleClickListener() {
+
+            @Override
+            public void doubleClick(DoubleClickEvent event) {
+                logDetailsAction.run();
+            }
+        });
+    }
+
+    private void createColumnComparators() {
+        dateComparator = new ViewerComparator() {
+
+            @Override
+            public int compare(Viewer viewer, Object e1, Object e2) {
+                LogEntry l1 = (LogEntry) e1;
+                LogEntry l2 = (LogEntry) e2;
+                return l1.getDate().compareTo(l2.getDate()) * sortDirection;
+            }
+        };
+
+        severityComparator = new ViewerComparator() {
+
+            @Override
+            public int compare(Viewer viewer, Object e1, Object e2) {
+                LogEntry l1 = (LogEntry) e1;
+                LogEntry l2 = (LogEntry) e2;
+                if (l1.getSeverity() < l2.getSeverity()) {
+                    return -1 * sortDirection;
+                }
+                if (l1.getSeverity() > l2.getSeverity()) {
+                    return 1 * sortDirection;
+                }
+                return 0;
+            }
+        };
+
+        messageComparator = new ViewerComparator() {
+
+            @Override
+            public int compare(Viewer viewer, Object e1, Object e2) {
+                LogEntry l1 = (LogEntry) e1;
+                LogEntry l2 = (LogEntry) e2;
+                return l1.getMessage().compareTo(l2.getMessage())
+                        * sortDirection;
+            }
+        };
+
+    }
+
+    private void setDefaultShownSeverities() {
+        shownSeverities.put(Level.INFO.ordinal(), true);
+        shownSeverities.put(Level.DEBUG.ordinal(), true);
+        shownSeverities.put(Level.WARNING.ordinal(), true);
+        shownSeverities.put(Level.ERROR.ordinal(), true);
+    }
+
+    private void addManagerListeners() {
+        logManager.addLogListener(logListener);
+        logManager.applyFilter(shownSeverities);
+    }
+
+    private void createActions() {
+        exportLogAction = createExportLogAction();
+        clearLogAction = createClearLogAction();
+        deleteLogAction = createDeleteLogAction();
+        scrollLockAction = createScrollLockAction();
+        logDetailsAction = createLogDetailsAction();
+
+        filterAction = createFilterAction();
+        activateViewAction = createActivateViewAction();
+        showTextFilter = createShowTextFilter();
+        groupByAction = createGroupByAction();
+    }
+
+    private IAction createExportLogAction() {
+        Action action = new Action("Export log") {
+            @Override
+            public void run() {
+                FileDialog fd = new FileDialog(Display.getDefault()
+                        .getActiveShell(), SWT.SAVE);
+                fd.setOverwrite(true);
+                fd.setFileName("OIC_Simulator_ServerLog.log");
+                fd.setFilterExtensions(Constants.SAVE_LOG_FILTER_EXTENSIONS);
+                String name = fd.open();
+                List<LogEntry> logEntries = logManager.getLogEntries();
+                StringBuilder sb = new StringBuilder();
+                for (LogEntry entry : logEntries) {
+                    sb.append(entry.toString());
+                }
+                String data = sb.toString();
+                BufferedWriter out = null;
+                try {
+                    out = new BufferedWriter(new FileWriter(name));
+                    out.write(data);
+                } catch (IOException e) {
+                    e.printStackTrace();
+                    MessageDialog.openError(
+                            Display.getDefault().getActiveShell(),
+                            "Export error",
+                            "Could not export log. IO exception: "
+                                    + e.getMessage());
+                } finally {
+                    try {
+                        out.close();
+                    } catch (IOException e) {
+                        // Error occurred during close. Ignoring
+                    }
+                }
+            }
+        };
+        action.setToolTipText("Export log");
+
+        action.setImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/export_log_e.gif"));
+        action.setDisabledImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/export_log_d.gif"));
+        action.setEnabled(true);
+
+        return action;
+    }
+
+    private IAction createClearLogAction() {
+        Action action = new Action("Clear log") {
+
+            @Override
+            public void run() {
+                logManager.clearLog();
+            }
+        };
+        action.setToolTipText("Clear log");
+
+        action.setImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/clear_e.gif"));
+        action.setDisabledImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/clear_d.gif"));
+        action.setEnabled(true);
+        return action;
+    }
+
+    private IAction createDeleteLogAction() {
+        Action action = new Action("Delete log entry") {
+
+            @Override
+            @SuppressWarnings("unchecked")
+            public void run() {
+                IStructuredSelection selection = (IStructuredSelection) tree
+                        .getViewer().getSelection();
+                List<LogEntry> entries = (List<LogEntry>) tree.getViewer()
+                        .getInput();
+                LogEntry selectedEntry = (LogEntry) selection.getFirstElement();
+                if (null != selectedEntry) {
+                    LogEntry toBeShownEntry = null;
+                    for (LogEntry entry : entries) {
+                        if (entry.equals(selectedEntry)) {
+                            int size = entries.size();
+                            int index = entries.indexOf(selectedEntry);
+                            if (index + 1 < size) {
+                                toBeShownEntry = entries.get(index + 1);
+                            } else if (index > 0) {
+                                toBeShownEntry = entries.get(index - 1);
+                            }
+                            break;
+                        }
+                    }
+                    logManager.removeEntry(selectedEntry);
+                    if (null != toBeShownEntry) {
+                        tree.getViewer().setSelection(
+                                new StructuredSelection(toBeShownEntry));
+                    }
+                }
+            }
+        };
+        action.setToolTipText("Delete log entry");
+        action.setImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/delete_e.gif"));
+        action.setDisabledImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/delete_d.gif"));
+        action.setEnabled(false);
+        return action;
+    }
+
+    private IAction createScrollLockAction() {
+        Action action = new Action("Scroll lock") {
+
+            @Override
+            public void run() {
+                scrollLockDisabled = !this.isChecked();
+            };
+
+            @Override
+            public int getStyle() {
+                return IAction.AS_CHECK_BOX;
+            }
+        };
+        action.setToolTipText("Scroll lock");
+        action.setImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/lock_e.gif"));
+        action.setDisabledImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/lock_d.gif"));
+        action.setEnabled(true);
+        return action;
+    }
+
+    private IAction createLogDetailsAction() {
+        Action action = new Action("Details...") {
+
+            @Override
+            public void run() {
+                Display.getDefault().asyncExec(new Runnable() {
+
+                    @Override
+                    public void run() {
+                        LogEntry x = (LogEntry) ((IStructuredSelection) tree
+                                .getViewer().getSelection()).getFirstElement();
+
+                        new LogDetailsDialog(Display.getDefault()
+                                .getActiveShell(), LogManager.getSeverityName(x
+                                .getSeverity()), LogManager.getSeverityIcon(x
+                                .getSeverity()), x.getDate(), x.getMessage())
+                                .open();
+                    }
+                });
+            }
+        };
+        action.setToolTipText("Details...");
+        action.setImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/log_details_e.gif"));
+        action.setDisabledImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/log_details_e.gif"));
+        action.setEnabled(false);
+        return action;
+    }
+
+    private IAction createFilterAction() {
+        Action action = new Action("Filters ...") {
+
+            @Override
+            public void run() {
+                FilterDialog fd = new FilterDialog(Display.getDefault()
+                        .getActiveShell(), shownSeverities);
+                if (fd.open() == Window.OK) {
+                    logManager.applyFilter(shownSeverities);
+                }
+                tree.getViewer().refresh();
+            }
+        };
+        action.setToolTipText("Filters ...");
+
+        action.setImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/filter_e.gif"));
+        action.setDisabledImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/filter_d.gif"));
+        action.setEnabled(true);
+        return action;
+    }
+
+    private IAction createActivateViewAction() {
+        Action action = new Action("Activate view on new events",
+                IAction.AS_CHECK_BOX) {
+
+            @Override
+            public void run() {
+                activateOnChange = this.isChecked();
+            }
+        };
+        action.setChecked(activateOnChange);
+        action.setToolTipText("Activate view on new events");
+
+        action.setImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/prop_e.gif"));
+        action.setDisabledImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/prop_d.gif"));
+        action.setEnabled(true);
+        return action;
+    }
+
+    private IAction createShowTextFilter() {
+        Action action = new Action("Show text filter", IAction.AS_CHECK_BOX) {
+
+            @Override
+            public void run() {
+                Text filterControl = tree.getFilterControl();
+                Composite filterComposite = filterControl.getParent();
+                GridData gd = (GridData) filterComposite.getLayoutData();
+                boolean visible = isChecked();
+                gd.exclude = !visible;
+                filterComposite.setVisible(visible);
+                filterControl.setText("");
+                if (visible) {
+                    filterControl.selectAll();
+                    setFocus();
+                }
+                tree.layout(false);
+                hideTextFilter = !visible;
+            }
+        };
+        action.setToolTipText("Show text filter");
+
+        action.setImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/tree_mode_e.gif"));
+        action.setDisabledImageDescriptor(ImageDescriptor.createFromFile(
+                this.getClass(), "/icons/tree_mode_d.gif"));
+        action.setEnabled(true);
+        action.setChecked(!hideTextFilter);
+        if (hideTextFilter) {
+            action.run();
+        }
+        return action;
+    }
+
+    private IContributionItem createGroupByAction() {
+        IMenuManager manager = new MenuManager("Order by");
+        manager.add(sortByTimeAction);
+        manager.add(sortBySeverityAction);
+        manager.add(sortByMessageAction);
+        return manager;
+    }
+
+    class SortAction extends Action {
+
+        private final int sortBy;
+
+        public SortAction(String text, int sortBy) {
+            super(text, IAction.AS_RADIO_BUTTON);
+            this.sortBy = sortBy;
+
+            if (sortCandidate == sortBy) {
+                setChecked(true);
+            }
+        }
+
+        @Override
+        public void run() {
+            sortBySeverityAction.setChecked(false);
+            sortByTimeAction.setChecked(false);
+            sortCandidate = sortBy;
+            setChecked(true);
+
+            ViewerComparator comparator;
+            TreeColumn column;
+            if (sortBy == ORDER_BY_SEVERITY) {
+                comparator = severityComparator;
+                column = severityColumn;
+            } else if (sortBy == ORDER_BY_TIME) {
+                comparator = dateComparator;
+                column = dateColumn;
+            } else { // Order by message
+                comparator = messageComparator;
+                column = messageColumn;
+            }
+            TreeViewer viewer = tree.getViewer();
+            viewer.setComparator(comparator);
+            viewer.getTree().setSortColumn(column);
+            if (column.equals(sortColumn)) { // reverse sorting order
+                sortDirection = viewer.getTree().getSortDirection() == SWT.UP ? DOWN
+                        : UP;
+                viewer.getTree().setSortDirection(
+                        sortDirection == UP ? SWT.UP : SWT.DOWN);
+                viewer.refresh();
+            } else { // set this column as the one to sort by
+                sortDirection = DOWN;
+                viewer.getTree().setSortDirection(SWT.DOWN);
+            }
+            sortColumn = column;
+            refresh();
+        }
+    }
+
+    private void refresh() {
+        tree.getViewer().refresh();
+    }
+
+    @Override
+    public void setFocus() {
+        tree.setFocus();
+    }
+
+    @Override
+    public void dispose() {
+        logManager.removeLogListener(logListener);
+        super.dispose();
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/MetaPropertiesView.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/MetaPropertiesView.java
new file mode 100644 (file)
index 0000000..936d17d
--- /dev/null
@@ -0,0 +1,185 @@
+package oic.simulator.serviceprovider.view;
+
+import java.util.List;
+
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.listener.IResourceSelectionChangedUIListener;
+import oic.simulator.serviceprovider.manager.ResourceManager;
+import oic.simulator.serviceprovider.resource.MetaProperty;
+import oic.simulator.serviceprovider.resource.SimulatorResource;
+
+import org.eclipse.jface.viewers.ColumnLabelProvider;
+import org.eclipse.jface.viewers.IStructuredContentProvider;
+import org.eclipse.jface.viewers.TableViewer;
+import org.eclipse.jface.viewers.TableViewerColumn;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Table;
+import org.eclipse.ui.part.ViewPart;
+
+public class MetaPropertiesView extends ViewPart {
+
+    public static final String                  VIEW_ID       = "oic.simulator.serviceprovider.view.metaproperties";
+
+    private TableViewer                         tableViewer;
+
+    private final String[]                      columnHeaders = { "Property",
+            "Value"                                          };
+
+    private final Integer[]                     columnWidth   = { 150, 150 };
+
+    private IResourceSelectionChangedUIListener resourceSelectionChangedListener;
+
+    private ResourceManager                     resourceManager;
+
+    public MetaPropertiesView() {
+
+        resourceManager = Activator.getDefault().getResourceManager();
+
+        resourceSelectionChangedListener = new IResourceSelectionChangedUIListener() {
+
+            @Override
+            public void onResourceSelectionChange() {
+                Display.getDefault().asyncExec(new Runnable() {
+
+                    @Override
+                    public void run() {
+                        if (null != tableViewer) {
+                            updateViewer(checkSelection());
+                        }
+                    }
+                });
+            }
+        };
+    }
+
+    @Override
+    public void createPartControl(Composite parent) {
+        parent.setLayout(new GridLayout(1, false));
+
+        tableViewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL
+                | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER);
+
+        createColumns(tableViewer);
+
+        // make lines and header visible
+        final Table table = tableViewer.getTable();
+        table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+        table.setHeaderVisible(true);
+        table.setLinesVisible(true);
+
+        tableViewer.setContentProvider(new PropertycontentProvider());
+
+        addManagerListeners();
+
+        // Check whether there is any resource selected already
+        List<MetaProperty> propertyList = checkSelection();
+        if (null != propertyList) {
+            updateViewer(propertyList);
+        }
+
+    }
+
+    private List<MetaProperty> checkSelection() {
+        SimulatorResource resourceInSelection = resourceManager
+                .getCurrentResourceInSelection();
+        if (null != resourceInSelection) {
+            List<MetaProperty> metaPropertyList = resourceManager
+                    .getMetaProperties(resourceInSelection);
+            return metaPropertyList;
+        } else {
+            return null;
+        }
+    }
+
+    private void updateViewer(List<MetaProperty> metaPropertyList) {
+        if (null != tableViewer) {
+            Table tbl = tableViewer.getTable();
+            if (null != metaPropertyList) {
+                tableViewer.setInput(metaPropertyList.toArray());
+                if (!tbl.isDisposed()) {
+                    tbl.setLinesVisible(true);
+                }
+            } else {
+                if (!tbl.isDisposed()) {
+                    tbl.removeAll();
+                    tbl.setLinesVisible(false);
+                }
+            }
+        }
+    }
+
+    public void createColumns(TableViewer tableViewer) {
+        TableViewerColumn propName = new TableViewerColumn(tableViewer,
+                SWT.NONE);
+        propName.getColumn().setWidth(columnWidth[0]);
+        propName.getColumn().setText(columnHeaders[0]);
+        propName.setLabelProvider(new ColumnLabelProvider() {
+            @Override
+            public String getText(Object element) {
+                MetaProperty prop = (MetaProperty) element;
+                if (null != prop) {
+                    return prop.getPropName();
+                } else {
+                    return "";
+                }
+            }
+        });
+
+        TableViewerColumn propValue = new TableViewerColumn(tableViewer,
+                SWT.NONE);
+        propValue.getColumn().setWidth(columnWidth[1]);
+        propValue.getColumn().setText(columnHeaders[1]);
+        propValue.setLabelProvider(new ColumnLabelProvider() {
+            @Override
+            public String getText(Object element) {
+                MetaProperty prop = (MetaProperty) element;
+                if (null != prop) {
+                    return prop.getPropValue();
+                } else {
+                    return "";
+                }
+            }
+        });
+    }
+
+    private void addManagerListeners() {
+        resourceManager
+                .addResourceSelectionChangedUIListener(resourceSelectionChangedListener);
+    }
+
+    class PropertycontentProvider implements IStructuredContentProvider {
+
+        @Override
+        public void dispose() {
+        }
+
+        @Override
+        public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
+        }
+
+        @Override
+        public Object[] getElements(Object element) {
+            return (Object[]) element;
+        }
+
+    }
+
+    @Override
+    public void dispose() {
+        // Unregister the listener
+        if (null != resourceSelectionChangedListener) {
+            resourceManager
+                    .removeResourceSelectionChangedUIListener(resourceSelectionChangedListener);
+        }
+        super.dispose();
+    }
+
+    @Override
+    public void setFocus() {
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/MultiResourceOrchestrationView.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/MultiResourceOrchestrationView.java
new file mode 100644 (file)
index 0000000..99659a4
--- /dev/null
@@ -0,0 +1,19 @@
+package oic.simulator.serviceprovider.view;
+
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.ui.part.ViewPart;
+
+public class MultiResourceOrchestrationView extends ViewPart {
+
+    public static final String VIEW_ID = "oic.simulator.serviceprovider.view.orchestration";
+
+    @Override
+    public void createPartControl(Composite arg0) {
+        // TODO: To be done
+    }
+
+    @Override
+    public void setFocus() {
+        // TODO To be done
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/ResourceManagerView.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/ResourceManagerView.java
new file mode 100644 (file)
index 0000000..b620623
--- /dev/null
@@ -0,0 +1,430 @@
+package oic.simulator.serviceprovider.view;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.listener.IResourceListChangedUIListener;
+import oic.simulator.serviceprovider.manager.ResourceManager;
+import oic.simulator.serviceprovider.utils.Constants;
+import oic.simulator.serviceprovider.utils.Utility;
+import oic.simulator.serviceprovider.view.dialogs.CreateResourceWizard;
+import oic.simulator.serviceprovider.view.dialogs.DeleteCategory;
+import oic.simulator.serviceprovider.view.dialogs.DeleteResourceWizard;
+import oic.simulator.serviceprovider.view.dialogs.ResourceWizardDialog;
+
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.viewers.ITreeContentProvider;
+import org.eclipse.jface.viewers.LabelProvider;
+import org.eclipse.jface.viewers.TreeViewer;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.jface.wizard.WizardDialog;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.MenuAdapter;
+import org.eclipse.swt.events.MenuEvent;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.graphics.Color;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Group;
+import org.eclipse.swt.widgets.Menu;
+import org.eclipse.swt.widgets.MenuItem;
+import org.eclipse.swt.widgets.Tree;
+import org.eclipse.swt.widgets.TreeItem;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.dialogs.FilteredTree;
+import org.eclipse.ui.dialogs.PatternFilter;
+import org.eclipse.ui.part.ViewPart;
+
+public class ResourceManagerView extends ViewPart {
+
+    public static final String             VIEW_ID = "oic.simulator.serviceprovider.view.resourcemanager";
+
+    private Button                         createButton;
+    private Button                         deleteButton;
+
+    private TreeViewer                     treeViewer;
+
+    private IResourceListChangedUIListener resourceListChangedListener;
+
+    private ResourceManager                resourceManager;
+
+    public ResourceManagerView() {
+
+        resourceManager = Activator.getDefault().getResourceManager();
+
+        resourceListChangedListener = new IResourceListChangedUIListener() {
+
+            @Override
+            public void onResourceCreation() {
+                Display.getDefault().asyncExec(new Runnable() {
+
+                    @Override
+                    public void run() {
+                        if (null != treeViewer) {
+                            treeViewer.refresh();
+                            treeViewer.expandAll();
+                        }
+
+                        // Trigger the visibility of delete button
+                        changeDeleteVisibility();
+                    }
+                });
+            }
+
+            @Override
+            public void onResourceDeletion() {
+                Display.getDefault().asyncExec(new Runnable() {
+
+                    @Override
+                    public void run() {
+                        if (null != treeViewer) {
+                            treeViewer.refresh();
+                            treeViewer.expandAll();
+                        }
+
+                        // Trigger the visibility of delete button
+                        changeDeleteVisibility();
+                    }
+                });
+            }
+        };
+    }
+
+    public void changeDeleteVisibility() {
+        if (null == treeViewer) {
+            return;
+        }
+        boolean visibility;
+        Tree tree = treeViewer.getTree();
+        if (null != tree && !tree.isDisposed() && tree.getItemCount() > 0) {
+            visibility = true;
+        } else {
+            visibility = false;
+        }
+        if (null != deleteButton && !deleteButton.isDisposed()) {
+            deleteButton.setEnabled(visibility);
+        }
+    }
+
+    @Override
+    public void createPartControl(Composite parent) {
+        Composite compContent = new Composite(parent, SWT.NONE);
+        GridLayout baseLayout = new GridLayout(1, false);
+        compContent.setLayout(baseLayout);
+
+        GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        compContent.setLayoutData(gd);
+
+        Composite buttonComp = new Composite(compContent, SWT.NONE);
+        buttonComp.setLayout(new GridLayout(2, false));
+
+        gd = new GridData();
+        gd.horizontalAlignment = SWT.FILL;
+        gd.grabExcessHorizontalSpace = true;
+
+        buttonComp.setLayoutData(gd);
+
+        createButton = new Button(buttonComp, SWT.PUSH);
+        createButton.setText("Create");
+        createButton.setToolTipText("Create Simulator Resource(s)");
+
+        gd = new GridData();
+        gd.widthHint = 90;
+        createButton.setLayoutData(gd);
+
+        deleteButton = new Button(buttonComp, SWT.PUSH);
+        deleteButton.setText("Delete");
+        deleteButton.setToolTipText("Delete Simulator Resource(s)");
+
+        gd = new GridData();
+        gd.widthHint = 90;
+        deleteButton.setLayoutData(gd);
+
+        Group resourceGroup = new Group(compContent, SWT.NONE);
+        resourceGroup.setText("Created Resources");
+
+        Color color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE);
+        resourceGroup.setBackground(color);
+
+        resourceGroup.setLayout(new GridLayout(1, false));
+        gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        resourceGroup.setLayoutData(gd);
+
+        PatternFilter filter = new PatternFilter();
+        FilteredTree filteredTree = new FilteredTree(resourceGroup,
+                SWT.H_SCROLL | SWT.V_SCROLL | SWT.SINGLE, filter, true);
+        treeViewer = filteredTree.getViewer();
+        treeViewer.getTree().setLayoutData(
+                new GridData(SWT.FILL, SWT.FILL, true, true));
+        treeViewer.setContentProvider(new TreeContentProvider());
+        treeViewer.setLabelProvider(new TreeLabelProvider());
+        treeViewer.setInput(new Object());
+
+        addUIListeners();
+
+        addManagerListeners();
+
+        // If there is at least one resource exist, then enable the delete
+        // resource button
+        changeDeleteVisibility();
+    }
+
+    private void addUIListeners() {
+
+        createButton.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {
+
+                    @Override
+                    public void run() {
+                        CreateResourceWizard createWizard = new CreateResourceWizard();
+                        ResourceWizardDialog wizardDialog = new ResourceWizardDialog(
+                                PlatformUI.getWorkbench().getDisplay()
+                                        .getActiveShell(), createWizard);
+                        int open = wizardDialog.open();
+                        if (open == WizardDialog.OK) {
+                            String configFilePath;
+                            int count;
+                            configFilePath = createWizard.getConfigFilePath();
+                            count = createWizard.getResourceCount();
+
+                            if (count <= 1) {
+                                // Single resource creation
+                                resourceManager.createResource(configFilePath);
+                            } else {
+                                // Multi-resource creation
+                                resourceManager.createResource(configFilePath,
+                                        count);
+                            }
+                        }
+                    }
+                });
+            }
+        });
+
+        deleteButton.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {
+
+                    @Override
+                    public void run() {
+                        DeleteResourceWizard deleteWizard = new DeleteResourceWizard();
+                        ResourceWizardDialog wizardDialog = new ResourceWizardDialog(
+                                PlatformUI.getWorkbench().getDisplay()
+                                        .getActiveShell(), deleteWizard);
+                        int open = wizardDialog.open();
+                        if (open == WizardDialog.OK) {
+                            DeleteCategory deleteCategory = deleteWizard
+                                    .getDeleteCategory();
+                            if (deleteCategory == DeleteCategory.BY_URI) {
+                                String uri = deleteWizard.getDeleteCandidate();
+                                boolean completeURI = Utility
+                                        .isUriComplete(uri);
+                                if (!completeURI) {
+                                    uri = Utility.displayNameToUri(uri);
+                                }
+                                resourceManager.deleteResourceByURI(uri);
+                            } else if (deleteCategory == DeleteCategory.BY_TYPE) {
+                                resourceManager
+                                        .deleteResourceByType(deleteWizard
+                                                .getDeleteCandidate());
+                            } else if (deleteCategory == DeleteCategory.ALL) {
+                                resourceManager.deleteAllResources();
+                            }
+                        }
+                    }
+                });
+            }
+        });
+
+        if (null != treeViewer) {
+            final Tree resourceTreeHead = treeViewer.getTree();
+            if (null != resourceTreeHead) {
+                // Below code adds a listener to the tree for selection changes
+                // and notifies the resource manager
+                resourceTreeHead.addSelectionListener(new SelectionAdapter() {
+                    @Override
+                    public void widgetSelected(SelectionEvent e) {
+                        TreeItem selectedItem = (TreeItem) e.item;
+                        if (null != selectedItem) {
+                            String selectedItemText = selectedItem.getText();
+                            if (!isSelectedTreeItemACategory(selectedItemText)) {
+                                selectedItemText = Utility
+                                        .displayNameToUri(selectedItemText);
+                            }
+                            // Propagate this selection change event to manager
+                            resourceManager
+                                    .resourceSelectionChanged(selectedItemText);
+                        }
+                    }
+                });
+                // Below code creates menu entries and shows them on right
+                // clicking a resource
+                final Menu menu = new Menu(resourceTreeHead);
+                resourceTreeHead.setMenu(menu);
+                menu.addMenuListener(new MenuAdapter() {
+                    @Override
+                    public void menuShown(MenuEvent e) {
+                        // Clear existing menu items
+                        MenuItem[] items = menu.getItems();
+                        for (int index = 0; index < items.length; index++) {
+                            items[index].dispose();
+                        }
+                        final String selectedItem = resourceTreeHead
+                                .getSelection()[0].getText();
+                        if (isSelectedTreeItemACategory(selectedItem)) {
+                            return;
+                        }
+                        MenuItem startItem = new MenuItem(menu, SWT.NONE);
+                        startItem.setText(Constants.START_RESOURCE_AUTOMATION);
+                        startItem.addSelectionListener(new SelectionAdapter() {
+                            @Override
+                            public void widgetSelected(SelectionEvent e) {
+                                // Block starting resource level
+                                // automation if any attribute level
+                                // automation is in progress for the
+                                // selected resource
+                                boolean started = resourceManager.isAttributeAutomationStarted(Utility
+                                        .displayNameToUri(selectedItem));
+                                if (started) {
+                                    MessageDialog
+                                            .openInformation(
+                                                    Display.getDefault()
+                                                            .getActiveShell(),
+                                                    "Attribute automation is in progress",
+                                                    "Attribute level automation for this resource is already in progress!!!\nPlease stop all "
+                                                            + "running attribute level automations to start resource level automation.");
+                                } else {
+                                    boolean status = resourceManager
+                                            .startResourceAutomationUIRequest(Utility
+                                                    .displayNameToUri(selectedItem));
+                                    String statusMsg = status ? "Automation started successfully!!!"
+                                            : "Automation request failed!!!";
+                                    MessageDialog.openInformation(Display
+                                            .getDefault().getActiveShell(),
+                                            "Automation Status", statusMsg);
+                                }
+                            }
+                        });
+
+                        MenuItem stopItem = new MenuItem(menu, SWT.NONE);
+                        stopItem.setText(Constants.STOP_RESOURCE_AUTOMATION);
+                        stopItem.addSelectionListener(new SelectionAdapter() {
+                            @Override
+                            public void widgetSelected(SelectionEvent e) {
+                                resourceManager
+                                        .stopResourceAutomationUIRequest(Utility
+                                                .displayNameToUri(selectedItem));
+                                String statusMsg = "Automation stop requested!!!";
+                                MessageDialog.openInformation(Display
+                                        .getDefault().getActiveShell(),
+                                        "Automation Status", statusMsg);
+                            }
+                        });
+
+                        // Set the initial visibility of menu items
+                        boolean status = resourceManager
+                                .isResourceAutomationStarted(Utility
+                                        .displayNameToUri(selectedItem));
+                        startItem.setEnabled(!status);
+                        stopItem.setEnabled(status);
+                    }
+                });
+            }
+        }
+    }
+
+    private boolean isSelectedTreeItemACategory(String selectedItem) {
+        boolean category = false;
+        if (null != selectedItem) {
+            category = resourceManager.isTypeExist(selectedItem);
+        }
+        return category;
+    }
+
+    public void addManagerListeners() {
+        resourceManager
+                .addResourceListChangedUIListener(resourceListChangedListener);
+    }
+
+    @Override
+    public void setFocus() {
+    }
+
+    @Override
+    public void dispose() {
+        // Unregister the listener
+        if (null != resourceListChangedListener) {
+            resourceManager
+                    .removeResourceListChangedUIListener(resourceListChangedListener);
+            resourceManager.resourceSelectionChanged(null);
+        }
+        super.dispose();
+    }
+}
+
+class TreeContentProvider implements ITreeContentProvider {
+
+    @Override
+    public void dispose() {
+    }
+
+    @Override
+    public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
+    }
+
+    @Override
+    public Object[] getChildren(Object parent) {
+        String resType = (String) parent;
+        List<String> members;
+        members = Activator.getDefault().getResourceManager()
+                .getURIListOfResourceType(resType);
+        if (null == members) {
+            members = new ArrayList<String>();
+        }
+        return members.toArray();
+    }
+
+    @Override
+    public Object[] getElements(Object parent) {
+        List<String> deptTypes;
+        deptTypes = Activator.getDefault().getResourceManager()
+                .getResourceTypeList();
+        if (null == deptTypes) {
+            deptTypes = new ArrayList<String>();
+        }
+        return deptTypes.toArray();
+    }
+
+    @Override
+    public Object getParent(Object child) {
+        return null;
+    }
+
+    @Override
+    public boolean hasChildren(Object parent) {
+        String resType = (String) parent;
+        if (Activator.getDefault().getResourceManager().isTypeExist(resType)) {
+            return true;
+        }
+        return false;
+    }
+}
+
+class TreeLabelProvider extends LabelProvider {
+    @Override
+    public String getText(Object element) {
+        String value = (String) element;
+        if (!Activator.getDefault().getResourceManager().isTypeExist(value)) {
+            value = Utility.uriToDisplayName(value);
+        }
+        return value;
+    }
+}
\ 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/CreateResourcePage.java
new file mode 100644 (file)
index 0000000..345c0dd
--- /dev/null
@@ -0,0 +1,297 @@
+package oic.simulator.serviceprovider.view.dialogs;
+
+import oic.simulator.serviceprovider.utils.Constants;
+
+import org.eclipse.jface.wizard.WizardPage;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.CCombo;
+import org.eclipse.swt.events.KeyAdapter;
+import org.eclipse.swt.events.KeyEvent;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Event;
+import org.eclipse.swt.widgets.FileDialog;
+import org.eclipse.swt.widgets.Group;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Listener;
+import org.eclipse.swt.widgets.Text;
+import org.eclipse.ui.PlatformUI;
+
+public class CreateResourcePage extends WizardPage {
+
+    private Button stdResourceRbtn;
+    private CCombo resourceTypeCmb;
+    private Button cusResourceRbtn;
+    private Text   locationTxt;
+    private Button btnBrowse;
+    private Text   noOfInstancesText;
+    private Label  resourceTypeLbl;
+    private Label  noOfInstancesLbl;
+    private Label  locationLbl;
+
+    private String configFilePath = null;
+    private int    resourceCount;
+
+    protected CreateResourcePage() {
+        super("Create Resource");
+        resourceCount = -1;
+    }
+
+    @Override
+    public void createControl(Composite parent) {
+        setPageComplete(false);
+        setTitle(Constants.CREATE_PAGE_TITLE);
+        setMessage(Constants.CREATE_PAGE_MESSAGE);
+        Composite compContent = new Composite(parent, SWT.NONE);
+        GridLayout gridLayout = new GridLayout(1, false);
+        compContent.setLayout(gridLayout);
+        GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        compContent.setLayoutData(gd);
+
+        Group configGroup = new Group(compContent, SWT.NONE);
+        gridLayout = new GridLayout(1, false);
+        gridLayout.verticalSpacing = 10;
+        gridLayout.marginTop = 5;
+        configGroup.setLayout(gridLayout);
+        gd = new GridData();
+        gd.horizontalAlignment = SWT.FILL;
+        gd.grabExcessHorizontalSpace = true;
+        configGroup.setLayoutData(gd);
+        configGroup.setText("Configuration File Type");
+
+        stdResourceRbtn = new Button(configGroup, SWT.RADIO);
+        stdResourceRbtn.setText("Standard Configuration");
+
+        Composite stdConfigComp = new Composite(configGroup, SWT.NONE);
+        stdConfigComp.setLayout(new GridLayout(2, false));
+        gd = new GridData();
+        gd.horizontalAlignment = SWT.FILL;
+        gd.grabExcessHorizontalSpace = true;
+        stdConfigComp.setLayoutData(gd);
+
+        resourceTypeLbl = new Label(stdConfigComp, SWT.NONE);
+        resourceTypeLbl.setText("ResourceType:");
+        resourceTypeLbl.setEnabled(false);
+
+        resourceTypeCmb = new CCombo(stdConfigComp, SWT.READ_ONLY | SWT.BORDER);
+        gd = new GridData();
+        gd.widthHint = 150;
+        resourceTypeCmb.setLayoutData(gd);
+        resourceTypeCmb.setEnabled(false);
+
+        cusResourceRbtn = new Button(configGroup, SWT.RADIO);
+        cusResourceRbtn.setText("Custom Configuration");
+
+        Composite cusConfigComp = new Composite(configGroup, SWT.NONE);
+        cusConfigComp.setLayout(new GridLayout(3, false));
+        gd = new GridData();
+        gd.horizontalAlignment = SWT.FILL;
+        gd.grabExcessHorizontalSpace = true;
+        cusConfigComp.setLayoutData(gd);
+
+        locationLbl = new Label(cusConfigComp, SWT.NONE);
+        locationLbl.setText("Location:");
+        locationLbl.setEnabled(false);
+
+        locationTxt = new Text(cusConfigComp, SWT.BORDER);
+        gd = new GridData();
+        gd.minimumWidth = 300;
+        gd.horizontalAlignment = SWT.FILL;
+        gd.grabExcessHorizontalSpace = true;
+        locationTxt.setLayoutData(gd);
+        locationTxt.setEnabled(false);
+
+        btnBrowse = new Button(cusConfigComp, SWT.NONE);
+        btnBrowse.setText("Browse");
+        gd = new GridData();
+        gd.widthHint = 80;
+        gd.horizontalAlignment = SWT.FILL;
+        btnBrowse.setLayoutData(gd);
+        btnBrowse.setEnabled(false);
+
+        Composite instanceComp = new Composite(compContent, SWT.NONE);
+        instanceComp.setLayout(new GridLayout(2, false));
+        gd = new GridData();
+        gd.horizontalAlignment = SWT.FILL;
+        gd.grabExcessHorizontalSpace = true;
+        instanceComp.setLayoutData(gd);
+
+        noOfInstancesLbl = new Label(instanceComp, SWT.NONE);
+        noOfInstancesLbl.setText("Number of Instances");
+
+        noOfInstancesText = new Text(instanceComp, SWT.BORDER);
+        gd = new GridData();
+        gd.widthHint = 50;
+        gd.horizontalAlignment = SWT.FILL;
+        noOfInstancesText.setLayoutData(gd);
+
+        // Adding the default value. It can be changed by the user.
+        noOfInstancesText.setText("1");
+
+        populateDataInUI();
+
+        addUIListeners();
+
+        setControl(compContent);
+    }
+
+    private void populateDataInUI() {
+        // Populate Resource-type in Combo
+        populateResourceTypeCombo();
+    }
+
+    private void populateResourceTypeCombo() {
+        /*
+         * List<String> configList; configList =
+         * Activator.getDefault().getManager().getResourceConfigurationList();
+         * if(null != configList) { Iterator<String> itr =
+         * configList.iterator(); while(itr.hasNext()) {
+         * resourceTypeCmb.add(itr.next()); } }
+         */
+
+        // TODO: Temporarily adding a resourceType for testing
+        resourceTypeCmb.add("oic.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() {
+        stdResourceRbtn.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+
+                // Set the configFilePath to the first item in the combo
+                if (resourceTypeCmb.getItemCount() > 0)
+                    resourceTypeCmb.select(0);
+
+                // TODO: Temporarily adding some random config file path
+                // To be removed after implementing resource configuration
+                configFilePath = "/Samplelight";
+
+                setPageComplete(isSelectionDone());
+
+                // Change the visibility of widgets
+                resourceTypeLbl.setEnabled(true);
+                resourceTypeCmb.setEnabled(true);
+                locationLbl.setEnabled(false);
+                locationTxt.setEnabled(false);
+                btnBrowse.setEnabled(false);
+
+            }
+        });
+
+        cusResourceRbtn.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                setPageComplete(isSelectionDone());
+
+                // Change the visibility of widgets
+                locationLbl.setEnabled(true);
+                locationTxt.setEnabled(true);
+                btnBrowse.setEnabled(true);
+                resourceTypeLbl.setEnabled(false);
+                resourceTypeCmb.setEnabled(false);
+
+            }
+        });
+
+        btnBrowse.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                FileDialog fileDialog = new FileDialog(PlatformUI
+                        .getWorkbench().getDisplay().getActiveShell(), SWT.NONE);
+                fileDialog
+                        .setFilterExtensions(Constants.BROWSE_RAML_FILTER_EXTENSIONS);
+                String configFileAbsolutePath = fileDialog.open();
+                locationTxt.setText(configFileAbsolutePath);
+            }
+        });
+
+        resourceTypeCmb.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                int index = resourceTypeCmb.getSelectionIndex();
+                if (index >= 0) {
+                    String selectedItem = resourceTypeCmb.getItem(index);
+                    if (null != selectedItem) {
+                        // TODO: Get the RAML configuration file path of the
+                        // selected resource
+                        // configFilePath =
+                        // Activator.getDefault().getManager().getConfigFilePath(selectedItem);
+
+                        setPageComplete(isSelectionDone());
+                    }
+                }
+            }
+        });
+
+        locationTxt.addModifyListener(new ModifyListener() {
+            @Override
+            public void modifyText(ModifyEvent e) {
+                configFilePath = locationTxt.getText();
+                setPageComplete(isSelectionDone());
+            }
+        });
+
+        noOfInstancesText.addListener(SWT.Verify, new Listener() {
+            @Override
+            public void handleEvent(Event e) {
+                String string = e.text;
+                char[] chars = new char[string.length()];
+                string.getChars(0, chars.length, chars, 0);
+                for (int i = 0; i < chars.length; i++) {
+                    if (!('0' <= chars[i] && chars[i] <= '9')) {
+                        e.doit = false;
+                        return;
+                    }
+                }
+            }
+        });
+
+        noOfInstancesText.addKeyListener(new KeyAdapter() {
+            @Override
+            public void keyReleased(KeyEvent e) {
+                setPageComplete(isSelectionDone());
+            }
+        });
+    }
+
+    private boolean isSelectionDone() {
+        boolean done = false;
+        try {
+            resourceCount = Integer.parseInt(noOfInstancesText.getText());
+        } catch (Exception e) {
+            resourceCount = -1;
+        }
+        if (cusResourceRbtn.getSelection()) {
+            configFilePath = locationTxt.getText();
+        }
+
+        if (null != configFilePath && configFilePath.length() > 0
+                && resourceCount >= 1) {
+            done = true;
+        }
+        return done;
+    }
+
+    public String getConfigFilePath() {
+        return configFilePath;
+    }
+
+    public int getResourceCount() {
+        return resourceCount;
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/CreateResourceWizard.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/CreateResourceWizard.java
new file mode 100644 (file)
index 0000000..5beab41
--- /dev/null
@@ -0,0 +1,43 @@
+package oic.simulator.serviceprovider.view.dialogs;
+
+import java.net.URL;
+
+import oic.simulator.serviceprovider.Activator;
+
+import org.eclipse.core.runtime.FileLocator;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.core.runtime.Path;
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.jface.wizard.Wizard;
+
+public class CreateResourceWizard extends Wizard {
+
+    private CreateResourcePage page;
+
+    public CreateResourceWizard() {
+        setWindowTitle("Create resources");
+        IPath path = new Path("/icons/oic_logo_64x64.png");
+        URL find = FileLocator.find(Activator.getDefault().getBundle(), path,
+                null);
+        setDefaultPageImageDescriptor(ImageDescriptor.createFromURL(find));
+    }
+
+    @Override
+    public void addPages() {
+        page = new CreateResourcePage();
+        addPage(page);
+    }
+
+    public String getConfigFilePath() {
+        return page.getConfigFilePath();
+    }
+
+    public int getResourceCount() {
+        return page.getResourceCount();
+    }
+
+    @Override
+    public boolean performFinish() {
+        return true;
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/DeleteCategory.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/DeleteCategory.java
new file mode 100644 (file)
index 0000000..ba2ff9d
--- /dev/null
@@ -0,0 +1,5 @@
+package oic.simulator.serviceprovider.view.dialogs;
+
+public enum DeleteCategory {
+    ALL, BY_TYPE, BY_URI, NONE
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/DeleteResourcePage.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/DeleteResourcePage.java
new file mode 100644 (file)
index 0000000..1272079
--- /dev/null
@@ -0,0 +1,219 @@
+package oic.simulator.serviceprovider.view.dialogs;
+
+import java.util.Iterator;
+import java.util.List;
+
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.utils.Constants;
+
+import org.eclipse.jface.wizard.WizardPage;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.CCombo;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Group;
+import org.eclipse.swt.widgets.Text;
+
+public class DeleteResourcePage extends WizardPage {
+
+    private Button         allRbtn;
+    private Button         byTypeRbtn;
+    private Button         byUriRbtn;
+
+    private CCombo         resourceTypeCmb;
+    private Text           resourceUriTxt;
+
+    private DeleteCategory deleteCategory;
+
+    // It will hold either the resource type or resource uri
+    private String         deleteCandidate;
+
+    protected DeleteResourcePage() {
+        super("Delete Resource");
+    }
+
+    @Override
+    public void createControl(Composite parent) {
+        setPageComplete(false);
+        setTitle(Constants.DELETE_PAGE_TITLE);
+        setMessage(Constants.DELETE_PAGE_MESSAGE);
+
+        Composite compContent = new Composite(parent, SWT.NONE);
+        compContent.setLayout(new GridLayout(1, false));
+        GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        compContent.setLayoutData(gd);
+
+        Group group = new Group(compContent, SWT.NONE);
+        group.setText("Select Category");
+        GridLayout gridLayout = new GridLayout(2, false);
+        gridLayout.verticalSpacing = 15;
+        gridLayout.marginTop = 10;
+        gridLayout.marginLeft = 10;
+        group.setLayout(gridLayout);
+        gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+        group.setLayoutData(gd);
+
+        allRbtn = new Button(group, SWT.RADIO);
+        allRbtn.setText("All resources");
+        gd = new GridData();
+        gd.horizontalSpan = 2;
+        gd.widthHint = 200;
+        allRbtn.setLayoutData(gd);
+
+        byTypeRbtn = new Button(group, SWT.RADIO);
+        byTypeRbtn.setText("All (By resource type)");
+        gd = new GridData();
+        gd.widthHint = 200;
+        byTypeRbtn.setLayoutData(gd);
+
+        resourceTypeCmb = new CCombo(group, SWT.READ_ONLY | SWT.BORDER);
+        gd = new GridData();
+        gd.widthHint = 200;
+        resourceTypeCmb.setLayoutData(gd);
+
+        byUriRbtn = new Button(group, SWT.RADIO);
+        byUriRbtn.setText("By Resource URI");
+        gd = new GridData();
+        gd.widthHint = 200;
+        byUriRbtn.setLayoutData(gd);
+
+        resourceUriTxt = new Text(group, SWT.BORDER);
+        gd = new GridData();
+        gd.widthHint = 300;
+        resourceUriTxt.setLayoutData(gd);
+
+        // Setting the initial visibility of controls
+        allRbtn.setSelection(false);
+        byTypeRbtn.setSelection(false);
+        byUriRbtn.setSelection(false);
+
+        resourceTypeCmb.setEnabled(false);
+        resourceUriTxt.setEnabled(false);
+
+        deleteCategory = DeleteCategory.NONE;
+
+        populateDataInUI();
+
+        addUIListeners();
+
+        setControl(compContent);
+    }
+
+    private void populateDataInUI() {
+        // Populate Resourcetype in Combo
+        populateResourceTypeCombo();
+    }
+
+    private void populateResourceTypeCombo() {
+
+        List<String> resourceTypeList;
+        resourceTypeList = Activator.getDefault().getResourceManager()
+                .getResourceTypeList();
+        if (null != resourceTypeList) {
+            Iterator<String> itr = resourceTypeList.iterator();
+            while (itr.hasNext()) {
+                resourceTypeCmb.add(itr.next());
+            }
+        }
+
+        // By default, select the first item in the combo
+        if (resourceTypeCmb.getItemCount() > 0) {
+            resourceTypeCmb.select(0);
+            deleteCandidate = resourceTypeCmb.getItem(resourceTypeCmb
+                    .getSelectionIndex());
+        }
+    }
+
+    public void addUIListeners() {
+        allRbtn.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                // Update the visibility of controls
+                resourceTypeCmb.setEnabled(false);
+                resourceUriTxt.setEnabled(false);
+
+                deleteCategory = DeleteCategory.ALL;
+                deleteCandidate = null;
+                setPageComplete(isSelectionDone());
+            }
+        });
+
+        byTypeRbtn.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                // Update the visibility of controls
+                resourceTypeCmb.setEnabled(true);
+                resourceUriTxt.setEnabled(false);
+
+                deleteCategory = DeleteCategory.BY_TYPE;
+                setPageComplete(isSelectionDone());
+            }
+        });
+
+        byUriRbtn.addSelectionListener(new SelectionAdapter() {
+            @Override
+            public void widgetSelected(SelectionEvent e) {
+                // Update the visibility of controls
+                resourceUriTxt.setEnabled(true);
+                resourceUriTxt.setFocus();
+                resourceTypeCmb.setEnabled(false);
+
+                deleteCategory = DeleteCategory.BY_URI;
+                setPageComplete(isSelectionDone());
+            }
+        });
+
+        resourceTypeCmb.addModifyListener(new ModifyListener() {
+            @Override
+            public void modifyText(ModifyEvent arg0) {
+                setPageComplete(isSelectionDone());
+            }
+        });
+
+        resourceUriTxt.addModifyListener(new ModifyListener() {
+            @Override
+            public void modifyText(ModifyEvent arg0) {
+                setPageComplete(isSelectionDone());
+            }
+        });
+    }
+
+    public boolean isSelectionDone() {
+        boolean done = false;
+        if (deleteCategory == DeleteCategory.ALL) {
+            done = true;
+        } else if (deleteCategory == DeleteCategory.BY_TYPE) {
+            int selectedItemIndex = resourceTypeCmb.getSelectionIndex();
+            if (selectedItemIndex >= 0) {
+                deleteCandidate = resourceTypeCmb.getItem(selectedItemIndex);
+                if (null != deleteCandidate && deleteCandidate.length() > 0) {
+                    done = true;
+                }
+            }
+        } else if (deleteCategory == DeleteCategory.BY_URI) {
+            deleteCandidate = resourceUriTxt.getText();
+            if (null != deleteCandidate && deleteCandidate.length() > 0) {
+                done = true;
+            }
+        }
+        return done;
+    }
+
+    public DeleteCategory getDeleteCategory() {
+        return deleteCategory;
+    }
+
+    public String getDeleteCandidate() {
+        return deleteCandidate;
+    }
+
+    public void setFocusToTextBox() {
+        resourceUriTxt.setFocus();
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/DeleteResourceWizard.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/DeleteResourceWizard.java
new file mode 100644 (file)
index 0000000..8b9a3b6
--- /dev/null
@@ -0,0 +1,70 @@
+package oic.simulator.serviceprovider.view.dialogs;
+
+import java.net.URL;
+
+import oic.simulator.serviceprovider.Activator;
+import oic.simulator.serviceprovider.utils.Utility;
+
+import org.eclipse.core.runtime.FileLocator;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.core.runtime.Path;
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.jface.wizard.Wizard;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.ui.PlatformUI;
+
+public class DeleteResourceWizard extends Wizard {
+
+    private DeleteResourcePage page;
+
+    public DeleteResourceWizard() {
+        setWindowTitle("Delete resources");
+        IPath path = new Path("/icons/oic_logo_64x64.png");
+        URL find = FileLocator.find(Activator.getDefault().getBundle(), path,
+                null);
+        setDefaultPageImageDescriptor(ImageDescriptor.createFromURL(find));
+    }
+
+    @Override
+    public void addPages() {
+        page = new DeleteResourcePage();
+        addPage(page);
+    }
+
+    @Override
+    public boolean performFinish() {
+        // Check the existence of the resource if the user has entered the uri
+        if (page.getDeleteCategory() == DeleteCategory.BY_URI) {
+            // Check whether the uri is in full form or short form
+            // If it is in short form, expand it to its full form.
+            String uri = page.getDeleteCandidate();
+            boolean uriComplete = Utility.isUriComplete(uri);
+            if (!uriComplete) {
+                uri = Utility.displayNameToUri(uri);
+            }
+            boolean exist = Activator.getDefault().getResourceManager()
+                    .isResourceExist(uri);
+            if (!exist) {
+                Shell activeShell = PlatformUI.getWorkbench().getDisplay()
+                        .getActiveShell();
+                MessageDialog dialog = new MessageDialog(activeShell,
+                        "Resource Not Found", null,
+                        "No resource exist with the given URI.",
+                        MessageDialog.INFORMATION, new String[] { "OK" }, 0);
+                dialog.open();
+                page.setFocusToTextBox();
+                return false;
+            }
+        }
+        return true;
+    }
+
+    public DeleteCategory getDeleteCategory() {
+        return page.getDeleteCategory();
+    }
+
+    public String getDeleteCandidate() {
+        return page.getDeleteCandidate();
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/FilterDialog.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/FilterDialog.java
new file mode 100644 (file)
index 0000000..e0f4397
--- /dev/null
@@ -0,0 +1,75 @@
+package oic.simulator.serviceprovider.view.dialogs;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Map;
+
+import oic.simulator.serviceprovider.manager.LogManager;
+
+import org.eclipse.jface.dialogs.TrayDialog;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Group;
+import org.eclipse.swt.widgets.Shell;
+
+public class FilterDialog extends TrayDialog {
+    private Map<Integer, Boolean> severities;
+
+    public FilterDialog(Shell shell, Map<Integer, Boolean> severities) {
+        super(shell);
+        this.severities = severities;
+    }
+
+    @Override
+    protected void configureShell(Shell shell) {
+        super.configureShell(shell);
+    }
+
+    @Override
+    protected Control createDialogArea(Composite parent) {
+        Composite composite = (Composite) super.createDialogArea(parent);
+        createSeverityGroup(composite);
+        getShell().setText("Filter details");
+        return composite;
+    }
+
+    /**
+     * Dynamically creates a check-box list for severity levels for user to
+     * choose from
+     */
+    private void createSeverityGroup(Composite parent) {
+        Group group = new Group(parent, SWT.NONE);
+        group.setLayout(new GridLayout());
+        GridData gd = new GridData(GridData.FILL_HORIZONTAL);
+        gd.widthHint = 275;
+        group.setLayoutData(gd);
+        group.setText("Severity Levels");
+
+        ArrayList<Integer> arrayList = new ArrayList<Integer>(
+                severities.keySet());
+        Collections.sort(arrayList);
+        for (final Integer i : arrayList) {
+            final Button checkbox = new Button(group, SWT.CHECK);
+            checkbox.setText(LogManager.getSeverityName(i));
+            checkbox.setSelection(severities.get(i));
+            checkbox.addSelectionListener(new SelectionAdapter() {
+
+                @Override
+                public void widgetSelected(SelectionEvent e) {
+                    severities.put(i, checkbox.getSelection());
+                }
+            });
+        }
+    }
+
+    @Override
+    public boolean isHelpAvailable() {
+        return false;
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/ResourceWizardDialog.java b/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/ResourceWizardDialog.java
new file mode 100644 (file)
index 0000000..59dd8e0
--- /dev/null
@@ -0,0 +1,34 @@
+package oic.simulator.serviceprovider.view.dialogs;
+
+import org.eclipse.jface.dialogs.IDialogConstants;
+import org.eclipse.jface.wizard.IWizard;
+import org.eclipse.jface.wizard.WizardDialog;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Shell;
+
+public class ResourceWizardDialog extends WizardDialog {
+
+    public ResourceWizardDialog(Shell parentShell, IWizard newWizard) {
+        super(parentShell, newWizard);
+    }
+
+    @Override
+    public boolean isHelpAvailable() {
+        return false;
+    }
+
+    @Override
+    public void finishPressed() {
+        super.finishPressed();
+    }
+
+    @Override
+    protected void createButtonsForButtonBar(Composite parent) {
+        super.createButtonsForButtonBar(parent);
+        Button finishButton = getButton(IDialogConstants.FINISH_ID);
+        if (finishButton != null) {
+            finishButton.setText(IDialogConstants.OK_LABEL);
+        }
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/jni/simulator_common_jni.h b/service/simulator/java/jni/simulator_common_jni.h
new file mode 100644 (file)
index 0000000..472748c
--- /dev/null
@@ -0,0 +1,89 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#ifndef SIMULATOR_COMMON_JNI_H_
+#define SIMULATOR_COMMON_JNI_H_
+
+#include <jni.h>
+
+typedef struct
+{
+    jclass classInteger;
+    jclass classDouble;
+    jclass classString;
+    jclass classHashMap;
+    jclass classVector;
+    jclass classSimulatorResource;
+    jclass classSimulatorResourceModel;
+    jclass classSimulatorResourceAttribute;
+    jclass classSimulatorRemoteResource;
+    jclass classSimulatorCallback;
+    jclass classMap;
+    jclass classMapEntry;
+    jclass classSet;
+    jclass classIterator;
+
+    jmethodID classIntegerCtor;
+    jmethodID classDoubleCtor;
+    jmethodID classHashMapCtor;
+    jmethodID classHashMapPut;
+    jmethodID classVectorCtor;
+    jmethodID classVectorAddElement;
+    jmethodID classSimulatorResourceCtor;
+    jmethodID classSimulatorResourceSetURI;
+    jmethodID classSimulatorResourceSetResourceType;
+    jmethodID classSimulatorResourceSetInterfaceType;
+    jmethodID classSimulatorResourceSetName;
+    jmethodID classSimulatorResourceModelCtor;
+    jmethodID classSimulatorResourceAttributeCtor;
+    jmethodID classSimulatorResourceModelId;
+    jmethodID classMapEntrySet;
+    jmethodID classMapGetKey;
+    jmethodID classMapGetValue;
+    jmethodID classIteratorId;
+    jmethodID classHasNextId;
+    jmethodID classNextId;
+} SimulatorClassRefs;
+
+static jfieldID GetHandleField(JNIEnv *env, jobject jobj)
+{
+    jclass cls = env->GetObjectClass(jobj);
+    return env->GetFieldID(cls, "nativeHandle", "J");
+}
+
+template <typename T>
+static T *GetHandle(JNIEnv *env, jobject jobj)
+{
+    jlong handle = env->GetLongField(jobj, GetHandleField(env, jobj));
+    return reinterpret_cast<T *>(handle);
+}
+
+template <typename T>
+static void SetHandle(JNIEnv *env, jobject jobj, T *type)
+{
+    jlong handle = reinterpret_cast<jlong>(type);
+
+    env->SetLongField(jobj, GetHandleField(env, jobj), handle);
+}
+
+JNIEnv *getEnv();
+void releaseEnv();
+
+#endif
diff --git a/service/simulator/java/jni/simulator_manager_jni.cpp b/service/simulator/java/jni/simulator_manager_jni.cpp
new file mode 100644 (file)
index 0000000..3cb5573
--- /dev/null
@@ -0,0 +1,653 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "simulator_manager_jni.h"
+#include "simulator_resource_server_jni.h"
+#include "simulator_common_jni.h"
+#include "simulator_manager.h"
+#include "simulator_remote_resource_jni.h"
+#include "simulator_resource_model_jni.h"
+
+SimulatorClassRefs gSimulatorClassRefs;
+std::mutex gEnvMutex;
+JavaVM *gvm;
+
+JNIEnv *getEnv()
+{
+    std::unique_lock<std::mutex> lock(gEnvMutex);
+    if (nullptr == gvm)
+        return NULL;
+
+    JNIEnv *env = NULL;
+    jint ret = gvm->GetEnv((void **)&env, JNI_VERSION_1_6);
+    switch (ret)
+    {
+        case JNI_OK:
+            return env;
+        case JNI_EDETACHED:
+            if (0 == gvm->AttachCurrentThread((void **)&env, NULL))
+                return env;
+    }
+
+    return NULL;
+}
+
+void releaseEnv()
+{
+    std::unique_lock<std::mutex> lock(gEnvMutex);
+    if (nullptr == gvm)
+        return;
+    gvm->DetachCurrentThread();
+}
+
+class JNILogger : public ILogger
+{
+    public:
+        void setJavaLogger(JNIEnv *env, jobject logger)
+        {
+            m_logger = env->NewWeakGlobalRef(logger);
+        }
+
+        void write(std::string time, ILogger::Level level, std::string message)
+        {
+            JNIEnv *env = getEnv();
+            if (nullptr == env)
+                return;
+
+            jobject logger = env->NewLocalRef(m_logger);
+            if (!logger)
+            {
+                releaseEnv();
+                return;
+            }
+
+            jclass loggerCls = env->GetObjectClass(logger);
+            if (!loggerCls)
+            {
+                releaseEnv();
+                return;
+            }
+
+            jmethodID writeMId = env->GetMethodID(loggerCls, "write",
+                                                  "(Ljava/lang/String;ILjava/lang/String;)V");
+            if (!writeMId)
+            {
+                releaseEnv();
+                return;
+            }
+
+            jstring msg = env->NewStringUTF(message.c_str());
+            jstring timeStr = env->NewStringUTF(time.c_str());
+            env->CallVoidMethod(logger, writeMId, timeStr, static_cast<jint>(level), msg);
+            env->DeleteLocalRef(msg);
+            env->DeleteLocalRef(timeStr);
+            releaseEnv();
+        }
+
+    private:
+        jweak m_logger;
+};
+
+
+jobject SimulatorRemoteResourceToJava(JNIEnv *env, jlong resource)
+{
+    jmethodID constructor = env->GetMethodID(gSimulatorClassRefs.classSimulatorRemoteResource, "<init>",
+                            "(J)V");
+    if (NULL == constructor)
+    {
+        return NULL;
+    }
+
+    jobject resourceObj = (jobject) env->NewObject(gSimulatorClassRefs.classSimulatorRemoteResource,
+                          constructor, resource);
+    if (NULL == resourceObj)
+    {
+        return NULL;
+    }
+
+    return resourceObj;
+}
+
+class JNIFoundResourceListener
+{
+    public:
+        void setJavaFoundResourceListener(JNIEnv *env, jobject listener)
+        {
+            m_listener = env->NewWeakGlobalRef(listener);
+        }
+
+        void onFoundResource(std::shared_ptr<SimulatorRemoteResource> resource)
+        {
+            JNIEnv *env = getEnv();
+            if (nullptr == env)
+                return;
+
+            jobject foundResourceListener = env->NewLocalRef(m_listener);
+            if (!foundResourceListener)
+            {
+                releaseEnv();
+                return;
+            }
+
+            jclass foundResourceCls = env->GetObjectClass(foundResourceListener);
+            if (!foundResourceCls)
+            {
+                releaseEnv();
+                return;
+            }
+
+            jmethodID foundResourceMId = env->GetMethodID(foundResourceCls, "onResourceCallback",
+                                         "(Lorg/oic/simulator/clientcontroller/SimulatorRemoteResource;)V");
+            if (!foundResourceMId)
+            {
+                releaseEnv();
+                return;
+            }
+
+            JniSimulatorRemoteResource *jniSimulatorResource = new JniSimulatorRemoteResource(resource);
+
+            if (!jniSimulatorResource)
+            {
+                releaseEnv();
+                return;
+            }
+
+            jobject simulatorResource = SimulatorRemoteResourceToJava(env,
+                                        reinterpret_cast<jlong>(jniSimulatorResource));
+
+            env->CallVoidMethod(foundResourceListener, foundResourceMId, simulatorResource);
+            if ((env)->ExceptionCheck())
+            {
+                releaseEnv();
+                return;
+            }
+
+            releaseEnv();
+        }
+
+    private:
+        jweak m_listener;
+
+};
+
+void onResourceModelChange(jweak jlistenerRef, const std::string &uri,
+                           const SimulatorResourceModel &resModel)
+{
+    JNIEnv *env = getEnv();
+    if (nullptr == env)
+        return;
+
+    jobject modelChangeListener = env->NewLocalRef(jlistenerRef);
+    if (!modelChangeListener)
+    {
+        releaseEnv();
+        return;
+    }
+
+    jclass modelChangeCls = env->GetObjectClass(modelChangeListener);
+    if (!modelChangeCls)
+    {
+        releaseEnv();
+        return;
+    }
+
+    jmethodID foundModelChangeMId = env->GetMethodID(modelChangeCls, "onResourceModelChanged",
+                                    "(Ljava/lang/String;Lorg/oic/simulator/serviceprovider/SimulatorResourceModel;)V");
+    if (!foundModelChangeMId)
+    {
+        releaseEnv();
+        return;
+    }
+
+    JniSimulatorResourceModel *jniModel = new JniSimulatorResourceModel(resModel);
+    if (!jniModel)
+    {
+        releaseEnv();
+        return;
+    }
+
+    jobject jModel = JniSimulatorResourceModel::toJava(env, reinterpret_cast<jlong>(jniModel));
+
+    jstring jUri = env->NewStringUTF(uri.c_str());
+
+    env->CallVoidMethod(modelChangeListener, foundModelChangeMId, jUri, jModel);
+    if ((env)->ExceptionCheck())
+    {
+        releaseEnv();
+        return;
+    }
+
+    env->DeleteLocalRef(jUri);
+
+    releaseEnv();
+}
+
+
+JNIEXPORT jobject JNICALL
+Java_org_oic_simulator_SimulatorManagerNativeInterface_createResource
+(JNIEnv *env, jclass object, jstring configPath, jobject listener)
+{
+    if (!configPath)
+        return NULL;
+
+    if (!listener)
+        return NULL;
+
+    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);
+    SimulatorResourceServerPtr resource = SimulatorManager::getInstance()->createResource(
+            configPathCStr, callback);
+    if (nullptr == resource)
+    {
+        if (configPathCStr)
+            env->ReleaseStringUTFChars(configPath, configPathCStr);
+        return NULL;
+    }
+
+    JniSimulatorResource *jniSimResource = new JniSimulatorResource(resource);
+    jobject jSimulatorResource = JniSimulatorResource::toJava(env,
+                                 reinterpret_cast<jlong>(jniSimResource));
+
+    jniSimResource->setResourceInfo(env, jSimulatorResource);
+
+    if (configPathCStr)
+        env->ReleaseStringUTFChars(configPath, configPathCStr);
+    return jSimulatorResource;
+}
+
+JNIEXPORT jobjectArray JNICALL
+Java_org_oic_simulator_SimulatorManagerNativeInterface_createResources
+(JNIEnv *env, jclass object, jstring configPath, jint count, jobject listener)
+{
+    if (!configPath)
+        return NULL;
+
+    if (!listener)
+        return NULL;
+
+    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<SimulatorResourceServerPtr> resources =
+        SimulatorManager::getInstance()->createResource(configPathCStr, count, callback);
+
+    // Construct the object array and send it java layer
+    jobjectArray resourceArray = env->NewObjectArray(resources.size(),
+                                 gSimulatorClassRefs.classSimulatorResource, NULL);
+    if (resourceArray)
+    {
+        for (size_t i = 0; i < resources.size(); i++)
+        {
+            JniSimulatorResource *jniSimResource = new JniSimulatorResource(resources[i]);
+            jobject jSimulatorResource = JniSimulatorResource::toJava(env,
+                                         reinterpret_cast<jlong>(jniSimResource));
+            jniSimResource->setResourceInfo(env, jSimulatorResource);
+            env->SetObjectArrayElement(resourceArray, i, jSimulatorResource);
+        }
+    }
+
+    if (configPathCStr)
+        env->ReleaseStringUTFChars(configPath, configPathCStr);
+    return resourceArray;
+}
+
+JNIEXPORT jobjectArray JNICALL
+Java_org_oic_simulator_SimulatorManagerNativeInterface_getResources
+(JNIEnv *env, jclass object)
+{
+    //TODO: Need to implement this method
+    return nullptr;
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_SimulatorManagerNativeInterface_deleteResource
+(JNIEnv *env, jclass object, jobject jResource)
+{
+    if (!jResource)
+        return;
+
+    SimulatorResourceServerPtr resource =
+        JniSimulatorResource::getJniSimulatorResourcePtr(env, jResource);
+    if (!resource)
+        return;
+
+    SimulatorManager::getInstance()->deleteResource(resource);
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_SimulatorManagerNativeInterface_deleteResources
+(JNIEnv *env, jclass object, jstring resourceType)
+{
+    std::string type;
+    const char *typeCStr = NULL;
+    if (resourceType)
+    {
+        typeCStr = env->GetStringUTFChars(resourceType, NULL);
+        type = typeCStr;
+    }
+
+    SimulatorManager::getInstance()->deleteResources(type);
+    if (typeCStr)
+        env->ReleaseStringUTFChars(resourceType, typeCStr);
+}
+
+JNIEXPORT jint JNICALL
+Java_org_oic_simulator_SimulatorManagerNativeInterface_findResource
+(JNIEnv *env, jobject object, jstring resourceType, jobject listener)
+{
+    const char *typeCStr = NULL;
+
+    if (resourceType)
+    {
+        typeCStr = env->GetStringUTFChars(resourceType, NULL);
+    }
+
+    JNIFoundResourceListener *resourceListener = new JNIFoundResourceListener();
+    resourceListener->setJavaFoundResourceListener(env, listener);
+
+    SimulatorResult result = SimulatorManager::getInstance()->findResource(typeCStr,
+                             std::bind(&JNIFoundResourceListener::onFoundResource, resourceListener, std::placeholders::_1));
+
+    if (typeCStr)
+        env->ReleaseStringUTFChars(resourceType, typeCStr);
+    return result;
+}
+
+JNIEXPORT jobject JNICALL
+Java_org_oic_simulator_SimulatorManagerNativeInterface_getFoundResources
+(JNIEnv *env, jobject object, jstring resourceType)
+{
+    const char *typeCStr = NULL;
+    if (resourceType)
+    {
+        typeCStr = env->GetStringUTFChars(resourceType, NULL);
+    }
+
+    std::vector<SimulatorRemoteResourcePtr> resourceList;
+    resourceList = SimulatorManager::getInstance()->getFoundResources(typeCStr);
+    if (resourceList.empty())
+    {
+        if (typeCStr)
+            env->ReleaseStringUTFChars(resourceType, typeCStr);
+        return NULL;
+    }
+
+    jobject vectorObj = env->NewObject(gSimulatorClassRefs.classVector,
+                                       gSimulatorClassRefs.classVectorCtor);
+    if (!vectorObj)
+    {
+        if (typeCStr)
+            env->ReleaseStringUTFChars(resourceType, typeCStr);
+        return NULL;
+    }
+
+    // Convert to java SimulatorRemoteResource object
+    for (unsigned int i = 0; i < resourceList.size(); i++)
+    {
+        JniSimulatorRemoteResource *jniSimulatorResource = new JniSimulatorRemoteResource(resourceList[i]);
+        if (!jniSimulatorResource)
+        {
+            if (typeCStr)
+                env->ReleaseStringUTFChars(resourceType, typeCStr);
+            return NULL;
+        }
+
+        jobject resource = SimulatorRemoteResourceToJava(env,
+                           reinterpret_cast<jlong>(jniSimulatorResource));
+        env->CallVoidMethod(vectorObj, gSimulatorClassRefs.classVectorAddElement, resource);
+    }
+
+    if (typeCStr)
+        env->ReleaseStringUTFChars(resourceType, typeCStr);
+    return vectorObj;
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_SimulatorManagerNativeInterface_setLogger
+(JNIEnv *env, jclass object, jobject logger)
+{
+    static std::shared_ptr<ILogger> target(new JNILogger());
+    dynamic_cast<JNILogger *>(target.get())->setJavaLogger(env, logger);
+    SimulatorManager::getInstance()->setLogger(target);
+}
+
+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/Integer", gSimulatorClassRefs.classInteger))
+    {
+        return JNI_ERR;
+    }
+
+    if (false == getClassRef(env, "java/lang/Double", gSimulatorClassRefs.classDouble))
+    {
+        return JNI_ERR;
+    }
+
+    if (false == getClassRef(env, "java/lang/String", gSimulatorClassRefs.classString))
+    {
+        return JNI_ERR;
+    }
+
+    if (false == getClassRef(env, "java/util/HashMap", gSimulatorClassRefs.classHashMap))
+    {
+        return JNI_ERR;
+    }
+
+    if (false == getClassRef(env, "java/util/Vector", gSimulatorClassRefs.classVector))
+    {
+        return JNI_ERR;
+    }
+
+    if (false == getClassRef(env, "java/util/Map", gSimulatorClassRefs.classMap))
+    {
+        return JNI_ERR;
+    }
+
+    if (false == getClassRef(env, "java/util/Map$Entry", gSimulatorClassRefs.classMapEntry))
+    {
+        return JNI_ERR;
+    }
+
+    if (false == getClassRef(env, "java/util/Set", gSimulatorClassRefs.classSet))
+    {
+        return JNI_ERR;
+    }
+
+    if (false == getClassRef(env, "java/util/Iterator", gSimulatorClassRefs.classIterator))
+    {
+        return JNI_ERR;
+    }
+
+    if (false == getClassRef(env, "org/oic/simulator/serviceprovider/SimulatorResourceServer",
+                             gSimulatorClassRefs.classSimulatorResource))
+    {
+        return JNI_ERR;
+    }
+
+    if (false == getClassRef(env, "org/oic/simulator/serviceprovider/SimulatorResourceModel",
+                             gSimulatorClassRefs.classSimulatorResourceModel))
+    {
+        return JNI_ERR;
+    }
+
+    if (false == getClassRef(env, "org/oic/simulator/SimulatorResourceAttribute",
+                             gSimulatorClassRefs.classSimulatorResourceAttribute))
+    {
+        return JNI_ERR;
+    }
+
+    if (false == getClassRef(env, "org/oic/simulator/clientcontroller/SimulatorRemoteResource",
+                             gSimulatorClassRefs.classSimulatorRemoteResource))
+    {
+        return JNI_ERR;
+    }
+
+    // Get the reference to methods
+    gSimulatorClassRefs.classIntegerCtor = env->GetMethodID(gSimulatorClassRefs.classInteger, "<init>",
+                                           "(I)V");
+    if (!gSimulatorClassRefs.classIntegerCtor)
+        return JNI_ERR;
+
+    gSimulatorClassRefs.classDoubleCtor = env->GetMethodID(gSimulatorClassRefs.classDouble, "<init>",
+                                          "(D)V");
+    if (!gSimulatorClassRefs.classDoubleCtor)
+        return JNI_ERR;
+
+    gSimulatorClassRefs.classHashMapCtor = env->GetMethodID(gSimulatorClassRefs.classHashMap, "<init>",
+                                           "()V");
+    if (!gSimulatorClassRefs.classHashMapCtor)
+        return JNI_ERR;
+
+    gSimulatorClassRefs.classHashMapPut = env->GetMethodID(gSimulatorClassRefs.classHashMap, "put",
+                                          "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
+    if (!gSimulatorClassRefs.classHashMapPut)
+        return JNI_ERR;
+
+    gSimulatorClassRefs.classVectorCtor = env->GetMethodID(gSimulatorClassRefs.classVector, "<init>",
+                                          "()V");
+    if (!gSimulatorClassRefs.classVectorCtor)
+        return JNI_ERR;
+
+    gSimulatorClassRefs.classVectorAddElement = env->GetMethodID(gSimulatorClassRefs.classVector,
+            "addElement",
+            "(Ljava/lang/Object;)V");
+    if (!gSimulatorClassRefs.classVectorAddElement)
+        return JNI_ERR;
+
+    gSimulatorClassRefs.classMapEntrySet = env->GetMethodID(
+            gSimulatorClassRefs.classMap, "entrySet", "()Ljava/util/Set;");
+    if (!gSimulatorClassRefs.classMapEntrySet)
+        return JNI_ERR;
+
+    gSimulatorClassRefs.classMapGetKey = env->GetMethodID(
+            gSimulatorClassRefs.classMapEntry, "getKey", "()Ljava/lang/Object;");
+    if (!gSimulatorClassRefs.classMapGetKey)
+        return JNI_ERR;
+
+    gSimulatorClassRefs.classMapGetValue = env->GetMethodID(
+            gSimulatorClassRefs.classMapEntry, "getValue", "()Ljava/lang/Object;");
+    if (!gSimulatorClassRefs.classMapGetValue)
+        return JNI_ERR;
+
+    gSimulatorClassRefs.classIteratorId = env->GetMethodID(
+            gSimulatorClassRefs.classSet, "iterator", "()Ljava/util/Iterator;");
+    if (!gSimulatorClassRefs.classIteratorId)
+        return JNI_ERR;
+
+    gSimulatorClassRefs.classHasNextId = env->GetMethodID(
+            gSimulatorClassRefs.classIterator, "hasNext", "()Z");
+    if (!gSimulatorClassRefs.classHasNextId)
+        return JNI_ERR;
+
+    gSimulatorClassRefs.classNextId = env->GetMethodID(
+                                          gSimulatorClassRefs.classIterator, "next", "()Ljava/lang/Object;");
+    if (!gSimulatorClassRefs.classNextId)
+        return JNI_ERR;
+
+    gSimulatorClassRefs.classSimulatorResourceCtor = env->GetMethodID(
+                gSimulatorClassRefs.classSimulatorResource, "<init>", "(J)V");
+    if (!gSimulatorClassRefs.classSimulatorResourceCtor)
+        return JNI_ERR;
+
+    gSimulatorClassRefs.classSimulatorResourceSetURI = env->GetMethodID(
+                gSimulatorClassRefs.classSimulatorResource, "setURI", "(Ljava/lang/String;)V");
+    if (!gSimulatorClassRefs.classSimulatorResourceSetURI)
+        return JNI_ERR;
+
+    gSimulatorClassRefs.classSimulatorResourceSetResourceType = env->GetMethodID(
+                gSimulatorClassRefs.classSimulatorResource, "setResourceType", "(Ljava/lang/String;)V");
+    if (!gSimulatorClassRefs.classSimulatorResourceSetResourceType)
+        return JNI_ERR;
+
+    gSimulatorClassRefs.classSimulatorResourceSetInterfaceType = env->GetMethodID(
+                gSimulatorClassRefs.classSimulatorResource, "setInterfaceType", "(Ljava/lang/String;)V");
+    if (!gSimulatorClassRefs.classSimulatorResourceSetInterfaceType)
+        return JNI_ERR;
+
+    gSimulatorClassRefs.classSimulatorResourceSetName = env->GetMethodID(
+                gSimulatorClassRefs.classSimulatorResource, "setName", "(Ljava/lang/String;)V");
+    if (!gSimulatorClassRefs.classSimulatorResourceSetName)
+        return JNI_ERR;
+
+    gSimulatorClassRefs.classSimulatorResourceModelCtor = env->GetMethodID(
+                gSimulatorClassRefs.classSimulatorResourceModel, "<init>", "(J)V");
+    if (!gSimulatorClassRefs.classSimulatorResourceModelCtor)
+        return JNI_ERR;
+
+    gSimulatorClassRefs.classSimulatorResourceAttributeCtor = env->GetMethodID(
+                gSimulatorClassRefs.classSimulatorResourceAttribute, "<init>", "(J)V");
+    if (!gSimulatorClassRefs.classSimulatorResourceAttributeCtor)
+        return JNI_ERR;
+
+    gSimulatorClassRefs.classSimulatorResourceModelId = env->GetMethodID(
+                gSimulatorClassRefs.classSimulatorResourceModel, "<init>", "(J)V");
+    if (!gSimulatorClassRefs.classSimulatorResourceModelId)
+        return JNI_ERR;
+
+    gvm = vm;
+    return JNI_VERSION_1_6;
+}
+
+JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *vm, void *reserved)
+{
+}
+
+#ifdef __cplusplus
+}
+#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
new file mode 100644 (file)
index 0000000..93595d8
--- /dev/null
@@ -0,0 +1,66 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#ifndef SIMULATOR_MANAGER_JNI_H_
+#define SIMULATOR_MANAGER_JNI_H_
+
+#include <jni.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+JNIEXPORT jobject JNICALL
+Java_org_oic_simulator_SimulatorManagerNativeInterface_createResource
+(JNIEnv *env, jclass object, jstring jConfigPath, jobject jListener);
+
+JNIEXPORT jobjectArray JNICALL
+Java_org_oic_simulator_SimulatorManagerNativeInterface_createResources
+(JNIEnv *env, jclass object, jstring jConfigPath, jint count, jobject jListener);
+
+JNIEXPORT jobjectArray JNICALL
+Java_org_oic_simulator_SimulatorManageNativeInterface_getResources
+(JNIEnv *env, jclass object);
+
+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_setLogger
+(JNIEnv *env, jclass object, jobject logger);
+
+JNIEXPORT jint JNICALL
+Java_org_oic_simulator_SimulatorManagerNativeInterface_findResource
+(JNIEnv *env, jobject interfaceObject, jstring jResourceType, jobject jListener);
+
+JNIEXPORT jobject JNICALL
+Java_org_oic_simulator_SimulatorManagerNativeInterface_getFoundResources
+(JNIEnv *env, jobject interfaceObject, jstring jResourceType);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif //SIMULATOR_MANAGER_JNI_H_
diff --git a/service/simulator/java/jni/simulator_remote_resource_jni.cpp b/service/simulator/java/jni/simulator_remote_resource_jni.cpp
new file mode 100644 (file)
index 0000000..e0fddca
--- /dev/null
@@ -0,0 +1,544 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "simulator_remote_resource_jni.h"
+#include "simulator_common_jni.h"
+#include "simulator_error_codes.h"
+#include "simulator_resource_jni_util.h"
+#include "simulator_resource_model_jni.h"
+
+extern SimulatorClassRefs gSimulatorClassRefs;
+
+SimulatorRemoteResourcePtr JniSimulatorRemoteResource::getResourceHandle
+(JNIEnv *env, jobject object)
+{
+    JniSimulatorRemoteResource *jniResource = GetHandle<JniSimulatorRemoteResource>(env, object);
+    if (env->ExceptionCheck() || !jniResource)
+    {
+        return nullptr;
+    }
+
+    return jniResource->m_resource;
+}
+
+class JNIOnObserveListener
+{
+    public:
+        void setJavaOnObserveListener(JNIEnv *env, jobject listener)
+        {
+            m_listener = env->NewWeakGlobalRef(listener);
+        }
+
+        void onObserveCallback(const int eCode,
+                               const SimulatorResourceModel &representation,
+                               const int sequenceNumber)
+        {
+            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 != eCode && OC_STACK_RESOURCE_CREATED != eCode
+                && OC_STACK_RESOURCE_DELETED != eCode)
+            {
+                jmethodID midL = env->GetMethodID(onObserveCls, "onObserveFailed", "(Ljava/lang/Throwable;)V");
+                if (!midL)
+                {
+                    releaseEnv();
+                    return;
+                }
+                env->CallVoidMethod(onObserveListener, midL);
+            }
+            else
+            {
+                SimulatorResourceModel *rep = new SimulatorResourceModel(representation);
+                jlong handle = reinterpret_cast<jlong>(rep);
+                jobject jRepresentation = env->NewObject(gSimulatorClassRefs.classSimulatorResourceModel,
+                                          gSimulatorClassRefs.classSimulatorResourceModelId, handle, true);
+                if (!jRepresentation)
+                {
+                    releaseEnv();
+                    return;
+                }
+
+                jmethodID midL = env->GetMethodID(onObserveCls, "onObserveCompleted",
+                                                  "(Lorg/oic/simulator/SimulatorResourceModel;I)V");
+                if (!midL)
+                {
+                    releaseEnv();
+                    return;
+                }
+
+                env->CallVoidMethod(onObserveListener, midL, jRepresentation,
+                                    static_cast<jint>(sequenceNumber));
+                if (env->ExceptionCheck())
+                {
+                    releaseEnv();
+                }
+            }
+        }
+
+    private:
+        jweak m_listener;
+};
+
+class JNIOnGetListener
+{
+    public:
+        void setJavaOnGetListener(JNIEnv *env, jobject listener)
+        {
+            m_listener = env->NewWeakGlobalRef(listener);
+        }
+
+        void onGetCallback(const int eCode,
+                           const SimulatorResourceModel &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;
+            }
+
+            if (OC_STACK_OK != eCode && OC_STACK_RESOURCE_CREATED != eCode
+                && OC_STACK_RESOURCE_DELETED != eCode)
+            {
+                jmethodID midL = env->GetMethodID(onGetCls, "onGetFailed", "(Ljava/lang/Throwable;)V");
+                if (!midL)
+                {
+                    releaseEnv();
+                    return;
+                }
+                env->CallVoidMethod(onGetListener, midL);
+            }
+            else
+            {
+                SimulatorResourceModel *rep = new SimulatorResourceModel(representation);
+                jlong handle = reinterpret_cast<jlong>(rep);
+                jobject jRepresentation = env->NewObject(gSimulatorClassRefs.classSimulatorResourceModel,
+                                          gSimulatorClassRefs.classSimulatorResourceModelId, handle, true);
+                if (!jRepresentation)
+                {
+                    releaseEnv();
+                    return;
+                }
+
+                jmethodID midL = env->GetMethodID(onGetCls, "onGetCompleted",
+                                                  "(Lorg/oic/simulator/SimulatorResourceModel;)V");
+                if (!midL)
+                {
+                    releaseEnv();
+                    return;
+                }
+
+                env->CallVoidMethod(onGetListener, midL, jRepresentation);
+                if (env->ExceptionCheck())
+                {
+                    releaseEnv();
+                }
+            }
+        }
+
+    private:
+        jweak m_listener;
+};
+
+class JNIOnPutListener
+{
+    public:
+        void setJavaOnPutListener(JNIEnv *env, jobject listener)
+        {
+            m_listener = env->NewWeakGlobalRef(listener);
+        }
+
+        void onPutCallback(const int eCode,
+                           const SimulatorResourceModel &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;
+            }
+
+            if (OC_STACK_OK != eCode && OC_STACK_RESOURCE_CREATED != eCode
+                && OC_STACK_RESOURCE_DELETED != eCode)
+            {
+                jmethodID midL = env->GetMethodID(onGetCls, "onPutFailed", "(Ljava/lang/Throwable;)V");
+                if (!midL)
+                {
+                    releaseEnv();
+                    return;
+                }
+                env->CallVoidMethod(onPutListener, midL);
+            }
+            else
+            {
+                SimulatorResourceModel *rep = new SimulatorResourceModel(representation);
+                jlong handle = reinterpret_cast<jlong>(rep);
+                jobject jRepresentation = env->NewObject(gSimulatorClassRefs.classSimulatorResourceModel,
+                                          gSimulatorClassRefs.classSimulatorResourceModelId, handle, true);
+                if (!jRepresentation)
+                {
+                    releaseEnv();
+                    return;
+                }
+
+                jmethodID midL = env->GetMethodID(onGetCls, "onPutCompleted",
+                                                  "(Lorg/oic/simulator/SimulatorResourceModel;)V");
+                if (!midL)
+                {
+                    releaseEnv();
+                    return;
+                }
+
+                env->CallVoidMethod(onPutListener, midL, jRepresentation);
+                if (env->ExceptionCheck())
+                {
+                    releaseEnv();
+                }
+            }
+        }
+
+    private:
+        jweak m_listener;
+};
+
+class JNIOnPostListener
+{
+    public:
+        void setJavaOnPostListener(JNIEnv *env, jobject listener)
+        {
+            m_listener = env->NewWeakGlobalRef(listener);
+        }
+
+        void onPostCallback(const int eCode,
+                            const SimulatorResourceModel &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;
+            }
+
+            if (OC_STACK_OK != eCode && OC_STACK_RESOURCE_CREATED != eCode
+                && OC_STACK_RESOURCE_DELETED != eCode)
+            {
+                jmethodID midL = env->GetMethodID(onGetCls, "onPostFailed", "(Ljava/lang/Throwable;)V");
+                if (!midL)
+                {
+                    releaseEnv();
+                    return;
+                }
+                env->CallVoidMethod(onPostListener, midL);
+            }
+            else
+            {
+                SimulatorResourceModel *rep = new SimulatorResourceModel(representation);
+                jlong handle = reinterpret_cast<jlong>(rep);
+                jobject jRepresentation = env->NewObject(gSimulatorClassRefs.classSimulatorResourceModel,
+                                          gSimulatorClassRefs.classSimulatorResourceModelId, handle, true);
+                if (!jRepresentation)
+                {
+                    releaseEnv();
+                    return;
+                }
+
+                jmethodID midL = env->GetMethodID(onGetCls, "onPostCompleted",
+                                                  "(Lorg/oic/simulator/SimulatorResourceModel;)V");
+                if (!midL)
+                {
+                    releaseEnv();
+                    return;
+                }
+
+                env->CallVoidMethod(onPostListener, midL, jRepresentation);
+                if (env->ExceptionCheck())
+                {
+                    releaseEnv();
+                }
+            }
+        }
+
+    private:
+        jweak m_listener;
+
+};
+
+
+JNIEXPORT jint JNICALL
+Java_org_oic_simulator_SimulatorRemoteResource_observe
+(JNIEnv *env, jobject thiz, jint observeType, jobject jQueryParamsMap, jobject jListener)
+{
+    if (!jListener)
+        return SIMULATOR_BAD_INPUT;
+
+    SimulatorRemoteResourcePtr resource = JniSimulatorRemoteResource::getResourceHandle(env,
+                                           thiz);
+    if (nullptr == resource)
+        return SIMULATOR_RESOURCE_NOT_FOUND;
+
+    std::map<std::string, std::string> queryParams;
+    if (jQueryParamsMap)
+        convertJavaMapToQueryParamsMap(env, jQueryParamsMap, queryParams);
+
+    SimulatorRemoteResource::ObserveType type = SimulatorRemoteResource::OBSERVE;
+    if (1 == observeType)
+        type = SimulatorRemoteResource::OBSERVE_ALL;
+
+    JNIOnObserveListener *onObserveListener = new JNIOnObserveListener();
+    onObserveListener->setJavaOnObserveListener(env, jListener);
+
+    return resource->observe(type, queryParams,
+                                                std::bind(&JNIOnObserveListener::onObserveCallback,
+                                                onObserveListener, std::placeholders::_1,
+                                                std::placeholders::_2, std::placeholders::_3));
+}
+
+JNIEXPORT jint JNICALL
+Java_org_oic_simulator_SimulatorRemoteResource_cancelObserve
+(JNIEnv *env, jobject thiz)
+{
+    SimulatorRemoteResourcePtr resource = JniSimulatorRemoteResource::getResourceHandle(env,
+                                           thiz);
+    if (nullptr == resource)
+        return SIMULATOR_RESOURCE_NOT_FOUND;
+
+    return resource->cancelObserve();
+}
+
+JNIEXPORT jint JNICALL
+Java_org_oic_simulator_SimulatorRemoteResource_get
+(JNIEnv *env, jobject thiz, jstring jResourceType, jstring jResourceInterface,
+ jobject jQueryParamsMap, jobject jListener)
+{
+    if (!jListener)
+        return SIMULATOR_BAD_INPUT;
+
+    SimulatorRemoteResourcePtr resource = JniSimulatorRemoteResource::getResourceHandle(env,
+                                           thiz);
+    if (nullptr == resource)
+        return SIMULATOR_RESOURCE_NOT_FOUND;
+
+    // Resource type
+    const char *typeCStr = NULL;
+    std::string resourceType;
+    if (jResourceType)
+    {
+        typeCStr = env->GetStringUTFChars(jResourceType, NULL);
+        resourceType = typeCStr;
+    }
+
+    // Interface type
+    const char *interfaceCStr = NULL;
+    std::string interfaceType;
+    if (jResourceInterface)
+    {
+        interfaceCStr = env->GetStringUTFChars(jResourceInterface, NULL);
+        interfaceType = interfaceCStr;
+    }
+
+    // Query parameters
+    std::map<std::string, std::string> queryParams;
+    if (jQueryParamsMap)
+        convertJavaMapToQueryParamsMap(env, jQueryParamsMap, queryParams);
+
+    // Create listener
+    JNIOnGetListener *onGetListener = new JNIOnGetListener();
+    onGetListener->setJavaOnGetListener(env, jListener);
+
+    SimulatorResult result = resource->get(resourceType, interfaceType,
+                                            queryParams,
+                                            std::bind(&JNIOnGetListener::onGetCallback,
+                                            onGetListener, std::placeholders::_1,
+                                            std::placeholders::_2));
+
+    if (typeCStr)
+        env->ReleaseStringUTFChars(jResourceType, typeCStr);
+
+    if (interfaceCStr)
+        env->ReleaseStringUTFChars(jResourceInterface, interfaceCStr);
+
+    return result;
+}
+
+JNIEXPORT jint JNICALL
+Java_org_oic_simulator_SimulatorRemoteResource_put
+(JNIEnv *env, jobject thiz, jstring jResourceType, jstring jResourceInterface,
+ jobject jRepresentation, jobject jQueryParamsMap, jobject jListener)
+{
+    if (!jListener)
+        return SIMULATOR_BAD_INPUT;
+
+    SimulatorRemoteResourcePtr resource = JniSimulatorRemoteResource::getResourceHandle(env,
+                                           thiz);
+    if (nullptr == resource)
+        return SIMULATOR_RESOURCE_NOT_FOUND;
+
+    // Resource type
+    const char *typeCStr = NULL;
+    std::string resourceType;
+    if (jResourceType)
+    {
+        typeCStr = env->GetStringUTFChars(jResourceType, NULL);
+        resourceType = typeCStr;
+    }
+
+    // Interface type
+    const char *interfaceCStr = NULL;
+    std::string interfaceType;
+    if (jResourceInterface)
+    {
+        interfaceCStr = env->GetStringUTFChars(jResourceInterface, NULL);
+        interfaceType = interfaceCStr;
+    }
+
+    // Query parameters
+    std::map<std::string, std::string> queryParams;
+    if (jQueryParamsMap)
+        convertJavaMapToQueryParamsMap(env, jQueryParamsMap, queryParams);
+
+    SimulatorResourceModel resourceModel;
+    JniSimulatorResourceModel::getResourceModel(env, jRepresentation, resourceModel);
+
+    // Create listener
+    JNIOnPutListener *onPutListener = new JNIOnPutListener();
+    onPutListener->setJavaOnPutListener(env, jListener);
+
+    SimulatorResult result = resource->put(resourceType, interfaceType,
+                                            resourceModel, queryParams,
+                                            std::bind(&JNIOnPutListener::onPutCallback,
+                                            onPutListener, std::placeholders::_1,
+                                            std::placeholders::_2));
+
+    if (typeCStr)
+        env->ReleaseStringUTFChars(jResourceType, typeCStr);
+
+    if (interfaceCStr)
+        env->ReleaseStringUTFChars(jResourceInterface, interfaceCStr);
+
+    return result;
+}
+
+JNIEXPORT jint JNICALL
+Java_org_oic_simulator_SimulatorRemoteResource_post
+(JNIEnv *env, jobject thiz, jstring jResourceType, jstring jResourceInterface,
+ jobject jRepresentation, jobject jQueryParamsMap, jobject jListener)
+{
+    if (!jListener)
+        return SIMULATOR_BAD_INPUT;
+
+    SimulatorRemoteResourcePtr resource = JniSimulatorRemoteResource::getResourceHandle(env,
+                                           thiz);
+    if (nullptr == resource)
+        return SIMULATOR_RESOURCE_NOT_FOUND;
+
+    // Resource type
+    const char *typeCStr = NULL;
+    std::string resourceType;
+    if (jResourceType)
+    {
+        typeCStr = env->GetStringUTFChars(jResourceType, NULL);
+        resourceType = typeCStr;
+    }
+
+    // Interface type
+    const char *interfaceCStr = NULL;
+    std::string interfaceType;
+    if (jResourceInterface)
+    {
+        interfaceCStr = env->GetStringUTFChars(jResourceInterface, NULL);
+        interfaceType = interfaceCStr;
+    }
+
+    // Query parameters
+    std::map<std::string, std::string> queryParams;
+    if (jQueryParamsMap)
+        convertJavaMapToQueryParamsMap(env, jQueryParamsMap, queryParams);
+
+    SimulatorResourceModel resourceModel;
+    JniSimulatorResourceModel::getResourceModel(env, jRepresentation, resourceModel);
+
+    // Create listener
+    JNIOnPostListener *onPostListener = new JNIOnPostListener();
+    onPostListener->setJavaOnPostListener(env, jListener);
+
+    SimulatorResult result = resource->post(resourceType, interfaceType,
+                                            resourceModel, queryParams,
+                                            std::bind(&JNIOnPostListener::onPostCallback,
+                                            onPostListener, std::placeholders::_1,
+                                            std::placeholders::_2));
+
+    if (typeCStr)
+        env->ReleaseStringUTFChars(jResourceType, typeCStr);
+
+    if (interfaceCStr)
+        env->ReleaseStringUTFChars(jResourceInterface, interfaceCStr);
+
+    return result;
+}
+
diff --git a/service/simulator/java/jni/simulator_remote_resource_jni.h b/service/simulator/java/jni/simulator_remote_resource_jni.h
new file mode 100644 (file)
index 0000000..8439f43
--- /dev/null
@@ -0,0 +1,70 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#ifndef SIMULATOR_REMOTE_RESOURCE_JNI_H_
+#define SIMULATOR_REMOTE_RESOURCE_JNI_H_
+
+#include <jni.h>
+#include "simulator_remote_resource.h"
+
+class JniSimulatorRemoteResource
+{
+    public:
+        JniSimulatorRemoteResource(SimulatorRemoteResourcePtr &resource)
+        : m_resource(resource) {};
+        static SimulatorRemoteResourcePtr getResourceHandle(JNIEnv *env, jobject object);
+    private:
+        SimulatorRemoteResourcePtr m_resource;
+};
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+JNIEXPORT jint JNICALL
+Java_org_oic_simulator_SimulatorRemoteResource_observe
+(JNIEnv *env, jobject thiz, jint observeType, jobject jQueryParamsMap, jobject jListener);
+
+JNIEXPORT jint JNICALL
+Java_org_oic_simulator_SimulatorRemoteResource_cancelObserve
+(JNIEnv *env, jobject thiz);
+
+JNIEXPORT jint JNICALL
+Java_org_oic_simulator_SimulatorRemoteResource_get
+(JNIEnv *env, jobject thiz, jstring jResourceType, jstring jResourceInterface,
+ jobject jQueryParamsMap, jobject jListener);
+
+JNIEXPORT jint JNICALL
+Java_org_oic_simulator_SimulatorRemoteResource_put
+(JNIEnv *env, jobject thiz, jstring jResourceType, jstring jResourceInterface,
+ jobject jRepresentation, jobject jQueryParamsMap, jobject jListener);
+
+JNIEXPORT jint JNICALL
+Java_org_oic_simulator_SimulatorRemoteResource_post
+(JNIEnv *env, jobject thiz, jstring jResourceType, jstring jResourceInterface,
+ jobject jRepresentation, jobject jQueryParamsMap, jobject jListener);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
diff --git a/service/simulator/java/jni/simulator_resource_attributes_jni.cpp b/service/simulator/java/jni/simulator_resource_attributes_jni.cpp
new file mode 100644 (file)
index 0000000..62241de
--- /dev/null
@@ -0,0 +1,174 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "simulator_resource_attributes_jni.h"
+#include "simulator_resource_model.h"
+#include "simulator_common_jni.h"
+#include "simulator_error_codes.h"
+
+extern SimulatorClassRefs gSimulatorClassRefs;
+
+jobject JniSimulatorResourceAttribute::toJava(JNIEnv *env, jlong resource)
+{
+    jobject resourceObj = (jobject) env->NewObject(gSimulatorClassRefs.classSimulatorResourceAttribute,
+                          gSimulatorClassRefs.classSimulatorResourceAttributeCtor, resource);
+    if (NULL == resourceObj)
+    {
+        return NULL;
+    }
+
+    return resourceObj;
+}
+
+class attribute_value_visitor : public boost::static_visitor<jobject>
+{
+    public:
+        attribute_value_visitor(JNIEnv *env) : m_Env(env) {}
+
+        jobject operator ()(const int &value) const
+        {
+            jobject result = m_Env->NewObject(gSimulatorClassRefs.classInteger,
+                                              gSimulatorClassRefs.classIntegerCtor, value);
+            return result;
+        }
+
+        jobject operator ()(const double &value) const
+        {
+            jobject result = m_Env->NewObject(gSimulatorClassRefs.classDouble,
+                                              gSimulatorClassRefs.classDoubleCtor, value);
+            return result;
+        }
+
+        jobject operator ()(const std::string &value) const
+        {
+            jstring str = m_Env->NewStringUTF(value.c_str());
+            return static_cast<jobject>(str);
+        }
+
+    private:
+        JNIEnv *m_Env;
+};
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_SimulatorResourceAttribute_create
+(JNIEnv *env, jobject object, jstring attrName)
+{
+    if (!attrName)
+    {
+        std::cout << "SimulatorResourceAttribute_create: AttributeName is Empty";
+        return;
+    }
+
+    const char *attrNamePtr = env->GetStringUTFChars(attrName, NULL);
+    if (!attrNamePtr)
+        return;
+
+    std::string attrNameStr(attrNamePtr);
+    SimulatorResourceModel::Attribute *attribute = new SimulatorResourceModel::Attribute(attrNameStr);
+    SetHandle<SimulatorResourceModel::Attribute>(env, object, attribute);
+    if (env->ExceptionCheck())
+    {
+        delete attribute;
+    }
+
+    env->ReleaseStringUTFChars(attrName, attrNamePtr);
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_SimulatorResourceAttribute_dispose
+(JNIEnv *env, jobject object)
+{
+    SimulatorResourceModel::Attribute *attribute = GetHandle<SimulatorResourceModel::Attribute>(env,
+            object);
+    delete attribute;
+}
+
+JNIEXPORT int JNICALL
+Java_org_oic_simulator_SimulatorResourceAttribute_allowedValuesSize
+(JNIEnv *env, jobject object)
+{
+    SimulatorResourceModel::Attribute *attribute = GetHandle<SimulatorResourceModel::Attribute>(env,
+            object);
+    if (env->ExceptionCheck() || !attribute)
+    {
+        return SIMULATOR_ERROR;
+    }
+
+    return attribute->getAllowedValuesSize();
+}
+
+JNIEXPORT jstring JNICALL
+Java_org_oic_simulator_SimulatorResourceAttribute_valueToString
+(JNIEnv *env, jobject object)
+{
+    SimulatorResourceModel::Attribute *attribute = GetHandle<SimulatorResourceModel::Attribute>(env,
+            object);
+    if (env->ExceptionCheck() || !attribute)
+    {
+        return NULL;
+    }
+
+    std::string str = attribute->valueToString();
+    return env->NewStringUTF(str.c_str());
+}
+
+JNIEXPORT jstring JNICALL
+Java_org_oic_simulator_SimulatorResourceAttribute_allowedValuesToString
+(JNIEnv *env, jobject object)
+{
+    SimulatorResourceModel::Attribute *attribute = GetHandle<SimulatorResourceModel::Attribute>(env,
+            object);
+    if (env->ExceptionCheck() || !attribute)
+    {
+        return NULL;
+    }
+
+    std::string str = attribute->allowedValuesToString();
+    return env->NewStringUTF(str.c_str());
+}
+
+JNIEXPORT jstring JNICALL
+Java_org_oic_simulator_SimulatorResourceAttribute_getName
+(JNIEnv *env, jobject object)
+{
+    SimulatorResourceModel::Attribute *attribute = GetHandle<SimulatorResourceModel::Attribute>(env,
+            object);
+    if (env->ExceptionCheck() || !attribute)
+    {
+        return NULL;
+    }
+
+    std::string str = attribute->getName();
+    return env->NewStringUTF(str.c_str());
+}
+
+JNIEXPORT jobject JNICALL
+Java_org_oic_simulator_SimulatorResourceAttribute_getValue
+(JNIEnv *env, jobject object)
+{
+    SimulatorResourceModel::Attribute *attribute = GetHandle<SimulatorResourceModel::Attribute>(env,
+            object);
+    if (env->ExceptionCheck() || !attribute)
+    {
+        return NULL;
+    }
+
+    return boost::apply_visitor(attribute_value_visitor(env), attribute->getValue());
+}
\ No newline at end of file
diff --git a/service/simulator/java/jni/simulator_resource_attributes_jni.h b/service/simulator/java/jni/simulator_resource_attributes_jni.h
new file mode 100644 (file)
index 0000000..df7d2d5
--- /dev/null
@@ -0,0 +1,69 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#ifndef SIMULATOR_RESOURCE_ATTRIBUTE_JNI_H_
+#define SIMULATOR_RESOURCE_ATTRIBUTE_JNI_H_
+
+#include <jni.h>
+#include "simulator_resource_model.h"
+
+class JniSimulatorResourceAttribute
+{
+    public:
+        static jobject toJava(JNIEnv *env, jlong resource);
+};
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_SimulatorResourceAttribute_create
+(JNIEnv *, jobject, jstring);
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_SimulatorResourceAttribute_dispose
+(JNIEnv *, jobject);
+
+JNIEXPORT int JNICALL
+Java_org_oic_simulator_SimulatorResourceAttribute_allowedValuesSize
+(JNIEnv *, jobject);
+
+JNIEXPORT jstring JNICALL
+Java_org_oic_simulator_SimulatorResourceAttribute_valueToString
+(JNIEnv *, jobject);
+
+JNIEXPORT jstring JNICALL
+Java_org_oic_simulator_SimulatorResourceAttribute_allowedValuesToString
+(JNIEnv *, jobject);
+
+JNIEXPORT jstring JNICALL
+Java_org_oic_simulator_SimulatorResourceAttribute_getName
+(JNIEnv *, jobject);
+
+JNIEXPORT jobject JNICALL
+Java_org_oic_simulator_SimulatorResourceAttribute_getValue
+(JNIEnv *, jobject);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif //SIMULATOR_RESOURCE_ATTRIBUTE_JNI_H_
diff --git a/service/simulator/java/jni/simulator_resource_jni_util.cpp b/service/simulator/java/jni/simulator_resource_jni_util.cpp
new file mode 100644 (file)
index 0000000..802aa33
--- /dev/null
@@ -0,0 +1,168 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+#include "simulator_resource_jni_util.h"
+#include "simulator_common_jni.h"
+
+extern SimulatorClassRefs gSimulatorClassRefs;
+
+std::vector<int> convertIntegerVector(JNIEnv *env, jobject jVectorInt)
+{
+    std::vector<int> vectorInt;
+
+    jclass vectorClass = env->FindClass("java/util/Vector");
+    if (!vectorClass)
+    {
+        return vectorInt;
+    }
+
+    jmethodID size = env->GetMethodID(vectorClass, "size", "()I");
+    if (NULL == size)
+    {
+        return vectorInt;
+    }
+
+    jmethodID get = env->GetMethodID(vectorClass, "get", "(I)""Ljava/lang/Object;");
+    if (NULL == get)
+    {
+        return vectorInt;
+    }
+
+    jint jSize = env->CallIntMethod(jVectorInt, size);
+    int sizeOfVector = jSize;
+
+    for (int index = 0; index < sizeOfVector; index++)
+    {
+        jint jIndex = index;
+        jint jValue = env->CallIntMethod(jVectorInt, get, jIndex);
+        vectorInt.push_back((int)jValue);
+    }
+
+    return vectorInt;
+}
+
+std::vector<double> convertDoubleVector(JNIEnv *env, jobject jVectorDouble)
+{
+    std::vector<double> vectorDouble;
+
+    jclass vectorClass = env->FindClass("java/util/Vector");
+    if (!vectorClass)
+    {
+        return vectorDouble;
+    }
+
+    jmethodID size = env->GetMethodID(vectorClass, "size", "()I");
+    if (NULL == size)
+    {
+        return vectorDouble;
+    }
+
+    jmethodID get = env->GetMethodID(vectorClass, "get", "(I)""Ljava/lang/Object;");
+    if (NULL == get)
+    {
+        return vectorDouble;
+    }
+
+    jint jSize = env->CallIntMethod(jVectorDouble, size);
+    int sizeOfVector = jSize;
+
+    for (int index = 0; index < sizeOfVector; index++)
+    {
+        jint jIndex = index;
+        jdouble jValue = env->CallDoubleMethod(jVectorDouble, get, jIndex);
+        vectorDouble.push_back((double)jValue);
+    }
+
+    return vectorDouble;
+}
+
+std::vector<std::string> convertStringVector(JNIEnv *env, jobject jVectorString)
+{
+    std::vector<std::string> vectorString;
+
+    jclass vectorClass = env->FindClass("java/util/Vector");
+    if (!vectorClass)
+    {
+        return vectorString;
+    }
+
+    jmethodID size = env->GetMethodID(vectorClass, "size", "()I");
+    if (NULL == size)
+    {
+        return vectorString;
+    }
+
+    jmethodID get = env->GetMethodID(vectorClass, "get", "(I)""Ljava/lang/Object;");
+    if (NULL == get)
+    {
+        return vectorString;
+    }
+
+    jint jSize = env->CallIntMethod(jVectorString, size);
+    int sizeOfVector = jSize;
+
+    for (int index = 0; index < sizeOfVector; index++)
+    {
+        jint jIndex = index;
+        jstring jContactInfoObj = (jstring)env->CallObjectMethod(jVectorString, get, jIndex);
+        if (jContactInfoObj == NULL)
+        {
+            return vectorString;
+        }
+        const char *buff = env->GetStringUTFChars(jContactInfoObj, 0);
+        if (NULL != buff)
+        {
+            std::string tempString = buff;
+            vectorString.push_back(tempString);
+        }
+
+        env->ReleaseStringUTFChars(jContactInfoObj, buff);
+    }
+
+    return vectorString;
+}
+
+void convertJavaMapToQueryParamsMap(JNIEnv *env, jobject hashMap,
+                                    std::map<std::string, std::string> &queryParams)
+{
+    if (!hashMap) return;
+
+    jobject jEntrySet = env->CallObjectMethod(hashMap, gSimulatorClassRefs.classMapEntrySet);
+    jobject jIterator = env->CallObjectMethod(jEntrySet, gSimulatorClassRefs.classIteratorId);
+    if (!jEntrySet || !jIterator || env->ExceptionCheck()) return;
+
+    while (env->CallBooleanMethod(jIterator, gSimulatorClassRefs.classHasNextId))
+    {
+        jobject jEntry = env->CallObjectMethod(jIterator, gSimulatorClassRefs.classNextId);
+        if (!jEntry) return;
+        jstring jKey = (jstring)env->CallObjectMethod(jEntry, gSimulatorClassRefs.classMapGetKey);
+        if (!jKey) return;
+        jstring jValue = (jstring)env->CallObjectMethod(jEntry, gSimulatorClassRefs.classMapGetValue);
+        if (!jValue) return;
+
+        queryParams.insert(std::make_pair(env->GetStringUTFChars(jKey, NULL),
+                                  env->GetStringUTFChars(jValue, NULL)));
+
+        if (env->ExceptionCheck()) return;
+        env->DeleteLocalRef(jEntry);
+        env->DeleteLocalRef(jKey);
+        env->DeleteLocalRef(jValue);
+    }
+}
+
diff --git a/service/simulator/java/jni/simulator_resource_jni_util.h b/service/simulator/java/jni/simulator_resource_jni_util.h
new file mode 100644 (file)
index 0000000..3beb49b
--- /dev/null
@@ -0,0 +1,72 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file   simulator_resource_jni_util.h
+ *
+ * @brief  This file contains the utility functions for conversions from java to CPP
+ * and viceversa
+ */
+
+#ifndef __SIMULATOR_RESOURCE_JNI_UTIL_H_
+#define __SIMULATOR_RESOURCE_JNI_UTIL_H_
+
+#include <jni.h>
+#include <iostream>
+#include <vector>
+#include <map>
+
+#include "simulator_remote_resource.h"
+
+/**
+  * Utility function for converting a Java Vector of Strings to CPP Vector of Strings
+  *
+  * @param env - Default JNI Environment pointer
+  * @param jVectorString - Java Vector of Strings
+  *
+  * @return void
+  */
+std::vector<int> convertIntegerVector(JNIEnv *env, jobject jVectorInt);
+
+/**
+  * Utility function for converting a Java Vector of Strings to CPP Vector of Strings
+  *
+  * @param env - Default JNI Environment pointer
+  * @param jVectorString - Java Vector of Strings
+  *
+  * @return void
+  */
+std::vector<double> convertDoubleVector(JNIEnv *env, jobject jVectorDouble);
+
+/**
+  * Utility function for converting a Java Vector of Strings to CPP Vector of Strings
+  *
+  * @param env - Default JNI Environment pointer
+  * @param jVectorString - Java Vector of Strings
+  *
+  * @return void
+  */
+std::vector<std::string> convertStringVector(JNIEnv *env, jobject jVectorString);
+
+void convertJavaMapToQueryParamsMap(JNIEnv *env, jobject hashMap,
+                            std::map<std::string, std::string> &map);
+
+#endif //__SIMULATOR_RESOURCE_JNI_UTIL_H_
+
diff --git a/service/simulator/java/jni/simulator_resource_model_jni.cpp b/service/simulator/java/jni/simulator_resource_model_jni.cpp
new file mode 100644 (file)
index 0000000..b886d39
--- /dev/null
@@ -0,0 +1,234 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "simulator_resource_model_jni.h"
+#include "simulator_common_jni.h"
+#include "simulator_resource_attributes_jni.h"
+#include "simulator_error_codes.h"
+
+using namespace std;
+
+extern SimulatorClassRefs gSimulatorClassRefs;
+
+JniSimulatorResourceModel::JniSimulatorResourceModel(SimulatorResourceModel resourceModel)
+    : m_resourceModel(resourceModel)
+{}
+
+bool JniSimulatorResourceModel::getResourceModel(JNIEnv *env, jobject thiz,
+        SimulatorResourceModel &resourceModel)
+{
+    JniSimulatorResourceModel *resource = GetHandle<JniSimulatorResourceModel>(env, thiz);
+    if (env->ExceptionCheck())
+    {
+        cout << "Exception while converting the nativeHandle to JniSimulatorResourceModel" << endl;
+        return false;
+    }
+    resourceModel = resource->m_resourceModel;
+    return true;
+}
+
+jobject JniSimulatorResourceModel::toJava(JNIEnv *env, jlong resource)
+{
+    jobject resourceObj = (jobject) env->NewObject(gSimulatorClassRefs.classSimulatorResourceModel,
+                          gSimulatorClassRefs.classSimulatorResourceModelCtor, resource);
+    if (!resourceObj)
+    {
+        return NULL;
+    }
+    return resourceObj;
+}
+
+static jobject createHashMap(JNIEnv *env)
+{
+    jobject mapobj = env->NewObject(gSimulatorClassRefs.classHashMap,
+                                    gSimulatorClassRefs.classHashMapCtor);
+    return mapobj;
+}
+
+static void addEntryToHashMap(JNIEnv *env, jobject mapobj, jobject key, jobject value)
+{
+    if (!mapobj || !key || !value)
+    {
+        return;
+    }
+
+    env->CallObjectMethod(mapobj, gSimulatorClassRefs.classHashMapPut, key, value);
+}
+
+JNIEXPORT jint JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceModel_size
+(JNIEnv *env, jobject thiz)
+{
+    SimulatorResourceModel resourceModel;
+    bool result = JniSimulatorResourceModel::getResourceModel(env, thiz, resourceModel);
+    if (!result)
+    {
+        return SIMULATOR_ERROR;
+    }
+
+    return resourceModel.size();
+}
+
+JNIEXPORT jobject JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceModel_getAttributes
+(JNIEnv *env, jobject thiz)
+{
+    SimulatorResourceModel resourceModel;
+    bool result = JniSimulatorResourceModel::getResourceModel(env, thiz, resourceModel);
+    if (!result)
+    {
+        return NULL;
+    }
+
+    map<string, SimulatorResourceModel::Attribute> attributesMap = resourceModel.getAttributes();
+
+    // Create Java HashMap object
+    jobject jHashMap = NULL;
+    jHashMap = createHashMap(env);
+    if (!jHashMap)
+    {
+        return NULL;
+    }
+
+    for (auto & attributeEntry : attributesMap)
+    {
+
+        // Create JniSimulatorResourceAttribute object and put the attribute.second into it
+        SimulatorResourceModel::Attribute *attribute = new SimulatorResourceModel::Attribute(
+            attributeEntry.second);
+
+        // Create a java object for SimulatorResourceAttribute
+        jobject jAttribute = JniSimulatorResourceAttribute::toJava(env, reinterpret_cast<jlong>(attribute));
+
+        // Add an entry with attribute.first and javaSimualatorResourceAttribute to the HashMap
+        jstring jAttrName = env->NewStringUTF((attributeEntry.first).c_str());
+        addEntryToHashMap(env, jHashMap, static_cast<jobject>(jAttrName), jAttribute);
+        env->DeleteLocalRef(jAttrName);
+    }
+    return jHashMap;
+}
+
+JNIEXPORT jobject JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceModel_getAttribute
+(JNIEnv *env, jobject thiz, jstring jAttrName)
+{
+    if (!jAttrName)
+    {
+        std::cout << "getAttribute: AttributeName is Empty";
+        return NULL;
+    }
+
+    const char *attrName = env->GetStringUTFChars(jAttrName, NULL);
+    if (!attrName)
+    {
+        std::cout << "getAttribute: Failed to convert jstring to char string!";
+        return NULL;
+    }
+
+    SimulatorResourceModel resourceModel;
+    bool result = JniSimulatorResourceModel::getResourceModel(env, thiz, resourceModel);
+    if (!result)
+    {
+        std::cout << "getAttribute: getResourceModel failed!";
+        env->ReleaseStringUTFChars(jAttrName, attrName);
+        return NULL;
+    }
+
+    SimulatorResourceModel::Attribute *attribute = new SimulatorResourceModel::Attribute();
+    bool found = resourceModel.getAttribute(attrName, *attribute);
+    if (!found)
+    {
+        std::cout << "getAttribute: Attribute not found in ResourceModel!";
+        env->ReleaseStringUTFChars(jAttrName, attrName);
+        delete attribute;
+        return NULL;
+    }
+
+    env->ReleaseStringUTFChars(jAttrName, attrName);
+
+    // Create a java object for SimulatorResourceAttribute
+    jobject jsimulatorResourceAttribute = JniSimulatorResourceAttribute::toJava(env,
+                                          reinterpret_cast<jlong>(attribute));
+    return jsimulatorResourceAttribute;
+}
+
+JNIEXPORT jobjectArray JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceModel_getAllowedValues
+(JNIEnv *env, jobject thiz, jstring jAttrName)
+{
+    if (!jAttrName)
+    {
+        std::cout << "getAllowedValues: AttributeName is Empty";
+        return NULL;
+    }
+
+    const char *attrName = env->GetStringUTFChars(jAttrName, NULL);
+    if (!attrName)
+    {
+        std::cout << "getAllowedValues: Failed to convert jstring to char string!";
+        env->ReleaseStringUTFChars(jAttrName, attrName);
+        return NULL;
+    }
+
+    SimulatorResourceModel resourceModel;
+    bool result = JniSimulatorResourceModel::getResourceModel(env, thiz, resourceModel);
+    if (!result)
+    {
+        std::cout << "getAllowedValues: getResourceModel failed!";
+        env->ReleaseStringUTFChars(jAttrName, attrName);
+        return NULL;
+    }
+
+    SimulatorResourceModel::Attribute *attribute = new SimulatorResourceModel::Attribute();
+    bool found = resourceModel.getAttribute(attrName, *attribute);
+    if (!found)
+    {
+        std::cout << "getAllowedValues: Attribute not found in ResourceModel!";
+        env->ReleaseStringUTFChars(jAttrName, attrName);
+        delete attribute;
+        return NULL;
+    }
+
+    env->ReleaseStringUTFChars(jAttrName, attrName);
+
+    std::vector<std::string> values = attribute->allowedValuesToVectorString();
+
+    int size = attribute->getAllowedValuesSize();
+
+    // Create a jObjectArray for AllowedValues vector.
+    jobjectArray allowedValuesArr = env->NewObjectArray(size, env->FindClass("java/lang/String"),
+                                    env->NewStringUTF(""));
+
+    int i = 0;
+    for (std::vector<std::string>::iterator it = values.begin(); it != values.end(); ++it, i++)
+    {
+        env->SetObjectArrayElement(allowedValuesArr, i, env->NewStringUTF((*it).c_str()));
+    }
+    return allowedValuesArr;
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceModel_dispose
+(JNIEnv *env, jobject thiz)
+{
+    JniSimulatorResourceModel *resourceModel = GetHandle<JniSimulatorResourceModel>(env, thiz);
+    delete resourceModel;
+}
+
diff --git a/service/simulator/java/jni/simulator_resource_model_jni.h b/service/simulator/java/jni/simulator_resource_model_jni.h
new file mode 100644 (file)
index 0000000..0100076
--- /dev/null
@@ -0,0 +1,69 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#ifndef SIMULATOR_RESOURCE_MODEL_JNI_H_
+#define SIMULATOR_RESOURCE_MODEL_JNI_H_
+
+#include <jni.h>
+#include "simulator_resource_model.h"
+
+class JniSimulatorResourceModel
+{
+
+    public:
+        JniSimulatorResourceModel(SimulatorResourceModel);
+
+        static jobject toJava(JNIEnv *, jlong);
+        static bool getResourceModel(JNIEnv *env, jobject thiz, SimulatorResourceModel &resourceModel);
+    private:
+        SimulatorResourceModel m_resourceModel;
+};
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+JNIEXPORT jint JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceModel_size
+(JNIEnv *, jobject);
+
+JNIEXPORT jobject JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceModel_getAttributes
+(JNIEnv *, jobject);
+
+JNIEXPORT jobject JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceModel_getAttribute
+(JNIEnv *, jobject, jstring);
+
+JNIEXPORT jobjectArray JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceModel_getAllowedValues
+(JNIEnv *, jobject, jstring);
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceModel_dispose
+(JNIEnv *, jobject);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/service/simulator/java/jni/simulator_resource_server_jni.cpp b/service/simulator/java/jni/simulator_resource_server_jni.cpp
new file mode 100644 (file)
index 0000000..bde0c52
--- /dev/null
@@ -0,0 +1,575 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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"
+
+extern SimulatorClassRefs gSimulatorClassRefs;
+
+JniSimulatorResource::JniSimulatorResource(SimulatorResourceServerPtr &resource)
+    : m_sharedResource(resource) {}
+
+SimulatorResourceServerPtr JniSimulatorResource::getJniSimulatorResourcePtr(JNIEnv *env,
+        jobject thiz)
+{
+    JniSimulatorResource *resource = GetHandle<JniSimulatorResource>(env, thiz);
+    if (env->ExceptionCheck())
+    {
+        return NULL;
+    }
+    return resource->m_sharedResource;
+}
+
+jobject JniSimulatorResource::toJava(JNIEnv *env, jlong resource)
+{
+    jobject resourceObj = (jobject) env->NewObject(gSimulatorClassRefs.classSimulatorResource,
+                          gSimulatorClassRefs.classSimulatorResourceCtor, resource);
+    if (NULL == resourceObj)
+    {
+        return NULL;
+    }
+    return resourceObj;
+}
+
+void JniSimulatorResource::setResourceInfo(JNIEnv *env, jobject jobj)
+{
+    if (!env || !jobj)
+        return;
+
+    std::string uri = m_sharedResource->getURI();
+    std::string resourceType = m_sharedResource->getResourceType();
+    std::string name = m_sharedResource->getName();
+    std::string interfaceType = m_sharedResource->getInterfaceType();
+
+    jstring jURI = env->NewStringUTF(uri.c_str());
+    if (jURI)
+    {
+        env->CallVoidMethod(jobj, gSimulatorClassRefs.classSimulatorResourceSetURI, jURI);
+        env->DeleteLocalRef(jURI);
+    }
+
+    jstring jResourceType = env->NewStringUTF(resourceType.c_str());
+    if (jResourceType)
+    {
+        env->CallVoidMethod(jobj, gSimulatorClassRefs.classSimulatorResourceSetResourceType, jResourceType);
+        env->DeleteLocalRef(jResourceType);
+    }
+
+    jstring jName = env->NewStringUTF(name.c_str());
+    if (jName)
+    {
+        env->CallVoidMethod(jobj, gSimulatorClassRefs.classSimulatorResourceSetName, jName);
+        env->DeleteLocalRef(jName);
+    }
+
+    jstring jInterfaceType = env->NewStringUTF(interfaceType.c_str());
+    if (jInterfaceType)
+    {
+        env->CallVoidMethod(jobj, gSimulatorClassRefs.classSimulatorResourceSetInterfaceType,
+                            jInterfaceType);
+        env->DeleteLocalRef(jInterfaceType);
+    }
+}
+
+void onAutomationComplete(jweak jlistenerRef, const std::string &uri,
+                          const int automationID)
+{
+    std::cout << "onAutomationComplete JNI entry" << std::endl;
+    JNIEnv *env = getEnv();
+    if (nullptr == env)
+        return;
+
+    jobject autoCompleteListener = env->NewLocalRef(jlistenerRef);
+    if (!autoCompleteListener)
+    {
+        releaseEnv();
+        return;
+    }
+
+    jclass autoCompleteCls = env->GetObjectClass(autoCompleteListener);
+    if (!autoCompleteCls)
+    {
+        releaseEnv();
+        return;
+    }
+
+    jmethodID autoCompleteMId = env->GetMethodID(autoCompleteCls, "onAutomationComplete",
+                                "(Ljava/lang/String;I)V");
+    if (!autoCompleteMId)
+    {
+        releaseEnv();
+        return;
+    }
+
+    jstring jUri = env->NewStringUTF(uri.c_str());
+
+    env->CallVoidMethod(autoCompleteListener, autoCompleteMId, jUri, automationID);
+    if ((env)->ExceptionCheck())
+    {
+        releaseEnv();
+        return;
+    }
+
+    env->DeleteLocalRef(jUri);
+
+    releaseEnv();
+}
+
+JNIEXPORT jobject JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_getModel
+(JNIEnv *env, jobject object)
+{
+    SimulatorResourceServerPtr resource = JniSimulatorResource::getJniSimulatorResourcePtr(env, object);
+    if (nullptr == resource.get())
+    {
+        std::cout << "getModel: Resource is NULL";
+        return nullptr;
+    }
+
+    SimulatorResourceModel resModel = resource->getModel();
+    JniSimulatorResourceModel *model = new JniSimulatorResourceModel(resModel);
+    jobject jModel = JniSimulatorResourceModel::toJava(env, reinterpret_cast<jlong>(model));
+    return jModel;
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_updateAttributeFromAllowedValues
+(JNIEnv *env, jobject object, jstring attrName, jint index)
+{
+    SimulatorResourceServerPtr resource = JniSimulatorResource::getJniSimulatorResourcePtr(env, object);
+    if (nullptr == resource.get())
+    {
+        std::cout << "updateAttributeFromAllowedValues: Resource is NULL";
+        return;
+    }
+
+    const char *attrNamePtr = env->GetStringUTFChars(attrName, NULL);
+    if (!attrNamePtr)
+    {
+        std::cout << "updateAttributeFromAllowedValues: Failed to convert jstring to char string!";
+        return;
+    }
+
+    resource->updateAttributeFromAllowedValues(attrNamePtr, static_cast<int>(index));
+    env->ReleaseStringUTFChars(attrName, attrNamePtr);
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_setRange
+(JNIEnv *env, jobject object, jstring attrName, jint min, jint max)
+{
+    SimulatorResourceServerPtr resource = JniSimulatorResource::getJniSimulatorResourcePtr(env, object);
+    if (nullptr == resource.get())
+    {
+        std::cout << "setRange: Resource is NULL";
+        return;
+    }
+
+    const char *attrNamePtr = env->GetStringUTFChars(attrName, NULL);
+    if (!attrNamePtr)
+    {
+        std::cout << "setRange: Failed to convert jstring to char string!";
+        return;
+    }
+
+    resource->setRange(attrNamePtr, static_cast<int>(min), static_cast<int>(max));
+    env->ReleaseStringUTFChars(attrName, attrNamePtr);
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_setInterfaceType
+(JNIEnv *env, jobject jobject, const std::string &interfaceType)
+{
+    jstring jInterfaceType = env->NewStringUTF(interfaceType.c_str());
+    if (!jInterfaceType)
+    {
+        std::cout << "setInterfaceType: InterfaceType is NULL";
+        return;
+    }
+
+    env->CallVoidMethod(jobject, gSimulatorClassRefs.classSimulatorResourceSetInterfaceType,
+                        jInterfaceType);
+    env->DeleteLocalRef(jInterfaceType);
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_addAttributeInteger
+(JNIEnv *env, jobject jobject, jstring jKey, jint jValue)
+{
+    if (!jKey)
+    {
+        std::cout << "addAttributeInteger: AttributeName is Empty";
+        return;
+    }
+
+    SimulatorResourceServerPtr resource = JniSimulatorResource::getJniSimulatorResourcePtr(env,
+                                          jobject);
+    if (nullptr == resource.get())
+    {
+        std::cout << "addAttributeInteger: Resource is NULL";
+        return;
+    }
+
+    std::string str = env->GetStringUTFChars(jKey, NULL);
+    resource->addAttribute(str, static_cast<int>(jValue));
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_addAttributeDouble
+(JNIEnv *env, jobject jobject, jstring jKey, jdouble jValue)
+{
+    if (!jKey)
+    {
+        std::cout << "addAttributeDouble: AttributeName is Empty";
+        return;
+    }
+
+    SimulatorResourceServerPtr resource = JniSimulatorResource::getJniSimulatorResourcePtr(env,
+                                          jobject);
+    if (nullptr == resource.get())
+    {
+        std::cout << "addAttributeDouble: Resource is NULL";
+        return;
+    }
+
+    std::string str = env->GetStringUTFChars(jKey, NULL);
+    resource->addAttribute(str, static_cast<double>(jValue));
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_addAttributeBoolean
+(JNIEnv *env, jobject jobject, jstring jKey, jboolean jValue)
+{
+    if (!jKey)
+    {
+        std::cout << "addAttributeBoolean: AttributeName is Empty";
+        return;
+    }
+
+    SimulatorResourceServerPtr resource = JniSimulatorResource::getJniSimulatorResourcePtr(env,
+                                          jobject);
+    if (nullptr == resource.get())
+    {
+        std::cout << "addAttributeBoolean: Resource is NULL";
+        return;
+    }
+
+    std::string str = env->GetStringUTFChars(jKey, NULL);
+    resource->addAttribute(str, static_cast<bool>(jValue));
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_addAttributeStringN
+(JNIEnv *env, jobject jobject, jstring jKey, jstring jValue)
+{
+    if (!jKey)
+    {
+        std::cout << "addAttributeStringN: AttributeName is Empty";
+        return;
+    }
+
+    SimulatorResourceServerPtr resource = JniSimulatorResource::getJniSimulatorResourcePtr(env,
+                                          jobject);
+    if (nullptr == resource.get())
+    {
+        std::cout << "addAttributeStringN: Resource is NULL";
+        return;
+    }
+
+    std::string key = env->GetStringUTFChars(jKey, NULL);
+    std::string value = env->GetStringUTFChars(jValue, NULL);
+
+    resource->addAttribute(key, value);
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_updateAttributeInteger
+(JNIEnv *env, jobject jobject, jstring jKey, jint jValue)
+{
+    if (!jKey)
+    {
+        std::cout << "updateAttributeInteger: AttributeName is Empty";
+        return;
+    }
+
+    SimulatorResourceServerPtr resource = JniSimulatorResource::getJniSimulatorResourcePtr(env,
+                                          jobject);
+    if (nullptr == resource.get())
+    {
+        std::cout << "updateAttributeInteger: Resource is NULL";
+        return;
+    }
+
+    std::string str = env->GetStringUTFChars(jKey, NULL);
+    resource->updateAttribute(str, static_cast<int>(jValue));
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_updateAttributeDouble
+(JNIEnv *env, jobject jobject, jstring jKey, jdouble jValue)
+{
+    if (!jKey)
+    {
+        std::cout << "updateAttributeDouble: AttributeName is Empty";
+        return;
+    }
+
+    SimulatorResourceServerPtr resource = JniSimulatorResource::getJniSimulatorResourcePtr(env,
+                                          jobject);
+    if (nullptr == resource.get())
+    {
+        std::cout << "updateAttributeDouble: Resource is NULL";
+        return;
+    }
+
+    std::string str = env->GetStringUTFChars(jKey, NULL);
+    resource->updateAttribute(str, static_cast<double>(jValue));
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_updateAttributeBoolean
+(JNIEnv *env, jobject jobject, jstring jKey, jboolean jValue)
+{
+    if (!jKey)
+    {
+        std::cout << "updateAttributeBoolean: AttributeName is Empty";
+        return;
+    }
+
+    SimulatorResourceServerPtr resource = JniSimulatorResource::getJniSimulatorResourcePtr(env,
+                                          jobject);
+    if (nullptr == resource.get())
+    {
+        std::cout << "updateAttributeBoolean: Resource is NULL";
+        return;
+    }
+
+    std::string str = env->GetStringUTFChars(jKey, NULL);
+    resource->updateAttribute(str, static_cast<bool>(jValue));
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_updateAttributeStringN
+(JNIEnv *env, jobject jobject, jstring jKey, jstring jValue)
+{
+    if (!jKey)
+    {
+        std::cout << "updateAttributeStringN: AttributeName is Empty";
+        return;
+    }
+
+    SimulatorResourceServerPtr resource = JniSimulatorResource::getJniSimulatorResourcePtr(env,
+                                          jobject);
+    if (nullptr == resource.get())
+    {
+        std::cout << "updateAttributeStringN: Resource is NULL";
+        return;
+    }
+
+    std::string key = env->GetStringUTFChars(jKey, NULL);
+    std::string value = env->GetStringUTFChars(jValue, NULL);
+
+    resource->updateAttribute(key, value);
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_setAllowedValuesInteger
+(JNIEnv *env, jobject object, jstring jKey, jobject jAllowedValues)
+{
+    if (!jKey)
+    {
+        std::cout << "setAllowedValuesInteger: AttributeName is Empty";
+        return;
+    }
+
+    SimulatorResourceServerPtr resource = JniSimulatorResource::getJniSimulatorResourcePtr(env, object);
+    if (nullptr == resource.get())
+    {
+        std::cout << "setAllowedValuesInteger: Resource is NULL";
+        return;
+    }
+
+    std::string str = env->GetStringUTFChars(jKey, NULL);
+    resource->setAllowedValues(str, convertIntegerVector(env, jAllowedValues));
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_setAllowedValuesDouble
+(JNIEnv *env, jobject object, jstring jKey, jobject jAllowedValues)
+{
+    if (!jKey)
+    {
+        std::cout << "setAllowedValuesDouble: AttributeName is Empty";
+        return;
+    }
+
+    SimulatorResourceServerPtr resource = JniSimulatorResource::getJniSimulatorResourcePtr(env, object);
+    if (nullptr == resource.get())
+    {
+        std::cout << "setAllowedValuesDouble: Resource is NULL";
+        return;
+    }
+
+    std::string str = env->GetStringUTFChars(jKey, NULL);
+    resource->setAllowedValues(str, convertDoubleVector(env, jAllowedValues));
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_setAllowedValuesStringN
+(JNIEnv *env, jobject object, jstring jKey, jobject jAllowedValues)
+{
+    if (!jKey)
+    {
+        std::cout << "setAllowedValuesStringN: AttributeName is Empty";
+        return;
+    }
+
+    SimulatorResourceServerPtr resource = JniSimulatorResource::getJniSimulatorResourcePtr(env, object);
+    if (nullptr == resource.get())
+    {
+        std::cout << "setAllowedValuesStringN: Resource is NULL";
+        return;
+    }
+
+    std::string str = env->GetStringUTFChars(jKey, NULL);
+    resource->setAllowedValues(str, convertStringVector(env, jAllowedValues));
+}
+
+JNIEXPORT jint JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_startResourceAutomation
+(JNIEnv *env, jobject object, jint automationType, jobject listener)
+{
+    SimulatorResourceServerPtr resource = JniSimulatorResource::getJniSimulatorResourcePtr(env, object);
+    if (nullptr == resource.get())
+    {
+        return -1;
+    }
+
+    if (!listener)
+    {
+        return -1;
+    }
+
+    jweak jlistenerRef = env->NewWeakGlobalRef(listener);
+    updateCompleteCallback callback =  [jlistenerRef](const std::string & uri, const int automationID)
+    {
+        onAutomationComplete(jlistenerRef, uri, automationID);
+    };
+
+    AutomationType type = AutomationType::NORMAL;
+    if (1 == automationType)
+    {
+        type = AutomationType::RECURRENT;
+    }
+
+    int automationId;
+    if (SIMULATOR_SUCCESS != resource->startUpdateAutomation(type, callback,
+            automationId))
+        return -1;
+
+    return automationId;
+}
+
+JNIEXPORT jint JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_startAttributeAutomation
+(JNIEnv *env, jobject object, jstring attrName, jint automationType, jobject listener)
+{
+    std::cout << "starAttributeAutomation JNI" << std::endl;
+    SimulatorResourceServerPtr resource = JniSimulatorResource::getJniSimulatorResourcePtr(env, object);
+    if (nullptr == resource.get())
+    {
+        return -1;
+    }
+
+    if (!attrName)
+    {
+        return -1;
+    }
+
+    if (!listener)
+    {
+        return -1;
+    }
+
+    jweak jlistenerRef = env->NewWeakGlobalRef(listener);
+    updateCompleteCallback callback =  [jlistenerRef](const std::string & uri, const int automationID)
+    {
+        onAutomationComplete(jlistenerRef, uri, automationID);
+    };
+
+    const char *attrNamePtr = env->GetStringUTFChars(attrName, NULL);
+
+    AutomationType type = AutomationType::NORMAL;
+    if (1 == automationType)
+    {
+        type = AutomationType::RECURRENT;
+    }
+
+    int automationId = -1;
+    resource->startUpdateAutomation(attrNamePtr, type, callback, automationId);
+
+    env->ReleaseStringUTFChars(attrName, attrNamePtr);
+    return automationId;
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_stopAutomation
+(JNIEnv *env, jobject object, jint automationId)
+{
+    SimulatorResourceServerPtr resource = JniSimulatorResource::getJniSimulatorResourcePtr(env, object);
+    if (nullptr == resource.get())
+    {
+        return;
+    }
+
+    resource->stopUpdateAutomation(automationId);
+}
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_removeAttribute
+(JNIEnv *env, jobject jobject, jstring jKey)
+{
+    if (!jKey)
+    {
+        std::cout << "removeAttribute: AttributeName is Empty";
+        return;
+    }
+
+    SimulatorResourceServerPtr resource = JniSimulatorResource::getJniSimulatorResourcePtr(env,
+                                          jobject);
+    if (nullptr == resource.get())
+    {
+        std::cout << "removeAttribute: Resource is NULL";
+        return;
+    }
+
+    std::string str = env->GetStringUTFChars(jKey, NULL);
+    resource->removeAttribute(str);
+}
+
+JNIEXPORT void JNICALL Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_dispose
+(JNIEnv *env, jobject thiz)
+{
+    JniSimulatorResource *resource = GetHandle<JniSimulatorResource>(env, thiz);
+    delete resource;
+}
+
diff --git a/service/simulator/java/jni/simulator_resource_server_jni.h b/service/simulator/java/jni/simulator_resource_server_jni.h
new file mode 100644 (file)
index 0000000..f41479d
--- /dev/null
@@ -0,0 +1,121 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#ifndef SIMULATOR_RESOURCE_JNI_H_
+#define SIMULATOR_RESOURCE_JNI_H_
+
+#include <jni.h>
+#include "simulator_resource_server.h"
+
+class JniSimulatorResource
+{
+    public:
+        JniSimulatorResource(SimulatorResourceServerPtr &resource);
+
+        static jobject toJava(JNIEnv *env, jlong resource);
+        void setResourceInfo(JNIEnv *env, jobject jobj);
+        static SimulatorResourceServerPtr getJniSimulatorResourcePtr(JNIEnv *env, jobject thiz);
+    private:
+        SimulatorResourceServerPtr 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_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_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_addAttributeStringN
+(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_updateAttributeStringN
+(JNIEnv *, jobject, jstring, jstring);
+
+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_setAllowedValuesStringN
+(JNIEnv *, jobject, jstring, jobject);
+
+JNIEXPORT jint JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_startResourceAutomation
+(JNIEnv *, jobject, jint, jobject);
+
+JNIEXPORT jint JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_startAttributeAutomation
+(JNIEnv *, jobject, jstring, jint, jobject);
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_stopAutomation
+(JNIEnv *, jobject, jint);
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_removeAttribute
+(JNIEnv *, jobject, jstring);
+
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_dispose
+(JNIEnv *, jobject);
+
+}
+#endif
+#endif //SIMULATOR_RESOURCE_JNI_H_
diff --git a/service/simulator/java/sdk/.classpath b/service/simulator/java/sdk/.classpath
new file mode 100644 (file)
index 0000000..11f3b6f
--- /dev/null
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+    <classpathentry kind="src" path="src" />
+    <classpathentry kind="con"
+        path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7" />
+    <classpathentry kind="output" path="bin" />
+</classpath>
diff --git a/service/simulator/java/sdk/.project b/service/simulator/java/sdk/.project
new file mode 100644 (file)
index 0000000..e32400a
--- /dev/null
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+    <name>Simulator</name>
+    <comment></comment>
+    <projects>
+    </projects>
+    <buildSpec>
+        <buildCommand>
+            <name>org.eclipse.jdt.core.javabuilder</name>
+            <arguments>
+            </arguments>
+        </buildCommand>
+    </buildSpec>
+    <natures>
+        <nature>org.eclipse.jdt.core.javanature</nature>
+    </natures>
+</projectDescription>
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/AutomationType.java b/service/simulator/java/sdk/src/org/oic/simulator/AutomationType.java
new file mode 100644 (file)
index 0000000..5e51167
--- /dev/null
@@ -0,0 +1,28 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * This file provides a enum which contains the automation types.
+ */
+package org.oic.simulator;
+
+/**
+ * This Enum contains the different types of automation which are supported by
+ * the simulator.
+ */
+public enum AutomationType {
+    NORMAL, RECURRENT
+}
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/IAutomation.java b/service/simulator/java/sdk/src/org/oic/simulator/IAutomation.java
new file mode 100644 (file)
index 0000000..4908b37
--- /dev/null
@@ -0,0 +1,32 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * This file provides an interface for receiving notification when an automation completes.
+ */
+package org.oic.simulator;
+
+/**
+ * Interface 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 interface IAutomation {
+    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
new file mode 100644 (file)
index 0000000..aeaaded
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * This file provides an interface for handling the log messages.
+ */
+package org.oic.simulator;
+
+/**
+ * Interface for receiving log messages.
+ */
+public interface ILogger {
+    public enum Level {
+        INFO, DEBUG, WARNING, ERROR
+    }
+
+    /**
+     * This callback method will be called to notify the application about the
+     * status or problems along with their severity.
+     *
+     * @param time
+     *            Local time information when action/event logged.
+     * @param level
+     *            Level or Severity of the log.
+     * @param message
+     *            The log message describing the issue.
+     */
+    public void write(String time, int level, String message);
+}
\ No newline at end of file
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/OCSimulatorResult.java b/service/simulator/java/sdk/src/org/oic/simulator/OCSimulatorResult.java
new file mode 100644 (file)
index 0000000..296cd06
--- /dev/null
@@ -0,0 +1,131 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * This file provides a Enum which contains Status codes for Success and Errors.
+ */
+package org.oic.simulator;
+
+/**
+ * This Enum contains Status codes for Success and Errors.
+ */
+public enum OCSimulatorResult {
+    OC_STACK_OK,
+    OC_STACK_RESOURCE_CREATED,
+    OC_STACK_RESOURCE_DELETED,
+    OC_STACK_CONTINUE,
+    OC_STACK_INVALID_URI,
+    OC_STACK_INVALID_QUERY,
+    OC_STACK_INVALID_IP,
+    OC_STACK_INVALID_PORT,
+    OC_STACK_INVALID_CALLBACK,
+    OC_STACK_INVALID_METHOD,
+    OC_STACK_INVALID_PARAM,
+    OC_STACK_INVALID_OBSERVE_PARAM,
+    OC_STACK_NO_MEMORY,
+    OC_STACK_COMM_ERROR,
+    OC_STACK_NOTIMPL,
+    OC_STACK_NO_RESOURCE,
+    OC_STACK_RESOURCE_ERROR,
+    OC_STACK_SLOW_RESOURCE,
+    OC_STACK_REPEATED_REQUEST,
+    OC_STACK_NO_OBSERVERS,
+    OC_STACK_OBSERVER_NOT_FOUND,
+    OC_STACK_VIRTUAL_DO_NOT_HANDLE,
+    OC_STACK_INVALID_OPTION,
+    OC_STACK_MALFORMED_RESPONSE,
+    OC_STACK_PERSISTENT_BUFFER_REQUIRED,
+    OC_STACK_INVALID_REQUEST_HANDLE,
+    OC_STACK_INVALID_DEVICE_INFO,
+    OC_STACK_INVALID_JSON,
+    OC_STACK_PRESENCE_STOPPED,
+    OC_STACK_PRESENCE_TIMEOUT,
+    OC_STACK_PRESENCE_DO_NOT_HANDLE,
+    OC_STACK_ERROR,
+    OC_STACK_LISTENER_NOT_SET;
+
+    public static OCSimulatorResult conversion(int ordinal) {
+
+        OCSimulatorResult result = OCSimulatorResult.values()[31];
+
+        if (ordinal == 0)
+            result = OCSimulatorResult.values()[0];
+        else if (ordinal == 1)
+            result = OCSimulatorResult.values()[1];
+        else if (ordinal == 2)
+            result = OCSimulatorResult.values()[2];
+        else if (ordinal == 3)
+            result = OCSimulatorResult.values()[3];
+
+        else if (ordinal == 20)
+            result = OCSimulatorResult.values()[4];
+        else if (ordinal == 21)
+            result = OCSimulatorResult.values()[5];
+        else if (ordinal == 22)
+            result = OCSimulatorResult.values()[6];
+        else if (ordinal == 23)
+            result = OCSimulatorResult.values()[7];
+        else if (ordinal == 24)
+            result = OCSimulatorResult.values()[8];
+        else if (ordinal == 25)
+            result = OCSimulatorResult.values()[9];
+        else if (ordinal == 26)
+            result = OCSimulatorResult.values()[10];
+        else if (ordinal == 27)
+            result = OCSimulatorResult.values()[11];
+        else if (ordinal == 28)
+            result = OCSimulatorResult.values()[12];
+        else if (ordinal == 29)
+            result = OCSimulatorResult.values()[13];
+        else if (ordinal == 30)
+            result = OCSimulatorResult.values()[14];
+        else if (ordinal == 31)
+            result = OCSimulatorResult.values()[15];
+        else if (ordinal == 32)
+            result = OCSimulatorResult.values()[16];
+        else if (ordinal == 33)
+            result = OCSimulatorResult.values()[17];
+        else if (ordinal == 34)
+            result = OCSimulatorResult.values()[18];
+        else if (ordinal == 35)
+            result = OCSimulatorResult.values()[19];
+        else if (ordinal == 36)
+            result = OCSimulatorResult.values()[20];
+        else if (ordinal == 37)
+            result = OCSimulatorResult.values()[21];
+        else if (ordinal == 38)
+            result = OCSimulatorResult.values()[22];
+        else if (ordinal == 39)
+            result = OCSimulatorResult.values()[23];
+        else if (ordinal == 40)
+            result = OCSimulatorResult.values()[24];
+        else if (ordinal == 41)
+            result = OCSimulatorResult.values()[25];
+        else if (ordinal == 42)
+            result = OCSimulatorResult.values()[26];
+        else if (ordinal == 43)
+            result = OCSimulatorResult.values()[27];
+
+        else if (ordinal == 128)
+            result = OCSimulatorResult.values()[28];
+        else if (ordinal == 129)
+            result = OCSimulatorResult.values()[29];
+        else if (ordinal == 130)
+            result = OCSimulatorResult.values()[30];
+
+        return result;
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/SimulatorManager.java b/service/simulator/java/sdk/src/org/oic/simulator/SimulatorManager.java
new file mode 100644 (file)
index 0000000..13797cf
--- /dev/null
@@ -0,0 +1,164 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * This file contains a class which has the methods
+ * for creation and deletion of resources.
+ */
+package org.oic.simulator;
+
+import java.util.ArrayList;
+import java.util.Vector;
+
+import org.oic.simulator.clientcontroller.IFindResourceListener;
+import org.oic.simulator.clientcontroller.SimulatorRemoteResource;
+import org.oic.simulator.serviceprovider.IResourceModelChangedListener;
+import org.oic.simulator.serviceprovider.SimulatorResourceServer;
+
+/**
+ * This class provides a set of methods for creation and deletion of resources.
+ */
+public class SimulatorManager {
+
+    /**
+     * Set listener for receiving log messages.
+     *
+     * @param logger
+     *            {@link ILogger} to receive the log messages.
+     */
+    public static void setLogger(ILogger logger) {
+        SimulatorManagerNativeInterface.setLogger(logger);
+    }
+
+    /**
+     * API for creating a resource from a RAML configuration file whose path is
+     * given as a parameter.
+     *
+     * @param configPath
+     *            Path to RAML configuration file.
+     * @param listener
+     *            Listener for receiving notifications whenever there is a
+     *            change in the resource model.
+     * 
+     * @return {@link SimulatorResourceServer} - Created resource on success,
+     *         otherwise null.
+     */
+    public static SimulatorResourceServer createResource(String configPath,
+            IResourceModelChangedListener listener) {
+        SimulatorResourceServer simulatorResourceServerObj;
+        simulatorResourceServerObj = SimulatorManagerNativeInterface
+                .createResource(configPath, listener);
+        return simulatorResourceServerObj;
+    }
+
+    /**
+     * API for creating a set of resources from a RAML configuration file whose
+     * path is given as a parameter.
+     *
+     * @param configPath
+     *            Path to RAML configuration file.
+     * @param count
+     *            Number of resources to be created.
+     * @param listener
+     *            Listener for receiving notifications whenever there is a
+     *            change in the resource model.
+     * 
+     * @return Returns an array of {@link SimulatorResourceServer} objects one
+     *         for each created resource on success, otherwise null.
+     */
+    public static SimulatorResourceServer[] createResource(String configPath,
+            int count, IResourceModelChangedListener listener) {
+        SimulatorResourceServer[] simulatorResourceServers;
+        simulatorResourceServers = SimulatorManagerNativeInterface
+                .createResources(configPath, count, listener);
+        return simulatorResourceServers;
+    }
+
+    /**
+     * API for getting all locally created resources.
+     *
+     * @return Returns a list of {@link SimulatorResourceServer} objects on
+     *         success, otherwise null.
+     */
+    public static Vector<SimulatorResourceServer> getLocalResources() {
+        Vector<SimulatorResourceServer> simulatorResourceServerVector = null;
+        simulatorResourceServerVector = SimulatorManagerNativeInterface
+                .getResources();
+        return simulatorResourceServerVector;
+    }
+
+    /**
+     * API for deleting a specific resource.
+     *
+     * @param resource
+     *            {@link SimulatorResourceServer} object of the resource to be
+     *            deleted.
+     */
+    public static void deleteResource(SimulatorResourceServer resource) {
+        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.
+     */
+    public static void deleteResources(String resourceType) {
+        SimulatorManagerNativeInterface.deleteResources(resourceType);
+    }
+
+    /**
+     * API for discovering resources in the network. Callback is called whenever
+     * a resource is discovered in the network.
+     *
+     * @param resourceType
+     *            Required resource type
+     *
+     * @return OCSimulatorResult - return value of this API. It returns
+     *         OC_STACK_OK if success.
+     *
+     */
+    public OCSimulatorResult findResource(String resourceType,
+            IFindResourceListener listener) {
+        OCSimulatorResult result;
+        int ordinal = SimulatorManagerNativeInterface.findResource(
+                resourceType, listener);
+        result = OCSimulatorResult.conversion(ordinal);
+        return result;
+    }
+
+    /**
+     * API for getting the list of previously discovered resources in the
+     * network.
+     *
+     * @param resourceType
+     *            Required resource type
+     *
+     * @return ArrayList<SimulatorRemoteResource> - returns list of
+     *         SimulatorRemoteResource
+     *
+     */
+    public ArrayList<SimulatorRemoteResource> getFoundResources(
+            String resourceType) {
+        ArrayList<SimulatorRemoteResource> resourceList = SimulatorManagerNativeInterface
+                .getFoundResources(resourceType);
+        return resourceList;
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/SimulatorManagerNativeInterface.java b/service/simulator/java/sdk/src/org/oic/simulator/SimulatorManagerNativeInterface.java
new file mode 100644 (file)
index 0000000..d8970f9
--- /dev/null
@@ -0,0 +1,155 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * This file contains a class which provides a set of native methods
+ * for creation and deletion of resources.
+ */
+package org.oic.simulator;
+
+import java.util.List;
+import java.util.ArrayList;
+import java.util.Vector;
+
+import org.oic.simulator.clientcontroller.IFindResourceListener;
+import org.oic.simulator.clientcontroller.SimulatorRemoteResource;
+import org.oic.simulator.ILogger;
+import org.oic.simulator.serviceprovider.IResourceModelChangedListener;
+import org.oic.simulator.serviceprovider.SimulatorResourceServer;
+
+/**
+ * This class provides a set of native functions for creation 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.
+     */
+    public static native SimulatorResourceServer createResource(
+            String configPath, IResourceModelChangedListener listener);
+
+    /**
+     * Native function for creating several resources.
+     *
+     * @param configPath
+     *            Path to RAML configuration file.
+     * @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.
+     */
+    public static native SimulatorResourceServer[] createResources(
+            String configPath, int count, IResourceModelChangedListener listener);
+
+    /**
+     * Native function to get the list of locally created resources.
+     *
+     * @return A list of {@link SimulatorResourceServer} objects on success,
+     *         otherwise null.
+     */
+    public static native Vector<SimulatorResourceServer> getResources();
+
+    /**
+     * Native function to delete a specific resource
+     *
+     * @param resource
+     *            {@link SimulatorResourceServer} object of the resource to be
+     *            deleted.
+     */
+    public static native void deleteResource(SimulatorResourceServer resource);
+
+    /**
+     * Native function to delete all resources or resources of a specific type.
+     *
+     * @param resourceType
+     *            Type of the resource.
+     */
+    public static native void deleteResources(String resourceType);
+
+    /**
+     * Native function to set the logger listener for receiving the log messages
+     * from native layer.
+     */
+    public static native void setLogger(ILogger logger);
+
+    /**
+     * Native function for discovering resources.
+     *
+     * @param resourceType
+     *            - required resource type
+     *
+     * @return OCSimulatorResult - return value of this API. It returns
+     *         OC_STACK_OK if success.
+     *
+     */
+    public static native int findResource(String resourceType,
+            IFindResourceListener listener);
+
+    /**
+     * Native function for getting the list of previously discovered resources
+     * in the network.
+     *
+     * @param resourceType
+     *            - required resource type
+     *
+     * @return ArrayList<SimulatorRemoteResource> - returns list of
+     *         SimulatorRemoteResource
+     *
+     */
+    public static native ArrayList<SimulatorRemoteResource> getFoundResources(
+            String resourceType);
+
+    /**
+     * Method to get the URI for this resource
+     *
+     * @return resource URI
+     */
+    public static native String getUri();
+
+    /**
+     * Method to get the list of resource types
+     *
+     * @return List of resource types
+     */
+    public static native List<String> getResourceTypes();
+
+    /**
+     * Method to get the list of resource interfaces
+     *
+     * @return List of resource interface
+     */
+    public static native List<String> getResourceInterfaces();
+
+    /**
+     * Method to get a string representation of the resource's server ID. This
+     * is unique per-server independent on how it was discovered.
+     *
+     * @return server ID
+     */
+    public static native String getServerId();
+}
\ No newline at end of file
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/SimulatorResourceAttribute.java b/service/simulator/java/sdk/src/org/oic/simulator/SimulatorResourceAttribute.java
new file mode 100644 (file)
index 0000000..8682847
--- /dev/null
@@ -0,0 +1,130 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * This file contains a class which has a set of native methods for
+ * getting the information associated with a particular attribute.
+ */
+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 SimulatorResourceAttribute {
+
+    /**
+     * Handle to the native object of the simulator resource attribute.
+     */
+    private long nativeHandle;
+
+    public SimulatorResourceAttribute() {
+    }
+
+    /**
+     * Constructor for SimulatorResourceAttribute.
+     *
+     * @param nativeHandle
+     *            Handle to the native SimulatorResourceAttribute object.
+     */
+    private SimulatorResourceAttribute(long handle) {
+        nativeHandle = handle;
+    }
+
+    /**
+     * This constructor is used to create a new attribute.
+     *
+     * @param attrName
+     *            Name of the attribute
+     */
+    public SimulatorResourceAttribute(String attrName) {
+        create(attrName);
+    }
+
+    @Override
+    protected void finalize() throws Throwable {
+        dispose();
+    }
+
+    /**
+     * This generic API is used to get the value of an attribute whose type is
+     * given by the caller of the method.
+     *
+     * @param <T>
+     *            This specifies the type in which the value has to be returned.
+     *
+     * @return The attribute's value in a specified type.
+     */
+    public <T> T getAttributeValue() {
+        Object obj = getValue();
+        @SuppressWarnings("unchecked")
+        T t = (T) obj;
+        return t;
+    }
+
+    /**
+     * Native method to create a new attribute with the given name.
+     *
+     * @param attrName
+     *            Name of the attribute.
+     */
+    public native void create(String attrName);
+
+    /**
+     * Native method for getting the attribute's name.
+     *
+     * @return Attribute's name
+     */
+    public native String getName();
+
+    /**
+     * Native method for getting the attribute's value.
+     *
+     * @return Attribute's value represented as {@link Object}.
+     */
+    public native Object getValue();
+
+    /**
+     * Native method for getting the number of values in the allowed values
+     * list.
+     *
+     * @return Count of allowed values
+     */
+    public native int allowedValuesSize();
+
+    /**
+     * Native method for returning the string representation of the attribute's
+     * value.
+     *
+     * @return Attribute's value as {@link String}.
+     */
+    public native String valueToString();
+
+    /**
+     * Native method for returning the string representation of the attribute's
+     * allowed values.
+     *
+     * @return Attribute's allowed values as {@link String}.
+     */
+    public native String allowedValuesToString();
+
+    /**
+     * Native function to release the memory allocated to the native object for
+     * SimulatorResourceAttribute.
+     */
+    private native void dispose();
+
+}
\ No newline at end of file
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IFindResourceListener.java b/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IFindResourceListener.java
new file mode 100644 (file)
index 0000000..dc63e95
--- /dev/null
@@ -0,0 +1,38 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * This file provides interface for getting notification when resources are
+ * discovered in network.
+ */
+package org.oic.simulator.clientcontroller;
+
+import org.oic.simulator.clientcontroller.SimulatorRemoteResource;
+
+/**
+ * Provides interface for getting notification when resources are discovered in
+ * network.
+ */
+public interface IFindResourceListener {
+    /**
+     * This callback method will be called whenever resource is discovered in
+     * the network.
+     *
+     * @param resource
+     *            resource discovered in the network
+     */
+    public void onResourceCallback(SimulatorRemoteResource resource);
+}
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IGetListener.java b/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IGetListener.java
new file mode 100644 (file)
index 0000000..32abac6
--- /dev/null
@@ -0,0 +1,32 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * This file provides interface for get callback information.
+ */
+package org.oic.simulator.clientcontroller;
+
+import org.oic.simulator.serviceprovider.SimulatorResourceModel;
+
+/**
+ * An OnGetListener can be registered via the resource get call. Event listeners
+ * are notified asynchronously
+ */
+public interface IGetListener {
+    public void onGetCompleted(SimulatorResourceModel representation);
+
+    public void onGetFailed(Throwable ex);
+}
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IObserveListener.java b/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IObserveListener.java
new file mode 100644 (file)
index 0000000..a71384b
--- /dev/null
@@ -0,0 +1,53 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * This file provides interface for getting notification on resource model change.
+ */
+package org.oic.simulator.clientcontroller;
+
+import org.oic.simulator.serviceprovider.SimulatorResourceModel;
+
+/**
+ * Provides interface for getting notification when resource model of an
+ * observed resource gets changed. An OnObserveListener can be registered via
+ * the SimulatorRemoteResource observe call. Event listeners are notified
+ * asynchronously.
+ */
+public interface IObserveListener {
+    /**
+     * This callback method will be called whenever the resource model of an
+     * observed resource gets changed.
+     *
+     * @param representation
+     *            Updated Simulator Resource Model
+     *
+     * @param sequenceNumber
+     *            Observe Sequence number
+     */
+    public void onObserveCompleted(SimulatorResourceModel representation,
+            int sequenceNumber);
+
+    /**
+     * This callback method will be called whenever the resource model of an
+     * observed resource gets changed and there is a failure in notifying the
+     * updated resource model.
+     *
+     * @param resource
+     *            resource discovered in the network
+     */
+    public void onObserveFailed(Throwable ex);
+}
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IPostListener.java b/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IPostListener.java
new file mode 100644 (file)
index 0000000..e88b98e
--- /dev/null
@@ -0,0 +1,32 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * This file provides interface for post callback information.
+ */
+package org.oic.simulator.clientcontroller;
+
+import org.oic.simulator.serviceprovider.SimulatorResourceModel;
+
+/**
+ * An OnPostListener can be registered via the resource post call. Event
+ * listeners are notified asynchronously
+ */
+public interface IPostListener {
+    public void onPostCompleted(SimulatorResourceModel representation);
+
+    public void onPostFailed(Throwable ex);
+}
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IPutListener.java b/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/IPutListener.java
new file mode 100644 (file)
index 0000000..a9c0738
--- /dev/null
@@ -0,0 +1,32 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * This file provides interface for put callback information.
+ */
+package org.oic.simulator.clientcontroller;
+
+import org.oic.simulator.serviceprovider.SimulatorResourceModel;
+
+/**
+ * An OnPutListener can be registered via the resource put call. Event listeners
+ * are notified asynchronously
+ */
+public interface IPutListener {
+    public void onPutCompleted(SimulatorResourceModel representation);
+
+    public void onPutFailed(Throwable ex);
+}
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/SimulatorObserveType.java b/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/SimulatorObserveType.java
new file mode 100644 (file)
index 0000000..ef38085
--- /dev/null
@@ -0,0 +1,34 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * This file provides a enum which contains the observable types.
+ */
+package org.oic.simulator.clientcontroller;
+
+public enum SimulatorObserveType {
+    OBSERVE(0), OBSERVE_ALL(1), ;
+
+    private int value;
+
+    private SimulatorObserveType(int value) {
+        this.value = value;
+    }
+
+    public int getValue() {
+        return this.value;
+    }
+}
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/SimulatorRemoteResource.java b/service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/SimulatorRemoteResource.java
new file mode 100644 (file)
index 0000000..583c273
--- /dev/null
@@ -0,0 +1,216 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * This file contains a class which has a set of native methods for 
+ * communicating with a remote resource.  
+ */
+package org.oic.simulator.clientcontroller;
+
+import java.util.List;
+import java.util.Map;
+
+import org.oic.simulator.serviceprovider.SimulatorResourceModel;
+
+/**
+ * SimulatorRemoteResource represents a Resource running in the remote Simulator
+ * Server. It comes with a well-defined contract or interface onto which you can
+ * perform different operations or subscribe for event notifications.
+ */
+public class SimulatorRemoteResource {
+
+    private SimulatorRemoteResource(long nativeHandle) {
+        this.mNativeHandle = nativeHandle;
+    }
+
+    /**
+     * Method to get the URI for this resource
+     *
+     * @return resource URI
+     */
+    public native String getUri();
+
+    /**
+     * Method to get the list of resource types
+     *
+     * @return List of resource types
+     */
+    public native List<String> getResourceTypes();
+
+    /**
+     * Method to get the list of resource interfaces
+     *
+     * @return List of resource interface
+     */
+    public native List<String> getResourceInterfaces();
+
+    /**
+     * Method to get a string representation of the resource's server ID. This
+     * is unique per-server independent on how it was discovered.
+     *
+     * @return server ID
+     */
+    public native String getServerId();
+
+    /**
+     * Method to set observation on the resource
+     *
+     * @param observeType
+     *            allows the client to specify how it wants to observe
+     * @param queryParamsMap
+     *            map which can have the query parameter name and value
+     * @param onObserveListener
+     *            event handler The handler method will be invoked with a map of
+     *            attribute name and values.
+     *
+     */
+    public native void observe(SimulatorObserveType observeType,
+            Map<String, String> queryParamsMap,
+            IObserveListener onObserveListener);
+
+    /**
+     * Method to cancel the observation on the resource
+     *
+     */
+    public native void cancelObserve();
+
+    /**
+     * Method to get the attributes of a resource.
+     *
+     * @param queryParamsMap
+     *            map which can have the query parameter name and value
+     * @param onGetListener
+     *            The event handler will be invoked with a map of attribute name
+     *            and values. The event handler will also have the result from
+     *            this Get operation This will have error codes
+     */
+    public native void get(Map<String, String> queryParamsMap,
+            IGetListener onGetListener);
+
+    /**
+     * Method to get the attributes of a resource.
+     *
+     * @param resourceType
+     *            resourceType of the resource to operate on
+     * @param resourceInterface
+     *            interface type of the resource to operate on
+     * @param queryParamsMap
+     *            map which can have the query parameter name and value
+     * @param onGetListener
+     *            The event handler will be invoked with a map of attribute name
+     *            and values. The event handler will also have the result from
+     *            this Get operation This will have error codes
+     */
+    public void get(String resourceType, String resourceInterface,
+            Map<String, String> queryParamsMap, IGetListener onGetListener) {
+        this.get2(resourceType, resourceInterface, queryParamsMap,
+                onGetListener);
+    }
+
+    private native void get2(String resourceType, String resourceInterface,
+            Map<String, String> queryParamsMap, IGetListener onGetListener);
+
+    /**
+     * Method to set the representation of a resource (via PUT)
+     *
+     * @param representation
+     *            representation of the resource
+     * @param queryParamsMap
+     *            Map which can have the query parameter name and value
+     * @param onPutListener
+     *            event handler The event handler will be invoked with a map of
+     *            attribute name and values.
+     */
+    public native void put(SimulatorResourceModel representation,
+            Map<String, String> queryParamsMap, IPutListener onPutListener);
+
+    /**
+     * Method to set the representation of a resource (via PUT)
+     *
+     * @param resourceType
+     *            resource type of the resource to operate on
+     * @param resourceInterface
+     *            interface type of the resource to operate on
+     * @param representation
+     *            representation of the resource
+     * @param queryParamsMap
+     *            Map which can have the query parameter name and value
+     * @param onPutListener
+     *            event handler The event handler will be invoked with a map of
+     *            attribute name and values.
+     */
+    public void put(String resourceType, String resourceInterface,
+            SimulatorResourceModel representation,
+            Map<String, String> queryParamsMap, IPutListener onPutListener) {
+        this.put2(resourceType, resourceInterface, representation,
+                queryParamsMap, onPutListener);
+    }
+
+    private native void put2(String resourceType, String resourceInterface,
+            SimulatorResourceModel representation,
+            Map<String, String> queryParamsMap, IPutListener onPutListener);
+
+    /**
+     * Method to POST on a resource
+     *
+     * @param representation
+     *            representation of the resource
+     * @param queryParamsMap
+     *            Map which can have the query parameter name and value
+     * @param onPostListener
+     *            event handler The event handler will be invoked with a map of
+     *            attribute name and values.
+     */
+    public native void post(SimulatorResourceModel representation,
+            Map<String, String> queryParamsMap, IPostListener onPostListener);
+
+    /**
+     * Method to POST on a resource
+     *
+     * @param resourceType
+     *            resource type of the resource to operate on
+     * @param resourceInterface
+     *            interface type of the resource to operate on
+     * @param representation
+     *            representation of the resource
+     * @param queryParamsMap
+     *            Map which can have the query parameter name and value
+     * @param onPostListener
+     *            event handler The event handler will be invoked with a map of
+     *            attribute name and values.
+     */
+    public void post(String resourceType, String resourceInterface,
+            SimulatorResourceModel representation,
+            Map<String, String> queryParamsMap, IPostListener onPostListener) {
+        this.post2(resourceType, resourceInterface, representation,
+                queryParamsMap, onPostListener);
+    }
+
+    private native void post2(String resourceType, String resourceInterface,
+            SimulatorResourceModel representation,
+            Map<String, String> queryParamsMap, IPostListener onPostListener);
+
+    @Override
+    protected void finalize() throws Throwable {
+        super.finalize();
+
+        dispose();
+    }
+
+    private native void dispose();
+
+    private long mNativeHandle;
+}
diff --git a/service/simulator/java/sdk/src/org/oic/simulator/serviceprovider/IResourceModelChangedListener.java b/service/simulator/java/sdk/src/org/oic/simulator/serviceprovider/IResourceModelChangedListener.java
new file mode 100644 (file)
index 0000000..c8b2174
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * This file provides an interface for handling the resource model
+ * related notifications.
+ */
+package org.oic.simulator.serviceprovider;
+
+/**
+ * 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
+     *            Resource model 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/SimulatorResourceModel.java b/service/simulator/java/sdk/src/org/oic/simulator/serviceprovider/SimulatorResourceModel.java
new file mode 100644 (file)
index 0000000..fd69fba
--- /dev/null
@@ -0,0 +1,96 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * This file contains a class which has a set of native methods for accessing
+ * the resource model.
+ */
+package org.oic.simulator.serviceprovider;
+
+import org.oic.simulator.SimulatorResourceAttribute;
+import java.util.Map;
+
+/**
+ * This class represents the resource model of a resource and it provides a set
+ * of native methods for accessing the resource model.
+ */
+public class SimulatorResourceModel {
+
+    /**
+     * Handle to the native object of the simulator resource model.
+     */
+    private long nativeHandle;
+
+    /**
+     * Constructor for SimulatorResourceModel.
+     *
+     * @param nativeHandle
+     *            Handle to the native SimulatorResourceModel object.
+     */
+    private SimulatorResourceModel(long nativeHandle) {
+        this.nativeHandle = nativeHandle;
+    }
+
+    @Override
+    protected void finalize() throws Throwable {
+        dispose();
+    }
+
+    /**
+     * Native function for getting the total count of attributes in the resource
+     * model.
+     *
+     * @return Total number of attributes.
+     */
+    public native int size();
+
+    /**
+     * Native function for getting all attributes of a resource.
+     *
+     * @return Map of attributes with attribute name as the key and its
+     *         corresponding {@link SimulatorResourceAttribute} object as the
+     *         value.
+     */
+    public native Map<String, SimulatorResourceAttribute> getAttributes();
+
+    /**
+     * Native function to get a specific attribute of a resource. It takes the
+     * attribute name and returns an object of
+     * {@link SimulatorResourceAttribute}.
+     *
+     * @param attrName
+     *            Name of the attribute
+     *
+     * @return An object of SimulatorResourceAttribute.
+     */
+    public native SimulatorResourceAttribute getAttribute(String attrName);
+
+    /**
+     * Native function to get all the allowed values of a particular attribute.
+     *
+     * @param key
+     *            Name of the attribute
+     *
+     * @return An array of all possible values as strings.
+     */
+    public native String[] getAllowedValues(String key);
+
+    /**
+     * Native function to release the memory allocated to the native object for
+     * SimulatorResourceModel.
+     */
+    public native void dispose();
+}
\ 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
new file mode 100644 (file)
index 0000000..0df65f5
--- /dev/null
@@ -0,0 +1,342 @@
+/*
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * This file contains a class which has 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.
+ */
+package org.oic.simulator.serviceprovider;
+
+import java.util.Vector;
+
+import org.oic.simulator.IAutomation;
+
+/**
+ * This class represents a resource in the simulator. It provides a set of
+ * native methods for manipulating the attributes.
+ */
+public class SimulatorResourceServer {
+
+    private String resourceName;
+    private String resourceURI;
+    private String resourceType;
+    private String interfaceType;
+
+    private long   nativeHandle;
+
+    /**
+     * Constructor for SimulatorResourceServer.
+     *
+     * @param nativeHandle
+     *            Handle to the native {@link SimulatorResourceServer} object.
+     */
+    private SimulatorResourceServer(long nativeHandle) {
+        this.nativeHandle = nativeHandle;
+    }
+
+    /**
+     * API to set the name of the resource. Example: Light, Fan, etc.
+     *
+     * @param resourceName
+     *            Name of the resource.
+     */
+    public void setName(String resourceName) {
+        this.resourceName = resourceName;
+    }
+
+    /**
+     * API to set the URI of the resource. Example: /oic/light, /oic/fan, etc.
+     *
+     * @param resourceURI
+     *            URI of the resource.
+     */
+    private void setURI(String resourceURI) {
+        this.resourceURI = resourceURI;
+    }
+
+    /**
+     * API to set the type of the resource. Example: oic.light, oic.fan, etc.
+     *
+     * @param resourceType
+     *            Type of the resource.
+     */
+    private void setResourceType(String resourceType) {
+        this.resourceType = resourceType;
+    }
+
+    /**
+     * API to set the interface type of the resource. Example: oic.if.baseline,
+     * oic.if.b, etc.
+     *
+     * @param interfaceType
+     *            Interface type of the resource.
+     */
+    private void setInterfaceType(String interfaceType) {
+        this.interfaceType = interfaceType;
+    }
+
+    /**
+     * API to get the resource name. Example: Light, Fan, etc.
+     *
+     * @return Resource name.
+     */
+    public String getName() {
+        return resourceName;
+    }
+
+    /**
+     * API to get the resource URI. Example: /oic/light, /oic/fan, etc.
+     *
+     * @return Resource URI.
+     */
+    public String getURI() {
+        return resourceURI;
+    }
+
+    /**
+     * API to get the resource Type. Example: oic.light, oic.fan, etc.
+     *
+     * @return Resource type.
+     */
+    public String getResourceType() {
+        return resourceType;
+    }
+
+    /**
+     * API to get the interface type of the resource. Example: oic.if.baseline,
+     * oic.if.b, etc.
+     *
+     * @return Interface type of the resource.
+     */
+    public String getInterfaceType() {
+        return interfaceType;
+    }
+
+    @Override
+    protected void finalize() throws Throwable {
+        dispose();
+    }
+
+    /**
+     * Native function to get the {@link SimulatorResourceModel} of the
+     * corresponding resource.
+     *
+     * @return {@link SimulatorResourceModel} object on success, otherwise null.
+     */
+    public native SimulatorResourceModel getModel();
+
+    /**
+     * Native function to automatically update the value of an attribute from
+     * its allowed values.
+     *
+     * @param attrName
+     *            Name of the attribute
+     *
+     * @param index
+     *            Index of the value in the allowed values.
+     */
+    public native void updateAttributeFromAllowedValues(String attrName,
+            int index);
+
+    /**
+     * Native function to set the range of allowed values. This function is
+     * intended to be used for integral type attributes.
+     *
+     * @param attrName
+     *            Name of the attribute
+     * @param min
+     *            Minimum value in the range.
+     * @param max
+     *            Maximum value in the range.
+     */
+    public native void setRange(String attrName, int min, int max);
+
+    /**
+     * Native function to add an attribute whose value is of type int.
+     *
+     * @param key
+     *            Name of the attribute
+     * @param value
+     *            Initial value of the attribute
+     */
+    public native void addAttributeInteger(String key, int value);
+
+    /**
+     * Native function to add an attribute whose value is of type double.
+     *
+     * @param key
+     *            Name of the attribute
+     * @param value
+     *            Initial value of the attribute
+     */
+    public native void addAttributeDouble(String key, double value);
+
+    /**
+     * Native function to add an attribute whose value is of type Boolean.
+     *
+     * @param key
+     *            Name of the attribute
+     * @param value
+     *            Initial value of the attribute
+     */
+    public native void addAttributeBoolean(String key, Boolean value);
+
+    /**
+     * Native function to add an attribute whose value is of type String.
+     *
+     * @param key
+     *            Name of the attribute
+     * @param value
+     *            Initial value of the attribute
+     */
+    public native void addAttributeStringN(String key, String value);
+
+    /**
+     * Native function to update the value of an attribute whose value is of
+     * type int.
+     *
+     * @param key
+     *            Name of the attribute
+     * @param value
+     *            New value of the attribute
+     */
+    public native void updateAttributeInteger(String key, int value);
+
+    /**
+     * Native function to update the value of an attribute whose value is of
+     * type double.
+     *
+     * @param key
+     *            Name of the attribute
+     * @param value
+     *            New value of the attribute
+     */
+    public native void updateAttributeDouble(String key, double value);
+
+    /**
+     * Native function to update the value of an attribute whose value is of
+     * type boolean.
+     *
+     * @param key
+     *            Name of the attribute
+     * @param value
+     *            New value of the attribute
+     */
+    public native void updateAttributeBoolean(String key, Boolean value);
+
+    /**
+     * Native function to update the value of an attribute whose value is of
+     * type String.
+     *
+     * @param key
+     *            Name of the attribute
+     * @param value
+     *            New value of the attribute
+     */
+    public native void updateAttributeStringN(String key, String value);
+
+    /**
+     * Native function to set the allowed values of attribute whose value is of
+     * type int.
+     *
+     * @param key
+     *            Name of the attribute
+     * @param allowedValues
+     *            Allowed values of the attribute
+     */
+    public native void setAllowedValuesInteger(String key,
+            Vector<Integer> allowedValues);
+
+    /**
+     * Native function to set the allowed values of attribute whose value is of
+     * type double.
+     *
+     * @param key
+     *            Name of the attribute
+     * @param allowedValues
+     *            Allowed values of the attribute
+     */
+    public native void setAllowedValuesDouble(String key,
+            Vector<Double> allowedValues);
+
+    /**
+     * Native function to set the allowed values of attribute whose value is of
+     * type String.
+     *
+     * @param key
+     *            Name of the attribute
+     * @param allowedValues
+     *            Allowed values of the attribute
+     */
+    public native void setAllowedValuesStringN(String key,
+            Vector<String> allowedValues);
+
+    /**
+     * Native function to start the resource level automation. This automation
+     * involves automatically updating all the possible values for all the
+     * attributes sequentially.
+     *
+     * @param typeOfAutomation
+     *            Indicates whether the automation is one-time or recursive.
+     * @param listener
+     *            Listener to be notified when automation ends.
+     *
+     * @return Automation ID using which the automation can be stopped.
+     */
+    public native int startResourceAutomation(int typeOfAutomation,
+            IAutomation listener);
+
+    /**
+     * Native function to start the attribute level automation. This automation
+     * involves automatically updating all the possible values for a given
+     * attribute sequentially.
+     *
+     * @param attrName
+     *            Name of the attribute to be automated.
+     * @param typeOfAutomation
+     *            Indicates whether the automation is one-time or recursive.
+     * @param listener
+     *            Listener to be notified when automation ends.
+     *
+     * @return Automation ID using which the automation can be stopped.
+     */
+    public native int startAttributeAutomation(String attrName,
+            int typeOfAutomation, IAutomation listener);
+
+    /**
+     * Native function to stop the automation.
+     *
+     * @param automationId
+     *            Using which a specific automation can be stopped.
+     */
+    public native void stopAutomation(int automationId);
+
+    /**
+     * Native function to remove an attribute from the resource model.
+     *
+     * @param key
+     *            Name of the attribute to be deleted
+     */
+    public native void removeAttribute(String key);
+
+    /**
+     * Native function to release the memory allocated to the native object for
+     * SimulatorResourceServer.
+     */
+    private native void dispose();
+}
diff --git a/service/simulator/ramlparser/SConscript b/service/simulator/ramlparser/SConscript
new file mode 100755 (executable)
index 0000000..51e8fdd
--- /dev/null
@@ -0,0 +1,50 @@
+#******************************************************************\r
+#\r
+# Copyright 2014 Samsung Electronics All Rights Reserved.\r
+#\r
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+#\r
+# Licensed under the Apache License, Version 2.0 (the "License");\r
+# you may not use this file except in compliance with the License.\r
+# You may obtain a copy of the License at\r
+#\r
+#      http://www.apache.org/licenses/LICENSE-2.0\r
+#\r
+# Unless required by applicable law or agreed to in writing, software\r
+# distributed under the License is distributed on an "AS IS" BASIS,\r
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+# See the License for the specific language governing permissions and\r
+# limitations under the License.\r
+#\r
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+\r
+import os\r
+Import('env')\r
+lib_env = env.Clone()\r
+SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env')\r
+raml_env = lib_env.Clone()\r
+\r
+######################################################################\r
+# Build flags\r
+######################################################################\r
+raml_env.AppendUnique(CPPPATH = ['../../../extlibs/timer'])\r
+raml_env.AppendUnique(CPPPATH = ['raml/model','raml', '../../../extlibs/yaml/yaml/src' , '../../../extlibs/yaml/yaml/include'])\r
+raml_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])\r
+raml_env.AppendUnique(CPPDEFINES = ['LINUX'])\r
+\r
+raml_env.AppendUnique(CPPPATH = ['../../../extlibs/cjson/'])\r
+raml_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'libcoap','YamlParser'])\r
+raml_env.AppendUnique(LIBS = ['pthread'])\r
+\r
+raml_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x'])\r
+\r
+######################################################################\r
+# Source files and Targets\r
+######################################################################\r
+raml_src = [env.Glob('raml/model/*.cpp'), env.Glob('raml/*.cpp')]\r
+ramlsdk = raml_env.SharedLibrary('RamlParser', raml_src)\r
+\r
+raml_env.InstallTarget(ramlsdk, 'libRaml')\r
+\r
+SConscript('../../../extlibs/yaml/SConscript')\r
+\r
diff --git a/service/simulator/ramlparser/raml/IncludeResolver.cpp b/service/simulator/ramlparser/raml/IncludeResolver.cpp
new file mode 100755 (executable)
index 0000000..6065224
--- /dev/null
@@ -0,0 +1,73 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *             http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#include "IncludeResolver.h"\r
+\r
+namespace RAML\r
+{\r
+\r
+    YAML::Node IncludeResolver::readToYamlNode(const YAML::Node &yamlFile )\r
+    {\r
+        std::string value = yamlFile.as<std::string>();\r
+        YAML::Node yamlInclueNode = YAML::LoadFile(value);\r
+        return yamlInclueNode;\r
+    }\r
+\r
+    IncludeResolver::FileType IncludeResolver::getFileType(const YAML::Node &yamlNode )\r
+    {\r
+        IncludeResolver::FileType fileType = IncludeResolver::FileType::NOTAG;\r
+        if (yamlNode.Tag() == "!include")\r
+        {\r
+            std::string value = yamlNode.as<std::string>();\r
+            std::size_t found = value.find_last_of(".");\r
+            if (found > value.length())\r
+            {\r
+                fileType = IncludeResolver::FileType::FILE;\r
+                return fileType;\r
+            }\r
+            std::string extension = value.substr(found + 1);\r
+            if (std::find(Keys::AllowedRamlYamlTypes.begin(), Keys::AllowedRamlYamlTypes.end(),\r
+                          extension) != Keys::AllowedRamlYamlTypes.end())\r
+                fileType = IncludeResolver::FileType::NODE;\r
+            else if (extension == Keys::Json)\r
+                fileType = IncludeResolver::FileType::JSON;\r
+            else\r
+                fileType = IncludeResolver::FileType::FILE;\r
+        }\r
+        return fileType;\r
+    }\r
+\r
+    cJSON *IncludeResolver::readToJson(const YAML::Node &jsonFile)\r
+    {\r
+        return cJSON_Parse(readFromFile(jsonFile).c_str());\r
+    }\r
+\r
+    std::string IncludeResolver::readFromFile(const YAML::Node &file )\r
+    {\r
+        std::string val = file.as<std::string>();\r
+        std::ifstream fin((m_path + val).c_str());\r
+        if (!fin)\r
+            throw std::runtime_error("Error Include File not present ");\r
+        std::stringstream buffer;\r
+        buffer << fin.rdbuf();\r
+        return buffer.str();\r
+    }\r
+\r
+}\r
diff --git a/service/simulator/ramlparser/raml/IncludeResolver.h b/service/simulator/ramlparser/raml/IncludeResolver.h
new file mode 100755 (executable)
index 0000000..cb2cac3
--- /dev/null
@@ -0,0 +1,55 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *             http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#ifndef INCLUDE_RESOLVER_H\r
+#define INCLUDE_RESOLVER_H\r
+\r
+#include "yaml-cpp/yaml.h"\r
+#include "cJSON.h"\r
+#include "Utils.h"\r
+#include <fstream>\r
+#include "yaml-cpp/exceptions.h"\r
+\r
+namespace RAML\r
+{\r
+    class IncludeResolver\r
+    {\r
+\r
+        public:\r
+            enum class FileType\r
+            {\r
+                NODE, JSON, FILE, NOTAG , ERROR\r
+            };\r
+\r
+\r
+        public:\r
+            YAML::Node readToYamlNode(const YAML::Node &yamlFile );\r
+            cJSON *readToJson(const YAML::Node &jsonFile );\r
+            std::string readFromFile(const YAML::Node &file );\r
+            FileType getFileType(const YAML::Node &yamlNode );\r
+\r
+            IncludeResolver() {}\r
+            IncludeResolver(std::string &path) : m_path(path) {}\r
+        private:\r
+            std::string m_path;\r
+    };\r
+\r
+}\r
+#endif\r
diff --git a/service/simulator/ramlparser/raml/RamlParser.cpp b/service/simulator/ramlparser/raml/RamlParser.cpp
new file mode 100755 (executable)
index 0000000..e9e4d0e
--- /dev/null
@@ -0,0 +1,246 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *             http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#include "RamlParser.h"\r
+#include <map>\r
+\r
+namespace RAML\r
+{\r
+    RamlPtr RamlParser::build()\r
+    {\r
+        YAML::Node yamlRootNode = YAML::LoadFile(m_fileLocation + m_ramlName);\r
+        m_ramlPtr->readRamlFromYaml(yamlRootNode);\r
+        setDataFromRoot();\r
+        return (m_ramlPtr);\r
+\r
+    }\r
+    RamlPtr RamlParser::getRamlPtr()\r
+    {\r
+        return m_ramlPtr;\r
+    }\r
+    void RamlParser::setDataFromRoot()\r
+    {\r
+        setTypes(getRamlPtr()->getResources());\r
+        setTraits(getRamlPtr()->getResources());\r
+        setBodyDefaultMediaType(getRamlPtr()->getResources());\r
+        setBodySchema(getRamlPtr()->getResources());\r
+    }\r
+    void RamlParser::setBodyDefaultMediaType(std::map<std::string, RamlResource> resource)\r
+    {\r
+        if (getRamlPtr()->getMediaType().empty())\r
+        {\r
+            return;\r
+        }\r
+        for (auto it : resource)\r
+        {\r
+            std::string type = getRamlPtr()->getMediaType();\r
+\r
+            for (auto  action :  it.second.getActions())\r
+            {\r
+                if (action.second.getRequestBody().empty())\r
+                {\r
+                    std::string resName = it.first;\r
+                    getRamlPtr()->getResource(resName).getAction(action.first).setRequestBody(type);\r
+                }\r
+                for (auto  response : action.second.getResponses())\r
+                {\r
+                    if (response.second.getResponseBody().empty())\r
+                    {\r
+                        std::string resName = it.first;\r
+                        std::string responseCode = response.first;\r
+                        getRamlPtr()->getResource(resName).getAction(action.first).getResponse(\r
+                            responseCode).setResponseBody(\r
+                                type);\r
+                    }\r
+                }\r
+            }\r
+        }\r
+    }\r
+    void RamlParser::setBodySchema(std::map<std::string, RamlResource> resource)\r
+    {\r
+        if (getRamlPtr()->getSchemas().empty())\r
+        {\r
+            return;\r
+        }\r
+        for (auto  it : resource)\r
+        {\r
+            for (auto  action :  it.second.getActions())\r
+            {\r
+                for (auto  body :  action.second.getRequestBody())\r
+                {\r
+                    Schema *schema = body.second.getSchema();\r
+\r
+                    if (schema != NULL)\r
+                    {\r
+                        std::string schemaValue = schema->getSchema();\r
+                        auto pos = std::find_if(getRamlPtr()->getSchemas().begin(), getRamlPtr()->getSchemas().end(),\r
+                                                [schemaValue](std::pair<std::string, Schema> const & pair)\r
+                        {\r
+                            return (pair.first == schemaValue);\r
+                        });\r
+                        if (pos != getRamlPtr()->getSchemas().end())\r
+                        {\r
+                            schema->setSchema((pos->second.getSchema()));\r
+                        }\r
+                    }\r
+                }\r
+                for (auto  response : action.second.getResponses())\r
+                {\r
+                    for (auto  body :  response.second.getResponseBody())\r
+                    {\r
+                        Schema *schema = body.second.getSchema();\r
+                        if (schema != NULL)\r
+                        {\r
+                            std::string schemaValue = schema->getSchema();\r
+                            auto schemas = getRamlPtr()->getSchemas();\r
+\r
+                            auto iter = schemas.begin();\r
+                            for (; iter != schemas.end(); iter++)\r
+                            {\r
+                                if (((*iter).first) == schemaValue)\r
+                                    break;\r
+                            }\r
+                            if (iter != schemas.end())\r
+                            {\r
+                                schema->setSchema((*iter).second.getSchema());\r
+                            }\r
+                        }\r
+                    }\r
+                }\r
+            }\r
+        }\r
+    }\r
+    void RamlParser::setTypes(std::map<std::string, RamlResource> resource)\r
+    {\r
+        if (getRamlPtr()->getResourceTypes().empty())\r
+        {\r
+            return;\r
+        }\r
+        for (auto  it : resource)\r
+        {\r
+            auto resourceTypes = getRamlPtr()->getResourceTypes();\r
+            std::string typeValue = it.second.getResourceType();\r
+\r
+            auto iter = resourceTypes.begin();\r
+            for (; iter != resourceTypes.end(); iter++)\r
+            {\r
+                if (((*iter).first) == typeValue)\r
+                    break;\r
+            }\r
+            if (iter != resourceTypes.end())\r
+            {\r
+                std::string resName = it.first;\r
+                RamlResource &res = getRamlPtr()->getResource(resName);\r
+                RamlResource resType =  (*iter).second;\r
+\r
+                if (resType.getActions().empty())\r
+                    return;\r
+\r
+                for (auto resActions : resType.getActions())\r
+                {\r
+                    if (res.getActions().count(resActions.first) == 0)\r
+                        res.setAction(resActions.first, resActions.second);\r
+                }\r
+            }\r
+        }\r
+    }\r
+    void RamlParser::setTraits(std::map<std::string, RamlResource> resource)\r
+    {\r
+        if (getRamlPtr()->getTraits().empty())\r
+        {\r
+            return;\r
+        }\r
+        for (auto  it : resource)\r
+        {\r
+            auto trait = getRamlPtr()->getTraits();\r
+            for (auto act : it.second.getActions())\r
+            {\r
+                for (std::string  traitValue :  act.second.getTraits())\r
+                {\r
+                    auto iter = trait.begin();\r
+                    for (; iter != trait.end(); iter++)\r
+                    {\r
+                        if (((*iter).first) == traitValue)\r
+                            break;\r
+                    }\r
+                    if (iter != trait.end())\r
+                    {\r
+                        std::string resName = it.first;\r
+                        RamlResource &res = getRamlPtr()->getResource(resName);\r
+                        Action resTrait =  (*iter).second;\r
+\r
+                        Action &action = res.getAction(act.first);\r
+                        for (auto head : resTrait.getHeaders())\r
+                        {\r
+                            if (action.getHeaders().count(head.first) == 0)\r
+                                action.setHeader(head.first, head.second);\r
+                        }\r
+                        for (auto query : resTrait.getQueryParameters())\r
+                        {\r
+                            if (action.getQueryParameters().count(query.first) == 0)\r
+                                action.setQueryParameter(query.first, query.second);\r
+                        }\r
+                        for (auto resp : resTrait.getResponses())\r
+                        {\r
+                            if (action.getResponses().count(resp.first) == 0)\r
+                                action.setResponse(resp.first, resp.second);\r
+                        }\r
+                    }\r
+                }\r
+            }\r
+            for (std::string  traitValue :  it.second.getTraits())\r
+            {\r
+                auto iter = trait.begin();\r
+                for (; iter != trait.end(); iter++)\r
+                {\r
+                    if (((*iter).first) == traitValue)\r
+                        break;\r
+                }\r
+                if (iter != trait.end())\r
+                {\r
+                    std::string resName = it.first;\r
+                    RamlResource &res = getRamlPtr()->getResource(resName);\r
+                    Action resTrait =  (*iter).second;\r
+\r
+                    for (auto act : res.getActions())\r
+                    {\r
+                        Action &action = res.getAction(act.first);\r
+                        for (auto head : resTrait.getHeaders())\r
+                        {\r
+                            if (action.getHeaders().count(head.first) == 0)\r
+                                action.setHeader(head.first, head.second);\r
+                        }\r
+                        for (auto query : resTrait.getQueryParameters())\r
+                        {\r
+                            if (action.getQueryParameters().count(query.first) == 0)\r
+                                action.setQueryParameter(query.first, query.second);\r
+                        }\r
+                        for (auto resp : resTrait.getResponses())\r
+                        {\r
+                            if (action.getResponses().count(resp.first) == 0)\r
+                                action.setResponse(resp.first, resp.second);\r
+                        }\r
+                    }\r
+                }\r
+            }\r
+        }\r
+    }\r
+\r
+}\r
diff --git a/service/simulator/ramlparser/raml/RamlParser.h b/service/simulator/ramlparser/raml/RamlParser.h
new file mode 100755 (executable)
index 0000000..5db9c20
--- /dev/null
@@ -0,0 +1,59 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *             http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#ifndef RAML_PARSER_H\r
+#define RAML_PARSER_H\r
+\r
+#include "yaml-cpp/yaml.h"\r
+#include "Raml.h"\r
+#include "Utils.h"\r
+#include "RequestResponseBody.h"\r
+#include "RamlResource.h"\r
+#include "Action.h"\r
+#include "Response.h"\r
+#include <map>\r
+\r
+namespace RAML\r
+{\r
+    class RamlParser\r
+    {\r
+        private:\r
+            void setDataFromRoot();\r
+            void setBodyDefaultMediaType(std::map<std::string, RamlResource> resource);\r
+            void setBodySchema(std::map<std::string, RamlResource> resource);\r
+            void setTypes(std::map<std::string, RamlResource> resource);\r
+            void setTraits(std::map<std::string, RamlResource> resource);\r
+\r
+        public:\r
+            virtual RamlPtr build();\r
+            virtual RamlPtr getRamlPtr();\r
+            RamlParser(): m_ramlPtr(new Raml()) {}\r
+            RamlParser(std::string &fileLocation,\r
+                       std::string &ramlName): m_ramlPtr(new Raml(fileLocation)) ,\r
+                m_fileLocation(fileLocation) , m_ramlName(ramlName) {}\r
+        private:\r
+\r
+            RamlPtr m_ramlPtr;\r
+            std::string m_fileLocation;\r
+            std::string m_ramlName;\r
+    };\r
+\r
+}\r
+#endif\r
diff --git a/service/simulator/ramlparser/raml/Utils.h b/service/simulator/ramlparser/raml/Utils.h
new file mode 100755 (executable)
index 0000000..9daef9f
--- /dev/null
@@ -0,0 +1,119 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *             http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+\r
+#ifndef UTILS_H\r
+#define UTILS_H\r
+\r
+#include "yaml-cpp/yaml.h"\r
+#include "ActionType.h"\r
+\r
+namespace RAML\r
+{\r
+    namespace Keys\r
+    {\r
+        const std::string Title = "title";\r
+        const std::string Version = "version";\r
+        const std::string BaseUri = "baseUri";\r
+        const std::string Protocols = "protocols";\r
+        const std::string MediaType = "mediaType";\r
+        const std::string Schemas = "schemas";\r
+        const std::string ResourceTypes = "resourceTypes";\r
+        const std::string Traits = "traits";\r
+        const std::string IsTrait = "is";\r
+\r
+        const std::string Resource = "/";\r
+        const std::vector<std::string> ActionType = {"get", "post", "put", "delete", "head", "patch", "options", "trace"};\r
+\r
+        const std::string Responses = "responses";\r
+        const std::string Body = "body";\r
+        const std::string Schema = "schema";\r
+        const std::string Example = "example";\r
+\r
+        const std::string BaseUriParameters = "baseUriParameters";\r
+        const std::string UriParameters = "uriParameters";\r
+        const std::string Headers = "headers";\r
+        const std::string QueryParameters = "queryParameters";\r
+        const std::string FormParameters = "formParameters";\r
+        const std::string DisplayName = "displayName";\r
+        const std::string Description = "description";\r
+        const std::string Type = "type";\r
+        const std::string Enum = "enum";\r
+        const std::string Pattern = "pattern";\r
+        const std::string MinLength = "minLength";\r
+        const std::string MaxLength = "maxLength";\r
+        const std::string Minimum = "minimum";\r
+        const std::string Maximum = "maximum";\r
+        const std::string Repeat = "repeat";\r
+        const std::string Required = "required";\r
+        const std::string Default = "default";\r
+\r
+        const std::string Documentation = "documentation";\r
+        const std::string Content = "content";\r
+\r
+        const std::string Json = "json";\r
+        const std::vector<std::string> AllowedRamlYamlTypes = {"raml", "yaml", "yml"};\r
+\r
+    }\r
+\r
+\r
+#define READ_NODE_AS_STRING(yamlNode)                   \\r
+({                                                      \\r
+(yamlNode).as<std::string>();                           \\r
+})\r
+\r
+#define READ_NODE_AS_INT(yamlNode)                      \\r
+({                                                      \\r
+    (yamlNode).as<int>();                               \\r
+})\r
+\r
+#define READ_NODE_AS_LONG(yamlNode)                     \\r
+({                                                      \\r
+    (yamlNode).as<long>();                              \\r
+})\r
+#define READ_NODE_AS_BOOL(yamlNode)                     \\r
+({                                                      \\r
+        (yamlNode).as<bool>();                          \\r
+})\r
+\r
+#define GET_ACTION_TYPE(key)                            \\r
+({                                                      \\r
+    ActionType actionType;                              \\r
+    if (key == "get" )                                  \\r
+        actionType = ActionType::GET;                               \\r
+    else if (key == "post" )                            \\r
+        actionType = ActionType::POST;                              \\r
+    else if (key == "put" )                             \\r
+        actionType = ActionType::PUT;                               \\r
+    else if (key == "delete" )                          \\r
+        actionType = ActionType::DELETE;                            \\r
+    else if (key == "head" )                            \\r
+        actionType = ActionType::HEAD;                              \\r
+    else if (key == "patch" )                           \\r
+        actionType = ActionType::PATCH;                             \\r
+    else if (key == "options" )                         \\r
+        actionType = ActionType::OPTIONS;                           \\r
+    else if (key == "trace" )                           \\r
+        actionType = ActionType::TRACE;                             \\r
+    actionType;                                         \\r
+})\r
+\r
+}\r
+#endif\r
diff --git a/service/simulator/ramlparser/raml/model/AbstractParam.cpp b/service/simulator/ramlparser/raml/model/AbstractParam.cpp
new file mode 100755 (executable)
index 0000000..550af9a
--- /dev/null
@@ -0,0 +1,195 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *             http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#include "AbstractParam.h"\r
+\r
+\r
+namespace RAML\r
+{\r
+    std::string AbstractParam::getDefaultValue() const\r
+    {\r
+        return m_defaultValue;\r
+    }\r
+    void AbstractParam::setDefaultValue(const std::string &defaultValue)\r
+    {\r
+        m_defaultValue = defaultValue;\r
+    }\r
+\r
+    std::string AbstractParam::getDescription() const\r
+    {\r
+        return m_description;\r
+    }\r
+\r
+    void AbstractParam::setDescription(const std::string &description)\r
+    {\r
+        m_description = description;\r
+    }\r
+\r
+    std::string AbstractParam::getDisplayName() const\r
+    {\r
+        return m_displayName;\r
+    }\r
+\r
+    void AbstractParam::setDisplayName(const std::string &displayName)\r
+    {\r
+        m_displayName = displayName;\r
+    }\r
+\r
+    std::list<std::string> AbstractParam::getEnumeration() const\r
+    {\r
+        return m_enumeration;\r
+    }\r
+\r
+    void AbstractParam::setEnumeration(const std::string &enumeration)\r
+    {\r
+        m_enumeration.push_back(enumeration);\r
+    }\r
+\r
+    std::string AbstractParam::getExample() const\r
+    {\r
+        return m_example;\r
+    }\r
+\r
+    void AbstractParam::setExample(const std::string &example)\r
+    {\r
+        m_example = example;\r
+    }\r
+\r
+    int AbstractParam::getMaxLength() const\r
+    {\r
+        return m_maxLength;\r
+    }\r
+\r
+    void AbstractParam::setMaxLength(int maxLength)\r
+    {\r
+        m_maxLength = maxLength;\r
+    }\r
+\r
+    int AbstractParam::getMaximum() const\r
+    {\r
+        return m_maximum;\r
+    }\r
+\r
+    void AbstractParam::setMaximum(int maximum)\r
+    {\r
+        m_maximum = maximum;\r
+    }\r
+\r
+    int AbstractParam::getMinLength() const\r
+    {\r
+        return m_minLength;\r
+    }\r
+\r
+    void AbstractParam::setMinLength(int minLength)\r
+    {\r
+        m_minLength = minLength;\r
+    }\r
+\r
+    int AbstractParam::getMinimum() const\r
+    {\r
+        return m_minimum;\r
+    }\r
+\r
+    void AbstractParam::setMinimum(int minimum)\r
+    {\r
+        m_minimum = minimum;\r
+    }\r
+\r
+    std::string AbstractParam::getPattern() const\r
+    {\r
+        return m_pattern;\r
+    }\r
+\r
+    void AbstractParam::setPattern(const std::string &pattern)\r
+    {\r
+        m_pattern = pattern;\r
+    }\r
+\r
+    std::string AbstractParam::getType() const\r
+    {\r
+        return m_type;\r
+    }\r
+\r
+    void AbstractParam::setType(const std::string &type)\r
+    {\r
+        m_type = type;\r
+    }\r
+\r
+    bool AbstractParam::isRepeat() const\r
+    {\r
+        return m_repeat;\r
+    }\r
+\r
+    void AbstractParam::setRepeat(bool repeat)\r
+    {\r
+        m_repeat = repeat;\r
+    }\r
+\r
+    bool AbstractParam::isRequired() const\r
+    {\r
+        return m_required;\r
+    }\r
+\r
+    void AbstractParam::setRequired(bool required)\r
+    {\r
+        m_required = required;\r
+    }\r
+\r
+    void AbstractParam::readParameters(const YAML::Node &yamlNode)\r
+    {\r
+        for ( YAML::const_iterator it = yamlNode.begin(); it != yamlNode.end(); ++it )\r
+        {\r
+            std::string key = READ_NODE_AS_STRING(it->first);\r
+\r
+            if (key == Keys::Description)\r
+                setDescription(READ_NODE_AS_STRING(it->second));\r
+            else if (key == Keys::Default)\r
+                setDefaultValue(READ_NODE_AS_STRING(it->second));\r
+            else if (key == Keys::DisplayName)\r
+                setDisplayName(READ_NODE_AS_STRING(it->second));\r
+\r
+            else if (key == Keys::Example)\r
+                setExample(READ_NODE_AS_STRING(it->second));\r
+            else if (key == Keys::Maximum)\r
+                setMaximum(READ_NODE_AS_LONG(it->second));\r
+            else if (key == Keys::Minimum)\r
+                setMinimum(READ_NODE_AS_LONG(it->second));\r
+            else if (key == Keys::MaxLength)\r
+                setMaxLength(READ_NODE_AS_INT(it->second));\r
+            else if (key == Keys::MinLength)\r
+                setMinLength(READ_NODE_AS_INT(it->second));\r
+\r
+            else if (key == Keys::Pattern)\r
+                setPattern(READ_NODE_AS_STRING(it->second));\r
+            else if (key == Keys::Repeat)\r
+                setRepeat(READ_NODE_AS_BOOL(it->second));\r
+            else if (key == Keys::Required)\r
+                setRequired(READ_NODE_AS_BOOL(it->second));\r
+            else if (key == Keys::Type)\r
+                setType(READ_NODE_AS_STRING(it->second));\r
+            else if (key == Keys::Enum)\r
+            {\r
+                YAML::Node enumNode = it->second;\r
+                for ( YAML::const_iterator tt = enumNode.begin(); tt != enumNode.end(); ++tt )\r
+                    setEnumeration(READ_NODE_AS_STRING(*tt));\r
+            }\r
+        }\r
+    }\r
+}\r
diff --git a/service/simulator/ramlparser/raml/model/AbstractParam.h b/service/simulator/ramlparser/raml/model/AbstractParam.h
new file mode 100755 (executable)
index 0000000..fc3533c
--- /dev/null
@@ -0,0 +1,105 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *             http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#ifndef ABSTRACT_PARAM_H\r
+#define ABSTRACT_PARAM_H\r
+\r
+\r
+#include <map>\r
+#include <list>\r
+#include <string>\r
+#include "Utils.h"\r
+\r
+\r
+namespace RAML\r
+{\r
+    class AbstractParam\r
+    {\r
+        public:\r
+            virtual std::string getDefaultValue() const;\r
+            virtual void setDefaultValue(const std::string &defaultValue);\r
+\r
+            virtual std::string getDescription() const;\r
+            virtual void setDescription(const std::string &description);\r
+\r
+            virtual std::string getDisplayName() const;\r
+            virtual void setDisplayName(const std::string &displayName);\r
+\r
+            virtual std::list<std::string> getEnumeration() const;\r
+            virtual void setEnumeration(const std::string &enumeration);\r
+\r
+            virtual std::string getExample() const;\r
+            virtual void setExample(const std::string &example);\r
+\r
+            virtual int getMaxLength() const;\r
+            virtual void setMaxLength(int maxLength);\r
+\r
+            virtual int getMaximum() const;\r
+            virtual void setMaximum(int maximum);\r
+\r
+            virtual int getMinLength() const;\r
+            virtual void setMinLength(int minLength);\r
+\r
+            virtual int getMinimum() const;\r
+            virtual void setMinimum(int minimum);\r
+\r
+            virtual std::string getPattern() const;\r
+            virtual void setPattern(const std::string &pattern) ;\r
+\r
+            virtual std::string getType() const;\r
+            virtual void setType(const std::string &type);\r
+\r
+            virtual bool isRepeat() const;\r
+            virtual void setRepeat(bool repeat);\r
+\r
+            virtual bool isRequired() const;\r
+            virtual void setRequired(bool required);\r
+\r
+\r
+            AbstractParam() : m_maximum(0), m_minimum(0), m_minLength(0), m_maxLength(0), m_repeat(false),\r
+                m_required(false) {}\r
+            AbstractParam(const YAML::Node &yamlNode) : m_maximum(0), m_minimum(0), m_minLength(0),\r
+                m_maxLength(0), m_repeat(false), m_required(false)\r
+            {\r
+                readParameters(yamlNode);\r
+            }\r
+        private:\r
+            virtual void readParameters(const YAML::Node &yamlNode);\r
+\r
+        private:\r
+            std::string m_defaultValue;\r
+            std::string m_description;\r
+            std::string m_displayName;\r
+            std::list<std::string> m_enumeration;\r
+            std::string m_example;\r
+            int m_maxLength;\r
+            int m_maximum;\r
+            int m_minLength;\r
+            int m_minimum;\r
+            std::string m_pattern;\r
+            bool m_repeat;\r
+            bool m_required;\r
+            std::string m_type;\r
+\r
+\r
+    };\r
+\r
+}\r
+#endif\r
diff --git a/service/simulator/ramlparser/raml/model/Action.cpp b/service/simulator/ramlparser/raml/model/Action.cpp
new file mode 100755 (executable)
index 0000000..346fa9e
--- /dev/null
@@ -0,0 +1,192 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *             http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#include "Action.h"\r
+\r
+namespace RAML\r
+{\r
+    ActionType Action::getType() const\r
+    {\r
+        return m_type;\r
+    }\r
+    void Action::setType(const ActionType &type)\r
+    {\r
+        m_type = type;\r
+    }\r
+    std::string Action::getDescription() const\r
+    {\r
+        return m_description;\r
+    }\r
+    void Action::setDescription(const std::string &description)\r
+    {\r
+        m_description = description;\r
+    }\r
+    std::map<std::string, Header> Action::getHeaders() const\r
+    {\r
+        return m_headers;\r
+    }\r
+    void Action::setHeader(const std::string &headerName, const Header &header)\r
+    {\r
+        m_headers[headerName] = header;\r
+    }\r
+    std::map<std::string, QueryParameter> Action::getQueryParameters()const\r
+    {\r
+        return m_queryParameters;\r
+    }\r
+    void Action::setQueryParameter(const std::string &paramName, const QueryParameter &queryParameter)\r
+    {\r
+        m_queryParameters[paramName] = queryParameter;\r
+    }\r
+    RequestResponseBody &Action::getRequestBody(std::string bodyType)\r
+    {\r
+        return m_requestBody[bodyType];\r
+    }\r
+\r
+    std::map<std::string, RequestResponseBody> Action::getRequestBody() const\r
+    {\r
+        return m_requestBody;\r
+    }\r
+    void Action::setRequestBody(const std::string &typeName)\r
+    {\r
+        m_requestBody[typeName] = *(new RequestResponseBody(typeName));\r
+    }\r
+\r
+    void Action::setRequestBody(const std::string &typeName , const RequestResponseBody &body)\r
+    {\r
+        m_requestBody[typeName] = body;\r
+    }\r
+    Response &Action::getResponse(std::string responseCode)\r
+    {\r
+        return m_responses[responseCode];\r
+    }\r
+\r
+    std::map<std::string, Response> Action::getResponses() const\r
+    {\r
+        return m_responses;\r
+    }\r
+    void Action::setResponse(const std::string &responseCode, const Response &response)\r
+    {\r
+        m_responses[responseCode] = response;\r
+    }\r
+\r
+    std::list<std::string> Action::getProtocols() const\r
+    {\r
+        return m_protocols;\r
+    }\r
+    void Action::setProtocol(const std::string &protocol)\r
+    {\r
+        m_protocols.push_back(protocol);\r
+    }\r
+    std::map<std::string, UriParameter > Action::getBaseUriParameters() const\r
+    {\r
+        return m_baseUriParameters;\r
+    }\r
+    void Action::setBaseUriParameter(const std::string &paramName ,\r
+                                     const UriParameter  &baseUriParameter)\r
+    {\r
+        m_baseUriParameters[paramName] = baseUriParameter;\r
+    }\r
+\r
+    std::list<std::string> Action::getTraits() const\r
+    {\r
+        return m_trait;\r
+    }\r
+    void Action::setTrait(const std::string &trait)\r
+    {\r
+        m_trait.push_back(trait);\r
+    }\r
+    void Action::readAction(const ActionType actionType, const YAML::Node &yamlNode,\r
+                            IncludeResolver *includeResolver)\r
+    {\r
+        m_includeResolver = includeResolver;\r
+        m_type = actionType;\r
+        for ( YAML::const_iterator it = yamlNode.begin(); it != yamlNode.end(); ++it )\r
+        {\r
+            std::string key = READ_NODE_AS_STRING(it->first);\r
+\r
+            if (key == Keys::Description)\r
+                setDescription(READ_NODE_AS_STRING(it->second));\r
+            else if (key == Keys::Responses)\r
+            {\r
+                YAML::Node responseNode = it->second;\r
+                for ( YAML::const_iterator tt = responseNode.begin(); tt != responseNode.end(); ++tt )\r
+                {\r
+                    std::string responseCode = READ_NODE_AS_STRING(tt->first);\r
+                    setResponse(responseCode, *(new Response(tt->second, m_includeResolver)));\r
+                }\r
+            }\r
+            else if (key == Keys::Headers)\r
+            {\r
+                YAML::Node paramNode = it->second;\r
+                for ( YAML::const_iterator tt = paramNode.begin(); tt != paramNode.end(); ++tt )\r
+                {\r
+                    Header *header = new Header(tt->second);\r
+                    setHeader(READ_NODE_AS_STRING(tt->first), *header);\r
+                }\r
+            }\r
+            else if (key == Keys::QueryParameters)\r
+            {\r
+                YAML::Node paramNode = it->second;\r
+                for ( YAML::const_iterator tt = paramNode.begin(); tt != paramNode.end(); ++tt )\r
+                {\r
+                    QueryParameter *queryParameter = new QueryParameter(tt->second);\r
+                    setQueryParameter(READ_NODE_AS_STRING(tt->first), *queryParameter);\r
+                }\r
+            }\r
+            else if (key == Keys::Protocols)\r
+            {\r
+                YAML::Node protocolNode = it->second;\r
+                for ( YAML::const_iterator tt = protocolNode.begin(); tt != protocolNode.end(); ++tt )\r
+                {\r
+                    setProtocol(READ_NODE_AS_STRING(*tt));\r
+                }\r
+            }\r
+            else if (key == Keys::BaseUriParameters)\r
+            {\r
+                YAML::Node paramNode = it->second;\r
+                for ( YAML::const_iterator tt = paramNode.begin(); tt != paramNode.end(); ++tt )\r
+                {\r
+                    UriParameter *uriParameter = new UriParameter(tt->second);\r
+                    setBaseUriParameter(READ_NODE_AS_STRING(tt->first), *uriParameter);\r
+                }\r
+            }\r
+            else if (key == Keys::Body)\r
+            {\r
+                YAML::Node responseBody = it->second;\r
+\r
+                for ( YAML::const_iterator tt = responseBody.begin(); tt != responseBody.end(); ++tt )\r
+                {\r
+                    std::string type = READ_NODE_AS_STRING(tt->first);\r
+                    setRequestBody(type, *(new RequestResponseBody(type, tt->second, m_includeResolver)));\r
+                }\r
+            }\r
+            else if (key == Keys::IsTrait)\r
+            {\r
+                YAML::Node traitNode = it->second;\r
+                for ( YAML::const_iterator tt = traitNode.begin(); tt != traitNode.end(); ++tt )\r
+                {\r
+                    setTrait(READ_NODE_AS_STRING(*tt));\r
+                }\r
+            }\r
+        }\r
+    }\r
+\r
+};\r
+\r
diff --git a/service/simulator/ramlparser/raml/model/Action.h b/service/simulator/ramlparser/raml/model/Action.h
new file mode 100755 (executable)
index 0000000..c843bf4
--- /dev/null
@@ -0,0 +1,91 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *             http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#ifndef ACTION_H\r
+#define ACTION_H\r
+\r
+#include <map>\r
+#include <list>\r
+#include <string>\r
+#include "ActionType.h"\r
+#include "Header.h"\r
+#include "QueryParameter.h"\r
+#include "RequestResponseBody.h"\r
+#include "UriParameter.h"\r
+#include "Response.h"\r
+#include "Utils.h"\r
+#include "IncludeResolver.h"\r
+\r
+namespace RAML\r
+{\r
+    class Action\r
+    {\r
+        public:\r
+            virtual ActionType getType() const;\r
+            virtual void setType(const ActionType &type);\r
+            virtual std::string getDescription() const;\r
+            virtual void setDescription(const std::string &description);\r
+            virtual std::map<std::string, Header> getHeaders() const;\r
+            virtual void setHeader(const std::string &headerName, const Header &header);\r
+            virtual std::map<std::string, QueryParameter> getQueryParameters()const;\r
+            virtual void setQueryParameter(const std::string &paramName, const QueryParameter &queryParameter);\r
+            virtual RequestResponseBody &getRequestBody(std::string bodyType);\r
+            virtual std::map<std::string, RequestResponseBody> getRequestBody() const;\r
+            virtual void setRequestBody(const std::string &typeName);\r
+            virtual void setRequestBody(const std::string &typeName , const RequestResponseBody &body);\r
+            virtual Response &getResponse(std::string responseCode);\r
+            virtual std::map<std::string, Response> getResponses() const;\r
+            virtual void setResponse(const std::string &responseCode, const Response &response);\r
+            virtual std::list<std::string> getProtocols() const;\r
+            virtual void setProtocol(const std::string &protocol);\r
+            virtual std::map< std::string, UriParameter > getBaseUriParameters() const;\r
+            virtual void setBaseUriParameter(const std::string &paramName ,\r
+                                             const UriParameter  &baseUriParameter);\r
+            virtual std::list<std::string> getTraits() const;\r
+            virtual void setTrait(const std::string &trait);\r
+\r
+\r
+            Action() { }\r
+            Action(const ActionType actionType, const YAML::Node &yamlNode, IncludeResolver *includeResolver)\r
+            {\r
+                readAction(actionType, yamlNode, includeResolver);\r
+            }\r
+\r
+        private:\r
+            virtual void readAction(const ActionType actionType, const YAML::Node &yamlNode,\r
+                                    IncludeResolver *includeResolver);\r
+\r
+\r
+        private:\r
+            ActionType m_type;\r
+            std::string m_description;\r
+            std::map<std::string, Header> m_headers;\r
+            std::map<std::string, QueryParameter> m_queryParameters;\r
+            std::map<std::string, RequestResponseBody> m_requestBody;\r
+            std::map<std::string, Response> m_responses;\r
+            std::list<std::string> m_protocols;\r
+            std::map< std::string, UriParameter > m_baseUriParameters;\r
+            std::list<std::string> m_trait;\r
+\r
+        private:\r
+            IncludeResolver *m_includeResolver;\r
+    };\r
+}\r
+#endif\r
diff --git a/service/simulator/ramlparser/raml/model/ActionType.h b/service/simulator/ramlparser/raml/model/ActionType.h
new file mode 100755 (executable)
index 0000000..8921b1e
--- /dev/null
@@ -0,0 +1,32 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *             http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#ifndef ACTION_TYPE_H\r
+#define ACTION_TYPE_H\r
+\r
+namespace RAML\r
+{\r
+    enum class ActionType\r
+    {\r
+        GET, POST, PUT, DELETE, HEAD, PATCH, OPTIONS, TRACE, NONE\r
+    };\r
+\r
+}\r
+#endif\r
diff --git a/service/simulator/ramlparser/raml/model/DocumentationItem.cpp b/service/simulator/ramlparser/raml/model/DocumentationItem.cpp
new file mode 100755 (executable)
index 0000000..4b83366
--- /dev/null
@@ -0,0 +1,43 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *             http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#include "DocumentationItem.h"\r
+\r
+namespace RAML\r
+{\r
+\r
+    std::string DocumentationItem::getTitle() const\r
+    {\r
+        return m_title;\r
+    }\r
+    void DocumentationItem::setTitle(const std::string &title)\r
+    {\r
+        m_title = title;\r
+    }\r
+    std::string DocumentationItem::getContent() const\r
+    {\r
+        return m_content;\r
+    }\r
+    void DocumentationItem::setContent(const std::string &content)\r
+    {\r
+        m_content = content;\r
+    }\r
+\r
+}\r
diff --git a/service/simulator/ramlparser/raml/model/DocumentationItem.h b/service/simulator/ramlparser/raml/model/DocumentationItem.h
new file mode 100755 (executable)
index 0000000..d432ede
--- /dev/null
@@ -0,0 +1,48 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *             http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#ifndef DOCUMENTATION_ITEM_H\r
+#define DOCUMENTATION_ITEM_H\r
+\r
+#include <string>\r
+\r
+\r
+namespace RAML\r
+{\r
+    class DocumentationItem\r
+    {\r
+\r
+        public:\r
+            virtual std::string getTitle() const;\r
+            virtual void setTitle(const std::string &title);\r
+            virtual std::string getContent() const;\r
+            virtual void setContent(const std::string &content);\r
+\r
+            DocumentationItem();\r
+            DocumentationItem(const std::string &title , const std::string &content) : m_title(title),\r
+                m_content(content) {}\r
+        private:\r
+            std::string m_title;\r
+            std::string m_content;\r
+\r
+    };\r
+\r
+}\r
+#endif\r
diff --git a/service/simulator/ramlparser/raml/model/FormParameter.h b/service/simulator/ramlparser/raml/model/FormParameter.h
new file mode 100755 (executable)
index 0000000..b62d954
--- /dev/null
@@ -0,0 +1,36 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *             http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#ifndef FORM_PARAMETER_H\r
+#define FORM_PARAMETER_H\r
+\r
+#include "AbstractParam.h"\r
+\r
+namespace RAML\r
+{\r
+    class FormParameter: public AbstractParam\r
+    {\r
+        public:\r
+            FormParameter(const YAML::Node &yamlNode) : AbstractParam(yamlNode) {}\r
+            FormParameter() {}\r
+    };\r
+\r
+}\r
+#endif\r
diff --git a/service/simulator/ramlparser/raml/model/Header.h b/service/simulator/ramlparser/raml/model/Header.h
new file mode 100755 (executable)
index 0000000..47e03f7
--- /dev/null
@@ -0,0 +1,37 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *             http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#ifndef HEADER_PARAMETER_H\r
+#define HEADER_PARAMETER_H\r
+\r
+#include "AbstractParam.h"\r
+\r
+namespace RAML\r
+{\r
+    class Header: public AbstractParam\r
+    {\r
+        public:\r
+            Header(const YAML::Node &yamlNode) : AbstractParam(yamlNode) {}\r
+            Header() {}\r
+    };\r
+\r
+}\r
+#endif\r
+\r
diff --git a/service/simulator/ramlparser/raml/model/QueryParameter.h b/service/simulator/ramlparser/raml/model/QueryParameter.h
new file mode 100755 (executable)
index 0000000..d414378
--- /dev/null
@@ -0,0 +1,36 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *             http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#ifndef QUERY_PARAMETER_H\r
+#define QUERY_PARAMETER_H\r
+\r
+#include "AbstractParam.h"\r
+\r
+namespace RAML\r
+{\r
+    class QueryParameter: public AbstractParam\r
+    {\r
+        public:\r
+            QueryParameter(const YAML::Node &yamlNode) : AbstractParam(yamlNode) {}\r
+            QueryParameter() {}\r
+    };\r
+\r
+}\r
+#endif\r
diff --git a/service/simulator/ramlparser/raml/model/Raml.cpp b/service/simulator/ramlparser/raml/model/Raml.cpp
new file mode 100755 (executable)
index 0000000..a9864b4
--- /dev/null
@@ -0,0 +1,263 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *             http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#include "Raml.h"\r
+\r
+namespace RAML\r
+{\r
+\r
+    std::string Raml::getTitle() const\r
+    {\r
+        return m_title;\r
+    }\r
+    void Raml::setTitle(const std::string &title)\r
+    {\r
+        m_title = title;\r
+    }\r
+\r
+    std::string Raml::getVersion() const\r
+    {\r
+        return m_version;\r
+    }\r
+    void Raml::setVersion(const std::string &version)\r
+    {\r
+        m_version = version;\r
+    }\r
+\r
+    std::string Raml::getBaseUri() const\r
+    {\r
+        return m_baseUri;\r
+    }\r
+    void Raml::setBaseUri(const std::string &baseUri)\r
+    {\r
+        m_baseUri = baseUri;\r
+    }\r
+\r
+    std::list<std::string> Raml::getProtocols() const\r
+    {\r
+        return m_protocols;\r
+    }\r
+    void Raml::setProtocol(const std::string &protocol)\r
+    {\r
+        m_protocols.push_back(protocol);\r
+    }\r
+    std::map<std::string, UriParameter> Raml::getBaseUriParameters() const\r
+    {\r
+        return m_baseUriParameters;\r
+    }\r
+    void Raml::setBaseUriParameter(const std::string &paramName, const UriParameter &uriParameter)\r
+    {\r
+        m_baseUriParameters[paramName] = uriParameter;\r
+    }\r
+\r
+    std::string Raml::getMediaType() const\r
+    {\r
+        return m_mediaType;\r
+    }\r
+    void Raml::setMediaType(const std::string &mediaType)\r
+    {\r
+        m_mediaType = mediaType;\r
+    }\r
+\r
+    std::list<std::pair<std::string, Schema> > Raml::getSchemas() const\r
+    {\r
+        return m_schemas;\r
+    }\r
+\r
+    void Raml::setSchema(const std::pair<std::string, Schema> &schema)\r
+    {\r
+        m_schemas.push_back(schema);\r
+    }\r
+\r
+    std::list<std::pair<std::string, RamlResource> > Raml::getResourceTypes() const\r
+    {\r
+        return m_resourceTypes;\r
+    }\r
+    void Raml::setResourceType(const std::pair<std::string, RamlResource> &resourceType)\r
+    {\r
+        m_resourceTypes.push_back(resourceType);\r
+    }\r
+\r
+    std::list<std::pair<std::string, Action> > Raml::getTraits() const\r
+    {\r
+        return m_traits;\r
+    }\r
+    void Raml::setTrait(const std::pair<std::string, Action> &trait)\r
+    {\r
+        m_traits.push_back(trait);\r
+    }\r
+    RamlResource &Raml::getResource(std::string resourceName)\r
+    {\r
+        return m_resources[resourceName];\r
+    }\r
+\r
+    std::map<std::string, RamlResource> Raml::getResources() const\r
+    {\r
+        return m_resources;\r
+    }\r
+\r
+    void Raml::setResource(const std::string &resourceKey, const RamlResource &resource)\r
+    {\r
+        m_resources[resourceKey] = resource;\r
+    }\r
+\r
+    void Raml::setDocumentationItem(const DocumentationItem &documentationItem)\r
+    {\r
+        m_documentation.push_back(documentationItem);\r
+    }\r
+\r
+    std::list<DocumentationItem> Raml::getDocumentation() const\r
+    {\r
+        return m_documentation;\r
+    }\r
+    void Raml::readRamlFromYaml(const YAML::Node &yamlNode )\r
+    {\r
+        if (yamlNode.Type() == YAML::NodeType::Map)\r
+        {\r
+            for ( YAML::const_iterator it = yamlNode.begin(); it != yamlNode.end(); ++it )\r
+            {\r
+                std::string key = READ_NODE_AS_STRING(it->first);\r
+                if (key == Keys::Title)\r
+                {\r
+                    setTitle(READ_NODE_AS_STRING(it->second));\r
+                }\r
+                else if (key == Keys::Version)\r
+                {\r
+                    setVersion(READ_NODE_AS_STRING(it->second));\r
+                }\r
+                else if (key == Keys::BaseUri)\r
+                {\r
+                    setBaseUri(READ_NODE_AS_STRING(it->second));\r
+                }\r
+                else if ((key == Keys::BaseUriParameters) || (key == Keys::UriParameters))\r
+                {\r
+                    YAML::Node paramNode = it->second;\r
+                    for ( YAML::const_iterator tt = paramNode.begin(); tt != paramNode.end(); ++tt )\r
+                    {\r
+                        UriParameter *uriParameter = new UriParameter(tt->second);\r
+                        setBaseUriParameter(READ_NODE_AS_STRING(tt->first), *uriParameter);\r
+                    }\r
+                }\r
+                else if (key == Keys::Protocols)\r
+                {\r
+                    YAML::Node protocolNode = it->second;\r
+                    for ( YAML::const_iterator tt = protocolNode.begin(); tt != protocolNode.end(); ++tt )\r
+                    {\r
+                        setProtocol(READ_NODE_AS_STRING(*tt));\r
+                    }\r
+                }\r
+                else if (key == Keys::MediaType)\r
+                {\r
+                    setMediaType(READ_NODE_AS_STRING(it->second));\r
+                }\r
+                else if (key == Keys::Documentation)\r
+                {\r
+                    YAML::Node docNode = it->second;\r
+                    for ( YAML::const_iterator iit = docNode.begin(); iit != docNode.end(); ++iit )\r
+                    {\r
+                        std::string title ;\r
+                        std::string content ;\r
+\r
+                        for ( YAML::const_iterator tt = (*iit).begin(); tt != (*iit).end(); ++tt )\r
+                        {\r
+                            std::string key = READ_NODE_AS_STRING(tt->first);\r
+\r
+                            if (key == Keys::Title)\r
+                                title = READ_NODE_AS_STRING(tt->second);\r
+                            else if (key == Keys::Content)\r
+                                content = READ_NODE_AS_STRING(tt->second);\r
+\r
+                        }\r
+                        setDocumentationItem(*(new DocumentationItem(title, content)));\r
+                    }\r
+                }\r
+                else if (key == Keys::Schemas)\r
+                {\r
+                    YAML::Node schemaNode = it->second;\r
+                    for ( YAML::const_iterator iit = schemaNode.begin(); iit != schemaNode.end(); ++iit )\r
+                    {\r
+                        for ( YAML::const_iterator tt = (*iit).begin(); tt != (*iit).end(); ++tt )\r
+                        {\r
+                            std::string key = READ_NODE_AS_STRING(tt->first);\r
+                            std::pair<std::string, Schema> schema;\r
+\r
+                            IncludeResolver::FileType fileType = m_includeResolver->getFileType(tt->second);\r
+                            if ((fileType == IncludeResolver::FileType::JSON) || (fileType == IncludeResolver::FileType::FILE))\r
+                            {\r
+                                Schema *schemaPtr = new Schema(m_includeResolver->readFromFile(tt->second));\r
+                                schema = std::make_pair(key, *schemaPtr);\r
+                            }\r
+                            else\r
+                            {\r
+                                std::string value = READ_NODE_AS_STRING(tt->second);\r
+                                schema = std::make_pair(key, *(new Schema(value)));\r
+                            }\r
+                            setSchema(schema);\r
+                        }\r
+                    }\r
+                }\r
+\r
+                else if (key.compare(0, Keys::Resource.length(), Keys::Resource)  == 0)\r
+                {\r
+                    RamlResource *resource = new RamlResource(key, it->second, m_includeResolver, getBaseUri());\r
+                    setResource(key, *resource);\r
+                }\r
+                else if (key == Keys::Traits)\r
+                {\r
+                    YAML::Node traitNode = it->second;\r
+                    for ( YAML::const_iterator tt = traitNode.begin(); tt != traitNode.end(); ++tt )\r
+                    {\r
+                        for (auto elem : *tt)\r
+                        {\r
+                            std::string trait = READ_NODE_AS_STRING(elem.first);\r
+                            Action *action = new Action(ActionType::NONE, elem.second , m_includeResolver);\r
+\r
+                            std::pair<std::string, Action> resourceTrait;\r
+                            resourceTrait = std::make_pair(trait, *action);\r
+\r
+                            setTrait(resourceTrait);\r
+                        }\r
+                    }\r
+                }\r
+                else if (key == Keys::ResourceTypes)\r
+                {\r
+                    YAML::Node typeNode = it->second;\r
+                    for ( YAML::const_iterator tt = typeNode.begin(); tt != typeNode.end(); ++tt )\r
+                    {\r
+                        for (auto elem : *tt)\r
+                        {\r
+                            std::string type = READ_NODE_AS_STRING(elem.first);\r
+                            RamlResource *resource = new RamlResource(type, elem.second, m_includeResolver, getBaseUri());\r
+\r
+                            std::pair<std::string, RamlResource> resourceType;\r
+                            resourceType = std::make_pair(type, *resource);\r
+\r
+                            setResourceType(resourceType);\r
+\r
+                        }\r
+\r
+                    }\r
+                }\r
+            }\r
+        }\r
+\r
+    }\r
+\r
+}\r
diff --git a/service/simulator/ramlparser/raml/model/Raml.h b/service/simulator/ramlparser/raml/model/Raml.h
new file mode 100755 (executable)
index 0000000..c3c537c
--- /dev/null
@@ -0,0 +1,108 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *             http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#ifndef RAML_H\r
+#define RAML_H\r
+\r
+#include <map>\r
+#include <list>\r
+#include <string>\r
+#include "AbstractParam.h"\r
+#include "UriParameter.h"\r
+#include "QueryParameter.h"\r
+#include "FormParameter.h"\r
+#include "Header.h"\r
+\r
+#include "RequestResponseBody.h"\r
+#include "RamlResource.h"\r
+#include "ActionType.h"\r
+#include "Action.h"\r
+#include "Response.h"\r
+#include "Schema.h"\r
+#include "IncludeResolver.h"\r
+\r
+#include "DocumentationItem.h"\r
+#include "yaml-cpp/yaml.h"\r
+#include "Utils.h"\r
+#include "cJSON.h"\r
+\r
+\r
+namespace RAML\r
+{\r
+    class Raml\r
+    {\r
+        public:\r
+            virtual std::string getTitle() const;\r
+            virtual void setTitle(const std::string &title);\r
+\r
+            virtual std::string getVersion() const;\r
+            virtual void setVersion(const std::string &version);\r
+\r
+            virtual std::string getBaseUri() const;\r
+            virtual void setBaseUri(const std::string &baseUri);\r
+\r
+            virtual std::list<std::string> getProtocols() const;\r
+            virtual void setProtocol(const std::string &protocol);\r
+\r
+\r
+            virtual std::map<std::string, UriParameter> getBaseUriParameters() const;\r
+            virtual void setBaseUriParameter(const std::string &paramName, const UriParameter &uriParameter);\r
+\r
+            virtual std::string getMediaType() const;\r
+            virtual void setMediaType(const std::string &mediaType);\r
+\r
+            virtual std::list<std::pair<std::string, Schema> > getSchemas() const;\r
+            virtual void setSchema(const std::pair<std::string, Schema> &schema);\r
+\r
+            virtual std::list<std::pair<std::string, RamlResource> > getResourceTypes() const;\r
+            virtual void setResourceType(const std::pair<std::string, RamlResource> &resourceType);\r
+\r
+            virtual std::list<std::pair<std::string, Action> > getTraits() const;\r
+            virtual void setTrait(const std::pair<std::string, Action> &trait);\r
+\r
+            virtual RamlResource &getResource(std::string resourceName);\r
+            virtual std::map<std::string, RamlResource> getResources() const;\r
+            virtual void setResource(const std::string &resourceKey, const RamlResource &resource);\r
+\r
+            virtual void setDocumentationItem(const DocumentationItem &documentationItem);\r
+            virtual std::list<DocumentationItem> getDocumentation() const;\r
+\r
+            void readRamlFromYaml(const YAML::Node &yamlNode);\r
+            Raml() : m_includeResolver(new IncludeResolver()) {}\r
+            Raml(std::string &resourceLocation) : m_includeResolver(new IncludeResolver(resourceLocation)) {}\r
+        private:\r
+            std::string m_title;\r
+            std::string m_version;\r
+            std::string m_baseUri;\r
+            std::list<std::string> m_protocols;\r
+            std::map<std::string, UriParameter> m_baseUriParameters;\r
+            std::string m_mediaType;\r
+            std::list <std::pair<std::string, Schema> > m_schemas;\r
+            std::list <std::pair<std::string, RamlResource> > m_resourceTypes;\r
+            std::list <std::pair<std::string, Action> > m_traits;\r
+            std::map<std::string, RamlResource> m_resources;\r
+            std::list<DocumentationItem> m_documentation;\r
+            IncludeResolver *m_includeResolver;\r
+    };\r
+\r
+    typedef std::shared_ptr<Raml> RamlPtr;\r
+\r
+}\r
+#endif\r
diff --git a/service/simulator/ramlparser/raml/model/RamlResource.cpp b/service/simulator/ramlparser/raml/model/RamlResource.cpp
new file mode 100755 (executable)
index 0000000..df5f617
--- /dev/null
@@ -0,0 +1,178 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *             http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#include "RamlResource.h"\r
+\r
+\r
+namespace RAML\r
+{\r
+    RamlResource *RamlResource::getParentResource()\r
+    {\r
+        return m_parentResource;\r
+    }\r
+    void RamlResource::setParentResource(RamlResource *parentResource)\r
+    {\r
+        m_parentResource = parentResource;\r
+    }\r
+\r
+    std::string RamlResource::getDisplayName() const\r
+    {\r
+        return m_displayName;\r
+    }\r
+    void RamlResource::setDisplayName(const std::string &displayName)\r
+    {\r
+        m_displayName = displayName;\r
+    }\r
+    std::string RamlResource::getDescription() const\r
+    {\r
+        return m_description;\r
+    }\r
+    void RamlResource::setDescription(const std::string &description)\r
+    {\r
+        m_description = description;\r
+    }\r
+    std::string RamlResource::getParentUri() const\r
+    {\r
+        return m_parentUri;\r
+    }\r
+    void RamlResource::setParentUri(const std::string &parentUri)\r
+    {\r
+        m_parentUri = parentUri;\r
+    }\r
+    std::string RamlResource::getRelativeUri() const\r
+    {\r
+        return m_relativeUri;\r
+    }\r
+    void RamlResource::setRelativeUri(const std::string &relativeUri)\r
+    {\r
+        m_relativeUri = relativeUri;\r
+    }\r
+    std::map<std::string, UriParameter> RamlResource::getUriParameters() const\r
+    {\r
+        return m_uriParameters;\r
+    }\r
+    void RamlResource::setUriParameter(const std::string &paramName, const UriParameter &uriParameter)\r
+    {\r
+        m_uriParameters[paramName] = uriParameter;\r
+    }\r
+    std::map<std::string, UriParameter > RamlResource::getBaseUriParameters() const\r
+    {\r
+        return m_baseUriParameters;\r
+    }\r
+    void RamlResource::setBaseUriParameter(const std::string &paramName,\r
+                                           const UriParameter &baseUriParameter)\r
+    {\r
+        m_baseUriParameters[paramName] = baseUriParameter;\r
+    }\r
+    Action &RamlResource::getAction(ActionType actionType)\r
+    {\r
+        return m_actions[actionType];\r
+    }\r
+\r
+    std::map<ActionType , Action> RamlResource::getActions() const\r
+    {\r
+        return m_actions;\r
+    }\r
+    void RamlResource::setAction(const ActionType &actiontype , const Action &action )\r
+    {\r
+        m_actions[actiontype] = action;\r
+    }\r
+    std::map<std::string, RamlResource> RamlResource::getResources() const\r
+    {\r
+        return m_resources;\r
+    }\r
+    void RamlResource::setResource(const std::string &resourceName, const RamlResource &resources)\r
+    {\r
+        m_resources[resourceName] = resources;\r
+    }\r
+    std::list<std::string> RamlResource::getTraits() const\r
+    {\r
+        return m_traits;\r
+    }\r
+    void RamlResource::setTrait(const std::string &trait)\r
+    {\r
+        m_traits.push_back(trait);\r
+    }\r
+    std::string RamlResource::getResourceType() const\r
+    {\r
+        return m_resourceType;\r
+    }\r
+    void RamlResource::setResourceType(const std::string &type)\r
+    {\r
+        m_resourceType = type;\r
+    }\r
+    std::string RamlResource::getResourceUri() const\r
+    {\r
+        return (m_parentUri + m_relativeUri);\r
+    }\r
+    void RamlResource::readResource(const std::string resourceKey, const YAML::Node &yamlNode,\r
+                                    IncludeResolver *includeResolver, const std::string &parentUri)\r
+    {\r
+        m_includeResolver = includeResolver;\r
+        m_relativeUri = resourceKey;\r
+        m_parentUri = parentUri;\r
+        for ( YAML::const_iterator it = yamlNode.begin(); it != yamlNode.end(); ++it )\r
+        {\r
+            std::string key = READ_NODE_AS_STRING(it->first);\r
+\r
+            if (key == Keys::DisplayName)\r
+                setDisplayName(READ_NODE_AS_STRING(it->second));\r
+            else if (key == Keys::Description)\r
+                setDescription(READ_NODE_AS_STRING(it->second));\r
+            else if (std::find(Keys::ActionType.begin(), Keys::ActionType.end(), key) != Keys::ActionType.end())\r
+            {\r
+                ActionType actionType = GET_ACTION_TYPE(key);\r
+\r
+                setAction(actionType, *(new Action(actionType, it->second, m_includeResolver)));\r
+            }\r
+            else if (key == Keys::UriParameters)\r
+            {\r
+                YAML::Node paramNode = it->second;\r
+                for ( YAML::const_iterator tt = paramNode.begin(); tt != paramNode.end(); ++tt )\r
+                {\r
+                    UriParameter *uriParameter = new UriParameter(tt->second);\r
+                    setUriParameter(READ_NODE_AS_STRING(tt->first), *uriParameter);\r
+                }\r
+            }\r
+            else if (key == Keys::BaseUriParameters)\r
+            {\r
+                YAML::Node paramNode = it->second;\r
+                for ( YAML::const_iterator tt = paramNode.begin(); tt != paramNode.end(); ++tt )\r
+                {\r
+                    UriParameter *uriParameter = new UriParameter(tt->second);\r
+                    setBaseUriParameter(READ_NODE_AS_STRING(tt->first), *uriParameter);\r
+                }\r
+            }\r
+            else if (key == Keys::IsTrait)\r
+            {\r
+                YAML::Node traitNode = it->second;\r
+                for ( YAML::const_iterator tt = traitNode.begin(); tt != traitNode.end(); ++tt )\r
+                {\r
+                    setTrait(READ_NODE_AS_STRING(*tt));\r
+                }\r
+            }\r
+            else if (key == Keys::Type)\r
+            {\r
+                setResourceType(READ_NODE_AS_STRING(it->second));\r
+            }\r
+        }\r
+    }\r
+\r
+}\r
diff --git a/service/simulator/ramlparser/raml/model/RamlResource.h b/service/simulator/ramlparser/raml/model/RamlResource.h
new file mode 100755 (executable)
index 0000000..ebcbf3c
--- /dev/null
@@ -0,0 +1,95 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *             http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#ifndef RESOURCE_H\r
+#define RESOURCE_H\r
+\r
+#include <map>\r
+#include <list>\r
+#include <string>\r
+#include "UriParameter.h"\r
+#include "ActionType.h"\r
+#include "Action.h"\r
+#include "Utils.h"\r
+#include "IncludeResolver.h"\r
+\r
+namespace RAML\r
+{\r
+    class RamlResource\r
+    {\r
+        public:\r
+            virtual RamlResource *getParentResource();\r
+            virtual void setParentResource(RamlResource *parentResource);\r
+\r
+            virtual std::string getDisplayName() const;\r
+            virtual void setDisplayName(const std::string &displayName);\r
+\r
+            virtual std::string getDescription() const;\r
+            virtual void setDescription(const std::string &description);\r
+\r
+            virtual std::string getParentUri() const;\r
+            virtual void setParentUri(const std::string &parentUri);\r
+\r
+            virtual std::string getRelativeUri() const;\r
+            virtual void setRelativeUri(const std::string &relativeUri);\r
+\r
+            virtual std::map<std::string, UriParameter> getUriParameters() const;\r
+            virtual void setUriParameter(const std::string &paramName, const UriParameter &uriParameter);\r
+\r
+            virtual std::map<std::string, UriParameter > getBaseUriParameters() const;\r
+            virtual void setBaseUriParameter(const std::string &paramName,\r
+                                             const UriParameter &baseUriParameter);\r
+\r
+            virtual Action &getAction(ActionType actionType);\r
+            virtual std::map<ActionType , Action> getActions() const;\r
+            virtual void setAction(const ActionType &actiontype , const Action &action );\r
+\r
+            virtual std::map<std::string, RamlResource> getResources() const;\r
+            virtual void setResource(const std::string &resourceName, const RamlResource &resources);\r
+\r
+            virtual std::list<std::string> getTraits() const;\r
+            virtual void setTrait(const std::string &trait);\r
+\r
+            virtual std::string getResourceType() const;\r
+            virtual void setResourceType(const std::string &type);\r
+\r
+            virtual std::string getResourceUri() const;\r
+            RamlResource() {}\r
+            RamlResource(const std::string resourceKey, const YAML::Node &yamlNode ,\r
+                         IncludeResolver *includeResolver, const std::string &parentUri) { readResource(resourceKey, yamlNode, includeResolver, parentUri); }\r
+        private:\r
+            void readResource(const std::string resourceKey, const YAML::Node &yamlNode,\r
+                              IncludeResolver *includeResolver, const std::string &parentUri);\r
+        private:\r
+            std::string m_displayName;\r
+            std::string m_description;\r
+            std::string m_relativeUri;\r
+            std::map<std::string, UriParameter> m_uriParameters;\r
+            std::map<std::string, UriParameter > m_baseUriParameters;\r
+            std::map<ActionType , Action> m_actions;\r
+            std::list<std::string> m_traits;\r
+            std::string m_resourceType;\r
+            RamlResource *m_parentResource;\r
+            std::string m_parentUri;\r
+            std::map<std::string, RamlResource> m_resources;\r
+            IncludeResolver *m_includeResolver;\r
+    };\r
+}\r
+#endif\r
diff --git a/service/simulator/ramlparser/raml/model/RequestResponseBody.cpp b/service/simulator/ramlparser/raml/model/RequestResponseBody.cpp
new file mode 100755 (executable)
index 0000000..366e026
--- /dev/null
@@ -0,0 +1,97 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *             http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#include "RequestResponseBody.h"\r
+\r
+namespace RAML\r
+{\r
+\r
+    std::string RequestResponseBody::getType() const\r
+    {\r
+        return m_type;\r
+    }\r
+    void RequestResponseBody::setType(const std::string &type)\r
+    {\r
+        m_type = type;\r
+    }\r
+    Schema *RequestResponseBody::getSchema() const\r
+    {\r
+        return m_schema;\r
+    }\r
+    void RequestResponseBody::setSchema(Schema *schema)\r
+    {\r
+        m_schema = schema;\r
+    }\r
+    std::string RequestResponseBody::getExample() const\r
+    {\r
+        return m_example;\r
+    }\r
+    void RequestResponseBody::setExample(const std::string &example)\r
+    {\r
+        m_example = example;\r
+    }\r
+    std::map<std::string, FormParameter > RequestResponseBody::getFormParameters() const\r
+    {\r
+        return m_formParameters ;\r
+    }\r
+    void RequestResponseBody::setFormParameter(const std::string &paramName,\r
+            const FormParameter  &formParameter)\r
+    {\r
+        m_formParameters[paramName] = formParameter;\r
+    }\r
+    void RequestResponseBody::readRequestResponseBody(const std::string &type,\r
+            const YAML::Node &yamlNode,\r
+            IncludeResolver *includeResolver)\r
+    {\r
+        m_type = type;\r
+        m_schema = NULL;\r
+        m_includeResolver = includeResolver;\r
+        for ( YAML::const_iterator it = yamlNode.begin(); it != yamlNode.end(); ++it )\r
+        {\r
+            std::string key = READ_NODE_AS_STRING(it->first);\r
+\r
+            if (key == Keys::Schema)\r
+            {\r
+                IncludeResolver::FileType fileType = m_includeResolver->getFileType(it->second);\r
+                if ((fileType == IncludeResolver::FileType::JSON) || (fileType == IncludeResolver::FileType::FILE))\r
+                {\r
+                    setSchema(new Schema(m_includeResolver->readFromFile(it->second)));\r
+                }\r
+                else\r
+                {\r
+                    std::string value = READ_NODE_AS_STRING(it->second);\r
+                    setSchema(new Schema(value));\r
+                }\r
+            }\r
+            else if (key == Keys::Example)\r
+                setExample(READ_NODE_AS_STRING(it->second));\r
+            else if (key == Keys::FormParameters)\r
+            {\r
+                YAML::Node paramNode = it->second;\r
+                for ( YAML::const_iterator tt = paramNode.begin(); tt != paramNode.end(); ++tt )\r
+                {\r
+                    FormParameter *formParameter = new FormParameter(tt->second);\r
+                    setFormParameter(READ_NODE_AS_STRING(tt->first), *formParameter);\r
+                }\r
+            }\r
+        }\r
+    }\r
+\r
+}\r
diff --git a/service/simulator/ramlparser/raml/model/RequestResponseBody.h b/service/simulator/ramlparser/raml/model/RequestResponseBody.h
new file mode 100755 (executable)
index 0000000..6c3e6bb
--- /dev/null
@@ -0,0 +1,61 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *             http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#ifndef REQUEST_RESPONSE_BODY_H\r
+#define REQUEST_RESPONSE_BODY_H\r
+\r
+#include <map>\r
+#include <list>\r
+#include "FormParameter.h"\r
+#include "Utils.h"\r
+#include "IncludeResolver.h"\r
+#include "Schema.h"\r
+\r
+namespace RAML\r
+{\r
+    class RequestResponseBody\r
+    {\r
+        public:\r
+            virtual std::string getType() const;\r
+            virtual void setType(const std::string &type);\r
+            virtual Schema *getSchema() const;\r
+            virtual void setSchema(Schema *schema);\r
+            virtual std::string getExample() const;\r
+            virtual void setExample(const std::string &example);\r
+            virtual std::map<std::string, FormParameter > getFormParameters() const;\r
+            virtual void setFormParameter(const std::string &paramName, const FormParameter  &formParameter);\r
+            RequestResponseBody(): m_schema(NULL) {}\r
+            RequestResponseBody(const std::string type) : m_type(type), m_schema(NULL) {}\r
+            RequestResponseBody(const std::string type, const YAML::Node &yamlNode,\r
+                                IncludeResolver *includeResolver) { readRequestResponseBody(type, yamlNode, includeResolver); }\r
+        private:\r
+            virtual void readRequestResponseBody(const std::string &type, const YAML::Node &yamlNode,\r
+                                                 IncludeResolver *includeResolver) ;\r
+        private:\r
+            std::string m_type;\r
+            Schema *m_schema;\r
+            std::string m_example;\r
+            std::map<std::string, FormParameter > m_formParameters;\r
+            IncludeResolver *m_includeResolver;\r
+\r
+\r
+    };\r
+}\r
+#endif\r
diff --git a/service/simulator/ramlparser/raml/model/ResourceProperties.cpp b/service/simulator/ramlparser/raml/model/ResourceProperties.cpp
new file mode 100755 (executable)
index 0000000..9b6a122
--- /dev/null
@@ -0,0 +1,103 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *             http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#include "ResourceProperties.h"\r
+\r
+namespace RAML\r
+{\r
+\r
+    void ResourceProperties::readJson()\r
+    {\r
+        if (! m_cjson)\r
+            return;\r
+        cJSON *jsonrt = cJSON_GetObjectItem(m_cjson, "rt");\r
+        m_rt = jsonrt->valuestring;\r
+\r
+        cJSON *jsonif = cJSON_GetObjectItem(m_cjson, "if");\r
+        m_if = jsonif->valuestring;\r
+\r
+        cJSON *jsonProperties = cJSON_GetObjectItem(m_cjson, "properties");\r
+        cJSON *childProperties = jsonProperties->child;\r
+\r
+        while (childProperties)\r
+        {\r
+            std::string attName = childProperties->string;\r
+\r
+            std::string attType = cJSON_GetObjectItem(childProperties, "type")->valuestring;\r
+            if (attType == "string")\r
+            {\r
+                addAttribute(attName , std::string(cJSON_GetObjectItem(childProperties, "default")->valuestring));\r
+                cJSON *allowedvalues = cJSON_GetObjectItem(childProperties, "values");\r
+                if (allowedvalues)\r
+                {\r
+                    int size = cJSON_GetArraySize(allowedvalues);\r
+                    int idx = 0;\r
+                    std::vector<std::string> allwdValues;\r
+\r
+                    do\r
+                    {\r
+                        allwdValues.push_back(cJSON_GetArrayItem(allowedvalues, idx)->valuestring);\r
+\r
+                    }\r
+                    while ( ++idx < size);\r
+\r
+                    setAllowedValues(attName, allwdValues);\r
+                }\r
+            }\r
+            else\r
+            {\r
+                addAttribute(attName , int(cJSON_GetObjectItem(childProperties, "default")->valueint));\r
+                cJSON *allowedvalues = cJSON_GetObjectItem(childProperties, "values");\r
+                if (allowedvalues)\r
+                {\r
+                    int size = cJSON_GetArraySize(allowedvalues);\r
+                    int idx = 0;\r
+                    std::vector<int> allwdValues;\r
+\r
+                    do\r
+                    {\r
+                        allwdValues.push_back(cJSON_GetArrayItem(allowedvalues, idx)->valueint);\r
+\r
+                    }\r
+                    while ( ++idx < size);\r
+\r
+                    setAllowedValues(attName, allwdValues);\r
+                }\r
+                cJSON *ranges = cJSON_GetObjectItem(childProperties, "range");\r
+                if (ranges)\r
+                {\r
+                    int sizeRange = cJSON_GetArraySize(ranges);\r
+                    if (sizeRange == 2)\r
+                    {\r
+                        setRange(attName , (cJSON_GetArrayItem(ranges, 0)->valueint) , (cJSON_GetArrayItem(ranges,\r
+                                 1)->valueint));\r
+                    }\r
+                }\r
+\r
+            }\r
+\r
+            setUpdateInterval(attName , cJSON_GetObjectItem(childProperties, "update_frequency")->valueint);\r
+            childProperties = childProperties->next;\r
+        }\r
+\r
+    }\r
+\r
+}\r
+\r
diff --git a/service/simulator/ramlparser/raml/model/ResourceProperties.h b/service/simulator/ramlparser/raml/model/ResourceProperties.h
new file mode 100755 (executable)
index 0000000..802bde9
--- /dev/null
@@ -0,0 +1,239 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *             http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#ifndef RESOURCE_PROPERTIES_H_\r
+#define RESOURCE_PROPERTIES_H_\r
+\r
+#include <string>\r
+#include <vector>\r
+#include <map>\r
+#include "cJSON.h"\r
+#include <boost/variant.hpp>\r
+#include <boost/lexical_cast.hpp>\r
+\r
+namespace RAML\r
+{\r
+\r
+    class ResourceProperties\r
+    {\r
+        public:\r
+            ResourceProperties() {}\r
+            ResourceProperties(cJSON *cjson) : m_cjson(cjson) { readJson();}\r
+\r
+            class Attribute\r
+            {\r
+                public:\r
+                    typedef boost::variant <\r
+                    int,\r
+                    double,\r
+                    std::string\r
+                    > ValueVariant;\r
+\r
+                    Attribute() = default;\r
+                    Attribute(const std::string &attrName) : m_name(attrName) {}\r
+\r
+                    inline std::string getName(void) const { return m_name; }\r
+                    inline void setName(const std::string &name) { m_name = name;}\r
+\r
+                    template <typename T>\r
+                    T getValue() const\r
+                    {\r
+                        T val = T();\r
+                        return boost::get<T>(m_value);\r
+                    }\r
+\r
+                    ValueVariant &getValue()\r
+                    {\r
+                        return m_value;\r
+                    }\r
+\r
+                    int getValueType() const\r
+                    {\r
+                        return m_value.which();\r
+                    }\r
+                    int getValueInt()\r
+                    {\r
+                        return boost::lexical_cast<int> (m_value);\r
+                    }\r
+                    std::string getValueString()\r
+                    {\r
+                        return boost::lexical_cast<std::string> (m_value);\r
+                    }\r
+\r
+                    template <typename T>\r
+                    void setValue(const T &value)\r
+                    {\r
+                        m_value = value;\r
+                    }\r
+\r
+                    inline void getRange(int &min, int &max) const\r
+                    {\r
+                        min = m_min;\r
+                        max = m_max;\r
+                    }\r
+\r
+                    inline void setRange(const int &min, const int &max)\r
+                    {\r
+                        m_min = min;\r
+                        m_max = max;\r
+                    }\r
+\r
+                    template <typename T>\r
+                    bool setAllowedValues(const std::vector<T> &values)\r
+                    {\r
+                        ValueVariant temp = values.at(0);\r
+                        if (temp.which() != m_value.which())\r
+                        {\r
+                            return false;\r
+                        }\r
+\r
+                        m_allowedValues.addValues(values);\r
+                        return true;\r
+                    }\r
+                    inline int getAllowedValuesSize() const\r
+                    {\r
+                        return m_allowedValues.size();\r
+                    }\r
+\r
+                    inline std::vector<ValueVariant> getAllowedValues()\r
+                    {\r
+                        return m_allowedValues.getValues();\r
+                    }\r
+\r
+                    int getUpdateFrequencyTime() {return m_updateInterval;}\r
+                    void setUpdateFrequencyTime(int interval) {m_updateInterval = interval;}\r
+\r
+                private:\r
+                    class AllowedValues\r
+                    {\r
+                        public:\r
+                            template <typename T>\r
+                            void addValue(const T &value)\r
+                            {\r
+                                ValueVariant temp = value;\r
+                                m_values.push_back(temp);\r
+                            }\r
+\r
+                            template <typename T>\r
+                            void addValues(const std::vector<T> &values)\r
+                            {\r
+                                for (auto value : values)\r
+                                {\r
+                                    ValueVariant vValue = value;\r
+                                    m_values.push_back(vValue);\r
+                                }\r
+                            }\r
+\r
+                            inline ValueVariant &at(int index)\r
+                            {\r
+                                return m_values.at(index);\r
+                            }\r
+                            inline int size() const\r
+                            {\r
+                                return m_values.size();\r
+                            }\r
+\r
+                            inline std::vector<ValueVariant> getValues()\r
+                            {\r
+                                return m_values;\r
+                            }\r
+\r
+                        private:\r
+                            std::vector<ValueVariant> m_values;\r
+                    };\r
+\r
+                    std::string m_name;\r
+                    ValueVariant m_value;\r
+                    int m_max;\r
+                    int m_min;\r
+                    AllowedValues m_allowedValues;\r
+                    int m_updateInterval;\r
+            };\r
+            int size() const { return m_attributes.size(); }\r
+            inline bool getAttribute(const std::string &attrName, Attribute &value)\r
+            {\r
+                if (m_attributes.end() != m_attributes.find(attrName))\r
+                {\r
+                    value = m_attributes[attrName];\r
+                    return true;\r
+                }\r
+\r
+                return false;\r
+            }\r
+\r
+            inline std::map<std::string, Attribute> getAttributes() const\r
+            {\r
+                return m_attributes;\r
+            }\r
+\r
+\r
+            template <typename T>\r
+            void addAttribute(const std::string &attrName, const T &attrValue)\r
+            {\r
+                if (m_attributes.end() == m_attributes.find(attrName))\r
+                {\r
+                    m_attributes[attrName] = Attribute(attrName);\r
+                    m_attributes[attrName].setValue(attrValue);\r
+                }\r
+            }\r
+\r
+        private:\r
+            inline void setRange(const std::string &attrName, const int min, const int max)\r
+            {\r
+                if (m_attributes.end() != m_attributes.find(attrName))\r
+                    m_attributes[attrName].setRange(min, max);\r
+            }\r
+\r
+\r
+            template <typename T>\r
+            void setAllowedValues(const std::string &attrName, const std::vector<T> &values)\r
+            {\r
+                if (m_attributes.end() != m_attributes.find(attrName))\r
+                    m_attributes[attrName].setAllowedValues(values);\r
+            }\r
+\r
+            inline void setUpdateInterval(const std::string &attrName, int interval)\r
+            {\r
+                if (m_attributes.end() != m_attributes.find(attrName))\r
+                    m_attributes[attrName].setUpdateFrequencyTime(interval);\r
+            }\r
+\r
+\r
+            inline void removeAttribute(const std::string &attrName)\r
+            {\r
+                m_attributes.erase(attrName);\r
+                return;\r
+            }\r
+            void readJson();\r
+\r
+        public:\r
+            std::string getResoureType() const {return m_rt; }\r
+            std::string getInterface() const {return m_if; }\r
+\r
+        private:\r
+            std::map<std::string, Attribute> m_attributes;\r
+            std::string m_rt;\r
+            std::string m_if;\r
+            cJSON *m_cjson;\r
+\r
+    };\r
+\r
+}\r
+#endif\r
diff --git a/service/simulator/ramlparser/raml/model/Response.cpp b/service/simulator/ramlparser/raml/model/Response.cpp
new file mode 100755 (executable)
index 0000000..8087d21
--- /dev/null
@@ -0,0 +1,90 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *             http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#include "Response.h"\r
+\r
+namespace RAML\r
+{\r
+\r
+    std::map<std::string, Header> Response::getHeaders() const\r
+    {\r
+        return m_headers;\r
+    }\r
+    void Response::setHeader(const std::string &headerName, const Header &header)\r
+    {\r
+        m_headers[headerName] = header;\r
+    }\r
+    std::string Response::getDescription() const\r
+    {\r
+        return m_description;\r
+    }\r
+    void Response::setDescription(const std::string &description)\r
+    {\r
+        m_description = description;\r
+    }\r
+    void Response::setResponseBody(const std::string &typeName)\r
+    {\r
+        m_responseBody[typeName] = *(new RequestResponseBody(typeName));\r
+    }\r
+    void Response::setResponseBody(const std::string &type, const RequestResponseBody &body)\r
+    {\r
+        m_responseBody[type] = body;\r
+    }\r
+    std::map<std::string, RequestResponseBody> Response::getResponseBody() const\r
+    {\r
+        return m_responseBody;\r
+    }\r
+    RequestResponseBody &Response::getResponseBody(std::string bodyType)\r
+    {\r
+        return m_responseBody[bodyType];\r
+    }\r
+\r
+    void Response::readResponse(const YAML::Node &yamlNode, IncludeResolver *includeResolver)\r
+    {\r
+        m_includeResolver = includeResolver;\r
+        for ( YAML::const_iterator it = yamlNode.begin(); it != yamlNode.end(); ++it )\r
+        {\r
+            std::string key = READ_NODE_AS_STRING(it->first);\r
+\r
+            if (key == Keys::Description)\r
+                setDescription(READ_NODE_AS_STRING(it->second));\r
+            else if (key == Keys::Body)\r
+            {\r
+                YAML::Node responseBody = it->second;\r
+\r
+                for ( YAML::const_iterator tt = responseBody.begin(); tt != responseBody.end(); ++tt )\r
+                {\r
+                    std::string type = READ_NODE_AS_STRING(tt->first);\r
+                    setResponseBody(type, *(new RequestResponseBody(type, tt->second, m_includeResolver)));\r
+                }\r
+            }\r
+            else if (key == Keys::Headers)\r
+            {\r
+                YAML::Node paramNode = it->second;\r
+                for ( YAML::const_iterator tt = paramNode.begin(); tt != paramNode.end(); ++tt )\r
+                {\r
+                    Header *header = new Header(tt->second);\r
+                    setHeader(READ_NODE_AS_STRING(tt->first), *header);\r
+                }\r
+            }\r
+        }\r
+    }\r
+\r
+}\r
diff --git a/service/simulator/ramlparser/raml/model/Response.h b/service/simulator/ramlparser/raml/model/Response.h
new file mode 100755 (executable)
index 0000000..cf720ec
--- /dev/null
@@ -0,0 +1,58 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *             http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#ifndef RESPONSE_H\r
+#define RESPONSE_H\r
+\r
+#include <map>\r
+#include <list>\r
+#include <string>\r
+#include "RequestResponseBody.h"\r
+#include "Header.h"\r
+#include "Utils.h"\r
+#include "IncludeResolver.h"\r
+\r
+namespace RAML\r
+{\r
+    class Response\r
+    {\r
+        public:\r
+            virtual std::map<std::string, Header> getHeaders() const;\r
+            virtual void setHeader(const std::string &headerName, const Header &header);\r
+            virtual std::string getDescription() const;\r
+            virtual void setDescription(const std::string &description);\r
+            virtual void setResponseBody(const std::string &typeName);\r
+            virtual void setResponseBody(const std::string &type, const RequestResponseBody &body) ;\r
+            virtual std::map<std::string, RequestResponseBody> getResponseBody() const;\r
+            virtual RequestResponseBody &getResponseBody(const std::string bodyType);\r
+\r
+\r
+            Response() {}\r
+            Response(const YAML::Node &yamlNode, IncludeResolver *includeResolver) { readResponse(yamlNode, includeResolver);}\r
+        private:\r
+            void readResponse(const YAML::Node &yamlNode, IncludeResolver *includeResolver) ;\r
+        private:\r
+            std::string m_description;\r
+            std::map<std::string, RequestResponseBody> m_responseBody;\r
+            std::map<std::string, Header> m_headers;\r
+            IncludeResolver *m_includeResolver;\r
+    };\r
+}\r
+#endif\r
diff --git a/service/simulator/ramlparser/raml/model/Schema.cpp b/service/simulator/ramlparser/raml/model/Schema.cpp
new file mode 100755 (executable)
index 0000000..39dece5
--- /dev/null
@@ -0,0 +1,46 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *             http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#include "Schema.h"\r
+namespace RAML\r
+{\r
+\r
+    cJSON *Schema::getJson() const\r
+    {\r
+        return m_cjson;\r
+    }\r
+    void Schema::setJson(cJSON *cjson)\r
+    {\r
+        m_cjson = cjson;\r
+    }\r
+    std::string Schema::getSchema() const\r
+    {\r
+        return m_schema;\r
+    }\r
+    void Schema::setSchema(const std::string &schema)\r
+    {\r
+        m_schema = schema;\r
+    }\r
+    ResourceProperties *Schema::getProperties() const\r
+    {\r
+        return m_resProperties;\r
+    }\r
+\r
+}\r
diff --git a/service/simulator/ramlparser/raml/model/Schema.h b/service/simulator/ramlparser/raml/model/Schema.h
new file mode 100755 (executable)
index 0000000..e4e90ae
--- /dev/null
@@ -0,0 +1,53 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *             http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#ifndef SCHEMAS_H\r
+#define SCHEMAS_H\r
+\r
+#include <string>\r
+#include "cJSON.h"\r
+#include "IncludeResolver.h"\r
+\r
+#include "ResourceProperties.h"\r
+\r
+namespace RAML\r
+{\r
+    class Schema\r
+    {\r
+        public:\r
+            virtual cJSON *getJson() const;\r
+            virtual void setJson(cJSON *cjson);\r
+            virtual std::string getSchema() const;\r
+            virtual void setSchema(const std::string &schema);\r
+            virtual ResourceProperties *getProperties() const;\r
+\r
+            Schema(cJSON *cjson): m_cjson(cjson) {}\r
+            Schema(const std::string &schema): m_schema(schema) , m_cjson(cJSON_Parse(schema.c_str())),\r
+                m_resProperties(new ResourceProperties(m_cjson) ) {}\r
+            Schema() {}\r
+\r
+        private:\r
+            cJSON *m_cjson;\r
+            std::string m_schema;\r
+            ResourceProperties *m_resProperties;\r
+    };\r
+\r
+}\r
+#endif\r
diff --git a/service/simulator/ramlparser/raml/model/UriParameter.h b/service/simulator/ramlparser/raml/model/UriParameter.h
new file mode 100755 (executable)
index 0000000..a96536e
--- /dev/null
@@ -0,0 +1,36 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *             http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#ifndef URI_PARAMETER_H\r
+#define URI_PARAMETER_H\r
+\r
+#include "AbstractParam.h"\r
+\r
+namespace RAML\r
+{\r
+    class UriParameter: public AbstractParam\r
+    {\r
+        public:\r
+            UriParameter(const YAML::Node &yamlNode) : AbstractParam(yamlNode) {}\r
+            UriParameter() {}\r
+    };\r
+\r
+}\r
+#endif\r
diff --git a/service/simulator/src/resource_manager.cpp b/service/simulator/src/resource_manager.cpp
new file mode 100644 (file)
index 0000000..7556787
--- /dev/null
@@ -0,0 +1,221 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "resource_manager.h"
+#include "simulator_logger.h"
+
+int ResourceManager::id;
+ResourceManager *ResourceManager::getInstance()
+{
+    static ResourceManager s_instance;
+    return &s_instance;
+}
+
+ResourceManager::ResourceManager()
+    : m_resourceCreator(new SimulatorResourceCreator()) {}
+
+ResourceManager::~ResourceManager()
+{
+    delete m_resourceCreator;
+}
+
+SimulatorResourceServerPtr ResourceManager::createResource(const std::string &configPath,
+        SimulatorResourceServer::ResourceModelChangedCB callback)
+{
+    /**
+     * TODO: Temporarily creating the light resource for testing the basic flow
+     * Once the config parser is included this method will simulate the resource based on the config file
+     */
+    SimulatorResourceServerPtr simulatorResource = m_resourceCreator->createResource(configPath);
+    simulatorResource->setModelChangeCallback(callback);
+    std::string uri = getURI(simulatorResource->getURI());
+    if(uri.empty())
+    {
+        SIM_LOG(ILogger::ERROR, "Cannot register resource. Resource URI is empty");
+        return NULL;
+    }
+    simulatorResource->setURI(uri);
+    SimulatorResult result = simulatorResource->start();
+    if (SIMULATOR_SUCCESS != result)
+    {
+        SIM_LOG(ILogger::ERROR, "Failed to register resource [" << simulatorResource->getURI() <<
+                "] with platform");
+        return NULL;
+    }
+
+    // Add the resource to resource list table
+    std::lock_guard<std::recursive_mutex> lock(m_listMutex);
+    m_resourceList[simulatorResource->getResourceType()].insert(
+        std::pair<std::string, SimulatorResourceServerPtr>(simulatorResource->getURI(), simulatorResource));
+    return simulatorResource;
+}
+
+std::vector<SimulatorResourceServerPtr> ResourceManager::createResource(
+    const std::string &configPath,
+    const int count, SimulatorResourceServer::ResourceModelChangedCB callback)
+{
+    std::vector<SimulatorResourceServerPtr> resourceList;
+    for (int i = 0; i < count; i++)
+    {
+        /**
+         * TODO: Temporarily creating the light resource for testing the basic flow
+         * Once the config parser is included this method will simulate the resource based on the config file
+         */
+        SimulatorResourceServerPtr simulatorResource = m_resourceCreator->createResource(configPath);
+        simulatorResource->setModelChangeCallback(callback);
+        std::string uri = getURI(simulatorResource->getURI());
+        if(uri.empty())
+        {
+            SIM_LOG(ILogger::ERROR, "Cannot register resource. Resource URI is empty");
+            break;
+        }
+        simulatorResource->setURI(uri);
+        SimulatorResult result = simulatorResource->start();
+        if (SIMULATOR_SUCCESS != result)
+        {
+            resourceList.clear();
+            SIM_LOG(ILogger::ERROR, "Failed to register resources!");
+            break;
+        }
+        else
+        {
+            resourceList.push_back(simulatorResource);
+        }
+    }
+
+    // Add the resource to resource list table
+    std::lock_guard<std::recursive_mutex> lock(m_listMutex);
+    for (auto & resource : resourceList)
+    {
+        m_resourceList[resource->getResourceType()].insert(
+            std::pair<std::string, SimulatorResourceServerPtr>(resource->getURI(), resource));
+    }
+
+    return resourceList;
+}
+
+std::vector<SimulatorResourceServerPtr> ResourceManager::getResources(
+    const std::string &resourceType)
+{
+    std::lock_guard<std::recursive_mutex> lock(m_listMutex);
+
+    std::vector<SimulatorResourceServerPtr> resourceList;
+    for (auto resourceTableEntry : m_resourceList)
+    {
+        if (!resourceType.empty() && resourceType.compare(resourceTableEntry.first))
+            continue;
+
+        for (auto resourceEntry : resourceTableEntry.second)
+        {
+            resourceList.push_back(resourceEntry.second);
+        }
+    }
+
+    return resourceList;
+}
+
+SimulatorResult ResourceManager::deleteResource(SimulatorResourceServerPtr &resource)
+{
+    std::lock_guard<std::recursive_mutex> lock(m_listMutex);
+
+    if (nullptr == resource)
+        return SIMULATOR_BAD_INPUT;
+
+    SimulatorResult result = SIMULATOR_RESOURCE_NOT_FOUND;
+
+    try
+    {
+        auto resourceTableEntry = m_resourceList.find(resource->getResourceType());
+        if (m_resourceList.end() != resourceTableEntry)
+        {
+            auto resourceEntry = resourceTableEntry->second.find(resource->getURI());
+            if (resourceTableEntry->second.end() != resourceEntry)
+            {
+                if (SIMULATOR_SUCCESS == resource->stop())
+                {
+                    resourceTableEntry->second.erase(resourceEntry);
+                    result = SIMULATOR_SUCCESS;
+                }
+                else
+                {
+                    result = SIMULATOR_ERROR;
+                }
+            }
+        }
+    }
+    catch (OC::OCException &except)
+    {
+        SIM_LOG(ILogger::ERROR, except.reason() << except.code())
+        result = SIMULATOR_ERROR;
+    }
+
+    return result;
+}
+
+SimulatorResult ResourceManager::deleteResources(const std::string &resourceType)
+{
+    std::lock_guard<std::recursive_mutex> lock(m_listMutex);
+
+    SimulatorResult result = SIMULATOR_RESOURCE_NOT_FOUND;
+    try
+    {
+        for (auto & resourceTableEntry : m_resourceList)
+        {
+            if (!resourceType.empty() && resourceType.compare(resourceTableEntry.first))
+                continue;
+
+            for (auto & resourceEntry : resourceTableEntry.second)
+            {
+                SimulatorResourceServerPtr resource = resourceEntry.second;
+                if (SIMULATOR_SUCCESS == resource->stop())
+                {
+                    resourceTableEntry.second.erase(resourceTableEntry.second.find(resource->getURI()));
+                    result = SIMULATOR_SUCCESS;
+                }
+                else
+                {
+                    return SIMULATOR_ERROR;
+                }
+            }
+        }
+    }
+    catch (OC::OCException &except)
+    {
+        SIM_LOG(ILogger::ERROR, except.reason() << except.code())
+        result = SIMULATOR_ERROR;
+    }
+
+    return result;
+}
+
+std::string ResourceManager::getURI(std::string uri)
+{
+    if(uri.empty())
+    {
+        return uri;
+    }
+    std::ostringstream os;
+    os << uri;
+    if ('/' != uri[uri.length() - 1])
+        os << '/';
+    os << "simulator/" << id++;
+    return os.str();
+}
+
diff --git a/service/simulator/src/resource_manager.h b/service/simulator/src/resource_manager.h
new file mode 100644 (file)
index 0000000..4e27d62
--- /dev/null
@@ -0,0 +1,135 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file   resource_manager.h
+ *
+ * @brief   This file provides a class for a set of APIs relating to resource management
+ *               in the Service Provider side.
+ */
+
+#ifndef RESOURCE_MANAGER_H_
+#define RESOURCE_MANAGER_H_
+
+#include <string>
+#include <vector>
+#include <map>
+#include <mutex>
+#include "simulator_resource_server.h"
+#include "simulator_resource_creator.h"
+#include "simulator_error_codes.h"
+
+/**
+ * @class   ResourceManager
+ * @brief   This class provides a set of functions for managing the resource(s) in the Service Provider Module.
+ */
+class ResourceManager
+{
+    public:
+        /**
+         * This method is used to create/obtain the singleton instance of ResourceManager.
+         *
+         * @return ResourceManager - Singleton instance of ResourceManager.
+         */
+        static ResourceManager *getInstance(void);
+
+        /**
+         * This method is called for creating a single resource from the configuration file.
+         *
+         * @param configPath - RAML configuration file path.
+         * @param callback - Callback method for receive notifications when resource model changes.
+         *
+         * @return SimulatorResourceServerPtr - Shared pointer of SimulatorResourceServer on success, otherwise NULL.
+         */
+        SimulatorResourceServerPtr createResource(const std::string &configPath,
+                SimulatorResourceServer::ResourceModelChangedCB callback);
+
+        /**
+         * This method is called for creating a collection of resources from the configuration file.
+         *
+         * @param configPath - RAML configuration file path.
+         * @param count - Number of resource to be created.
+         * @param callback - Callback method for receive notifications when resource model changes.
+         *
+         * @return SimulatorResourceServerPtr - A vector of Shared pointers of SimulatorResourceServer Objects.
+         */
+        std::vector<SimulatorResourceServerPtr> createResource(const std::string &configPath,
+                const int count,
+                SimulatorResourceServer::ResourceModelChangedCB callback);
+
+        /**
+         * This method is called for obtaining a list of created resources.
+         *
+         * @return SimulatorResourceServerPtr - A vector of Shared pointers of SimulatorResourceServer Objects.
+         */
+        std::vector<SimulatorResourceServerPtr> getResources(const std::string &resourceType = "");
+
+        /**
+         * This method is called for deleting a single resource.
+         *
+         * @param resource - Shared pointer of the SimulatorResourceServer to be deleted.
+         *
+         * @return SimulatorResult
+         */
+        SimulatorResult deleteResource(SimulatorResourceServerPtr &resource);
+
+        /**
+         * This method is called for deleting multiple resources.
+         * If this method is called without any parameter, then all resources will be deleted.
+         * If thie method is called with a specific resourcetype as a parameter, then all the resources
+         * of that particular type will be deleted.
+         *
+         * @param resourceType - Resource type of the resource
+         *
+         * @return SimulatorResult
+         */
+        SimulatorResult deleteResources(const std::string &resourceType = "");
+
+    private:
+        /**
+         * This method is called for obtaining a unique URI when creating multiple resources using createResource API.
+         * It appends a unique key to the given URI.
+         * 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.
+         *
+         * @param uri - URI of the resource
+         *
+         * @return Unique URI for the resource
+         */
+        std::string getURI(std::string uri);
+
+        ResourceManager();
+        ~ResourceManager();
+
+        SimulatorResourceCreator *m_resourceCreator;
+        static int id;
+
+        /**
+         * This multi-level map organizes the resources in the form of ResourceType as the key
+         * and a set of resources of that resourceType as the value.
+         * The value is another map which has the ResourceURI as the key and the shared pointer
+         * of the SimulatorResourceServer object as the value.
+         */
+        std::map<std::string, std::map<std::string, SimulatorResourceServerPtr>> m_resourceList;
+        std::recursive_mutex m_listMutex;
+};
+
+#endif
+
diff --git a/service/simulator/src/simulator_attribute_automation.cpp b/service/simulator/src/simulator_attribute_automation.cpp
new file mode 100644 (file)
index 0000000..c955b6d
--- /dev/null
@@ -0,0 +1,301 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "simulator_attribute_automation.h"
+#include "simulator_resource_server.h"
+#include <thread>
+
+#define SLEEP_FOR(X) if (X > 0) std::this_thread::sleep_for(std::chrono::milliseconds(X));
+
+AttributeUpdateAutomation::AttributeUpdateAutomation(
+    SimulatorResourceServer *resource, const std::string &attrName, updateCompleteCallback callback,
+    int automationId, std::function<void (const int)> finishedCallback, AutomationType type,
+    int interval)
+    : m_resource(resource),
+      m_attrName(attrName),
+      m_type(type),
+      m_id(automationId),
+      m_status(false),
+      m_stopRequested(false),
+      m_updateInterval(interval),
+      m_callback(callback),
+      m_finishedCallback(finishedCallback) {}
+
+SimulatorResult AttributeUpdateAutomation::start()
+{
+    if (true == m_status)
+        return SIMULATOR_AUTOMATION_ALREADY_STARTED;
+
+    // Check the validity of attribute
+    SimulatorResourceModel resModel = m_resource->getModel();
+    if (false == resModel.getAttribute(m_attrName, m_attribute))
+        return SIMULATOR_ERROR;
+
+    if (m_updateInterval < 0)
+    {
+        m_updateInterval = m_attribute.getUpdateFrequencyTime();
+        if (0 > m_updateInterval)
+            m_updateInterval = 0;
+    }
+
+    m_thread = new std::thread(&AttributeUpdateAutomation::updateAttribute, this);
+    m_status = true;
+
+    return SIMULATOR_SUCCESS;
+}
+
+void AttributeUpdateAutomation::stop()
+{
+    m_stopRequested = true;
+    m_thread->join();
+    m_status = false;
+}
+
+void AttributeUpdateAutomation::updateAttribute()
+{
+    do
+    {
+        setAttributeValue();
+        if (m_stopRequested)
+            break;
+    }
+    while (AutomationType::RECURRENT == m_type);
+
+    m_status = false;
+
+    // Notify application through callback
+    if (m_callback)
+        m_callback(m_resource->getURI(), m_id);
+    if (m_finishedCallback && !m_stopRequested)
+        m_finishedCallback(m_id);
+}
+
+void AttributeUpdateAutomation::setAttributeValue()
+{
+    if (0 == m_attribute.getValueType()) // For integer type values
+    {
+        int min;
+        int max;
+        m_attribute.getRange(min, max);
+        for (int value = min; value <= max; value++)
+        {
+            if (m_stopRequested)
+                break;
+            m_resource->updateAttribute(m_attribute.getName(), value);
+            SLEEP_FOR(m_updateInterval);
+        }
+    }
+    else
+    {
+        for (int index = 0; index < m_attribute.getAllowedValuesSize(); index++)
+        {
+            if (m_stopRequested)
+                break;
+            m_resource->updateAttributeFromAllowedValues(m_attribute.getName(), index);
+            SLEEP_FOR(m_updateInterval);
+        }
+    }
+}
+
+
+ResourceUpdateAutomation::ResourceUpdateAutomation(
+    SimulatorResourceServer *resource, updateCompleteCallback callback,
+    int automationId, std::function<void (const int)> finishedCallback, AutomationType type,
+    int interval)
+    : m_resource(resource),
+      m_type(type),
+      m_id(automationId),
+      m_status(false),
+      m_updateInterval(interval),
+      m_callback(callback),
+      m_finishedCallback(finishedCallback) {}
+
+SimulatorResult ResourceUpdateAutomation::start()
+{
+    if (true == m_status)
+        return SIMULATOR_AUTOMATION_ALREADY_STARTED;
+
+    m_resModel = m_resource->getModel();
+    std::map<std::string, SimulatorResourceModel::Attribute> attributes = m_resModel.getAttributes();
+    if (0 == attributes.size())
+    {
+        m_status = false;
+        return SIMULATOR_ERROR;
+    }
+
+    int id = 0;
+    for (auto & attribute : attributes)
+    {
+        AttributeUpdateAutomationPtr attributeAutomation = std::make_shared<AttributeUpdateAutomation>
+                (m_resource, attribute.first, nullptr, id,
+                 std::bind(&ResourceUpdateAutomation::finished, this, std::placeholders::_1),
+                 m_type, m_updateInterval);
+        m_attrUpdationList[id++] = attributeAutomation;
+        if (SIMULATOR_SUCCESS != attributeAutomation->start())
+        {
+            m_status = false;
+            stop();
+            return SIMULATOR_ERROR;
+        }
+    }
+
+    m_status = true;
+    return SIMULATOR_SUCCESS;
+}
+
+void ResourceUpdateAutomation::finished(int id)
+{
+    if (m_attrUpdationList.end() != m_attrUpdationList.find(id))
+    {
+        m_attrUpdationList.erase(m_attrUpdationList.find(id));
+    }
+
+    if (!m_attrUpdationList.size())
+    {
+        // Notify application through callback
+        if (m_callback)
+            m_callback(m_resource->getURI(), m_id);
+        if (m_finishedCallback)
+            m_finishedCallback(m_id);
+    }
+}
+void ResourceUpdateAutomation::stop()
+{
+    // Stop all the attributes updation
+    for (auto & attrAutomation : m_attrUpdationList)
+    {
+        (attrAutomation.second)->stop();
+    }
+
+    m_attrUpdationList.clear();
+    m_status = false;
+}
+
+UpdateAutomationManager::UpdateAutomationManager()
+    : m_automationId(0) {}
+
+SimulatorResult UpdateAutomationManager::startResourceAutomation(SimulatorResourceServer *resource,
+        int &id, updateCompleteCallback callback, AutomationType type, int interval)
+{
+    std::lock_guard<std::mutex> lock(m_mutex);
+
+    ResourceUpdateAutomationPtr resourceAutomation(new ResourceUpdateAutomation(
+                resource, callback, m_automationId,
+                std::bind(&UpdateAutomationManager::automationFinished, this, std::placeholders::_1),
+                type, interval));
+    SimulatorResult result = resourceAutomation->start();
+    if (SIMULATOR_SUCCESS != result)
+    {
+        id = -1;
+        return result;
+    }
+
+    m_resourceUpdationList[m_automationId] = resourceAutomation;
+    id = m_automationId++;
+    return result;
+}
+
+SimulatorResult UpdateAutomationManager::startAttributeAutomation(SimulatorResourceServer *resource,
+        const std::string &attrName, int &id, updateCompleteCallback callback, AutomationType type,
+        int interval)
+{
+    std::lock_guard<std::mutex> lock(m_mutex);
+
+    AttributeUpdateAutomationPtr attributeAutomation(new AttributeUpdateAutomation(
+                resource, attrName, callback, m_automationId,
+                std::bind(&UpdateAutomationManager::automationFinished, this, std::placeholders::_1),
+                type, interval));
+    SimulatorResult result = attributeAutomation->start();
+    if (SIMULATOR_SUCCESS != result)
+    {
+        id = -1;
+        return result;
+    }
+
+    m_attrUpdationList[m_automationId] = attributeAutomation;
+    id = m_automationId++;
+    return result;
+}
+
+std::vector<int> UpdateAutomationManager::getResourceAutomationIds()
+{
+    std::vector<int> ids;
+    std::lock_guard<std::mutex> lock(m_mutex);
+    for (auto & automation : m_resourceUpdationList)
+        ids.push_back(automation.first);
+
+    return ids;
+}
+
+std::vector<int> UpdateAutomationManager::getAttributeAutomationIds()
+{
+    std::vector<int> ids;
+    std::lock_guard<std::mutex> lock(m_mutex);
+    for (auto & automation : m_attrUpdationList)
+        ids.push_back(automation.first);
+
+    return ids;
+}
+
+void UpdateAutomationManager::stop(int automationId)
+{
+    std::lock_guard<std::mutex> lock(m_mutex);
+    if (m_resourceUpdationList.end() != m_resourceUpdationList.find(automationId))
+    {
+        m_resourceUpdationList[automationId]->stop();
+        m_resourceUpdationList.erase(m_resourceUpdationList.find(automationId));
+    }
+    else if (m_attrUpdationList.end() != m_attrUpdationList.find(automationId))
+    {
+        m_attrUpdationList[automationId]->stop();
+        m_attrUpdationList.erase(m_attrUpdationList.find(automationId));
+    }
+}
+
+void UpdateAutomationManager::stopAll()
+{
+    std::lock_guard<std::mutex> lock(m_mutex);
+    std::for_each(m_resourceUpdationList.begin(),
+                  m_resourceUpdationList.end(), [] (std::pair<int, ResourceUpdateAutomationPtr> element)
+    {
+        element.second->stop();
+    });
+    m_resourceUpdationList.clear();
+
+    std::for_each(m_attrUpdationList.begin(),
+                  m_attrUpdationList.end(), [] (std::pair<int, AttributeUpdateAutomationPtr> element)
+    {
+        element.second->stop();
+    });
+    m_attrUpdationList.clear();
+}
+
+void UpdateAutomationManager::automationFinished(int id)
+{
+    std::lock_guard<std::mutex> lock(m_mutex);
+    if (m_resourceUpdationList.end() != m_resourceUpdationList.find(id))
+    {
+        m_resourceUpdationList.erase(m_resourceUpdationList.find(id));
+    }
+    else if (m_attrUpdationList.end() != m_attrUpdationList.find(id))
+    {
+        m_attrUpdationList.erase(m_attrUpdationList.find(id));
+    }
+}
\ No newline at end of file
diff --git a/service/simulator/src/simulator_attribute_automation.h b/service/simulator/src/simulator_attribute_automation.h
new file mode 100644 (file)
index 0000000..36717cd
--- /dev/null
@@ -0,0 +1,119 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#ifndef SIMULATOR_RESOURCE_UPDATE_AUTOMATION_H_
+#define SIMULATOR_RESOURCE_UPDATE_AUTOMATION_H_
+
+#include "simulator_resource_model.h"
+#include "simulator_error_codes.h"
+
+class SimulatorResourceServer;
+
+enum class AutomationType
+{
+    NORMAL,
+    RECURRENT
+};
+
+typedef std::function<void (const std::string &, const int)> updateCompleteCallback;
+
+class AttributeUpdateAutomation
+{
+    public:
+        AttributeUpdateAutomation(SimulatorResourceServer *resource,
+                                  const std::string &attrName, updateCompleteCallback callback, int automationId,
+                                  std::function<void (const int)> finishedCallback, AutomationType type = AutomationType::NORMAL,
+                                  int interval = -1);
+        SimulatorResult start();
+        void stop();
+
+    private:
+        void updateAttribute();
+        void setAttributeValue();
+
+        SimulatorResourceServer *m_resource;
+        std::string m_attrName;
+        AutomationType m_type;
+        int m_id;
+        bool m_status;
+        std::thread *m_thread;
+        bool m_stopRequested;
+        int m_updateInterval;
+        SimulatorResourceModel::Attribute m_attribute;
+        updateCompleteCallback m_callback;
+        std::function<void (const int)> m_finishedCallback;
+};
+
+typedef std::shared_ptr<AttributeUpdateAutomation> AttributeUpdateAutomationPtr;
+
+class ResourceUpdateAutomation
+{
+    public:
+        ResourceUpdateAutomation(SimulatorResourceServer *resource, updateCompleteCallback callback,
+                                 int automationId, std::function<void (const int)> finishedCallback,
+                                 AutomationType type = AutomationType::NORMAL, int interval = -1);
+        SimulatorResult start();
+        void stop();
+        void finished(int id);
+
+    private:
+        void updateAttribute();
+        void setAttributeValue();
+
+        SimulatorResourceServer *m_resource;
+        AutomationType m_type;
+        int m_id;
+        bool m_status;
+        std::thread *m_thread;
+        int m_updateInterval;
+        SimulatorResourceModel m_resModel;
+        std::map<int, AttributeUpdateAutomationPtr> m_attrUpdationList;
+        updateCompleteCallback m_callback;
+        std::function<void (const int)> m_finishedCallback;
+};
+
+typedef std::shared_ptr<ResourceUpdateAutomation> ResourceUpdateAutomationPtr;
+
+class UpdateAutomationManager
+{
+    public:
+        UpdateAutomationManager();
+        SimulatorResult startResourceAutomation(SimulatorResourceServer *resource,
+                                                int &id, updateCompleteCallback callback,
+                                                AutomationType type = AutomationType::NORMAL, int interval = -1);
+        SimulatorResult startAttributeAutomation(SimulatorResourceServer *resource,
+                const std::string &attrName, int &id, updateCompleteCallback callback,
+                AutomationType type = AutomationType::NORMAL, int interval = -1);
+        std::vector<int> getResourceAutomationIds();
+        std::vector<int> getAttributeAutomationIds();
+        void stop(int automationId);
+        void stopAll();
+        void automationFinished(int id);
+
+    private:
+        std::map<int, ResourceUpdateAutomationPtr> m_resourceUpdationList;
+        std::map<int, AttributeUpdateAutomationPtr> m_attrUpdationList;
+        int m_automationId;
+        std::mutex m_mutex;
+};
+
+typedef std::shared_ptr<UpdateAutomationManager> UpdateAutomationManagerPtr;
+
+#endif //SIMULATOR_RESOURCE_UPDATE_AUTOMATION_H_
diff --git a/service/simulator/src/simulator_client.cpp b/service/simulator/src/simulator_client.cpp
new file mode 100644 (file)
index 0000000..297d6fc
--- /dev/null
@@ -0,0 +1,123 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "simulator_client.h"
+#include "simulator_logger.h"
+
+SimulatorClient *SimulatorClient::getInstance()
+{
+    static SimulatorClient s_instance;
+    return &s_instance;
+}
+
+SimulatorResult SimulatorClient::findResource(const std::string &resourceType,
+        ResourceFindCallback callback)
+{
+    // Construct the request query for discovery
+    std::string query = OC_MULTICAST_DISCOVERY_URI;
+    query.append("?rt=");
+    query.append(resourceType);
+
+    OCStackResult result = OC::OCPlatform::findResource("", query,
+                           CT_DEFAULT,
+                           std::bind(&SimulatorClient::onResourceFound, this,
+                                     std::placeholders::_1, callback));
+
+    if (OC_STACK_OK != result)
+    {
+        SIM_LOG(ILogger::ERROR, "Failed to find the resource!");
+        return SIMULATOR_ERROR;
+    }
+
+    return SIMULATOR_SUCCESS;
+}
+
+std::vector<SimulatorRemoteResourcePtr> SimulatorClient::getFoundResources(
+    const std::string &resourceType)
+{
+    std::lock_guard<std::recursive_mutex> lock(m_resourceListMutex);
+
+    std::map<std::string, SimulatorRemoteResourcePtr> tempList;
+    for (auto resourceTableEntry : m_resourceList)
+    {
+        if (resourceType.compare(resourceTableEntry.first))
+        {
+            tempList = resourceTableEntry.second;
+            break;
+        }
+        else
+        {
+            for (auto resourceEntry : resourceTableEntry.second)
+            {
+                tempList[resourceEntry.first] = resourceEntry.second;
+            }
+        }
+    }
+
+    // Convert map to vector
+    std::vector<SimulatorRemoteResourcePtr> resourceList;
+    for (auto & resource : tempList)
+        resourceList.push_back(resource.second);
+
+    return resourceList;
+}
+
+void SimulatorClient::onResourceFound(std::shared_ptr<OC::OCResource> resource,
+                                      ResourceFindCallback callback)
+{
+    if (nullptr == resource)
+    {
+        return;
+    }
+
+    std::string serverId = resource->sid();
+
+    // Construct SimulatorRemoteResource
+    SimulatorRemoteResourcePtr simulatorResource(new SimulatorRemoteResource(resource));
+
+    // Add the resource to list
+    for (auto & resourceType : resource->getResourceTypes())
+        addResourceToList(resourceType, serverId, simulatorResource);
+
+    callback(simulatorResource);
+}
+
+void SimulatorClient::addResourceToList(const std::string &resourceType, const std::string &sid,
+                                        SimulatorRemoteResourcePtr &resource)
+{
+    std::lock_guard<std::recursive_mutex> lock(m_resourceListMutex);
+
+    if (!resourceType.empty() && !sid.empty() && nullptr != resource)
+    {
+        auto resourceTableEntry = m_resourceList.find(resourceType);
+        if (m_resourceList.end() != resourceTableEntry)
+        {
+            auto resourceEntry = resourceTableEntry->second.find(sid);
+            if (resourceTableEntry->second.end() != resourceEntry)
+            {
+                return;
+            }
+        }
+
+        m_resourceList[resourceType].insert(std::pair<std::string, SimulatorRemoteResourcePtr>(sid,
+                                            resource));
+    }
+}
+
diff --git a/service/simulator/src/simulator_client.h b/service/simulator/src/simulator_client.h
new file mode 100644 (file)
index 0000000..329382e
--- /dev/null
@@ -0,0 +1,89 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @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_remote_resource.h"
+#include "simulator_error_codes.h"
+
+/**
+ * @class   SimulatorClient
+ * @brief   This class provides a set of functions for discovering the resources currently running on the servers.
+ */
+class SimulatorClient
+{
+    public:
+
+        /**
+         * API for getting singleton instance of SimulatorClient class.
+         *
+         * @return Instance of SimulatorClient class.
+         *
+         */
+        static SimulatorClient *getInstance(void);
+
+        /**
+         * API for discovering resources of a particular resource type.
+         * Callback is called when a resource is found.
+         *
+         * @param resourceType - required resource type
+         * @param callback - Returns SimulatorRemoteResource.
+         *
+         * @return SimulatorResult - return value of this API.
+         *                         It returns SIMULATOR_SUCCESS if success.
+         *
+         * NOTE: SimulatorResult is defined in simulator_error_codes.h.
+         */
+        SimulatorResult findResource(const std::string &resourceType, ResourceFindCallback callback);
+
+        /**
+         * API for getting list of already found resources.
+         *
+         * @param resourceType - resource type
+         *
+         * @return List of SimulatorRemoteResource
+         *
+         */
+        std::vector<SimulatorRemoteResourcePtr> getFoundResources(
+            const std::string &resourceType = "");
+
+    private:
+
+        SimulatorClient() = default;
+        ~SimulatorClient() = default;
+
+        void onResourceFound(std::shared_ptr<OC::OCResource> resource, ResourceFindCallback callback);
+        void addResourceToList(const std::string &resourceType, const std::string &sid,
+                               SimulatorRemoteResourcePtr &resource);
+
+        std::recursive_mutex m_resourceListMutex;
+        std::map<std::string, std::map<std::string, SimulatorRemoteResourcePtr>> m_resourceList;
+};
+
+#endif //SIMULATOR_CLIENT_H_
+
diff --git a/service/simulator/src/simulator_error_codes.h b/service/simulator/src/simulator_error_codes.h
new file mode 100644 (file)
index 0000000..7b09e4e
--- /dev/null
@@ -0,0 +1,42 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#ifndef SIMULATOR_ERROR_CODES_H_
+#define SIMULATOR_ERROR_CODES_H_
+
+#include <iostream>
+
+typedef enum
+{
+    SIMULATOR_SUCCESS = 0,
+    SIMULATOR_BAD_INPUT,
+    SIMULATOR_RESOURCE_NOT_FOUND,
+    SIMULATOR_RESOURCE_BUSY,
+    SIMULATOR_RESOURCE_ALREADY_REGISTERED,
+    SIMULATOR_RESOURCE_NOT_REGISTERED,
+    SIMULATOR_OPERATION_NOT_ALLOWED,
+    SIMULATOR_RESOURCE_ALREADY_OBSERVING,
+
+    // Attribute udpate automation related
+    SIMULATOR_AUTOMATION_ALREADY_STARTED,
+
+    SIMULATOR_ERROR = 255
+} SimulatorResult;
+#endif //SIMULATOR_ERROR_CODES_H_
\ No newline at end of file
diff --git a/service/simulator/src/simulator_logger.cpp b/service/simulator/src/simulator_logger.cpp
new file mode 100644 (file)
index 0000000..e8ed2ea
--- /dev/null
@@ -0,0 +1,117 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "simulator_logger.h"
+#include <sstream>
+#include <fstream>
+#include <time.h>
+
+class ConsoleLogger : public ILogger
+{
+    public:
+        void write(std::string time, ILogger::Level level, std::string message)
+        {
+            std::ostringstream out;
+            out << time << " " << ILogger::getString(level) << " " << message;
+            std::cout << out.str() << std::endl;
+        }
+};
+
+class FileLogger : public ILogger
+{
+    public:
+        FileLogger(std::string filePath) : m_filePath(filePath) {}
+
+        bool open()
+        {
+            m_out.open(m_filePath, std::ofstream::out);
+            return m_out.is_open();
+        }
+
+        void close()
+        {
+            if (m_out.is_open())
+                m_out.close();
+        }
+
+        void write(std::string time, ILogger::Level level, std::string message)
+        {
+            m_out << time << " " << ILogger::getString(level) << " " << message;
+        }
+
+    private:
+        std::ofstream m_out;
+        std::string m_filePath;
+};
+
+bool Logger::setDefaultConsoleTarget()
+{
+    if (nullptr != m_target)
+        return false;
+
+    m_target = std::make_shared<ConsoleLogger>();
+    return true;
+}
+
+bool Logger::setDefaultFileTarget(std::string &path)
+{
+    if (nullptr != m_target || path.empty())
+        return false;
+
+    time_t timeInfo = time(NULL);
+    struct tm *localTime = localtime(&timeInfo);
+    std::ostringstream newFileName;
+    newFileName << path << "/Simulator_";
+    newFileName << localTime->tm_year << localTime->tm_mon << localTime->tm_mday << localTime->tm_hour
+                << localTime->tm_min << localTime->tm_sec;
+    newFileName << ".log";
+
+    std::shared_ptr<FileLogger> fileLogger(new FileLogger(newFileName.str()));
+    if (fileLogger->open())
+    {
+        m_target = fileLogger;
+        return true;
+    }
+
+    return false;
+}
+
+void Logger::setCustomTarget(std::shared_ptr<ILogger> target)
+{
+    m_target = target;
+}
+
+void Logger::write(ILogger::Level level, std::ostringstream &str)
+{
+    if (nullptr != m_target)
+    {
+        time_t timeInfo = time(NULL);
+        struct tm *localTime = localtime(&timeInfo);
+        std::ostringstream timeStr;
+        timeStr << localTime->tm_hour << "." << localTime->tm_min << "." << localTime->tm_sec;
+        m_target->write(timeStr.str(), level, str.str());
+    }
+}
+
+auto simLogger() -> Logger &
+{
+    static Logger logger;
+    return logger;
+}
\ No newline at end of file
diff --git a/service/simulator/src/simulator_logger.h b/service/simulator/src/simulator_logger.h
new file mode 100644 (file)
index 0000000..9c7e407
--- /dev/null
@@ -0,0 +1,79 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file   simulator_logger.h
+ *
+ * @brief   This file provides the interface for logging messages to different targets (console/file).
+ */
+
+#ifndef SIMULATOR_LOGGER_H_
+#define SIMULATOR_LOGGER_H_
+
+#include <iostream>
+#include <memory>
+
+class ILogger
+{
+    public:
+        enum Level
+        {
+            INFO = 0,
+            DEBUG,
+            WARNING,
+            ERROR
+        };
+
+        static const char *getString(Level level)
+        {
+            switch (level)
+            {
+                case Level::INFO: return "INFO";
+                case Level::DEBUG: return "DEBUG";
+                case Level::WARNING: return "WARNING";
+                case Level::ERROR: return "ERROR";
+                default: return "UNKNOWN";
+            }
+        }
+
+        virtual void write(std::string, Level, std::string) = 0;
+};
+
+class Logger
+{
+    public:
+        bool setDefaultConsoleTarget();
+        bool setDefaultFileTarget(std::string &path);
+        void setCustomTarget(std::shared_ptr<ILogger> target);
+        void write(ILogger::Level level, std::ostringstream &str);
+
+    private:
+        std::shared_ptr<ILogger> m_target;
+};
+
+auto simLogger() -> Logger &;
+
+#ifndef SIM_LOG
+#define SIM_LOG(LEVEL, MSG) { \
+        simLogger().write(LEVEL, static_cast<std::ostringstream&>(std::ostringstream()<<MSG)); \
+    }
+#endif
+
+#endif
\ No newline at end of file
diff --git a/service/simulator/src/simulator_manager.cpp b/service/simulator/src/simulator_manager.cpp
new file mode 100644 (file)
index 0000000..b641656
--- /dev/null
@@ -0,0 +1,101 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "simulator_manager.h"
+#include "resource_manager.h"
+#include "simulator_client.h"
+
+using namespace OC;
+
+SimulatorManager *SimulatorManager::getInstance()
+{
+    static SimulatorManager s_instance;
+    return &s_instance;
+}
+
+SimulatorManager::SimulatorManager()
+{
+    OC::PlatformConfig conf
+    {
+        OC::ServiceType::InProc,
+        OC::ModeType::Both,
+        "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces
+        0,         // Uses randomly available port
+        OC::QualityOfService::LowQos
+    };
+
+    OC::OCPlatform::Configure(conf);
+}
+
+SimulatorResourceServerPtr SimulatorManager::createResource(const std::string &configPath,
+        SimulatorResourceServer::ResourceModelChangedCB callback)
+{
+    return ResourceManager::getInstance()->createResource(configPath, callback);
+}
+
+std::vector<SimulatorResourceServerPtr> SimulatorManager::createResource(
+    const std::string &configPath,
+    const int count, SimulatorResourceServer::ResourceModelChangedCB callback)
+{
+    return ResourceManager::getInstance()->createResource(configPath, count, callback);
+}
+
+std::vector<SimulatorResourceServerPtr> SimulatorManager::getResources(
+    const std::string &resourceType)
+{
+    return ResourceManager::getInstance()->getResources(resourceType);
+}
+
+SimulatorResult SimulatorManager::deleteResource(SimulatorResourceServerPtr &resource)
+{
+    return ResourceManager::getInstance()->deleteResource(resource);
+}
+
+SimulatorResult SimulatorManager::deleteResources(const std::string &resourceType)
+{
+    return ResourceManager::getInstance()->deleteResources(resourceType);
+}
+
+SimulatorResult SimulatorManager::findResource(const std::string &resourceType,
+        ResourceFindCallback callback)
+{
+    return SimulatorClient::getInstance()->findResource(resourceType, callback);
+}
+
+std::vector<SimulatorRemoteResourcePtr> SimulatorManager::getFoundResources(
+    const std::string resourceType)
+{
+    return SimulatorClient::getInstance()->getFoundResources(resourceType);
+}
+
+void SimulatorManager::setLogger(std::shared_ptr<ILogger> logger)
+{
+    simLogger().setCustomTarget(logger);
+}
+
+bool SimulatorManager::setDefaultConsoleLogger()
+{
+    return simLogger().setDefaultConsoleTarget();
+}
+
+bool SimulatorManager::setDefaultFileLogger(std::string &path)
+{
+    return simLogger().setDefaultFileTarget(path);
+}
\ No newline at end of file
diff --git a/service/simulator/src/simulator_remote_resource.cpp b/service/simulator/src/simulator_remote_resource.cpp
new file mode 100644 (file)
index 0000000..cdd8fd1
--- /dev/null
@@ -0,0 +1,201 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "simulator_remote_resource.h"
+#include "OCApi.h"
+
+SimulatorRemoteResource::SimulatorRemoteResource(std::shared_ptr<OC::OCResource> resource)
+    : m_ocResource(resource) {}
+
+std::string SimulatorRemoteResource::getURI() const
+{
+    return m_ocResource->uri();
+}
+
+std::string SimulatorRemoteResource::getHost() const
+{
+    return m_ocResource->host();
+}
+
+std::string SimulatorRemoteResource::getSID() const
+{
+    return m_ocResource->sid();
+}
+
+OCConnectivityType SimulatorRemoteResource::getConnectivityType() const
+{
+    return m_ocResource->connectivityType();
+}
+
+std::vector < std::string > SimulatorRemoteResource::getResourceTypes() const
+{
+    return m_ocResource->getResourceTypes();
+}
+
+std::vector < std::string > SimulatorRemoteResource::getResourceInterfaces() const
+{
+    return m_ocResource->getResourceInterfaces();
+}
+
+bool SimulatorRemoteResource::isObservable() const
+{
+    return m_ocResource->isObservable();
+}
+
+SimulatorResult SimulatorRemoteResource::observe(SimulatorRemoteResource::ObserveType type,
+        const QueryParamsMap &queryParams, RepresentationChangeCallback callback)
+{
+    std::lock_guard<std::mutex> lock(m_observeMutex);
+
+    static int observeState = false;
+    if (!observeState)
+    {
+        OC::ObserveCallback observeCallback = [callback](const OC::HeaderOptions & headerOptions,
+                                              const OC::OCRepresentation & rep, const int errorCode,
+                                              const int sequenceNum)
+        {
+            // Convert OCRepresentation to SimulatorResourceModel
+            SimulatorResourceModel resModel = SimulatorResourceModel::create(rep);
+            callback(errorCode, resModel, sequenceNum);
+        };
+
+        OC::ObserveType observeType =
+            (type == SimulatorRemoteResource::OBSERVE_ALL) ? OC::ObserveType::ObserveAll :
+            OC::ObserveType::Observe;
+        OCStackResult error = m_ocResource->observe(observeType, queryParams, observeCallback);
+        if (OC_STACK_OK == error)
+        {
+            observeState = true;
+            return SIMULATOR_SUCCESS;
+        }
+        else
+        {
+            return SIMULATOR_ERROR;
+        }
+    }
+
+    return SIMULATOR_RESOURCE_ALREADY_OBSERVING;
+}
+
+SimulatorResult SimulatorRemoteResource::cancelObserve()
+{
+    OCStackResult error = m_ocResource->cancelObserve();
+    if (OC_STACK_OK != error)
+        return SIMULATOR_ERROR;
+    return SIMULATOR_SUCCESS;
+}
+
+SimulatorResult SimulatorRemoteResource::get(const std::string &resourceType,
+        const std::string &interfaceType,
+        const QueryParamsMap &queryParams, ResponseCallback callback)
+{
+    OC::GetCallback getCallback = [callback](const OC::HeaderOptions & headerOptions,
+                                  const OC::OCRepresentation & rep, const int errorCode)
+    {
+        // Convert OCRepresentation to SimulatorResourceModel
+        SimulatorResourceModel resModel = SimulatorResourceModel::create(rep);
+        callback(errorCode, resModel);
+    };
+
+    // Convert SimulatorResourceModel to OcRepresentation
+    OCStackResult result = m_ocResource->get(resourceType, interfaceType, queryParams,
+                           getCallback);
+    if (OC_STACK_OK != result)
+    {
+        return SIMULATOR_ERROR;
+    }
+
+    return SIMULATOR_SUCCESS;
+}
+
+SimulatorResult SimulatorRemoteResource::get(const QueryParamsMap &queryParams,
+        ResponseCallback callback)
+{
+    std::string resourceType;
+    std::string interfaceType;
+    return get(resourceType, interfaceType, queryParams, callback);
+}
+
+SimulatorResult SimulatorRemoteResource::put(const std::string &resourceType,
+        const std::string &interfaceType,
+        const SimulatorResourceModel &representation,
+        const QueryParamsMap &queryParams, ResponseCallback callback)
+{
+    OC::PutCallback putCallback = [callback](const OC::HeaderOptions & headerOptions,
+                                  const OC::OCRepresentation & rep, const int errorCode)
+    {
+        // Convert OCRepresentation to SimulatorResourceModel
+        SimulatorResourceModel resModel = SimulatorResourceModel::create(rep);
+        callback(errorCode, resModel);
+    };
+
+    // Convert SimulatorResourceModel to OcRepresentation
+    OC::OCRepresentation ocRep = representation.getOCRepresentation();
+    OCStackResult result = m_ocResource->put(resourceType, interfaceType, ocRep, queryParams,
+                           putCallback);
+    if (OC_STACK_OK != result)
+    {
+        return SIMULATOR_ERROR;
+    }
+
+    return SIMULATOR_SUCCESS;
+}
+
+SimulatorResult SimulatorRemoteResource::put(const SimulatorResourceModel &representation,
+        const QueryParamsMap &queryParams, ResponseCallback callback)
+{
+    std::string resourceType;
+    std::string interfaceType;
+    return put(resourceType, interfaceType, representation, queryParams, callback);
+}
+
+SimulatorResult SimulatorRemoteResource::post(const std::string &resourceType,
+        const std::string &interfaceType,
+        const SimulatorResourceModel &representation,
+        const QueryParamsMap &queryParams, ResponseCallback callback)
+{
+    OC::PostCallback postCallback = [callback](const OC::HeaderOptions & headerOptions,
+                                    const OC::OCRepresentation & rep, const int errorCode)
+    {
+        // Convert OCRepresentation to SimulatorResourceModel
+        SimulatorResourceModel resModel = SimulatorResourceModel::create(rep);
+        callback(errorCode, resModel);
+    };
+
+    // Convert SimulatorResourceModel to OcRepresentation
+    OC::OCRepresentation ocRep = representation.getOCRepresentation();
+    OCStackResult result = m_ocResource->post(resourceType, interfaceType, ocRep, queryParams,
+                           postCallback);
+    if (OC_STACK_OK != result)
+    {
+        return SIMULATOR_ERROR;
+    }
+
+    return SIMULATOR_SUCCESS;
+}
+
+SimulatorResult SimulatorRemoteResource::post(const SimulatorResourceModel &representation,
+        const QueryParamsMap &queryParams, ResponseCallback callback)
+{
+    std::string resourceType;
+    std::string interfaceType;
+    return post(resourceType, interfaceType, representation, queryParams, callback);
+}
+
diff --git a/service/simulator/src/simulator_remote_resource.h b/service/simulator/src/simulator_remote_resource.h
new file mode 100644 (file)
index 0000000..6104569
--- /dev/null
@@ -0,0 +1,113 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file   simulator_remote_resource.h
+ *
+ * @brief   This file provides a class for handling remote resources by the client.
+ *
+ */
+
+#ifndef SIMULATOR_REMOTE_RESOURCE_H_
+#define SIMULATOR_REMOTE_RESOURCE_H_
+
+#include "simulator_resource_model.h"
+#include "simulator_error_codes.h"
+
+#include <string>
+#include <vector>
+#include "OCPlatform.h"
+#include "OCApi.h"
+
+/**
+ * @class   SimulatorRemoteResource
+ * @brief   This class represents the resource discovered in the network and provides APIs
+ *          for sending requests to discovered resource.
+ */
+class SimulatorRemoteResource
+{
+    public:
+        typedef enum
+        {
+            OBSERVE,
+            OBSERVE_ALL
+        } ObserveType;
+
+        // Typedef for query parameter map
+        typedef std::map<std::string, std::string> QueryParamsMap;
+
+        typedef std::function<void (int, const SimulatorResourceModel &, int)>
+        RepresentationChangeCallback;
+
+        typedef std::function<void (int, const SimulatorResourceModel &)>
+        ResponseCallback;
+
+        SimulatorRemoteResource(std::shared_ptr<OC::OCResource> resource);
+
+        std::string getURI() const;
+
+        std::string getHost() const;
+
+        std::string getSID() const;
+
+        OCConnectivityType getConnectivityType() const;
+
+        std::vector < std::string > getResourceTypes() const;
+
+        std::vector < std::string > getResourceInterfaces() const;
+
+        bool isObservable() const;
+
+        SimulatorResult observe(ObserveType type,
+                                const QueryParamsMap &queryParams, RepresentationChangeCallback callback);
+
+        SimulatorResult cancelObserve();
+
+        SimulatorResult get(const QueryParamsMap &queryParams,
+                            ResponseCallback callback);
+
+        SimulatorResult get(const std::string &resourceType, const std::string &interfaceType,
+                            const QueryParamsMap &queryParams, ResponseCallback callback);
+
+        SimulatorResult put(const SimulatorResourceModel &representation,
+                            const QueryParamsMap &queryParams, ResponseCallback callback);
+
+        SimulatorResult put(const std::string &resourceType, const std::string &interfaceType,
+                            const SimulatorResourceModel &representation,
+                            const QueryParamsMap &queryParams, ResponseCallback callback);
+
+        SimulatorResult post(const SimulatorResourceModel &representation,
+                             const QueryParamsMap &queryParams, ResponseCallback callback);
+
+        SimulatorResult post(const std::string &resourceType, const std::string &interfaceType,
+                             const SimulatorResourceModel &representation,
+                             const QueryParamsMap &queryParams, ResponseCallback callback);
+
+    private:
+
+        std::shared_ptr<OC::OCResource> m_ocResource;
+        std::mutex m_observeMutex;
+};
+
+typedef std::shared_ptr<SimulatorRemoteResource> SimulatorRemoteResourcePtr;
+typedef std::function<void(SimulatorRemoteResourcePtr)> ResourceFindCallback;
+
+#endif //SIMULATOR_REMOTE_RESOURCE_H_
+
diff --git a/service/simulator/src/simulator_resource_creator.cpp b/service/simulator/src/simulator_resource_creator.cpp
new file mode 100644 (file)
index 0000000..2364734
--- /dev/null
@@ -0,0 +1,93 @@
+/******************************************************************\r
+ *\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ *\r
+ *\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#include "simulator_resource_creator.h"\r
+#include "simulator_logger.h"\r
+#include <RamlParser.h>\r
+#include <boost/lexical_cast.hpp>\r
+\r
+using namespace RAML;\r
+\r
+SimulatorResourceServerPtr SimulatorResourceCreator::createResource(const std::string &configPath)\r
+{\r
+    std::shared_ptr<SimulatorResourceServer> resource(new SimulatorResourceServer);\r
+\r
+    if (configPath.length() > 0)\r
+    {\r
+        std::size_t found = configPath.find_last_of("/\\");\r
+        if (found > configPath.length())\r
+        {\r
+            return resource;\r
+        }\r
+        std::string filePath = configPath.substr(0, found) + "/";\r
+        std::string fileName = configPath.substr(found + 1);\r
+\r
+        RamlPtr raml = (new RamlParser(filePath, fileName))->build();\r
+        for (auto  resours : raml->getResources())\r
+        {\r
+            resource->setName(resours.first);\r
+            resource->setURI(resours.second.getResourceUri());\r
+            for (auto  action :  resours.second.getActions())\r
+            {\r
+                for (auto  response :  action.second.getResponses())\r
+                {\r
+                    for (auto bdy :  response.second.getResponseBody())\r
+                    {\r
+                        auto resourceProperties = bdy.second.getSchema()->getProperties();\r
+\r
+                        resource->setResourceType(resourceProperties->getResoureType());\r
+                        resource->setInterfaceType(resourceProperties->getInterface());\r
+\r
+                        for ( auto property : resourceProperties->getAttributes() )\r
+                        {\r
+                            int type = property.second.getValueType();\r
+                            if (type)\r
+                            {\r
+                                std::string attributeValue = property.second.getValueString();\r
+                                resource->addAttribute(property.second.getName(), std::string(attributeValue));\r
+                            }\r
+                            else\r
+                            {\r
+                                int attributeValue = property.second.getValueInt();\r
+                                resource->addAttribute(property.second.getName(), int(attributeValue));\r
+                            }\r
+\r
+                            resource->setUpdateInterval(property.second.getName(), property.second.getUpdateFrequencyTime());\r
+\r
+                            int min = 0, max = 0;\r
+                            property.second.getRange(min, max);\r
+                            resource->setRange(property.second.getName(), min, max);\r
+\r
+\r
+                            if (property.second.getAllowedValuesSize() > 0)\r
+                                resource->setAllowedValues(property.second.getName(), property.second.getAllowedValues());\r
+                        }\r
+                        SIM_LOG(ILogger::INFO, "Created sample resource");\r
+                        return resource;\r
+                    }\r
+                }\r
+\r
+            }\r
+        }\r
+    }\r
+    SIM_LOG(ILogger::INFO, "Created sample resource");\r
+    return resource;\r
+}\r
+\r
diff --git a/service/simulator/src/simulator_resource_creator.h b/service/simulator/src/simulator_resource_creator.h
new file mode 100644 (file)
index 0000000..ad88014
--- /dev/null
@@ -0,0 +1,36 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#ifndef SIMULATOR_RESOURCE_CREATOR_H_
+#define SIMULATOR_RESOURCE_CREATOR_H_
+
+#include "simulator_resource_server.h"
+
+class SimulatorResourceCreator
+{
+    public:
+        /**
+         * This is temporary method to get the light resource as parser
+         * needs to implemented/integrated
+         */
+        SimulatorResourceServerPtr createResource(const std::string &configPath);
+};
+
+#endif
\ No newline at end of file
diff --git a/service/simulator/src/simulator_resource_model.cpp b/service/simulator/src/simulator_resource_model.cpp
new file mode 100644 (file)
index 0000000..ce20a9d
--- /dev/null
@@ -0,0 +1,326 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "simulator_resource_model.h"
+#include <sstream>
+#include <boost/lexical_cast.hpp>
+
+class to_string_visitor : public boost::static_visitor<std::string>
+{
+    public:
+        template <typename T>
+        result_type operator ()(const T &value)
+        {
+            return boost::lexical_cast<std::string>(value);
+        }
+};
+
+class add_to_representation : public boost::static_visitor<>
+{
+    public:
+        add_to_representation(OC::OCRepresentation &rep, const std::string &key)
+            : m_rep(rep), m_key(key) {}
+
+        template <typename T>
+        void operator ()(const T &value)
+        {
+            m_rep.setValue(m_key, value);
+        }
+
+        OC::OCRepresentation &&getRep()
+        {
+            return std::move(m_rep);
+        }
+
+    private:
+        OC::OCRepresentation m_rep;
+        std::string m_key;
+};
+
+class range_validation : public boost::static_visitor<bool>
+{
+    public:
+        range_validation (SimulatorResourceModel::Attribute &attrItem)
+            : m_attrItem(attrItem) {}
+
+        bool operator ()(int &value)
+        {
+            int min, max;
+            m_attrItem.getRange(min, max);
+            if (value >= min && value <= max)
+                return true;
+            return false;
+        }
+
+        bool operator ()(double &value)
+        {
+            std::vector<SimulatorResourceModel::Attribute::ValueVariant> values
+                = m_attrItem.getAllowedValues();
+            for (SimulatorResourceModel::Attribute::ValueVariant & val : values)
+            {
+                SimulatorResourceModel::Attribute::ValueVariant vVal = value;
+                if (val == vVal)
+                    return true;
+            }
+            return false;
+        }
+
+        bool operator ()(std::string &value)
+        {
+            std::vector<SimulatorResourceModel::Attribute::ValueVariant> values
+                = m_attrItem.getAllowedValues();
+            for (SimulatorResourceModel::Attribute::ValueVariant & vVal : values)
+            {
+                std::string val = boost::get<std::string>(vVal);
+                if (val == value)
+                    return true;
+            }
+
+            return false;
+        }
+
+    private:
+        SimulatorResourceModel::Attribute &m_attrItem;
+};
+
+SimulatorResourceModel::Attribute::ValueVariant
+&SimulatorResourceModel::Attribute::AllowedValues::at(int index)
+{
+    return m_values.at(index);
+}
+
+int SimulatorResourceModel::Attribute::AllowedValues::size() const
+{
+    return m_values.size();
+}
+
+std::string SimulatorResourceModel::Attribute::AllowedValues::toString() const
+{
+    std::ostringstream stream;
+    stream << "[ ";
+    for (auto & value : m_values)
+    {
+        to_string_visitor visitor;
+        stream << boost::apply_visitor(visitor, value) << " ";
+    }
+    stream << "]";
+    return stream.str();
+}
+
+std::vector<std::string> SimulatorResourceModel::Attribute::AllowedValues::toVectorString() const
+{
+    std::vector<std::string> values;
+
+    for (auto & value : m_values)
+    {
+        to_string_visitor visitor;
+        values.push_back(boost::apply_visitor(visitor, value));
+    }
+    return values;
+}
+
+std::vector<SimulatorResourceModel::Attribute::ValueVariant>
+SimulatorResourceModel::Attribute::AllowedValues::getValues()
+{
+    return m_values;
+}
+
+std::string SimulatorResourceModel::Attribute::getName(void) const
+{
+    return m_name;
+}
+
+void SimulatorResourceModel::Attribute::setName(const std::string &name)
+{
+    m_name = name;
+}
+
+void SimulatorResourceModel::Attribute::getRange(int &min, int &max) const
+{
+    min = m_min;
+    max = m_max;
+}
+
+void SimulatorResourceModel::Attribute::setRange(const int &min, const int &max)
+{
+    m_min = min;
+    m_max = max;
+}
+
+int SimulatorResourceModel::Attribute::getAllowedValuesSize() const
+{
+    return m_allowedValues.size();
+}
+
+void SimulatorResourceModel::Attribute::setFromAllowedValue(const int allowedValueIndex)
+{
+    m_value = m_allowedValues.at(allowedValueIndex);
+}
+
+std::string SimulatorResourceModel::Attribute::valueToString() const
+{
+    to_string_visitor visitor;
+    return boost::apply_visitor(visitor, m_value);
+}
+
+std::string SimulatorResourceModel::Attribute::allowedValuesToString() const
+{
+    return m_allowedValues.toString();
+}
+
+std::vector<std::string> SimulatorResourceModel::Attribute::allowedValuesToVectorString() const
+{
+    return m_allowedValues.toVectorString();
+}
+
+void SimulatorResourceModel::Attribute::addValuetoRepresentation(OC::OCRepresentation &rep,
+        const std::string &key) const
+{
+    add_to_representation visitor(rep, key);
+    boost::apply_visitor(visitor, m_value);
+    rep = visitor.getRep();
+}
+
+bool SimulatorResourceModel::Attribute::compare(SimulatorResourceModel::Attribute &attribute)
+{
+    // Check the value types
+    if (m_value.which() != attribute.getValue().which())
+    {
+        return false;
+    }
+
+    // Check the value in allowed range
+    range_validation visitor(*this);
+    return boost::apply_visitor(visitor, attribute.getValue());
+}
+
+std::vector<SimulatorResourceModel::Attribute::ValueVariant>
+SimulatorResourceModel::Attribute::getAllowedValues()
+{
+    return m_allowedValues.getValues();
+}
+
+bool SimulatorResourceModel::getAttribute(const std::string &attrName, Attribute &value)
+{
+    if (m_attributes.end() != m_attributes.find(attrName))
+    {
+        value = m_attributes[attrName];
+        return true;
+    }
+
+    return false;
+}
+
+std::map<std::string, SimulatorResourceModel::Attribute> SimulatorResourceModel::getAttributes()
+const
+{
+    return m_attributes;
+}
+
+void SimulatorResourceModel::setRange(const std::string &attrName, const int min, const int max)
+{
+    if (m_attributes.end() != m_attributes.find(attrName))
+        m_attributes[attrName].setRange(min, max);
+}
+
+void SimulatorResourceModel::setUpdateInterval(const std::string &attrName, int interval)
+{
+    if (m_attributes.end() != m_attributes.find(attrName))
+        m_attributes[attrName].setUpdateFrequencyTime(interval);
+}
+
+void SimulatorResourceModel::updateAttributeFromAllowedValues(const std::string &attrName,
+        const int allowedValueIndex)
+{
+    if (m_attributes.end() != m_attributes.find(attrName))
+        m_attributes[attrName].setFromAllowedValue(allowedValueIndex);
+}
+
+void SimulatorResourceModel::removeAttribute(const std::string &attrName)
+{
+    m_attributes.erase(attrName);
+    return;
+}
+
+OC::OCRepresentation SimulatorResourceModel::getOCRepresentation() const
+{
+    OC::OCRepresentation rep;
+    for (auto & attribute : m_attributes)
+    {
+        (attribute.second).addValuetoRepresentation(rep, attribute.first);
+    }
+
+    return rep;
+}
+
+bool SimulatorResourceModel::update(OC::OCRepresentation &ocRep)
+{
+    if (0 == ocRep.size())
+        return true;
+
+    // Convert OCRepresentation to SimulatorResourceModel
+    SimulatorResourceModel resModel = create(ocRep);
+
+    return update(resModel);
+}
+
+bool SimulatorResourceModel::update(SimulatorResourceModel &repModel)
+{
+    std::map<std::string, SimulatorResourceModel::Attribute> attributes = repModel.getAttributes();
+    for (auto & attributeItem : attributes)
+    {
+        // Check the attribute presence
+        SimulatorResourceModel::Attribute attribute;
+        if (false == getAttribute((attributeItem.second).getName(), attribute))
+        {
+            return false;
+        }
+
+        // Check the validity of the value to be set
+        if (false == attribute.compare(attributeItem.second))
+        {
+            return false;
+        }
+        m_attributes[(attributeItem.second).getName()].setValue((attributeItem.second).getValue());
+    }
+
+    return true;
+}
+
+SimulatorResourceModel SimulatorResourceModel::create(const OC::OCRepresentation &ocRep)
+{
+    SimulatorResourceModel resModel;
+    for (auto & attributeItem : ocRep)
+    {
+        SimulatorResourceModel::Attribute attribute;
+        if (attributeItem.type() == OC::AttributeType::Integer)
+            attribute.setValue(attributeItem.getValue<int>());
+        if (attributeItem.type() == OC::AttributeType::Double)
+            attribute.setValue(attributeItem.getValue<double>());
+        if (attributeItem.type() == OC::AttributeType::String)
+            attribute.setValue(attributeItem.getValue<std::string>());
+
+        attribute.setName(attributeItem.attrname());
+        resModel.m_attributes[attributeItem.attrname()] = attribute;
+    }
+
+    return resModel;
+}
+
diff --git a/service/simulator/src/simulator_resource_model.h b/service/simulator/src/simulator_resource_model.h
new file mode 100644 (file)
index 0000000..07f9fdb
--- /dev/null
@@ -0,0 +1,257 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+/**
+ * @file   simulator_resource_model.h
+ *
+ * @brief   This file contains a class which represents the resource model for simulator
+ *             resources and provides a set of functions for updating the model.
+ */
+
+#ifndef SIMULATOR_RESOURCE_ATTRIBUTE_H_
+#define SIMULATOR_RESOURCE_ATTRIBUTE_H_
+
+#include <string>
+#include <vector>
+#include "OCPlatform.h"
+#include "OCApi.h"
+
+class SimulatorResourceServer;
+class SimulatorRemoteResource;
+/**
+ * @class   SimulatorResourceModel
+ * @brief   This class provides a set of functions for accessing and manipulating the resource model.
+ */
+class SimulatorResourceModel
+{
+        friend class SimulatorResourceServer;
+        friend class SimulatorRemoteResource;
+
+    public:
+
+        SimulatorResourceModel() = default;
+        SimulatorResourceModel(SimulatorResourceModel &&) = default;
+        SimulatorResourceModel(const SimulatorResourceModel &) = default;
+        SimulatorResourceModel &operator=(const SimulatorResourceModel &) = default;
+        SimulatorResourceModel &operator=(SimulatorResourceModel &&) = default;
+
+        virtual ~SimulatorResourceModel() {}
+
+        /**
+          * @class   Attribute
+          * @brief   This class represents a resource attribute whose values can be generic.
+          */
+        class Attribute
+        {
+            public:
+                typedef boost::variant <
+                int,
+                double,
+                std::string
+                > ValueVariant;
+
+                Attribute() = default;
+                Attribute(const std::string &attrName) : m_name(attrName) {}
+
+                std::string getName(void) const;
+                void setName(const std::string &name);
+
+                template <typename T>
+                T getValue() const
+                {
+                    T val = T();
+                    return boost::get<T>(m_value);
+                }
+
+                ValueVariant &getValue()
+                {
+                    return m_value;
+                }
+
+                int getValueType() const
+                {
+                    return m_value.which();
+                }
+
+                template <typename T>
+                void setValue(const T &value)
+                {
+                    m_value = value;
+                }
+
+                void setFromAllowedValue(const int allowedValueIndex);
+
+                void getRange(int &min, int &max) const;
+
+                void setRange(const int &min, const int &max);
+
+                template <typename T>
+                bool setAllowedValues(const std::vector<T> &values)
+                {
+                    ValueVariant temp = values.at(0);
+                    if (temp.which() != m_value.which())
+                    {
+                        return false;
+                    }
+
+                    m_allowedValues.addValues(values);
+                    return true;
+                }
+
+                /**
+                  * This method is used to get the size of the allowed values.
+                  *
+                  * @return Size of the allowed values
+                  */
+                int getAllowedValuesSize() const;
+
+                /**
+                  * This method is used to get the string representation of the value.
+                  *
+                  * @return Attribute's value as a string
+                  */
+                std::string valueToString() const;
+
+                /**
+                  * This method is used to get the string representation of all the allowed values.
+                  *
+                  * @return All allowed values as a string
+                  */
+                std::string allowedValuesToString() const;
+                std::vector<std::string> allowedValuesToVectorString() const;
+
+                void addValuetoRepresentation(OC::OCRepresentation &rep,
+                                              const std::string &key) const;
+
+                bool compare(Attribute &attribute);
+
+                std::vector<ValueVariant> getAllowedValues();
+
+                int getUpdateFrequencyTime() {return m_updateInterval;}
+                void setUpdateFrequencyTime(int interval) {m_updateInterval = interval;}
+
+            private:
+                class AllowedValues
+                {
+                    public:
+                        template <typename T>
+                        void addValue(const T &value)
+                        {
+                            ValueVariant temp = value;
+                            m_values.push_back(temp);
+                        }
+
+                        template <typename T>
+                        void addValues(const std::vector<T> &values)
+                        {
+                            for (auto value : values)
+                            {
+                                ValueVariant vValue = value;
+                                m_values.push_back(vValue);
+                            }
+                        }
+
+                        ValueVariant &at(int index);
+                        int size() const;
+                        std::string toString() const;
+                        std::vector<std::string> toVectorString() const;
+                        std::vector<ValueVariant> getValues();
+                    private:
+                        std::vector<ValueVariant> m_values;
+                };
+
+                std::string m_name;
+                ValueVariant m_value;
+                int m_max;
+                int m_min;
+                AllowedValues m_allowedValues;
+                int m_updateInterval;
+        };
+
+        /**
+         * This method is used to get the number of attributes in the resource.
+         *
+         * @return Count of attributes
+         */
+        int size() const { return m_attributes.size(); }
+
+        /**
+          * This method is used to get the value of an attribute.
+          *
+          * @param attrName - Attribute name
+          * @param value - Attribute value
+          *
+          * @return Boolean, true if attribute exists, otherwise false.
+          */
+        bool getAttribute(const std::string &attrName, Attribute &value);
+
+        /**
+          * This method is used to get the entire list of attributes in the form of key-value pair.
+          * Attribute name is the key and an instance of Attribute is the value.
+          *
+          * @return A map of all the attributes
+          */
+        std::map<std::string, Attribute> getAttributes() const;
+
+        static SimulatorResourceModel create(const OC::OCRepresentation &ocRep);
+
+        template <typename T>
+        void addAttribute(const std::string &attrName, const T &attrValue)
+        {
+            if (m_attributes.end() == m_attributes.find(attrName))
+            {
+                m_attributes[attrName] = Attribute(attrName);
+                m_attributes[attrName].setValue(attrValue);
+            }
+        }
+
+    private:
+        void setRange(const std::string &attrName, const int min, const int max);
+
+        template <typename T>
+        void setAllowedValues(const std::string &attrName, const std::vector<T> &values)
+        {
+            if (m_attributes.end() != m_attributes.find(attrName))
+                m_attributes[attrName].setAllowedValues(values);
+        }
+
+        void setUpdateInterval(const std::string &attrName, int interval);
+
+        template <typename T>
+        void updateAttribute(const std::string &attrName, const T &value)
+        {
+            if (m_attributes.end() != m_attributes.find(attrName))
+                m_attributes[attrName].setValue(value);
+        }
+
+        void updateAttributeFromAllowedValues(const std::string &attrName, const int allowedValueIndex);
+
+        void removeAttribute(const std::string &attrName);
+
+        OC::OCRepresentation getOCRepresentation() const;
+
+        bool update(OC::OCRepresentation &ocRep);
+
+        bool update(SimulatorResourceModel &repModel);
+
+        std::map<std::string, Attribute> m_attributes;
+};
+
+#endif
diff --git a/service/simulator/src/simulator_resource_server.cpp b/service/simulator/src/simulator_resource_server.cpp
new file mode 100644 (file)
index 0000000..84ebac6
--- /dev/null
@@ -0,0 +1,354 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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"
+#include "simulator_attribute_automation.h"
+#include "simulator_logger.h"
+
+SimulatorResourceServer::SimulatorResourceServer()
+    : m_resourceHandle(NULL),
+      m_property((OCResourceProperty) (OC_DISCOVERABLE | OC_OBSERVABLE)) {}
+
+SimulatorResult SimulatorResourceServer::setURI(const std::string &uri)
+{
+    if (m_resourceHandle)
+        return SIMULATOR_OPERATION_NOT_ALLOWED;
+    m_uri = uri;
+    return SIMULATOR_SUCCESS;
+}
+
+std::string SimulatorResourceServer::getURI() const
+{
+    return m_uri;
+}
+
+SimulatorResult SimulatorResourceServer::setResourceType(const std::string &resourceType)
+{
+    if (m_resourceHandle)
+        return SIMULATOR_OPERATION_NOT_ALLOWED;
+    m_resourceType = resourceType;
+    return SIMULATOR_SUCCESS;
+}
+
+std::string SimulatorResourceServer::getResourceType() const
+{
+    return m_resourceType;
+}
+
+SimulatorResult SimulatorResourceServer::setInterfaceType(const std::string &interfaceType)
+{
+    if (m_resourceHandle)
+        return SIMULATOR_OPERATION_NOT_ALLOWED;
+    m_interfaceType = interfaceType;
+    return SIMULATOR_SUCCESS;
+}
+
+std::string SimulatorResourceServer::getInterfaceType() const
+{
+    return m_interfaceType;
+}
+
+void SimulatorResourceServer::setName(const std::string &name)
+{
+    m_name = name;
+}
+
+std::string SimulatorResourceServer::getName() const
+{
+    return m_name;
+}
+
+SimulatorResult SimulatorResourceServer::setObservable(bool state)
+{
+    if (m_resourceHandle)
+        return SIMULATOR_OPERATION_NOT_ALLOWED;
+
+    if (true == state)
+        m_property = static_cast<OCResourceProperty>(m_property | OC_OBSERVABLE);
+    else
+        m_property = static_cast<OCResourceProperty>(m_property ^ OC_OBSERVABLE);
+
+    return SIMULATOR_SUCCESS;
+}
+
+bool SimulatorResourceServer::isObservable() const
+{
+    return (m_property & OC_OBSERVABLE);
+}
+
+SimulatorResult SimulatorResourceServer::start()
+{
+    if (m_resourceHandle)
+        return SIMULATOR_RESOURCE_ALREADY_REGISTERED;
+
+    if (m_uri.empty() || m_resourceType.empty() || m_interfaceType.empty()
+        || !m_callback)
+    {
+        return SIMULATOR_BAD_INPUT;
+    }
+
+    OCStackResult result = OC::OCPlatform::registerResource(m_resourceHandle,
+                           m_uri,
+                           m_resourceType,
+                           m_interfaceType,
+                           std::bind(&SimulatorResourceServer::entityHandler,
+                                     this, std::placeholders::_1), m_property);
+
+    if (OC_STACK_OK != result)
+        return SIMULATOR_ERROR;
+    return SIMULATOR_SUCCESS;
+}
+
+SimulatorResult SimulatorResourceServer::stop()
+{
+    if (nullptr == m_resourceHandle)
+    {
+        SIM_LOG(ILogger::ERROR, "Resourece is not registered!");
+        return SIMULATOR_RESOURCE_NOT_REGISTERED;
+    }
+
+    OCStackResult result = OC::OCPlatform::unregisterResource(m_resourceHandle);
+    if (OC_STACK_OK != result)
+        return SIMULATOR_ERROR;
+
+    m_resourceHandle = nullptr;
+    return SIMULATOR_SUCCESS;
+}
+
+void SimulatorResourceServer::setRange(const std::string &attrName, const int min, const int max)
+{
+    m_resModel.setRange(attrName, min, max);
+}
+
+void SimulatorResourceServer::setUpdateInterval(const std::string &attrName, int interval)
+{
+    m_resModel.setUpdateInterval(attrName, interval);
+}
+
+void SimulatorResourceServer::removeAttribute(const std::string &attrName)
+{
+    m_resModel.removeAttribute(attrName);
+    notifyListOfObservers();
+}
+
+void SimulatorResourceServer::updateAttributeFromAllowedValues(const std::string &attrName,
+        const int allowedValueIndex)
+{
+    m_resModel.updateAttributeFromAllowedValues(attrName, allowedValueIndex);
+    notifyListOfObservers();
+}
+
+SimulatorResourceModel SimulatorResourceServer::getModel() const
+{
+    return m_resModel;
+}
+
+void SimulatorResourceServer::setModelChangeCallback(ResourceModelChangedCB callback)
+{
+    m_callback = callback;
+}
+
+SimulatorResult SimulatorResourceServer::startUpdateAutomation(AutomationType type,
+        updateCompleteCallback callback, int &id)
+{
+    return m_updateAutomationMgr.startResourceAutomation(this, id, callback, type);
+}
+
+SimulatorResult SimulatorResourceServer::startUpdateAutomation(const std::string &attrName,
+        AutomationType type, updateCompleteCallback callback, int &id)
+{
+    return m_updateAutomationMgr.startAttributeAutomation(this, attrName, id, callback, type);
+}
+
+std::vector<int> SimulatorResourceServer::getResourceAutomationIds()
+{
+    return m_updateAutomationMgr.getResourceAutomationIds();
+}
+
+std::vector<int> SimulatorResourceServer::getAttributeAutomationIds()
+{
+    return m_updateAutomationMgr.getAttributeAutomationIds();
+}
+
+void SimulatorResourceServer::stopUpdateAutomation(const int id)
+{
+    m_updateAutomationMgr.stop(id);
+}
+
+OC::OCRepresentation SimulatorResourceServer::getOCRepresentation()
+{
+    return m_resModel.getOCRepresentation();
+}
+
+bool SimulatorResourceServer::modifyResourceModel(OC::OCRepresentation &ocRep)
+{
+    bool status = m_resModel.update(ocRep);
+    if (true == status)
+    {
+        notifyListOfObservers();
+    }
+    return status;
+}
+
+OCEntityHandlerResult SimulatorResourceServer::entityHandler(std::shared_ptr<OC::OCResourceRequest>
+        request)
+{
+    OCEntityHandlerResult errCode = OC_EH_ERROR;
+    if (!request)
+    {
+        return OC_EH_ERROR;
+    }
+
+    if (OC::RequestHandlerFlag::RequestFlag & request->getRequestHandlerFlag())
+    {
+        auto response = std::make_shared<OC::OCResourceResponse>();
+        response->setRequestHandle(request->getRequestHandle());
+        response->setResourceHandle(request->getResourceHandle());
+
+        if ("GET" == request->getRequestType())
+        {
+            SIM_LOG(ILogger::INFO, "[" << m_uri << "] GET request received");
+            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())
+        {
+            SIM_LOG(ILogger::INFO, "[" << m_uri << "] PUT request received");
+            OC::OCRepresentation rep = request->getResourceRepresentation();
+            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())
+        {
+            SIM_LOG(ILogger::INFO, "[" << m_uri << "] POST request received");
+            OC::OCRepresentation rep = request->getResourceRepresentation();
+            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())
+        {
+            SIM_LOG(ILogger::INFO, "[" << m_uri << "] DELETE request received!");
+            OC::OCRepresentation rep = request->getResourceRepresentation();
+
+            // 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
+        {
+            SIM_LOG(ILogger::INFO, "[" << m_uri << "] UNKNOWN type request received");
+            response->setResponseResult(OC_EH_ERROR);
+            OC::OCPlatform::sendResponse(response);
+            errCode = OC_EH_ERROR;
+        }
+    }
+
+    if (OC::RequestHandlerFlag::ObserverFlag & request->getRequestHandlerFlag())
+    {
+        if (false == isObservable())
+        {
+            SIM_LOG(ILogger::INFO, "[" << m_uri << "] OBSERVE request received");
+            SIM_LOG(ILogger::INFO, "[" << m_uri << "] Sending error as resource is in unobservable state");
+            return OC_EH_ERROR;
+        }
+
+        OC::ObservationInfo observationInfo = request->getObservationInfo();
+        if (OC::ObserveAction::ObserveRegister == observationInfo.action)
+        {
+            SIM_LOG(ILogger::INFO, "[" << m_uri << "] OBSERVE REGISTER request received");
+            m_interestedObservers.push_back(observationInfo.obsId);
+        }
+        else if (OC::ObserveAction::ObserveUnregister == observationInfo.action)
+        {
+            SIM_LOG(ILogger::INFO, "[" << m_uri << "] OBSERVE UNREGISTER request received");
+            m_interestedObservers.erase(std::remove(m_interestedObservers.begin(),
+                                                    m_interestedObservers.end(),
+                                                    observationInfo.obsId),
+                                        m_interestedObservers.end());
+        }
+        errCode = OC_EH_OK;
+    }
+
+    return errCode;
+}
+
+void SimulatorResourceServer::notifyListOfObservers ()
+{
+    if (!m_resourceHandle)
+    {
+        return;
+    }
+
+    if (m_interestedObservers.size())
+    {
+        std::shared_ptr<OC::OCResourceResponse> resourceResponse =
+        {std::make_shared<OC::OCResourceResponse>()};
+
+        resourceResponse->setErrorCode(200);
+        resourceResponse->setResponseResult(OC_EH_OK);
+        resourceResponse->setResourceRepresentation(getOCRepresentation(), OC::DEFAULT_INTERFACE);
+
+        SIM_LOG(ILogger::INFO, "[" << m_uri << "] Sending notification to all observers" << m_uri);
+        OC::OCPlatform::notifyListOfObservers(m_resourceHandle, m_interestedObservers, resourceResponse);
+    }
+
+    if (m_callback)
+    {
+        m_callback(m_uri, m_resModel);
+    }
+}
diff --git a/service/simulator/src/simulator_resource_server.h b/service/simulator/src/simulator_resource_server.h
new file mode 100644 (file)
index 0000000..e0dfc89
--- /dev/null
@@ -0,0 +1,303 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_resource_model.h"
+#include "simulator_attribute_automation.h"
+#include "simulator_error_codes.h"
+
+class ResourceManager;
+/**
+ * @class   SimulatorResourceServer
+ * @brief   This class provides a set of functions for operating and automating a resource.
+ */
+class SimulatorResourceServer
+{
+        friend class ResourceManager;
+
+    public:
+        typedef std::function<void (const std::string &uri, const SimulatorResourceModel &resModel)>
+        ResourceModelChangedCB;
+
+        SimulatorResourceServer();
+
+        /**
+         * This method is used to set the resource URI.
+         *
+         * @param uri - Resource URI
+         *
+         * @return SimulatorResult
+         */
+        SimulatorResult setURI(const std::string &uri);
+
+        /**
+         * This method is used to get the resource URI.
+         *
+         * @return Resource URI
+         */
+        std::string getURI() const;
+
+        /**
+         * This method is used to set the resource type.
+         *
+         * @param resourceType - Resource Type
+         *
+         * @return SimulatorResult
+         */
+        SimulatorResult setResourceType(const std::string &resourceType);
+
+        /**
+         * This method is used to get the resource URI.
+         *
+         * @return Resource Type
+         */
+        std::string getResourceType() const;
+
+        /**
+         * This method is used to set the interface type of the resource.
+         *
+         * @param interfaceType - Interface Type of the resource
+         *
+         * @return SimulatorResult
+         */
+        SimulatorResult setInterfaceType(const std::string &interfaceType);
+
+        /**
+         * This method is used to get the interface type of the resource.
+         *
+         * @return Interface type of the resource
+         */
+        std::string getInterfaceType() const;
+
+        /**
+         * This method is used to set the name of the resource.
+         *
+         * @param name - Name of the resource
+         *
+         * @return void
+         */
+        void setName(const std::string &name);
+
+        /**
+         * This method is used to get the name of the resource.
+         *
+         * @return Resource name
+         */
+        std::string getName() const;
+
+        /**
+         * This method is used to set whether resource can be observable or not.
+         *
+         * @param state - true for resource observable, otherwise false.
+         *
+         * @return SimulatorResult
+         */
+        SimulatorResult setObservable(bool state);
+
+        /**
+         * This method is used to get the observable state of resource.
+         *
+         * @return bool - true if resource is observable, otherwise false.
+         */
+        bool isObservable() const;
+
+        /**
+         * This method is used 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 id - Identifier for automation will be returned
+         *
+         * @return SimulatorResult
+         */
+        SimulatorResult startUpdateAutomation(AutomationType type,
+                                              updateCompleteCallback callback, int &id);
+
+        /**
+         * 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 id - Identifier for automation will be returned
+         *
+         * @return SimulatorResult
+         */
+        SimulatorResult startUpdateAutomation(const std::string &attrName, AutomationType type,
+                                              updateCompleteCallback callback, int &id);
+
+        /**
+         * This method is used to get the Ids of all ongoing resource update automation .
+         *
+         * @return Ids as vector of int
+         */
+        std::vector<int> getResourceAutomationIds();
+
+        /**
+         * This method is used to get the Ids of all ongoing attribute update automation .
+         *
+         * @return Ids as vector of int
+         */
+        std::vector<int> getAttributeAutomationIds();
+
+        /**
+        * This method is used to stop the automation.
+        *
+        * @param id - Identifier for automation
+        */
+        void stopUpdateAutomation(const int id);
+
+        /**
+         * This method is used to add a new attribute to the resource model.
+         *
+         * @param attrName - Name of the attribute
+         * @param attrValue - Value of the attribute
+         *
+         * @return void
+         */
+        template <typename T>
+        void addAttribute(const std::string &attrName, const T &attrValue)
+        {
+            m_resModel.addAttribute(attrName, attrValue);
+            notifyListOfObservers();
+        }
+
+        /**
+         * This method is used 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
+         *
+         * @return void
+         */
+        void setRange(const std::string &attrName, const int min, const int max);
+
+        /**
+         * This method is used to set the allowed values of an attribute.
+         *
+         * @param attrName - Name of the attribute
+         * @param values - Allowed values
+         *
+         * @return void
+         */
+        template <typename T>
+        void setAllowedValues(const std::string &attrName, const std::vector<T> &values)
+        {
+            m_resModel.setAllowedValues(attrName, values);
+        }
+
+        /**
+         * This method is used 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
+         *
+         * @return void
+         */
+        void setUpdateInterval(const std::string &attrName, int interval);
+
+        /**
+         * This method is used to update the value of an attribute.
+         *
+         * @param attrName - Name of the attribute
+         * @param value - Value of the attribute
+         *
+         * @return void
+         */
+        template <typename T>
+        void updateAttribute(const std::string &attrName, const T &value)
+        {
+            m_resModel.updateAttribute(attrName, value);
+            notifyListOfObservers();
+        }
+
+        /**
+         * This method is used 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
+         *
+         * @return void
+         */
+        void updateAttributeFromAllowedValues(const std::string &attrName, const int allowedValueIndex);
+
+        /**
+          * This method is used to remove an attribute from the resource model.
+          *
+          * @param attName - Name of the attribute to be removed
+          *
+          * @return void
+          */
+        void removeAttribute(const std::string &attName);
+
+        /**
+         * This method is used to get the object of SimulatorResourceModel.
+         * Attributes of the resource are accessed using this object.
+         *
+         * @return SimulatorResourceModel - Resource model of the resource
+         */
+        SimulatorResourceModel getModel() const;
+
+        /**
+         * This method is used to set the callback for receiving the notifications when the
+         * resource model changes.
+         *
+         * @param callback - Callback to be set for receiving the notifications.
+         *
+         * @return SimulatorResourceModel - Resource model of the resource
+         */
+        void setModelChangeCallback(ResourceModelChangedCB callback);
+
+    private:
+        SimulatorResult start();
+        SimulatorResult stop();
+        OC::OCRepresentation getOCRepresentation();
+        bool modifyResourceModel(OC::OCRepresentation &ocRep);
+        OCEntityHandlerResult entityHandler(std::shared_ptr<OC::OCResourceRequest> request);
+        void notifyListOfObservers ();
+
+        SimulatorResourceModel m_resModel;
+        std::string m_uri;
+        std::string m_resourceType;
+        std::string m_interfaceType;
+        std::string m_name;
+        ResourceModelChangedCB m_callback;
+        UpdateAutomationManager m_updateAutomationMgr;
+
+        OCResourceHandle m_resourceHandle;
+        OCResourceProperty m_property;
+        OC::ObservationIds m_interestedObservers;
+};
+
+typedef std::shared_ptr<SimulatorResourceServer> SimulatorResourceServerPtr;
+
+#endif