From 4b952ddd988b864d4774daaca9888c76fa4b141c Mon Sep 17 00:00:00 2001 From: coderhyme Date: Wed, 10 Jun 2015 18:52:14 +0900 Subject: [PATCH] Basic implementation of PrimitiveResource and ServerBuilder It include base facilities for Resource Manipulation and ServerBuilder. Change-Id: I28b774fd06691f2ed06462e248297e64b8f3b96b Signed-off-by: coderhyme Reviewed-on: https://gerrit.iotivity.org/gerrit/1232 Reviewed-by: Uze Choi Tested-by: Uze Choi --- service/basis/SConscript | 3 +- service/basis/common/SConscript | 30 + service/basis/common/primitiveResource/SConscript | 85 +++ .../primitiveResource/include/PresenceSubscriber.h | 79 +++ .../primitiveResource/include/PrimitiveException.h | 122 ++-- .../primitiveResource/include/PrimitiveResource.h | 150 ++--- .../primitiveResource/include/ResourceAttributes.h | 686 +++++++++++---------- .../ResourceAtrributesConverter.h} | 311 +++++----- .../primitiveResource/src/PresenceSubscriber.cpp | 107 ++++ .../primitiveResource/src/PrimitiveResource.cpp | 208 ++++--- .../primitiveResource/src/PrimtiveException.cpp | 39 ++ .../primitiveResource/src/ResourceAttributes.cpp | 586 +++++++++--------- .../{src => unittests}/ResourceAttributesTest.cpp | 14 +- service/basis/serverBuilder/SConscript | 62 ++ .../basis/serverBuilder/include/PrimitiveRequest.h | 18 +- .../serverBuilder/include/PrimitiveResponse.h | 68 +- .../include/PrimitiveServerResource.h | 179 ++++-- .../basis/serverBuilder/include/ServerBuilder.h | 102 --- .../include/internal/RequestHandler.h | 102 +++ .../basis/serverBuilder/src/PrimitiveResponse.cpp | 95 ++- .../serverBuilder/src/PrimitiveServerResource.cpp | 332 +++++----- service/basis/serverBuilder/src/ServerBuilder.cpp | 189 ------ 22 files changed, 2098 insertions(+), 1469 deletions(-) create mode 100644 service/basis/common/SConscript create mode 100644 service/basis/common/primitiveResource/SConscript create mode 100644 service/basis/common/primitiveResource/include/PresenceSubscriber.h rename service/basis/common/primitiveResource/include/{InternalUtil.h => internal/ResourceAtrributesConverter.h} (94%) mode change 100755 => 100644 create mode 100644 service/basis/common/primitiveResource/src/PresenceSubscriber.cpp create mode 100644 service/basis/common/primitiveResource/src/PrimtiveException.cpp rename service/basis/common/primitiveResource/{src => unittests}/ResourceAttributesTest.cpp (97%) mode change 100755 => 100644 create mode 100644 service/basis/serverBuilder/SConscript delete mode 100644 service/basis/serverBuilder/include/ServerBuilder.h create mode 100644 service/basis/serverBuilder/include/internal/RequestHandler.h delete mode 100644 service/basis/serverBuilder/src/ServerBuilder.cpp diff --git a/service/basis/SConscript b/service/basis/SConscript index 28f6e70..71185ab 100644 --- a/service/basis/SConscript +++ b/service/basis/SConscript @@ -25,10 +25,11 @@ import platform Import('env') +SConscript('common/SConscript') #SConscript('resourceBroker/SConscript') #SConscript('resourceCache/SConscript') #SConscript('resourceContainer/SConscript') -#SConscript('serverBuilder/SConscript') +SConscript('serverBuilder/SConscript') #SConscript('sdk/SConscript') diff --git a/service/basis/common/SConscript b/service/basis/common/SConscript new file mode 100644 index 0000000..70586b3 --- /dev/null +++ b/service/basis/common/SConscript @@ -0,0 +1,30 @@ +#****************************************************************** +# +# Copyright 2015 Samsung Electronics All Rights Reserved. +# +#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +## +# basis build script +## +import platform + +Import('env') + +SConscript('primitiveResource/SConscript') + + diff --git a/service/basis/common/primitiveResource/SConscript b/service/basis/common/primitiveResource/SConscript new file mode 100644 index 0000000..6068501 --- /dev/null +++ b/service/basis/common/primitiveResource/SConscript @@ -0,0 +1,85 @@ +#****************************************************************** +# +# Copyright 2015 Samsung Electronics All Rights Reserved. +# +#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +## +# things_manager project build script +## +import os +Import('env') + +# Add third party libraries +lib_env = env.Clone() +SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', exports = 'lib_env') + +src_dir = lib_env.get('SRC_DIR') + +service_common_env = lib_env.Clone() +target_os = env.get('TARGET_OS') + +###################################################################### +# Build flags +###################################################################### +service_common_env.AppendUnique(CPPPATH = [env.get('SRC_DIR')+'/extlibs', 'include', 'src']) + +if target_os not in ['windows', 'winrt']: + service_common_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall']) + if target_os != 'android': + service_common_env.AppendUnique(CXXFLAGS = ['-pthread']) + +if target_os == 'android': + service_common_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions']) + service_common_env.PrependUnique(LIBS = ['gnustl_shared', 'compatibility', 'log']) + +service_common_env.AppendUnique(LIBS = ['dl']) + +###################################################################### +# Source files and Targets +###################################################################### +service_common_src = env.Glob('src/*.cpp') +service_common_static = service_common_env.StaticLibrary('ServiceCommon', service_common_src) +service_common_shared = service_common_env.SharedLibrary('ServiceCommon', service_common_src) + +service_common_env.InstallTarget([service_common_static,service_common_shared], 'libServiceCommon') + +###################################################################### +# Build Test +###################################################################### +service_common_test_env = service_common_env.Clone(); +service_common_test_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')]) + +gtest = File(src_dir + '/extlibs/gtest/gtest-1.7.0/lib/.libs/libgtest.a') +gtest_main = File(src_dir + '/extlibs/gtest/gtest-1.7.0/lib/.libs/libgtest_main.a') + +service_common_test_env.PrependUnique(LIBS = [ + 'oc', + 'octbstack', + 'oc_logger', + 'connectivity_abstraction', + 'coap', + 'libServiceCommon', + gtest, + gtest_main + ]) + +service_common_test_src = env.Glob('unittests/*.cpp') + +service_common_test = service_common_test_env.Program('service_common_test', service_common_test_src) +Alias("service_common_test", service_common_test) +env.AppendTarget('service_common_test') \ No newline at end of file diff --git a/service/basis/common/primitiveResource/include/PresenceSubscriber.h b/service/basis/common/primitiveResource/include/PresenceSubscriber.h new file mode 100644 index 0000000..93ba659 --- /dev/null +++ b/service/basis/common/primitiveResource/include/PresenceSubscriber.h @@ -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. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef __PRESENCESUBSCRIBER_H +#define __PRESENCESUBSCRIBER_H + +#include +#include + +#include + +typedef std::function< void(OCStackResult, const unsigned int, const std::string&) > SubscribeCallback; + +class PresenceSubscriber +{ +public: + PresenceSubscriber(); + + PresenceSubscriber(PresenceSubscriber&&) = default; + + /** + * @throw PlatformException + */ + PresenceSubscriber(const std::string& host, OCConnectivityType connectivityType, + SubscribeCallback presenceHandler); + + /** + * @throw PlatformException + */ + PresenceSubscriber(const std::string& host, const std::string& resourceType, + OCConnectivityType connectivityType, SubscribeCallback presenceHandler); + + ~PresenceSubscriber(); + + PresenceSubscriber& operator=(PresenceSubscriber&&) = default; + + /** + * @throw PlatformException + */ + void unsubscribe(); + + bool isSubscribing() const; + +private: + OCDoHandle m_handle; +}; + +/** + * @throw PlatformException + */ +void subscribePresence(OCDoHandle& handle, const std::string& host, + OCConnectivityType connectivityType, SubscribeCallback presenceHandler); + +/** + * @throw PlatformException + */ +void subscribePresence(OCDoHandle& handle, const std::string& host, const std::string& resourceType, + OCConnectivityType connectivityType, SubscribeCallback presenceHandler); + +void unsubscribePresence(OCDoHandle handle); + +#endif // __PRESENCESUBSCRIBER_H diff --git a/service/basis/common/primitiveResource/include/PrimitiveException.h b/service/basis/common/primitiveResource/include/PrimitiveException.h index f230713..1440ca4 100755 --- a/service/basis/common/primitiveResource/include/PrimitiveException.h +++ b/service/basis/common/primitiveResource/include/PrimitiveException.h @@ -1,48 +1,74 @@ -//****************************************************************** -// -// Copyright 2015 Samsung Electronics All Rights Reserved. -// -//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -#ifndef __PRIMITIVEEXCEPTION_H -#define __PRIMITIVEEXCEPTION_H - -class PrimitiveException: public std::exception -{ -public: - PrimitiveException() {} - PrimitiveException(const std::string& what) {} -}; - -class BadGetException: public PrimitiveException -{ -public: - BadGetException(const std::string& what) - { - - } -}; - -class InvalidKeyException: public PrimitiveException -{ -public: - InvalidKeyException(const std::string& what) - { - - } -}; - -#endif //__PRIMITIVEEXCEPTION_H +//****************************************************************** +// +// Copyright 2015 Samsung Electronics All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef __PRIMITIVEEXCEPTION_H +#define __PRIMITIVEEXCEPTION_H + +#include + +#include + +class PrimitiveException: public std::exception +{ +public: + PrimitiveException() {} + PrimitiveException(const std::string& what) : m_what{ what } {} + + const char* what() const noexcept override + { + return m_what.c_str(); + } + +private: + std::string m_what; +}; + +class PlatformException: public PrimitiveException +{ +public: + PlatformException(OCStackResult reason); + + OCStackResult getReasonCode() const; + std::string getReason() const; + +private: + OCStackResult m_reason; +}; + + +class BadGetException: public PrimitiveException +{ +public: + BadGetException(const std::string& what) + { + + } +}; + +class InvalidKeyException: public PrimitiveException +{ +public: + InvalidKeyException(const std::string& what) + { + + } +}; + +#endif //__PRIMITIVEEXCEPTION_H diff --git a/service/basis/common/primitiveResource/include/PrimitiveResource.h b/service/basis/common/primitiveResource/include/PrimitiveResource.h index 0d33e7c..f8453f1 100755 --- a/service/basis/common/primitiveResource/include/PrimitiveResource.h +++ b/service/basis/common/primitiveResource/include/PrimitiveResource.h @@ -1,72 +1,78 @@ -//****************************************************************** -// -// Copyright 2015 Samsung Electronics All Rights Reserved. -// -//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -#ifndef __PRIMITIVERESOURCE_H -#define __PRIMITIVERESOURCE_H - -#include -#include -#include - -#include - -using HeaderOption = OC::HeaderOption::OCHeaderOption; -using HeaderOptions = std::vector; - -class ResourceAttributes; -class ResponseStatement; - -class PrimitiveResource { -public: - using Ptr = std::shared_ptr; - - using GetCallback = std::function; - - using SetCallback = std::function; - - using ObserveCallback = std::function; - -private: - using BaseResource = OC::OCResource; - using BaseResourcePtr = std::shared_ptr; - -public: - static PrimitiveResource::Ptr create(const BaseResourcePtr&); - - void requestGet(GetCallback); - void requestSet(const ResourceAttributes&, SetCallback); - void requestObserve(ObserveCallback); - void cancelObserve(); - -// @brief Properties getters. - std::string getUri() const; - std::string getHost() const; - std::vector getTypes() const; - std::vector getInterfaces() const; - - bool isObservable() const; - -private: - PrimitiveResource(const BaseResourcePtr&); - -private: - BaseResourcePtr m_ocResource; -}; - -#endif // __PRIMITIVERESOURCE_H +//****************************************************************** +// +// Copyright 2015 Samsung Electronics All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef __PRIMITIVERESOURCE_H +#define __PRIMITIVERESOURCE_H + +#include +#include +#include + +#include + +using HeaderOption = OC::HeaderOption::OCHeaderOption; +using HeaderOptions = std::vector; + +class ResourceAttributes; +class ResponseStatement; + +class PrimitiveResource +{ +public: + using Ptr = std::shared_ptr; + + using GetCallback = std::function; + + using SetCallback = std::function; + + using ObserveCallback = std::function; + +private: + using BaseResource = OC::OCResource; + using BaseResourcePtr = BaseResource::Ptr; + +public: + static PrimitiveResource::Ptr create(const BaseResourcePtr&); + + void requestGet(GetCallback); + void requestSet(const ResourceAttributes&, SetCallback); + void requestObserve(ObserveCallback); + void cancelObserve(); + + std::string getUri() const; + std::string getHost() const; + std::vector< std::string > getTypes() const; + std::vector< std::string > getInterfaces() const; + + bool isObservable() const; + +private: + PrimitiveResource(const BaseResourcePtr&); + +private: + BaseResourcePtr m_ocResource; +}; + +using FindCallback = std::function)>; + +void discoverResource(const std::string& host, const std::string& resourceURI, + OCConnectivityType connectivityType, FindCallback resourceHandler); + +#endif // __PRIMITIVERESOURCE_H diff --git a/service/basis/common/primitiveResource/include/ResourceAttributes.h b/service/basis/common/primitiveResource/include/ResourceAttributes.h index f12a4ba..6a522e0 100755 --- a/service/basis/common/primitiveResource/include/ResourceAttributes.h +++ b/service/basis/common/primitiveResource/include/ResourceAttributes.h @@ -1,315 +1,371 @@ -//****************************************************************** -// -// Copyright 2015 Samsung Electronics All Rights Reserved. -// -//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT 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 __RESOURCEATTRIBUTES_H -#define __RESOURCEATTRIBUTES_H - -#include -#include - -// To avoid conflict using different boost::variant configuration with OC. -// It causes compile errors. -#include - -#include -#include -#include - -#include "PrimitiveException.h" - -class ResourceAttributes -{ -private: - template< typename T > struct is_supported_type_helper; - - using ValueVariant = boost::variant< - std::nullptr_t, - int, - double, - bool, - std::string, - ResourceAttributes - >; - - template < typename T > - using enable_if_supported = typename std::enable_if< - is_supported_type_helper< T >::type::value >::type; - - template < typename VISITOR > - class KeyValueVisitorHelper : public boost::static_visitor<> { - public: - KeyValueVisitorHelper(VISITOR& visitor) : - m_visitor(visitor) - { - } - - template < typename T > - void operator()(const std::string& key, const T& value) const - { - m_visitor(key, value); - } - - private: - VISITOR& m_visitor; - }; - -public: - template < typename T > - using is_supported_type = typename is_supported_type_helper< T >::type; - - class Value - { - public: - Value(); - Value(const Value&); - Value(Value&&); - - template< typename T, typename = enable_if_supported< T > > - Value(T&& value) : - m_data { new ValueVariant{ std::forward(value) } } { - } - - template< typename T, typename = enable_if_supported< T > > - Value& operator=(T&& rhs) - { - *m_data = std::forward< T >(rhs); - return *this; - } - - Value& operator=(const char*); - Value& operator=(std::nullptr_t); - - template< typename T, typename = enable_if_supported< T > > - bool operator==(const T& rhs) const - { - try - { - return get< T >() == rhs; - } - catch (const BadGetException&) - { - return false; - } - } - - bool operator==(const char*) const; - - bool operator==(std::nullptr_t) const; - - template< typename T > - typename std::add_lvalue_reference< const T >::type get() const - { - return checkedGet< T >(); - } - - template< typename T > - typename std::add_lvalue_reference< T >::type get() - { - return checkedGet< T >(); - } - - private: - template< typename T, typename = enable_if_supported< T > > - typename std::add_lvalue_reference< T >::type checkedGet() const - { - try - { - return boost::get< T >(*m_data); - } - catch (const boost::bad_get&) - { - throw BadGetException{ "" }; - } - } - - public: - boost::scoped_ptr< ValueVariant > m_data; - }; - - class KeyValuePair; - class iterator; - class const_iterator; - -public: - ResourceAttributes() = default; - ResourceAttributes(const ResourceAttributes&) = default; - ResourceAttributes(ResourceAttributes&&) = default; - - ResourceAttributes& operator=(const ResourceAttributes&) = default; - ResourceAttributes& operator=(ResourceAttributes&&) = default; - - iterator begin(); - iterator end(); - - const_iterator begin() const; - const_iterator end() const; - - const_iterator cbegin() const; - const_iterator cend() const; - - Value& operator[](const std::string&); - - Value& at(const std::string&); - const Value& at(const std::string&) const; - - bool erase(const std::string&); - - bool empty() const; - size_t size() const; - -private: - template < typename VISITOR > - void visit(VISITOR& visitor) const { - KeyValueVisitorHelper helper { visitor }; - - for (const auto& i : m_keyValues) - { - boost::variant key { i.first }; - boost::apply_visitor(helper, key, *i.second.m_data); - } - } - -private: - std::unordered_map< std::string, Value > m_keyValues; - - friend class ResourceAttributesConverter; -}; - -template< typename T, typename = typename std::enable_if< - ResourceAttributes::is_supported_type< T >::value >::type > -bool operator==(const T& lhs, const ResourceAttributes::Value& rhs) -{ - return rhs == lhs; -} - -template< typename T > struct ResourceAttributes::is_supported_type_helper -{ - using type = boost::mpl::contains::type>; -}; - -class ResourceAttributes::KeyValuePair -{ -private: - class KeyVisitor : public boost::static_visitor { - public: - result_type operator()(iterator*) const; - result_type operator()(const_iterator*) const; - }; - - class ValueVisitor : public boost::static_visitor { - public: - result_type operator()(iterator*); - result_type operator()(const_iterator*); - }; - - class ConstValueVisitor : public boost::static_visitor { - public: - result_type operator()(iterator*) const; - result_type operator()(const_iterator*) const; - }; - -public: - const std::string& key() const; - const ResourceAttributes::Value& value() const; - ResourceAttributes::Value& value(); - -private: - KeyValuePair(const KeyValuePair&) = default; - KeyValuePair(boost::variant&&); - - KeyValuePair& operator=(const KeyValuePair&) = default; - -private: - boost::variant m_iterRef; - - KeyVisitor m_keyVisitor; - ValueVisitor m_valueVisitor; - ConstValueVisitor m_constValueVisitor; - - friend class iterator; - friend class const_iterator; -}; - -class ResourceAttributes::iterator: public std::iterator< std::forward_iterator_tag, - ResourceAttributes::KeyValuePair > -{ -private: - using base_iterator = std::unordered_map< std::string, Value >::iterator; - -public: - iterator(); - iterator(const iterator&) = default; - - iterator& operator=(const iterator&) = default; - - reference operator*(); - pointer operator->(); - - iterator& operator++(); - iterator operator++(int); - - bool operator==(const iterator&) const; - bool operator!=(const iterator&) const; - -private: - explicit iterator(ResourceAttributes&); - explicit iterator(base_iterator&&); - -private: - base_iterator m_cur; - ResourceAttributes::KeyValuePair m_keyValuePair; - - friend class ResourceAttributes; -}; - -class ResourceAttributes::const_iterator: public std::iterator< std::forward_iterator_tag, - const ResourceAttributes::KeyValuePair > -{ -private: - using base_iterator = std::unordered_map< std::string, Value >::const_iterator; - -public: - const_iterator(); - const_iterator(const const_iterator&) = default; - const_iterator(const ResourceAttributes::iterator&); - - const_iterator& operator=(const const_iterator&) = default; - const_iterator& operator=(const ResourceAttributes::iterator&); - - reference operator*() const; - pointer operator->() const; - - const_iterator& operator++(); - const_iterator operator++(int); - - bool operator==(const const_iterator&) const; - bool operator!=(const const_iterator&) const; - -private: - explicit const_iterator(const ResourceAttributes&); - explicit const_iterator(base_iterator&&); - -private: - base_iterator m_cur; - ResourceAttributes::KeyValuePair m_keyValuePair; - - friend class ResourceAttributes; -}; - -#endif // __RESOURCEATTRIBUTES_H +//****************************************************************** +// +// Copyright 2015 Samsung Electronics All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef __RESOURCEATTRIBUTES_H +#define __RESOURCEATTRIBUTES_H + +// To avoid conflict using different boost::variant configuration with OC. +// It causes compile errors. +#include + +#include +#include + +#include +#include +#include +#include +#include +#include + +#include + +class ResourceAttributes +{ +private: + template< typename T > struct is_supported_type_helper; + + using ValueVariant = boost::variant< + std::nullptr_t, + int, + double, + bool, + std::string, + ResourceAttributes + >; + + template< typename T > + using mpl_begin = typename boost::mpl::begin::type; + + template< typename T > + using enable_if_supported = typename std::enable_if< + is_supported_type_helper< T >::type::value >::type; + + template< typename T > + using disable_if_unsupported = typename std::enable_if< + !is_supported_type_helper< T >::type::value >::type; + + template< typename VISITOR > + class KeyValueVisitorHelper: public boost::static_visitor< > + { + public: + KeyValueVisitorHelper(VISITOR& visitor) : + m_visitor( visitor ) + { + } + + template< typename T > + void operator()(const std::string& key, const T& value) const + { + m_visitor(key, value); + } + + private: + VISITOR& m_visitor; + }; + +public: + template< typename T > + using is_supported_type = typename is_supported_type_helper< T >::type; + + class Value + { + public: + Value(); + Value(const Value&); + Value(Value&&); + + template< typename T, typename = enable_if_supported< T > > + Value(T&& value) : + m_data{ new ValueVariant{ std::forward< T >(value) } } + { + } + + Value& operator=(const Value&); + Value& operator=(Value&&) = default; + + template< typename T, typename = enable_if_supported< T > > + Value& operator=(T&& rhs) + { + *m_data = std::forward< T >(rhs); + return *this; + } + + Value& operator=(const char*); + Value& operator=(std::nullptr_t); + + template< typename T > + typename std::add_lvalue_reference< const T >::type get() const + { + return checkedGet< T >(); + } + + template< typename T > + typename std::add_lvalue_reference< T >::type get() + { + return checkedGet< T >(); + } + + bool isTypeEqualWith(const Value& rhs) const + { + return m_data->which() == rhs.m_data->which(); + } + + template< typename T, enable_if_supported< T >* = nullptr > + bool isTypeOf() const + { + using iter = boost::mpl::find< ValueVariant::types, int >::type; + + return m_data->which() + == boost::mpl::distance< mpl_begin< ValueVariant::types >, iter >::value; + } + + template< typename T, disable_if_unsupported< T >* = nullptr > + bool isTypeOf() const + { + return false; + } + + friend bool operator==(const Value&, const Value&); + + template< typename T > + friend bool operator==(const Value&, const T&); + + bool operator==(const char*) const; + + private: + template< typename T, typename = enable_if_supported< T > > + typename std::add_lvalue_reference< T >::type checkedGet() const + { + try + { + return boost::get< T >(*m_data); + } + catch (const boost::bad_get&) + { + throw BadGetException{ "" }; + } + } + + template< typename T, typename U > + bool equals(const U& rhs) const + { + try + { + return get< T >() == rhs; + } + catch (const BadGetException&) + { + return false; + } + } + + public: + boost::scoped_ptr< ValueVariant > m_data; + }; + + class KeyValuePair; + class iterator; + class const_iterator; + +public: + ResourceAttributes() = default; + ResourceAttributes(const ResourceAttributes&) = default; + ResourceAttributes(ResourceAttributes&&) = default; + + ResourceAttributes& operator=(const ResourceAttributes&) = default; + ResourceAttributes& operator=(ResourceAttributes&&) = default; + + iterator begin(); + iterator end(); + + const_iterator begin() const; + const_iterator end() const; + + const_iterator cbegin() const; + const_iterator cend() const; + + Value& operator[](const std::string&); + + Value& at(const std::string&); + const Value& at(const std::string&) const; + + bool erase(const std::string&); + + bool contains(const std::string&) const; + bool empty() const; + size_t size() const; + + friend bool operator==(const ResourceAttributes&, const ResourceAttributes&); + +private: + template< typename VISITOR > + void visit(VISITOR& visitor) const + { + KeyValueVisitorHelper< VISITOR > helper{ visitor }; + + for (const auto& i : m_keyValues) + { + boost::variant< const std::string& > key{ i.first }; + boost::apply_visitor(helper, key, *i.second.m_data); + } + } + +private: + std::unordered_map< std::string, Value > m_keyValues; + + friend class ResourceAttributesConverter; +}; + +template< typename T > struct ResourceAttributes::is_supported_type_helper +{ + using type = boost::mpl::contains::type>; +}; + +template< typename T > +bool operator==(const ResourceAttributes::Value& lhs, const T& rhs) +{ + using TypeChecker = typename std::enable_if< + ResourceAttributes::is_supported_type< T >::value >::type; + + return lhs.equals< T >(rhs); +} + +template< typename T > +bool operator==(const T& lhs, const ResourceAttributes::Value& rhs) +{ + return rhs == lhs; +} + +bool operator==(const char* lhs, const ResourceAttributes::Value& rhs); + +class ResourceAttributes::KeyValuePair +{ +private: + class KeyVisitor: public boost::static_visitor< const std::string& > + { + public: + result_type operator()(iterator*) const; + result_type operator()(const_iterator*) const; + }; + + class ValueVisitor: public boost::static_visitor< Value& > + { + public: + result_type operator()(iterator*); + result_type operator()(const_iterator*); + }; + + class ConstValueVisitor: public boost::static_visitor< const Value& > + { + public: + result_type operator()(iterator*) const; + result_type operator()(const_iterator*) const; + }; + +public: + const std::string& key() const; + const ResourceAttributes::Value& value() const; + ResourceAttributes::Value& value(); + +private: + KeyValuePair(const KeyValuePair&) = default; + KeyValuePair(boost::variant< iterator*, const_iterator* >&&); + + KeyValuePair& operator=(const KeyValuePair&) = default; + +private: + boost::variant< iterator*, const_iterator* > m_iterRef; + + KeyVisitor m_keyVisitor; + ValueVisitor m_valueVisitor; + ConstValueVisitor m_constValueVisitor; + + friend class iterator; + friend class const_iterator; +}; + +class ResourceAttributes::iterator: public std::iterator< std::forward_iterator_tag, + ResourceAttributes::KeyValuePair > +{ +private: + using base_iterator = std::unordered_map< std::string, Value >::iterator; + +public: + iterator(); + iterator(const iterator&) = default; + + iterator& operator=(const iterator&) = default; + + reference operator*(); + pointer operator->(); + + iterator& operator++(); + iterator operator++(int); + + bool operator==(const iterator&) const; + bool operator!=(const iterator&) const; + +private: + explicit iterator(ResourceAttributes&); + explicit iterator(base_iterator&&); + +private: + base_iterator m_cur; + ResourceAttributes::KeyValuePair m_keyValuePair; + + friend class ResourceAttributes; +}; + +class ResourceAttributes::const_iterator: public std::iterator< std::forward_iterator_tag, + const ResourceAttributes::KeyValuePair > +{ +private: + using base_iterator = std::unordered_map< std::string, Value >::const_iterator; + +public: + const_iterator(); + const_iterator(const const_iterator&) = default; + const_iterator(const ResourceAttributes::iterator&); + + const_iterator& operator=(const const_iterator&) = default; + const_iterator& operator=(const ResourceAttributes::iterator&); + + reference operator*() const; + pointer operator->() const; + + const_iterator& operator++(); + const_iterator operator++(int); + + bool operator==(const const_iterator&) const; + bool operator!=(const const_iterator&) const; + +private: + explicit const_iterator(const ResourceAttributes&); + explicit const_iterator(base_iterator&&); + +private: + base_iterator m_cur; + ResourceAttributes::KeyValuePair m_keyValuePair; + + friend class ResourceAttributes; +}; + +#endif // __RESOURCEATTRIBUTES_H diff --git a/service/basis/common/primitiveResource/include/InternalUtil.h b/service/basis/common/primitiveResource/include/internal/ResourceAtrributesConverter.h old mode 100755 new mode 100644 similarity index 94% rename from service/basis/common/primitiveResource/include/InternalUtil.h rename to service/basis/common/primitiveResource/include/internal/ResourceAtrributesConverter.h index d7d407f..92d8547 --- a/service/basis/common/primitiveResource/include/InternalUtil.h +++ b/service/basis/common/primitiveResource/include/internal/ResourceAtrributesConverter.h @@ -1,155 +1,156 @@ -//****************************************************************** -// -// Copyright 2015 Samsung Electronics All Rights Reserved. -// -//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -#ifndef __INTERNALUTIL_H -#define __INTERNALUTIL_H - -#include "ResourceAttributes.h" - -#include - -class ResourceAttributesConverter -{ -private: - ResourceAttributesConverter() = delete; - - template< typename T > - using SupportedType = typename std::enable_if< - ResourceAttributes::is_supported_type< T >::type::value, T >::type; - - template< typename T > - using UnsupportedType = typename std::enable_if< - !ResourceAttributes::is_supported_type< T >::type::value, T >::type; - - class ResourceAttributesBuilder - { - public: - ResourceAttributesBuilder() = default; - - void insertItemTo(const OC::OCRepresentation::AttributeItem& item) - { - switch (item.type()) - { - case OC::AttributeType::Null: - return putValue(item.attrname(), nullptr); - - case OC::AttributeType::Integer: - return putValue(item.attrname(), item.getValue< int >()); - - case OC::AttributeType::Double: - return putValue(item.attrname(), item.getValue< double >()); - - case OC::AttributeType::Boolean: - return putValue(item.attrname(), item.getValue< bool >()); - - case OC::AttributeType::String: - return putValue(item.attrname(), item.getValue< std::string >()); - - case OC::AttributeType::OCRepresentation: - return putValue(item.attrname(), - ResourceAttributesConverter::fromOCRepresentation( - item.getValue< OC::OCRepresentation >())); - - case OC::AttributeType::Vector: - // ResourceAttributes doesn't support vector yet! - return; - } - } - - ResourceAttributes&& extract() - { - return std::move(m_target); - } - - private: - template< typename T > - void putValue(const std::string key, T&& value) - { - putValue< T >(key, std::forward< T >(value)); - } - - template< typename T > - void putValue(const std::string key, SupportedType< T > && value) - { - m_target[key] = std::forward< T >(value); - } - - template< typename T > - void putValue(const std::string key, UnsupportedType< T > && value) - { - } - - private: - ResourceAttributes m_target; - }; - - class AttrVisitor - { - public: - AttrVisitor() = default; - - template< typename T > - void operator()(const std::string& key, const T& value) - { - m_target[key] = value; - } - - void operator()(const std::string& key, const std::nullptr_t&) - { - m_target.setNULL(key); - } - - void operator()(const std::string& key, const ResourceAttributes& value) - { - m_target[key] = ResourceAttributesConverter::toOCRepresentation(value); - } - - OC::OCRepresentation&& extract() - { - return std::move(m_target); - } - - private: - OC::OCRepresentation m_target; - }; - -public: - static ResourceAttributes fromOCRepresentation(const OC::OCRepresentation& ocRepresentation) - { - ResourceAttributesBuilder builder; - - for (const auto& item : ocRepresentation) - { - builder.insertItemTo(item); - } - - return builder.extract(); - } - - static OC::OCRepresentation toOCRepresentation(const ResourceAttributes& resourceAttributes) - { - AttrVisitor visitor; - - resourceAttributes.visit(visitor); - - return visitor.extract(); - } -}; - -#endif // __INTERNALUTIL_H +//****************************************************************** +// +// Copyright 2015 Samsung Electronics All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef __RESOURCEATTRIBUTESCONVERTER_H +#define __RESOURCEATTRIBUTESCONVERTER_H + +#include + +#include + +class ResourceAttributesConverter +{ +private: + ResourceAttributesConverter() = delete; + + template< typename T > + using SupportedType = typename std::enable_if< + ResourceAttributes::is_supported_type< T >::type::value, T >::type; + + template< typename T > + using UnsupportedType = typename std::enable_if< + !ResourceAttributes::is_supported_type< T >::type::value, T >::type; + + class ResourceAttributesBuilder + { + public: + ResourceAttributesBuilder() = default; + + void insertItemTo(const OC::OCRepresentation::AttributeItem& item) + { + switch (item.type()) + { + case OC::AttributeType::Null: + return putValue(item.attrname(), nullptr); + + case OC::AttributeType::Integer: + return putValue(item.attrname(), item.getValue< int >()); + + case OC::AttributeType::Double: + return putValue(item.attrname(), item.getValue< double >()); + + case OC::AttributeType::Boolean: + return putValue(item.attrname(), item.getValue< bool >()); + + case OC::AttributeType::String: + return putValue(item.attrname(), item.getValue< std::string >()); + + case OC::AttributeType::OCRepresentation: + return putValue(item.attrname(), + ResourceAttributesConverter::fromOCRepresentation( + item.getValue< OC::OCRepresentation >())); + + case OC::AttributeType::Vector: + // ResourceAttributes doesn't support vector yet! + return; + } + } + + ResourceAttributes&& extract() + { + return std::move(m_target); + } + + private: + template< typename T > + void putValue(const std::string key, T&& value) + { + putValue< T >(key, std::forward< T >(value)); + } + + template< typename T > + void putValue(const std::string key, SupportedType< T > && value) + { + m_target[key] = std::forward< T >(value); + } + + template< typename T > + void putValue(const std::string key, UnsupportedType< T > && value) + { + } + + private: + ResourceAttributes m_target; + }; + + class AttrVisitor + { + public: + AttrVisitor() = default; + + template< typename T > + void operator()(const std::string& key, const T& value) + { + m_target[key] = value; + } + + void operator()(const std::string& key, const std::nullptr_t&) + { + m_target.setNULL(key); + } + + void operator()(const std::string& key, const ResourceAttributes& value) + { + m_target[key] = ResourceAttributesConverter::toOCRepresentation(value); + } + + OC::OCRepresentation&& extract() + { + return std::move(m_target); + } + + private: + OC::OCRepresentation m_target; + }; + +public: + static ResourceAttributes fromOCRepresentation(const OC::OCRepresentation& ocRepresentation) + { + ResourceAttributesBuilder builder; + + for (const auto& item : ocRepresentation) + { + builder.insertItemTo(item); + } + + return builder.extract(); + } + + static OC::OCRepresentation toOCRepresentation(const ResourceAttributes& resourceAttributes) + { + AttrVisitor visitor; + + resourceAttributes.visit(visitor); + + return visitor.extract(); + } +}; + +#endif // __RESOURCEATTRIBUTESCONVERTER_H diff --git a/service/basis/common/primitiveResource/src/PresenceSubscriber.cpp b/service/basis/common/primitiveResource/src/PresenceSubscriber.cpp new file mode 100644 index 0000000..19eb996 --- /dev/null +++ b/service/basis/common/primitiveResource/src/PresenceSubscriber.cpp @@ -0,0 +1,107 @@ +//****************************************************************** +// +// Copyright 2015 Samsung Electronics All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include + +#include + +#include + +void subscribePresence(OCDoHandle& handle, const std::string& host, + OCConnectivityType connectivityType, SubscribeCallback presenceHandler) +{ + OCStackResult result = OC::OCPlatform::subscribePresence(handle, host, connectivityType, presenceHandler); + + if (result != OC_STACK_OK) + { + throw PlatformException(result); + } +} + +void subscribePresence(OCDoHandle& handle, const std::string& host, + const std::string& resourceType, OCConnectivityType connectivityType, + SubscribeCallback presenceHandler) +{ + OCStackResult result = OC::OCPlatform::subscribePresence(handle, host, resourceType, + connectivityType, presenceHandler); + + if (result != OC_STACK_OK) + { + throw PlatformException(result); + } +} + +void unsubscribePresence(OCDoHandle handle) +{ + OCStackResult result = OC::OCPlatform::unsubscribePresence(handle); + + if (result != OC_STACK_OK) + { + throw PlatformException(result); + } +} + + +PresenceSubscriber::PresenceSubscriber() : + m_handle{ nullptr } +{ +} + +PresenceSubscriber::PresenceSubscriber(const std::string& host, + OCConnectivityType connectivityType, SubscribeCallback presenceHandler) : + m_handle{ nullptr } +{ + subscribePresence(m_handle, host, connectivityType, presenceHandler); +} + +PresenceSubscriber::PresenceSubscriber(const std::string& host, const std::string& resourceType, + OCConnectivityType connectivityType, SubscribeCallback presenceHandler) : + m_handle{ nullptr } +{ + subscribePresence(m_handle, host, resourceType, connectivityType, presenceHandler); +} + +PresenceSubscriber::~PresenceSubscriber() +{ + if (m_handle) + { + try + { + unsubscribe(); + } + catch (...) + { + } + } +} + +void PresenceSubscriber::unsubscribe() +{ + if (m_handle == nullptr) return; + + unsubscribePresence(m_handle); + + m_handle = nullptr; +} + +bool PresenceSubscriber::isSubscribing() const +{ + return m_handle != nullptr; +} diff --git a/service/basis/common/primitiveResource/src/PrimitiveResource.cpp b/service/basis/common/primitiveResource/src/PrimitiveResource.cpp index 0df9cdd..448a5d7 100755 --- a/service/basis/common/primitiveResource/src/PrimitiveResource.cpp +++ b/service/basis/common/primitiveResource/src/PrimitiveResource.cpp @@ -1,93 +1,115 @@ -//****************************************************************** -// -// Copyright 2015 Samsung Electronics All Rights Reserved. -// -//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -#include "PrimitiveResource.h" -#include "ResourceAttributes.h" -#include "ResponseStatement.h" -#include "InternalUtil.h" - -using OC::QueryParamsMap; -using OC::OCRepresentation; -using OC::ObserveType; - -using std::bind; -using std::shared_ptr; -using std::vector; -using std::string; - -using namespace std::placeholders; - -namespace { - -ResponseStatement createResponseStatement( - const OCRepresentation& ocRepresentation) { - return ResponseStatement::create( - ResourceAttributesConverter::fromOCRepresentation(ocRepresentation)); -} - -} // unnamed namespace - -PrimitiveResource::PrimitiveResource(const BaseResourcePtr& ocResource) : - m_ocResource(ocResource) { -} - -PrimitiveResource::Ptr PrimitiveResource::create(const BaseResourcePtr& ptr) { - return std::shared_ptr < PrimitiveResource > (new PrimitiveResource(ptr)); -} - -void PrimitiveResource::requestGet(GetCallback callback) { - m_ocResource->get(QueryParamsMap(), - bind(callback, _1, bind(createResponseStatement, _2), _3)); -} - -void PrimitiveResource::requestSet(const ResourceAttributes& attrs, - SetCallback callback) { - m_ocResource->put(ResourceAttributesConverter::toOCRepresentation(attrs), - QueryParamsMap(), - bind(callback, _1, bind(createResponseStatement, _2), _3)); -} - -void PrimitiveResource::requestObserve(ObserveCallback callback) { - m_ocResource->observe(ObserveType::ObserveAll, QueryParamsMap(), - bind(callback, _1, bind(createResponseStatement, _2), _3, _4)); -} - -void PrimitiveResource::cancelObserve() { - m_ocResource->cancelObserve(); -} - -bool PrimitiveResource::isObservable() const { - return m_ocResource->isObservable(); -} - -string PrimitiveResource::getUri() const { - return m_ocResource->uri(); -} - -string PrimitiveResource::getHost() const { - return m_ocResource->host(); -} - -vector PrimitiveResource::getTypes() const { - return m_ocResource->getResourceTypes(); -} - -vector PrimitiveResource::getInterfaces() const { - return m_ocResource->getResourceInterfaces(); -} +//****************************************************************** +// +// Copyright 2015 Samsung Electronics All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include +#include +#include + +#include + +#include + +using OC::QueryParamsMap; +using OC::OCRepresentation; +using OC::ObserveType; + +using std::bind; +using std::shared_ptr; +using std::vector; +using std::string; + +using namespace std::placeholders; + +namespace +{ + + ResponseStatement createResponseStatement(const OCRepresentation& ocRepresentation) + { + return ResponseStatement::create( + ResourceAttributesConverter::fromOCRepresentation(ocRepresentation)); + } + +} // unnamed namespace + +PrimitiveResource::PrimitiveResource(const BaseResourcePtr& ocResource) : + m_ocResource{ ocResource } +{ +} + +PrimitiveResource::Ptr PrimitiveResource::create(const BaseResourcePtr& ptr) +{ + return std::shared_ptr< PrimitiveResource >(new PrimitiveResource{ ptr }); +} + +void PrimitiveResource::requestGet(GetCallback callback) +{ + m_ocResource->get(QueryParamsMap(), bind(callback, _1, bind(createResponseStatement, _2), _3)); +} + +void PrimitiveResource::requestSet(const ResourceAttributes& attrs, SetCallback callback) +{ + m_ocResource->put(ResourceAttributesConverter::toOCRepresentation(attrs), QueryParamsMap{}, + bind(callback, _1, bind(createResponseStatement, _2), _3)); +} + +void PrimitiveResource::requestObserve(ObserveCallback callback) +{ + m_ocResource->observe(ObserveType::ObserveAll, QueryParamsMap{}, + bind(callback, _1, bind(createResponseStatement, _2), _3, _4)); +} + +void PrimitiveResource::cancelObserve() +{ + m_ocResource->cancelObserve(); +} + +bool PrimitiveResource::isObservable() const +{ + return m_ocResource->isObservable(); +} + +string PrimitiveResource::getUri() const +{ + return m_ocResource->uri(); +} + +string PrimitiveResource::getHost() const +{ + return m_ocResource->host(); +} + +vector< string > PrimitiveResource::getTypes() const +{ + return m_ocResource->getResourceTypes(); +} + +vector< string > PrimitiveResource::getInterfaces() const +{ + return m_ocResource->getResourceInterfaces(); +} + + + +void discoverResource(const std::string& host, const std::string& resourceURI, + OCConnectivityType connectivityType, FindCallback resourceHandler) +{ + OC::OCPlatform::findResource(host, resourceURI, connectivityType, + std::bind(&PrimitiveResource::create, std::placeholders::_1)); +} diff --git a/service/basis/common/primitiveResource/src/PrimtiveException.cpp b/service/basis/common/primitiveResource/src/PrimtiveException.cpp new file mode 100644 index 0000000..535a5de --- /dev/null +++ b/service/basis/common/primitiveResource/src/PrimtiveException.cpp @@ -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. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include + +#include + +PlatformException::PlatformException(OCStackResult reason) : + PrimitiveException{ "Failed : " + OC::OCException::reason(reason) }, + m_reason { reason } +{ +} + +OCStackResult PlatformException::getReasonCode() const +{ + return m_reason; +} + +std::string PlatformException::getReason() const +{ + return OC::OCException::reason(m_reason); +} diff --git a/service/basis/common/primitiveResource/src/ResourceAttributes.cpp b/service/basis/common/primitiveResource/src/ResourceAttributes.cpp index 5a4659d..31c5952 100755 --- a/service/basis/common/primitiveResource/src/ResourceAttributes.cpp +++ b/service/basis/common/primitiveResource/src/ResourceAttributes.cpp @@ -1,279 +1,307 @@ -//****************************************************************** -// -// Copyright 2015 Samsung Electronics All Rights Reserved. -// -//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -#include "ResourceAttributes.h" -#include "InternalUtil.h" - - -ResourceAttributes::Value::Value() : - m_data{ new ValueVariant{} } -{ -} - -ResourceAttributes::Value::Value(const Value& from) : - m_data{ new ValueVariant{ *from.m_data } } -{ -} - -ResourceAttributes::Value::Value(Value&& from) : - m_data{ new ValueVariant{} } -{ - m_data->swap(*from.m_data); -} - -auto ResourceAttributes::Value::operator=(const char* rhs) -> Value& -{ - *m_data = std::string{ rhs }; - return *this; -} - -auto ResourceAttributes::Value::operator=(std::nullptr_t) -> Value& -{ - *m_data = nullptr; - return *this; -} - -bool ResourceAttributes::Value::operator==(const char* rhs) const -{ - return operator==< std::string >(std::string{ rhs }); -} - -bool ResourceAttributes::Value::operator==(std::nullptr_t) const -{ - return operator==< std::nullptr_t >(nullptr); -} - -auto ResourceAttributes::KeyValuePair::KeyVisitor::operator() (iterator* iter) const - -> result_type { - return iter->m_cur->first; -} - -auto ResourceAttributes::KeyValuePair::KeyVisitor::operator() (const_iterator* iter) const - -> result_type { - return iter->m_cur->first; -} - -auto ResourceAttributes::KeyValuePair::ValueVisitor::operator() (iterator* iter) - -> result_type { - return iter->m_cur->second; -} - -auto ResourceAttributes::KeyValuePair::ValueVisitor::operator() (const_iterator* iter) - -> result_type { - // should not reach here. - throw BadGetException(""); -} - -auto ResourceAttributes::KeyValuePair::ConstValueVisitor::operator() (iterator*iter) const - -> result_type { - return iter->m_cur->second; -} - -auto ResourceAttributes::KeyValuePair::ConstValueVisitor::operator() (const_iterator* iter) const - -> result_type { - return iter->m_cur->second; -} - -auto ResourceAttributes::KeyValuePair::key() const -> const std::string& -{ - return boost::apply_visitor(m_keyVisitor, m_iterRef); -} - -auto ResourceAttributes::KeyValuePair::value() const -> const Value& -{ - return boost::apply_visitor(m_constValueVisitor, m_iterRef); -} - -auto ResourceAttributes::KeyValuePair::value() -> Value& -{ - return boost::apply_visitor(m_valueVisitor, m_iterRef); -} - - -ResourceAttributes::KeyValuePair::KeyValuePair(boost::variant&& ref) : - m_iterRef{ ref } -{ -} - - -ResourceAttributes::iterator::iterator() : - iterator{ base_iterator{} } -{ -} - -ResourceAttributes::iterator::iterator(ResourceAttributes& attrs) : - iterator{ attrs.m_keyValues.begin() } -{ -} - -ResourceAttributes::iterator::iterator(base_iterator&& iter) : - m_cur{ std::move(iter) }, - m_keyValuePair{ this } -{ -} - -auto ResourceAttributes::iterator::operator*() -> KeyValuePair& -{ - return m_keyValuePair; -} - -auto ResourceAttributes::iterator::iterator::operator->() -> KeyValuePair* -{ - return &m_keyValuePair; -} - -auto ResourceAttributes::iterator::operator++() -> iterator& -{ - ++m_cur; - return *this; -} - -auto ResourceAttributes::iterator::operator++(int) -> iterator -{ - iterator iter(*this); - ++(*this); - return iter; -} - -bool ResourceAttributes::iterator::operator==(const iterator& rhs) const -{ - return m_cur == rhs.m_cur; -} - -bool ResourceAttributes::iterator::operator!=(const iterator& rhs) const -{ - return !(*this == rhs); -} - - -ResourceAttributes::const_iterator::const_iterator() : - const_iterator{ base_iterator{} } -{ -} - -ResourceAttributes::const_iterator::const_iterator(const ResourceAttributes& attrs) : - const_iterator{ attrs.m_keyValues.begin() } -{ -} - -ResourceAttributes::const_iterator::const_iterator(base_iterator&& iter) : - m_cur{ iter }, m_keyValuePair{ this } -{ -} - -ResourceAttributes::const_iterator::const_iterator(const ResourceAttributes::iterator& iter) : - m_cur{ iter.m_cur }, m_keyValuePair{ this } -{ -} - -auto ResourceAttributes::const_iterator::operator=(const ResourceAttributes::iterator& iter) -> const_iterator& { - m_cur = iter.m_cur; - return *this; -} - -auto ResourceAttributes::const_iterator::operator*() const -> reference -{ - return m_keyValuePair; -} -auto ResourceAttributes::const_iterator::operator->() const -> pointer -{ - return &m_keyValuePair; -} - -auto ResourceAttributes::const_iterator::operator++() -> const_iterator& -{ - ++m_cur; - return *this; -} - -auto ResourceAttributes::const_iterator::operator++(int) -> const_iterator -{ - const_iterator iter(*this); - ++(*this); - return iter; -} - -bool ResourceAttributes::const_iterator::operator==(const const_iterator& rhs) const -{ - return m_cur == rhs.m_cur; -} - -bool ResourceAttributes::const_iterator::operator!=(const const_iterator& rhs) const -{ - return !(*this == rhs); -} - -auto ResourceAttributes::begin() -> iterator -{ - return iterator{ *this }; -} - -auto ResourceAttributes::end() -> iterator -{ - return iterator{ m_keyValues.end() }; -} - - -auto ResourceAttributes::begin() const -> const_iterator -{ - return const_iterator{ m_keyValues.begin() }; -} - -auto ResourceAttributes::cbegin() const -> const_iterator -{ - return const_iterator{ m_keyValues.begin() }; -} - -auto ResourceAttributes::cend() const -> const_iterator -{ - return const_iterator{ m_keyValues.end() }; -} - -auto ResourceAttributes::operator[](const std::string & key) -> Value& -{ - return m_keyValues[key]; -} - -auto ResourceAttributes::at(const std::string & key) -> Value& -{ - try - { - return m_keyValues.at(key); - } - catch (const std::out_of_range&) - { - throw InvalidKeyException{ "" }; - } -} - -bool ResourceAttributes::erase(const std::string& key) -{ - return m_keyValues.erase(key) == 1U; -} - -bool ResourceAttributes::empty() const -{ - return m_keyValues.empty(); -} - -size_t ResourceAttributes::size() const -{ - return m_keyValues.size(); -} - +//****************************************************************** +// +// Copyright 2015 Samsung Electronics All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include + +#include + +bool operator==(const char* lhs, const ResourceAttributes::Value& rhs) +{ + return rhs == lhs; +} + +bool operator==(const ResourceAttributes::Value& lhs, const ResourceAttributes::Value& rhs) +{ + return *lhs.m_data == *rhs.m_data; +} + +bool operator==(const ResourceAttributes& lhs, const ResourceAttributes& rhs) +{ + return lhs.m_keyValues == rhs.m_keyValues; +} + +ResourceAttributes::Value::Value() : + m_data{ new ValueVariant{} } +{ +} + +ResourceAttributes::Value::Value(const Value& from) : + m_data{ new ValueVariant{ *from.m_data } } +{ +} + +ResourceAttributes::Value::Value(Value&& from) : + m_data{ new ValueVariant{} } +{ + m_data->swap(*from.m_data); +} + + +auto ResourceAttributes::Value::operator=(const Value& rhs) -> Value& +{ + *m_data = new ValueVariant{ *rhs.m_data }; + return *this; +} + +auto ResourceAttributes::Value::operator=(const char* rhs) -> Value& +{ + *m_data = std::string{ rhs }; + return *this; +} + +auto ResourceAttributes::Value::operator=(std::nullptr_t) -> Value& +{ + *m_data = nullptr; + return *this; +} + +bool ResourceAttributes::Value::operator==(const char* rhs) const +{ + return equals< std::string >(rhs); +} + +//bool ResourceAttributes::Value::operator==(std::nullptr_t) const +//{ +// return isTypeOf< std::nullptr_t >(); +//} + +auto ResourceAttributes::KeyValuePair::KeyVisitor::operator() (iterator* iter) const + -> result_type { + return iter->m_cur->first; +} + +auto ResourceAttributes::KeyValuePair::KeyVisitor::operator() (const_iterator* iter) const + -> result_type { + return iter->m_cur->first; +} + +auto ResourceAttributes::KeyValuePair::ValueVisitor::operator() (iterator* iter) + -> result_type { + return iter->m_cur->second; +} + +auto ResourceAttributes::KeyValuePair::ValueVisitor::operator() (const_iterator* iter) + -> result_type { + // should not reach here. + throw BadGetException(""); +} + +auto ResourceAttributes::KeyValuePair::ConstValueVisitor::operator() (iterator*iter) const + -> result_type { + return iter->m_cur->second; +} + +auto ResourceAttributes::KeyValuePair::ConstValueVisitor::operator() (const_iterator* iter) const + -> result_type { + return iter->m_cur->second; +} + +auto ResourceAttributes::KeyValuePair::key() const -> const std::string& +{ + return boost::apply_visitor(m_keyVisitor, m_iterRef); +} + +auto ResourceAttributes::KeyValuePair::value() const -> const Value& +{ + return boost::apply_visitor(m_constValueVisitor, m_iterRef); +} + +auto ResourceAttributes::KeyValuePair::value() -> Value& +{ + return boost::apply_visitor(m_valueVisitor, m_iterRef); +} + + +ResourceAttributes::KeyValuePair::KeyValuePair(boost::variant&& ref) : + m_iterRef{ ref } +{ +} + + +ResourceAttributes::iterator::iterator() : + iterator{ base_iterator{} } +{ +} + +ResourceAttributes::iterator::iterator(ResourceAttributes& attrs) : + iterator{ attrs.m_keyValues.begin() } +{ +} + +ResourceAttributes::iterator::iterator(base_iterator&& iter) : + m_cur{ std::move(iter) }, + m_keyValuePair{ this } +{ +} + +auto ResourceAttributes::iterator::operator*() -> KeyValuePair& +{ + return m_keyValuePair; +} + +auto ResourceAttributes::iterator::iterator::operator->() -> KeyValuePair* +{ + return &m_keyValuePair; +} + +auto ResourceAttributes::iterator::operator++() -> iterator& +{ + ++m_cur; + return *this; +} + +auto ResourceAttributes::iterator::operator++(int) -> iterator +{ + iterator iter(*this); + ++(*this); + return iter; +} + +bool ResourceAttributes::iterator::operator==(const iterator& rhs) const +{ + return m_cur == rhs.m_cur; +} + +bool ResourceAttributes::iterator::operator!=(const iterator& rhs) const +{ + return !(*this == rhs); +} + + +ResourceAttributes::const_iterator::const_iterator() : + const_iterator{ base_iterator{} } +{ +} + +ResourceAttributes::const_iterator::const_iterator(const ResourceAttributes& attrs) : + const_iterator{ attrs.m_keyValues.begin() } +{ +} + +ResourceAttributes::const_iterator::const_iterator(base_iterator&& iter) : + m_cur{ iter }, m_keyValuePair{ this } +{ +} + +ResourceAttributes::const_iterator::const_iterator(const ResourceAttributes::iterator& iter) : + m_cur{ iter.m_cur }, m_keyValuePair{ this } +{ +} + +auto ResourceAttributes::const_iterator::operator=(const ResourceAttributes::iterator& iter) -> const_iterator& { + m_cur = iter.m_cur; + return *this; +} + +auto ResourceAttributes::const_iterator::operator*() const -> reference +{ + return m_keyValuePair; +} +auto ResourceAttributes::const_iterator::operator->() const -> pointer +{ + return &m_keyValuePair; +} + +auto ResourceAttributes::const_iterator::operator++() -> const_iterator& +{ + ++m_cur; + return *this; +} + +auto ResourceAttributes::const_iterator::operator++(int) -> const_iterator +{ + const_iterator iter(*this); + ++(*this); + return iter; +} + +bool ResourceAttributes::const_iterator::operator==(const const_iterator& rhs) const +{ + return m_cur == rhs.m_cur; +} + +bool ResourceAttributes::const_iterator::operator!=(const const_iterator& rhs) const +{ + return !(*this == rhs); +} + +auto ResourceAttributes::begin() -> iterator +{ + return iterator{ *this }; +} + +auto ResourceAttributes::end() -> iterator +{ + return iterator{ m_keyValues.end() }; +} + + +auto ResourceAttributes::begin() const -> const_iterator +{ + return const_iterator{ m_keyValues.begin() }; +} + +auto ResourceAttributes::cbegin() const -> const_iterator +{ + return const_iterator{ m_keyValues.begin() }; +} + +auto ResourceAttributes::cend() const -> const_iterator +{ + return const_iterator{ m_keyValues.end() }; +} + +auto ResourceAttributes::operator[](const std::string& key) -> Value& +{ + return m_keyValues[key]; +} + +auto ResourceAttributes::at(const std::string& key) -> Value& +{ + try + { + return m_keyValues.at(key); + } + catch (const std::out_of_range&) + { + throw InvalidKeyException{ "" }; + } +} + +bool ResourceAttributes::erase(const std::string& key) +{ + return m_keyValues.erase(key) == 1U; +} + +bool ResourceAttributes::contains(const std::string& key) const +{ + return m_keyValues.find(key) != m_keyValues.end(); +} + +bool ResourceAttributes::empty() const +{ + return m_keyValues.empty(); +} + +size_t ResourceAttributes::size() const +{ + return m_keyValues.size(); +} + diff --git a/service/basis/common/primitiveResource/src/ResourceAttributesTest.cpp b/service/basis/common/primitiveResource/unittests/ResourceAttributesTest.cpp old mode 100755 new mode 100644 similarity index 97% rename from service/basis/common/primitiveResource/src/ResourceAttributesTest.cpp rename to service/basis/common/primitiveResource/unittests/ResourceAttributesTest.cpp index 9defd7e..93908bc --- a/service/basis/common/primitiveResource/src/ResourceAttributesTest.cpp +++ b/service/basis/common/primitiveResource/unittests/ResourceAttributesTest.cpp @@ -17,8 +17,9 @@ // limitations under the License. // //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + #include -#include +#include #include @@ -47,7 +48,7 @@ TEST_F(ResourceAttributesTest, InsertWithSquareBracket) TEST_F(ResourceAttributesTest, ValueThrowsIfTypeDoesNotMatch) { - resourceAttributes[KEY] = 1; + resourceAttributes[KEY] = 1; auto& valueRef = resourceAttributes[KEY]; ASSERT_THROW(valueRef.get< std::string >(), BadGetException); @@ -123,9 +124,12 @@ TEST_F(ResourceAttributesTest, CanHaveNestedResourceAttributes) nested["nested"] = "nested_value"; resourceAttributes[KEY] = nested; - ASSERT_TRUE(resourceAttributes[KEY].get()["nested"] == "nested_value"); + ASSERT_TRUE("nested_value" == resourceAttributes[KEY].get()["nested"]); } + + + class ResourceAttributesIteratorTest: public Test { public: @@ -206,6 +210,7 @@ TEST_F(ResourceAttributesIteratorTest, ConstIteratesCam) ASSERT_EQ(1, resourceAttributes[KEY]); } + TEST(ResourceAttributesValueTest, MovedValueHasNull) { ResourceAttributes::Value one { 1 }; @@ -214,6 +219,9 @@ TEST(ResourceAttributesValueTest, MovedValueHasNull) ASSERT_EQ(nullptr, one); } + + + TEST(ResourceAttributesConverterTest, OCRepresentationCanBeConvertedIntoResourceAttributes) { constexpr double value = 9876; diff --git a/service/basis/serverBuilder/SConscript b/service/basis/serverBuilder/SConscript new file mode 100644 index 0000000..b550979 --- /dev/null +++ b/service/basis/serverBuilder/SConscript @@ -0,0 +1,62 @@ +#****************************************************************** +# +# Copyright 2015 Samsung Electronics All Rights Reserved. +# +#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +## +# things_manager project build script +## +import os +Import('env') + +# Add third party libraries +lib_env = env.Clone() +SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', exports = 'lib_env') + +server_builder_env = lib_env.Clone() +target_os = env.get('TARGET_OS') + +###################################################################### +# Build flags +###################################################################### +server_builder_env.AppendUnique(CPPPATH = [ + '../common/primitiveResource/include/', + ]) + +server_builder_env.AppendUnique(CPPPATH = [env.get('SRC_DIR')+'/extlibs', 'include', 'src']) + +if target_os not in ['windows', 'winrt']: + server_builder_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall']) + if target_os != 'android': + server_builder_env.AppendUnique(CXXFLAGS = ['-pthread']) + +if target_os == 'android': + server_builder_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions']) + server_builder_env.PrependUnique(LIBS = ['gnustl_shared', 'compatibility', 'log']) + +server_builder_env.AppendUnique(LIBS = ['dl']) + +###################################################################### +# Source files and Targets +###################################################################### +server_builder_src = env.Glob('src/*.cpp') +server_builder_static = server_builder_env.StaticLibrary('ServerBuilder', server_builder_src) +server_builder_shared = server_builder_env.SharedLibrary('ServerBuilder', server_builder_src) + +server_builder_env.InstallTarget([server_builder_static,server_builder_shared], 'libServerBuilder') + diff --git a/service/basis/serverBuilder/include/PrimitiveRequest.h b/service/basis/serverBuilder/include/PrimitiveRequest.h index 025c7fc..76c80ea 100644 --- a/service/basis/serverBuilder/include/PrimitiveRequest.h +++ b/service/basis/serverBuilder/include/PrimitiveRequest.h @@ -21,13 +21,25 @@ #ifndef __PRIMITIVEREQUEST__H #define __PRIMITIVEREQUEST__H - #include class PrimitiveRequest { - std::string getResourceUri() const; -}; +public: + explicit PrimitiveRequest(const std::string& resourceUri) : + m_resourceUri(resourceUri) + { + } + + PrimitiveRequest& operator=(PrimitiveRequest&) = delete; + std::string getResourceUri() const + { + return m_resourceUri; + } + +private: + std::string m_resourceUri; +}; #endif diff --git a/service/basis/serverBuilder/include/PrimitiveResponse.h b/service/basis/serverBuilder/include/PrimitiveResponse.h index 7fb9733..c9ea353 100644 --- a/service/basis/serverBuilder/include/PrimitiveResponse.h +++ b/service/basis/serverBuilder/include/PrimitiveResponse.h @@ -21,40 +21,60 @@ #ifndef __PRIMITIVERESPONSE_H #define __PRIMITIVERESPONSE_H -class Handler; +#include +#include -class PrimitiveResponse +#include + +class ResourceAttributes; +class RequestHandler; + +class PrimitiveGetResponse { - public: - static PrimitiveResponse DEFAULT; +public: + static PrimitiveGetResponse defaultAction(); + + static PrimitiveGetResponse create(const OCEntityHandlerResult&, int errorCode); + + static PrimitiveGetResponse create(const ResourceAttributes&); + static PrimitiveGetResponse create(const ResourceAttributes&, + const OCEntityHandlerResult&, int errorCode); + + static PrimitiveGetResponse create(ResourceAttributes&&); + static PrimitiveGetResponse create(ResourceAttributes&&, const OCEntityHandlerResult&, + int errorCode); + + RequestHandler* getHandler() const; - static PrimitiveResponse createResponse(const ResourceAttributes &attrs); +private: + PrimitiveGetResponse(RequestHandler*); - shared_ptr m_handler; +private: + std::shared_ptr< RequestHandler > m_handler; }; -class GetDefaultHandler +class PrimitiveSetResponse { - public: - OCResponse handle(ServerResource &resource) - { - // build response - } -}; +public: + static PrimitiveSetResponse defaultAction(); -GetRequestHandler m_getRequestHandler; + static PrimitiveSetResponse create(const OCEntityHandlerResult&, int errorCode); -void onGet() -{ - Request request; - Attributes attributes; + static PrimitiveSetResponse create(const ResourceAttributes&); + static PrimitiveSetResponse create(const ResourceAttributes&, + const OCEntityHandlerResult&, int errorCode); + + static PrimitiveSetResponse create(ResourceAttributes&&); + static PrimitiveSetResponse create(ResourceAttributes&&, const OCEntityHandlerResult&, + int errorCode); - if (m_getRequestHandler) - { - GetPrimitiveResponse response = m_getRequestHandler(request, attributes); + RequestHandler* getHandler() const; - return response->getHandler()->handle(*this); - } -} +private: + PrimitiveSetResponse(RequestHandler*); + +private: + std::shared_ptr< RequestHandler > m_handler; +}; #endif diff --git a/service/basis/serverBuilder/include/PrimitiveServerResource.h b/service/basis/serverBuilder/include/PrimitiveServerResource.h index fa9d85d..4729f52 100644 --- a/service/basis/serverBuilder/include/PrimitiveServerResource.h +++ b/service/basis/serverBuilder/include/PrimitiveServerResource.h @@ -21,65 +21,164 @@ #ifndef __PRIMITIVESERVERRESOURCE_H #define __PRIMITIVESERVERRESOURCE_H +#include +#include +#include +#include + +#include +#include +#include + +namespace OC +{ + class OCResourceRequest; +} + +class NoLockException : public PrimitiveException +{ +}; + +class DeadLockException : public PrimitiveException +{ +}; + class PrimitiveServerResource { - private: - PrimitiveServerResource(); - PrimitiveServerResource(OCResourceHandle baseResourceHandle); - OCEntityHandlerResult entityHandler(std::shared_ptr request); +private: + class WeakGuard; + +public: +// enum class AutoNotifyPolicy { +// NEVER, +// ALWAYS, +// UPDATED +// }; + + using Ptr = std::shared_ptr; + using ConstPtr = std::shared_ptr; + class Builder + { public: - class Builder - { - public: - Builder(const std::string &uri, const std::string &type, - const std::string &interface); + Builder(const std::string& uri, const std::string& type, const std::string& interface); - Builder &setDiscoverable(bool discoverable); - Builder &setObservable(bool observable); + Builder& setDiscoverable(bool discoverable); + Builder& setObservable(bool observable); - Builder &setAttributes(const ResourceAttributes &attrs); + Builder& setAttributes(const ResourceAttributes&); + Builder& setAttributes(ResourceAttributes&&); - PrimitiveServerResource create() const; + /** + * @throw PlatformException + */ + PrimitiveServerResource::Ptr create(); - private: - std::string m_uri; - std::string m_type; - std::string m_interface; - uint8_t m_property; - }; + private: + std::string m_uri; + std::string m_type; + std::string m_interface; - typedef std::function < - PrimitiveResponse(const PrimitiveRequest &, const ResourceAttributes &) > GetRequestHandler; - typedef std::function < - PrimitiveResponse(const PrimitiveRequest &, const ResourceAttributes &) > SetRequestHandler; + uint8_t m_properties; - template - void setAttribute(const std::string &key, const T &value); + ResourceAttributes m_resourceAttributes; + }; - template - T getAttribute(T &key) const; + class LockGuard; - bool hasAttribute(const std::string &key) const; + typedef std::function< PrimitiveGetResponse(const PrimitiveRequest&, const ResourceAttributes&) > GetRequestHandler; + typedef std::function< PrimitiveSetResponse(const PrimitiveRequest&, const ResourceAttributes&) > SetRequestHandler; - const ResourceAttributes &getAttributes() const; - ResourceAttributes &getAttributes(); +public: + PrimitiveServerResource(PrimitiveServerResource&&) = delete; + PrimitiveServerResource(const PrimitiveServerResource&) = delete; - bool isObservable() const; - bool isDiscoverable() const; + PrimitiveServerResource& operator=(PrimitiveServerResource&&) = delete; + PrimitiveServerResource& operator=(const PrimitiveServerResource&) = delete; - void setGetRequestHandler(GetRequestHandler); - void setSetRequestHandler(SetRequestHandler); + template< typename T > + void setAttribute(const std::string& key, const T &value) + { + WeakGuard lock(*this); + m_resourceAttributes[key] = value; + } - void notify(); + template< typename T > + T getAttribute(const std::string& key) const + { + WeakGuard lock(*this); + return m_resourceAttributes.at(key).get< T >(); + } - std::string getUri() const; - std::vector getTypes() const; - std::vector getInterfaces() const; + bool hasAttribute(const std::string& key) const; - private: - OCResourceHandle m_resourceHandle; + ResourceAttributes& getAttributes(); + const ResourceAttributes& getAttributes() const; + +// bool isObservable() const; +// bool isDiscoverable() const; + + void setGetRequestHandler(GetRequestHandler); + void setSetRequestHandler(SetRequestHandler); + + // void notify(); + +// void setAutoNotifyPolicy(AutoNotifyPolicy); + +private: + PrimitiveServerResource(ResourceAttributes&&); + + OCEntityHandlerResult entityHandler(std::shared_ptr< OC::OCResourceRequest >); + + OCEntityHandlerResult handleRequest(std::shared_ptr< OC::OCResourceRequest >); + OCEntityHandlerResult handleRequestGet(std::shared_ptr< OC::OCResourceRequest >); + OCEntityHandlerResult handleRequestSet(std::shared_ptr< OC::OCResourceRequest >); + OCEntityHandlerResult handleObserve(std::shared_ptr< OC::OCResourceRequest >); + + void assertOwnLock() const; + +private: + OCResourceHandle m_resourceHandle; + ResourceAttributes m_resourceAttributes; + + GetRequestHandler m_getRequestHandler; + SetRequestHandler m_setRequestHandler; + + mutable std::atomic m_lockOwner; + mutable std::mutex m_mutex; +}; + +class PrimitiveServerResource::LockGuard +{ +public: + LockGuard(const PrimitiveServerResource&); + ~LockGuard(); + + LockGuard(const LockGuard&) = delete; + LockGuard(LockGuard&&) = delete; + + LockGuard& operator=(const LockGuard&) = delete; + LockGuard& operator=(LockGuard&&) = delete; + +private: + const PrimitiveServerResource& m_serverResource; }; +class PrimitiveServerResource::WeakGuard +{ +public: + WeakGuard(const PrimitiveServerResource&); + ~WeakGuard(); + + WeakGuard(const WeakGuard&) = delete; + WeakGuard(WeakGuard&&) = delete; + + WeakGuard& operator=(const WeakGuard&) = delete; + WeakGuard& operator=(WeakGuard&&) = delete; + +private: + const PrimitiveServerResource& m_serverResource; + bool m_hasLocked; +}; #endif diff --git a/service/basis/serverBuilder/include/ServerBuilder.h b/service/basis/serverBuilder/include/ServerBuilder.h deleted file mode 100644 index 0b42daf..0000000 --- a/service/basis/serverBuilder/include/ServerBuilder.h +++ /dev/null @@ -1,102 +0,0 @@ -//****************************************************************** -// -// Copyright 2015 Samsung Electronics All Rights Reserved. -// -//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= - -#include -#include -#include -#include -#include - -class ResourceAttributes -{ - public: - /* - * @brief Value manipulation helper class. - * You may need to wrap OCRepresent::AttributeItem class. - * Do not expose the class as the part of API. - */ - class Item - { - public: - /* - * @brief Get the value as the type of T - * - * @throw BadCastException if the type is not correct. - */ - template - T get() const; - - /** - * @brief Get the value as the type of T - * - * @return True if the type is correct. - */ - template - bool get(T &var) const; - - // ... - // we need other helper methods for this class. - // please refer OCRepresent::AttributeItem class. - }; - - /** - * @brief There will be container in this class, and we need iterator for that. - * Implement one or just define alias. - */ - typedef std::unordered_map::const_iterator const_iterator; - - /** - * @brief std::map style get method. - */ - Item &operator[](const std::string &key); - - /** - * @brief std::map style get method. - * - * @throw InvalidKeyException If no value for the key. - */ - Item &at(const std::string &key); - - /** - * @brief std::map style get method. - * - * @throw InvalidKeyException If no value for the key. - */ - const Item &at(const std::string &key) const; - - /** - * @return True if there is a value for the key. - */ - bool contains(const std::string &key) const; - - const_iterator cbegin() const; - const_iterator cend() const; - - size_t getSize() const; - bool isEmpty() const; - - template - void insert(const std::string &key, const T &value); - - void remove(const std::string &key); - - void clear(); -}; - diff --git a/service/basis/serverBuilder/include/internal/RequestHandler.h b/service/basis/serverBuilder/include/internal/RequestHandler.h new file mode 100644 index 0000000..b185404 --- /dev/null +++ b/service/basis/serverBuilder/include/internal/RequestHandler.h @@ -0,0 +1,102 @@ +//****************************************************************** +// +// Copyright 2015 Samsung Electronics All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef __REQUESTHANDLER_H +#define __REQUESTHANDLER_H + +#include + +#include + +#include + +class RequestHandler +{ +public: + virtual ~RequestHandler() + { + } + + virtual std::shared_ptr< OC::OCResourceResponse > buildResponse(PrimitiveServerResource&) = 0; +}; + +class SimpleRequestHandler: public RequestHandler +{ +public: + SimpleRequestHandler(const OCEntityHandlerResult& result = OC_EH_OK, int errorCode = 200) : + m_result{ result }, m_errorCode{ errorCode } + { + } + + std::shared_ptr< OC::OCResourceResponse > buildResponse(PrimitiveServerResource& resource) override + { + auto response = std::make_shared< OC::OCResourceResponse >(); + + response->setErrorCode(getErrorCode(resource)); + response->setResponseResult(getResponseResult(resource)); + response->setResourceRepresentation(getOCRepresentation(resource)); + + return response; + } + +protected: + virtual int getErrorCode(PrimitiveServerResource&) + { + return m_errorCode; + } + + virtual OCEntityHandlerResult getResponseResult(PrimitiveServerResource&) + { + return m_result; + } + + virtual OC::OCRepresentation getOCRepresentation(PrimitiveServerResource& resource) + { + PrimitiveServerResource::LockGuard lock{ resource }; + return ResourceAttributesConverter::toOCRepresentation(resource.getAttributes()); + } + +private: + OCEntityHandlerResult m_result; + int m_errorCode; +}; + + +class CustomAttrRequestHandler: public SimpleRequestHandler +{ +public: + template + CustomAttrRequestHandler(T&& attrs, + const OCEntityHandlerResult& result = OC_EH_OK, int errorCode = 200) : + SimpleRequestHandler{ result, errorCode }, m_attrs{ std::forward(attrs) } + { + } + +protected: + virtual OC::OCRepresentation getOCRepresentation(PrimitiveServerResource& resource) override + { + return ResourceAttributesConverter::toOCRepresentation(m_attrs); + } + +private: + ResourceAttributes m_attrs; +}; + +#endif // __REQUESTHANDLER_H diff --git a/service/basis/serverBuilder/src/PrimitiveResponse.cpp b/service/basis/serverBuilder/src/PrimitiveResponse.cpp index bb2e273..619f55c 100644 --- a/service/basis/serverBuilder/src/PrimitiveResponse.cpp +++ b/service/basis/serverBuilder/src/PrimitiveResponse.cpp @@ -18,4 +18,97 @@ // //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -#include "PrimitiveResponse.h" +#include + +#include + +PrimitiveGetResponse PrimitiveGetResponse::defaultAction() +{ + static PrimitiveGetResponse defaultRes { new SimpleRequestHandler }; + + return defaultRes; +} + +PrimitiveGetResponse PrimitiveGetResponse::create(const OCEntityHandlerResult& result, + int errorCode) +{ + return PrimitiveGetResponse { new SimpleRequestHandler { result, errorCode } }; +} + +PrimitiveGetResponse PrimitiveGetResponse::create(const ResourceAttributes& attrs) +{ + return PrimitiveGetResponse { new CustomAttrRequestHandler { attrs } }; +} + +PrimitiveGetResponse PrimitiveGetResponse::create(const ResourceAttributes& attrs, + const OCEntityHandlerResult& result, int errorCode) +{ + return PrimitiveGetResponse { new CustomAttrRequestHandler { attrs, result, errorCode } }; +} + +PrimitiveGetResponse PrimitiveGetResponse::create(ResourceAttributes&& result) +{ + return PrimitiveGetResponse { new CustomAttrRequestHandler { std::move(result) } }; +} + +PrimitiveGetResponse PrimitiveGetResponse::create(ResourceAttributes&& attrs, + const OCEntityHandlerResult& result, int errorCode) +{ + return PrimitiveGetResponse { new CustomAttrRequestHandler { std::move(attrs), result, errorCode } }; +} + +PrimitiveGetResponse::PrimitiveGetResponse(RequestHandler* handler) : + m_handler{ handler } +{ +} + +RequestHandler* PrimitiveGetResponse::getHandler() const +{ + return m_handler.get(); +} + + +PrimitiveSetResponse PrimitiveSetResponse::defaultAction() +{ + static PrimitiveSetResponse defaultRes { new SimpleRequestHandler }; + + return defaultRes; +} + +PrimitiveSetResponse PrimitiveSetResponse::create(const OCEntityHandlerResult& result, + int errorCode) +{ + return PrimitiveSetResponse { new SimpleRequestHandler { result, errorCode } }; +} + +PrimitiveSetResponse PrimitiveSetResponse::create(const ResourceAttributes& attrs) +{ + return PrimitiveSetResponse { new CustomAttrRequestHandler { attrs } }; +} + +PrimitiveSetResponse PrimitiveSetResponse::create(const ResourceAttributes& attrs, + const OCEntityHandlerResult& result, int errorCode) +{ + return PrimitiveSetResponse { new CustomAttrRequestHandler { attrs, result, errorCode } }; +} + +PrimitiveSetResponse PrimitiveSetResponse::create(ResourceAttributes&& result) +{ + return PrimitiveSetResponse { new CustomAttrRequestHandler { std::move(result) } }; +} + +PrimitiveSetResponse PrimitiveSetResponse::create(ResourceAttributes&& attrs, + const OCEntityHandlerResult& result, int errorCode) +{ + return PrimitiveSetResponse { new CustomAttrRequestHandler { std::move(attrs), result, errorCode } }; +} + +PrimitiveSetResponse::PrimitiveSetResponse(RequestHandler* handler) : + m_handler{ handler } +{ +} + +RequestHandler* PrimitiveSetResponse::getHandler() const +{ + return m_handler.get(); +} diff --git a/service/basis/serverBuilder/src/PrimitiveServerResource.cpp b/service/basis/serverBuilder/src/PrimitiveServerResource.cpp index 8235b36..7f68867 100644 --- a/service/basis/serverBuilder/src/PrimitiveServerResource.cpp +++ b/service/basis/serverBuilder/src/PrimitiveServerResource.cpp @@ -24,223 +24,267 @@ #include #include -#include "OCPlatform.h" +#include -using namespace OC; +#include -PrimitiveServerResource::PrimitiveServerResource(OCResourceHandle &baseResourceHandle) +namespace +{ + uint8_t makePropertyFlags(uint8_t base, uint8_t target, bool add) + { + if (add) + { + return base | target; + } + + return base & ~target; + } + + template + OCEntityHandlerResult sendResponse(PrimitiveServerResource& resource, + std::shared_ptr< OC::OCResourceRequest > ocRequest, RESPONSE&& response) + { + auto ocResponse = response.getHandler()->buildResponse(resource); + + ocResponse->setRequestHandle(ocRequest->getRequestHandle()); + ocResponse->setResourceHandle(ocRequest->getResourceHandle()); + + if (OC::OCPlatform::sendResponse(ocResponse) == OC_STACK_OK) + { + return OC_EH_OK; + } + return OC_EH_ERROR; + } + + template< typename HANDLER, typename RESPONSE = typename std::decay::type::result_type> + OCEntityHandlerResult handleRequest(PrimitiveServerResource& resource, + std::shared_ptr< OC::OCResourceRequest > ocRequest, HANDLER&& handler) + { + if (handler) + { + ResourceAttributes attrs{ ResourceAttributesConverter::fromOCRepresentation( + ocRequest->getResourceRepresentation()) }; + + return sendResponse(resource, ocRequest, handler( + PrimitiveRequest{ ocRequest->getResourceUri() }, attrs)); + } + + return sendResponse(resource, ocRequest, RESPONSE::defaultAction()); + } +} // unnamed namespace + + +PrimitiveServerResource::PrimitiveServerResource(ResourceAttributes&& attrs) : + m_resourceHandle{}, m_resourceAttributes{ std::move(attrs) }, + m_getRequestHandler{}, m_setRequestHandler{}, + m_mutex { } { - m_resourceHandle = baseResourceHandle; } PrimitiveServerResource::Builder::Builder(const std::string &uri, const std::string &type, - const std::string &interface) + const std::string &interface) : + m_uri{ uri }, m_type{ type }, m_interface{ interface }, m_properties{ 0 } { - m_uri = uri; - m_type = type; - m_interface = interface; - m_property = 0; } -PrimitiveServerResource::Builder &PrimitiveServerResource::Builder::setDiscoverable( - bool discoverable) +PrimitiveServerResource::Builder& PrimitiveServerResource::Builder::setDiscoverable( + bool discoverable) { - //set flag - if (discoverable) - m_property |= OC_DISCOVERABLE; - else - m_property ^ = OC_DISCOVERABLE; + m_properties = ::makePropertyFlags(m_properties, OC_DISCOVERABLE, discoverable); return *this; } -PrimitiveServerResource::Builder &PrimitiveServerResource::Builder::setObservable(bool observable) +PrimitiveServerResource::Builder& PrimitiveServerResource::Builder::setObservable(bool observable) { - //set flag - if (observable) - m_property |= OC_OBSERVABLE; - else - m_property ^ = OC_OBSERVABLE; + m_properties = ::makePropertyFlags(m_properties, OC_OBSERVABLE, observable); return *this; } -PrimitiveServerResource::Builder &PrimitiveServerResource::Builder::setAttributes( - const ResourceAttributes &attrs) +PrimitiveServerResource::Builder& PrimitiveServerResource::Builder::setAttributes( + const ResourceAttributes &attrs) { - //set Attributemap + m_resourceAttributes = attrs; return *this; } -PrimitiveServerResource PrimitiveServerResource::Builder::create() const +PrimitiveServerResource::Builder& PrimitiveServerResource::Builder::setAttributes( + ResourceAttributes &&attrs) { - //TODO: EntityHandler param change - OCResourceHandle handle = NULL; - EntityHandler cb = std::bind(&PrimitiveServerResource::entityHandler, this, std::placeholders::_1); - OCStackResult result = OCPlatform::registerResource( handle, m_uri, - m_type, m_interface, cb, m_property); - - if (OC_STACK_OK != result) - { - //TODO: Throw error exception. - } - return PrimitiveServerResource(handle); + m_resourceAttributes = std::move(attrs); + return *this; } -OCEntityHandlerResult PrimitiveServerResource::entityHandler(std::shared_ptr - request) +PrimitiveServerResource::Ptr PrimitiveServerResource::Builder::create() { - OCEntityHandlerResult ehResult = OC_EH_ERROR; - if (request) - { - //TODO: simplify Code. + OCResourceHandle handle{ nullptr }; + PrimitiveServerResource::Ptr server { new PrimitiveServerResource{ std::move(m_resourceAttributes) } }; + OC::EntityHandler entityHandler{ std::bind(&PrimitiveServerResource::entityHandler, server.get(), + std::placeholders::_1) }; - // Get the request type and request flag - std::string requestType = request->getRequestType(); - int requestFlag = request->getRequestHandlerFlag(); - - if (requestFlag & RequestHandlerFlag::RequestFlag) - { - auto pResponse = std::make_shared(); - pResponse->setRequestHandle(request->getRequestHandle()); - pResponse->setResourceHandle(request->getResourceHandle()); - - // If the request type is GET - if (requestType == "GET") - { - cout << "\t\t\trequestType : GET\n"; - //TODO: implementation sevral method for "default" or "custom" -// pResponse->setErrorCode(200); -// pResponse->setResponseResult(OC_EH_OK); -// pResponse->setResourceRepresentation(get()); -// if(OC_STACK_OK == OCPlatform::sendResponse(pResponse)) -// { -// ehResult = OC_EH_OK; -// } - } - else if (requestType == "PUT") - { - cout << "\t\t\trequestType : PUT\n"; - //TODO: implementation sevral method for "default" or "custom" - -// OCRepresentation rep = request->getResourceRepresentation(); -// -// // Do related operations related to PUT request -// // Update the lightResource -// put(rep); -// pResponse->setErrorCode(200); -// pResponse->setResponseResult(OC_EH_OK); -// pResponse->setResourceRepresentation(get()); -// if(OC_STACK_OK == OCPlatform::sendResponse(pResponse)) -// { -// ehResult = OC_EH_OK; -// } - } - } + OCStackResult result = OC::OCPlatform::registerResource(handle, m_uri, m_type, m_interface, entityHandler, + m_properties); - if (requestFlag & RequestHandlerFlag::ObserverFlag) - { - ObservationInfo observationInfo = request->getObservationInfo(); - if (ObserveAction::ObserveRegister == observationInfo.action) - { - m_interestedObservers.push_back(observationInfo.obsId); - } - else if (ObserveAction::ObserveUnregister == observationInfo.action) - { - m_interestedObservers.erase(std::remove( - m_interestedObservers.begin(), - m_interestedObservers.end(), - observationInfo.obsId), - m_interestedObservers.end()); - } - - pthread_t threadId; - - cout << "\t\trequestFlag : Observer\n"; - gObservation = 1; - static int startedThread = 0; - - // Observation happens on a different thread in ChangeLightRepresentation function. - // If we have not created the thread already, we will create one here. - if (!startedThread) - { - pthread_create (&threadId, NULL, ChangeLightRepresentation, (void *)this); - startedThread = 1; - } - ehResult = OC_EH_OK; - } - } - else + if (OC_STACK_OK != result) { - std::cout << "Request invalid" << std::endl; + throw PlatformException(result); } - return ehResult; -} + server->m_resourceHandle = handle; + return server; +} -template -void PrimitiveServerResource::setAttribute(const std::string &key, const T &value) +bool PrimitiveServerResource::hasAttribute(const std::string& key) const { - + WeakGuard lock(*this); + return m_resourceAttributes.contains(key); } -template -T PrimitiveServerResource::getAttribute(T &key) const +ResourceAttributes& PrimitiveServerResource::getAttributes() { - + assertOwnLock(); + return m_resourceAttributes; } -bool PrimitiveServerResource::hasAttribute(const std::string &key) const +const ResourceAttributes& PrimitiveServerResource::getAttributes() const { - + assertOwnLock(); + return m_resourceAttributes; } -const ResourceAttributes &PrimitiveServerResource::getAttributes() const +void PrimitiveServerResource::assertOwnLock() const { - + if (m_lockOwner != std::this_thread::get_id()) + { + throw NoLockException{ }; + } } -ResourceAttributes &PrimitiveServerResource::getAttributes() -{ -} +//bool PrimitiveServerResource::isObservable() const +//{ +// // TODO : fill +//} +// +//bool PrimitiveServerResource::isDiscoverable() const +//{ +// // TODO : fill +//} -bool PrimitiveServerResource:: isObservable() const +void PrimitiveServerResource::setGetRequestHandler(GetRequestHandler h) { - + m_getRequestHandler = h; } -bool PrimitiveServerResource::isDiscoverable() const +void PrimitiveServerResource::setSetRequestHandler(SetRequestHandler h) { - + m_setRequestHandler = h; } -void PrimitiveServerResource::setGetRequestHandler(GetRequestHandler) +//void PrimitiveServerResource::notify() +//{ +// // TODO : fill +//} + +OCEntityHandlerResult PrimitiveServerResource::entityHandler( + std::shared_ptr< OC::OCResourceRequest > request) { + if (!request) + { + return OC_EH_ERROR; + } + + try + { + if (request->getRequestHandlerFlag() & OC::RequestHandlerFlag::RequestFlag) + { + return handleRequest(request); + } + if (request->getRequestHandlerFlag() & OC::RequestHandlerFlag::ObserverFlag) + { + return handleObserve(request); + } + } + catch (...) + { + // TODO : how to notify the error? + } + + return OC_EH_ERROR; } -void PrimitiveServerResource::setSetRequestHandler(SetRequestHandler) +OCEntityHandlerResult PrimitiveServerResource::handleRequest( + std::shared_ptr< OC::OCResourceRequest > request) { + if (request->getRequestType() == "GET") + { + return handleRequestGet(request); + } + + if (request->getRequestType() == "PUT" || request->getRequestType() == "POST") + { + return handleRequestSet(request); + } + return OC_EH_ERROR; } -void PrimitiveServerResource::notify() +OCEntityHandlerResult PrimitiveServerResource::handleRequestGet( + std::shared_ptr< OC::OCResourceRequest > request) { + return ::handleRequest(*this, request, m_getRequestHandler); +} +OCEntityHandlerResult PrimitiveServerResource::handleRequestSet( + std::shared_ptr< OC::OCResourceRequest > request) +{ + return ::handleRequest(*this, request, m_setRequestHandler); } -std::string PrimitiveServerResource::getUri() const +OCEntityHandlerResult PrimitiveServerResource::handleObserve( + std::shared_ptr< OC::OCResourceRequest > request) { +// if (!isObservable()) +// { +// return OC_EH_ERROR; +// } + return OC_EH_OK; } -std::vector PrimitiveServerResource::getTypes() const +PrimitiveServerResource::LockGuard::LockGuard(const PrimitiveServerResource& serverResource) : + m_serverResource(serverResource) { + if (m_serverResource.m_lockOwner == std::this_thread::get_id()) + { + throw DeadLockException{ }; + } + m_serverResource.m_mutex.lock(); + m_serverResource.m_lockOwner = std::this_thread::get_id(); } -std::vector PrimitiveServerResource::getInterfaces() const +PrimitiveServerResource::LockGuard::~LockGuard() { + m_serverResource.m_lockOwner = std::thread::id(); + m_serverResource.m_mutex.unlock(); +} +PrimitiveServerResource::WeakGuard::WeakGuard(const PrimitiveServerResource& serverResource) : + m_serverResource(serverResource), m_hasLocked{ false } +{ + if (m_serverResource.m_lockOwner != std::this_thread::get_id()) + { + m_serverResource.m_mutex.lock(); + m_hasLocked = true; + } } +PrimitiveServerResource::WeakGuard::~WeakGuard() +{ + if (m_hasLocked) + { + m_serverResource.m_mutex.unlock(); + } +} diff --git a/service/basis/serverBuilder/src/ServerBuilder.cpp b/service/basis/serverBuilder/src/ServerBuilder.cpp deleted file mode 100644 index c44f5d7..0000000 --- a/service/basis/serverBuilder/src/ServerBuilder.cpp +++ /dev/null @@ -1,189 +0,0 @@ -//****************************************************************** -// -// Copyright 2015 Samsung Electronics All Rights Reserved. -// -//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= - -#include -#include -#include -#include -#include - -class ResourceAttributes -{ - public: - /* - * @brief Value manipulation helper class. - * You may need to wrap OCRepresent::AttributeItem class. - * Do not expose the class as the part of API. - */ - class Item - { - public: - /* - * @brief Get the value as the type of T - * - * @throw BadCastException if the type is not correct. - */ - template - T get() const; - - /** - * @brief Get the value as the type of T - * - * @return True if the type is correct. - */ - template - bool get(T &var) const; - - // ... - // we need other helper methods for this class. - // please refer OCRepresent::AttributeItem class. - }; - - /** - * @brief There will be container in this class, and we need iterator for that. - * Implement one or just define alias. - */ - typedef std::unordered_map::const_iterator const_iterator; - - /** - * @brief std::map style get method. - */ - Item &operator[](const std::string &key); - - /** - * @brief std::map style get method. - * - * @throw InvalidKeyException If no value for the key. - */ - Item &at(const std::string &key); - - /** - * @brief std::map style get method. - * - * @throw InvalidKeyException If no value for the key. - */ - const Item &at(const std::string &key) const; - - /** - * @return True if there is a value for the key. - */ - bool contains(const std::string &key) const; - - const_iterator cbegin() const; - const_iterator cend() const; - - size_t getSize() const; - bool isEmpty() const; - - template - void insert(const std::string &key, const T &value); - - void remove(const std::string &key); - - void clear(); -}; - -class PrimitiveRequest -{ - std::string getResourceUri() const; -}; - -class PrimitiveResponse -{ - public: - static PrimitiveResponse DEFAULT; - - static PrimitiveResponse createResponse(const ResourceAttributes &attrs); -}; - -class PrimitiveServerResource -{ - private: - PrimitiveServerResource(); - public: - class Builder - { - public: - Builder(const std::string &uri, const std::string &type, - const std::string &interface); - - Builder &setProperties(uint8_t properties); - Builder &setDiscoverable(bool discoverable); - Builder &setObservable(bool observable); - - Builder &setAttributes(const ResourceAttributes &attrs); - - PrimitiveServerResource create() const; - }; - - typedef std::function < - PrimitiveResponse(const PrimitiveRequest &, const ResourceAttributes &) > GetRequestHandler; - typedef std::function < - PrimitiveResponse(const PrimitiveRequest &, const ResourceAttributes &) > SetRequestHandler; - - template - void setAttribute(const std::string &key, const T &value); - - template - T getAttribute() const; - - bool hasAttribute(const std::string &key) const; - - const ResourceAttributes &getAttributes() const; - ResourceAttributes &getAttributes(); - - uint8_t getProperties() const; - bool isObservable() const; - bool isDiscoverable() const; - - void setGetRequestHandler(GetRequestHandler); - void setSetRequestHandler(SetRequestHandler); - - void notify(); - - std::string getUri() const; - std::vector getTypes() const; - std::vector getInterfaces() const; -}; - -void example() -{ - PrimitiveServerResource server = PrimitiveServerResource::Builder("uri", "type", - "interface").setObservable(true).create(); - - server.setAttribute("key1", "value"); - server.setAttribute("key2", 0); - - server.setGetRequestHandler( - [](const PrimitiveRequest &, const ResourceAttributes &) -> PrimitiveResponse - { - // If you want to let the default handler handle the request which sends attributes in the server as the response, return DEFAULT. - return PrimitiveResponse::DEFAULT; - - // or if you want to send back with user defined response - ResourceAttributes responseAttrs; - responseAttrs["key"] = 0; - - return PrimitiveResponse::createResponse(responseAttrs); - }); - - // If you want to notify observers of attributes changed. - server.notify(); -} -- 2.7.4