1 //******************************************************************
3 // Copyright 2015 Samsung Electronics All Rights Reserved.
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
11 // http://www.apache.org/licenses/LICENSE-2.0
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
21 #include "RCSResourceObject.h"
26 #include "RequestHandler.h"
27 #include "AssertUtils.h"
28 #include "AtomicHelper.h"
29 #include "ResourceAttributesConverter.h"
30 #include "ResourceAttributesUtils.h"
31 #include "RCSRequest.h"
32 #include "RCSRepresentation.h"
33 #include "InterfaceHandler.h"
36 #include "OCPlatform.h"
38 #define LOG_TAG "RCSResourceObject"
42 using namespace OIC::Service;
44 inline bool hasProperty(uint8_t base, uint8_t target)
46 return (base & target) == target;
49 inline uint8_t makePropertyFlags(uint8_t base, uint8_t target, bool add)
56 return base & ~target;
59 OCEntityHandlerResult sendResponse(const std::shared_ptr< OC::OCResourceRequest >& ocRequest,
60 const std::shared_ptr< OC::OCResourceResponse >& ocResponse)
62 ocResponse->setRequestHandle(ocRequest->getRequestHandle());
63 ocResponse->setResourceHandle(ocRequest->getResourceHandle());
67 if (OC::OCPlatform::sendResponse(ocResponse) == OC_STACK_OK)
72 catch (const OC::OCException& e)
74 OIC_LOG_V(WARNING, LOG_TAG, "Error (%s)", e.what());
80 RCSResourceAttributes getAttributesFromOCRequest(
81 const std::shared_ptr< OC::OCResourceRequest >& request)
83 return ResourceAttributesConverter::fromOCRepresentation(
84 request->getResourceRepresentation());
87 template< typename HANDLER, typename RESPONSE =
88 typename std::decay<HANDLER>::type::result_type >
89 RESPONSE invokeHandler(const RCSResourceObject::Ptr& resObj, RCSResourceAttributes& attrs,
90 const std::shared_ptr< OC::OCResourceRequest >& ocRequest,
91 std::shared_ptr< HANDLER > handler)
95 return (*handler)(RCSRequest{ resObj, ocRequest }, attrs);
98 return RESPONSE::defaultAction();
101 typedef void (RCSResourceObject::* AutoNotifyFunc)
102 (bool, RCSResourceObject::AutoNotifyPolicy) const;
104 std::function<void()> createAutoNotifyInvoker(AutoNotifyFunc autoNotifyFunc,
105 const RCSResourceObject& resourceObject,
106 const RCSResourceAttributes& resourceAttributes,
107 RCSResourceObject::AutoNotifyPolicy autoNotifyPolicy)
109 if(autoNotifyPolicy == RCSResourceObject::AutoNotifyPolicy::UPDATED)
111 auto&& compareAttributesFunc =
112 std::bind(std::not_equal_to<RCSResourceAttributes>(),
114 std::cref(resourceAttributes));
115 return std::bind(autoNotifyFunc,
116 &resourceObject, std::move(compareAttributesFunc), autoNotifyPolicy);
118 else if(autoNotifyPolicy == RCSResourceObject::AutoNotifyPolicy::ALWAYS)
120 return std::bind(autoNotifyFunc,
121 &resourceObject, true, autoNotifyPolicy);
126 } // unnamed namespace
133 RCSResourceObject::Builder::Builder(std::string uri, std::string type,
134 std::string interface) :
135 m_uri{ std::move(uri) },
136 m_types{ std::move(type) },
137 m_interfaces{ std::move(interface) },
138 m_defaultInterface { BASELINE_INTERFACE },
139 m_properties{ OC_DISCOVERABLE | OC_OBSERVABLE },
140 m_resourceAttributes{ }
144 RCSResourceObject::Builder& RCSResourceObject::Builder::addInterface(std::string interface)
146 m_interfaces.push_back(std::move(interface));
150 RCSResourceObject::Builder& RCSResourceObject::Builder::addType(std::string type)
152 m_types.push_back(std::move(type));
156 RCSResourceObject::Builder& RCSResourceObject::Builder::setDefaultInterface(
157 std::string interface)
159 if (std::find(m_interfaces.begin(), m_interfaces.end(), interface) ==
162 throw RCSBadRequestException{"The interface should be added, first."};
165 m_defaultInterface = std::move(interface);
170 RCSResourceObject::Builder& RCSResourceObject::Builder::setDiscoverable(
173 m_properties = ::makePropertyFlags(m_properties, OC_DISCOVERABLE, discoverable);
177 RCSResourceObject::Builder& RCSResourceObject::Builder::setObservable(
180 m_properties = ::makePropertyFlags(m_properties, OC_OBSERVABLE, observable);
184 RCSResourceObject::Builder& RCSResourceObject::Builder::setSecureFlag(
187 m_properties = ::makePropertyFlags(m_properties, OC_SECURE, secureFlag);
190 RCSResourceObject::Builder& RCSResourceObject::Builder::setAttributes(
191 const RCSResourceAttributes& attrs)
193 m_resourceAttributes = attrs;
197 RCSResourceObject::Builder& RCSResourceObject::Builder::setAttributes(
198 RCSResourceAttributes&& attrs)
200 m_resourceAttributes = std::move(attrs);
204 RCSResourceObject::Ptr RCSResourceObject::Builder::build()
206 OCResourceHandle handle{ nullptr };
208 RCSResourceObject::Ptr server {
209 new RCSResourceObject{ m_uri, m_properties, std::move(m_resourceAttributes) } };
211 OC::EntityHandler entityHandler{ std::bind(&RCSResourceObject::entityHandler,
212 std::weak_ptr< RCSResourceObject >{ server }, std::placeholders::_1) };
214 typedef OCStackResult (*RegisterResource)(OCResourceHandle&, std::string&,
215 const std::string&, const std::string&, OC::EntityHandler, uint8_t);
217 invokeOCFunc(static_cast<RegisterResource>(OC::OCPlatform::registerResource),
218 handle, m_uri, m_types[0], m_interfaces[0], entityHandler, m_properties);
220 std::for_each(m_interfaces.begin() + 1, m_interfaces.end(),
221 [&handle](const std::string& interfaceName){
222 invokeOCFunc(OC::OCPlatform::bindInterfaceToResource, handle, interfaceName);
225 std::for_each(m_types.begin() + 1, m_types.end(),
226 [&handle](const std::string& typeName){
227 invokeOCFunc(OC::OCPlatform::bindTypeToResource, handle, typeName);
230 server->init(handle, m_interfaces, m_types, m_defaultInterface);
236 RCSResourceObject::RCSResourceObject(const std::string& uri,
237 uint8_t properties, RCSResourceAttributes&& attrs) :
238 m_properties{ properties },
242 m_defaultInterface{ },
244 m_resourceAttributes{ std::move(attrs) },
245 m_getRequestHandler{ },
246 m_setRequestHandler{ },
247 m_autoNotifyPolicy{ AutoNotifyPolicy::UPDATED },
248 m_setRequestHandlerPolicy{ SetRequestHandlerPolicy::NEVER },
249 m_attributeUpdatedListeners{ },
252 m_mutexAttributeUpdatedListeners{ }
254 m_lockOwner.reset(new AtomicThreadId);
257 void RCSResourceObject::init(OCResourceHandle handle,
258 const std::vector< std::string >& interfaces,
259 const std::vector< std::string >& types,
260 const std::string& defaultInterface)
262 m_resourceHandle = handle;
263 m_interfaces = interfaces;
265 m_defaultInterface = defaultInterface;
267 for (const auto& itf : interfaces)
269 m_interfaceHandlers.insert({ itf, getDefaultInterfaceHandler(itf,
270 m_defaultInterface) });
274 RCSResourceObject::~RCSResourceObject()
276 if (m_resourceHandle)
280 invokeOCFunc(OC::OCPlatform::unregisterResource, m_resourceHandle);
284 OIC_LOG(WARNING, LOG_TAG, "Failed to unregister resource.");
289 template< typename K, typename V >
290 void RCSResourceObject::setAttributeInternal(K&& key, V&& value)
292 bool needToNotify = false;
293 bool valueUpdated = false;
296 WeakGuard lock(*this);
298 if (lock.hasLocked())
301 valueUpdated = testValueUpdated(key, value);
304 m_resourceAttributes[std::forward< K >(key)] = std::forward< V >(value);
307 if (needToNotify) autoNotify(valueUpdated);
309 void RCSResourceObject::setAttribute(const std::string& key,
310 const RCSResourceAttributes::Value& value)
312 setAttributeInternal(key, value);
315 void RCSResourceObject::setAttribute(const std::string& key,
316 RCSResourceAttributes::Value&& value)
318 setAttributeInternal(key, std::move(value));
321 void RCSResourceObject::setAttribute(std::string&& key,
322 const RCSResourceAttributes::Value& value)
324 setAttributeInternal(std::move(key), value);
327 void RCSResourceObject::setAttribute(std::string&& key,
328 RCSResourceAttributes::Value&& value)
330 setAttributeInternal(std::move(key), std::move(value));
333 RCSResourceAttributes::Value RCSResourceObject::getAttributeValue(
334 const std::string& key) const
336 WeakGuard lock(*this);
337 return m_resourceAttributes.at(key);
340 bool RCSResourceObject::removeAttribute(const std::string& key)
342 bool needToNotify = false;
345 WeakGuard lock(*this);
347 if (m_resourceAttributes.erase(key))
350 needToNotify = lock.hasLocked();
354 if (needToNotify) autoNotify(true);
359 bool RCSResourceObject::containsAttribute(const std::string& key) const
361 WeakGuard lock(*this);
362 return m_resourceAttributes.contains(key);
365 RCSResourceAttributes& RCSResourceObject::getAttributes()
368 return m_resourceAttributes;
371 const RCSResourceAttributes& RCSResourceObject::getAttributes() const
374 return m_resourceAttributes;
377 void RCSResourceObject::expectOwnLock() const
379 if (getLockOwner() != std::this_thread::get_id())
381 throw NoLockException{ "Must acquire the lock first using LockGuard." };
385 std::thread::id RCSResourceObject::getLockOwner() const noexcept
390 void RCSResourceObject::setLockOwner(std::thread::id&& id) const noexcept
392 m_lockOwner->store(std::move(id));
395 bool RCSResourceObject::isObservable() const
397 return ::hasProperty(m_properties, OC_OBSERVABLE);
400 bool RCSResourceObject::isDiscoverable() const
402 return ::hasProperty(m_properties, OC_DISCOVERABLE);
405 void RCSResourceObject::setGetRequestHandler(GetRequestHandler h)
407 m_getRequestHandler = std::make_shared< GetRequestHandler >(std::move(h));
410 void RCSResourceObject::setSetRequestHandler(SetRequestHandler h)
412 m_setRequestHandler = std::make_shared< SetRequestHandler >(std::move(h));
415 void RCSResourceObject::notify() const
417 typedef OCStackResult (*NotifyAllObservers)(OCResourceHandle);
419 invokeOCFuncWithResultExpect({ OC_STACK_OK, OC_STACK_NO_OBSERVERS },
420 static_cast< NotifyAllObservers >(OC::OCPlatform::notifyAllObservers),
424 void RCSResourceObject::addAttributeUpdatedListener(const std::string& key,
425 AttributeUpdatedListener h)
427 std::lock_guard< std::mutex > lock(m_mutexAttributeUpdatedListeners);
429 m_attributeUpdatedListeners[key] =
430 std::make_shared< AttributeUpdatedListener >(std::move(h));
433 void RCSResourceObject::addAttributeUpdatedListener(std::string&& key,
434 AttributeUpdatedListener h)
436 std::lock_guard< std::mutex > lock(m_mutexAttributeUpdatedListeners);
438 m_attributeUpdatedListeners[std::move(key)] =
439 std::make_shared< AttributeUpdatedListener >(std::move(h));
442 bool RCSResourceObject::removeAttributeUpdatedListener(const std::string& key)
444 std::lock_guard< std::mutex > lock(m_mutexAttributeUpdatedListeners);
446 return m_attributeUpdatedListeners.erase(key) != 0;
449 bool RCSResourceObject::testValueUpdated(const std::string& key,
450 const RCSResourceAttributes::Value& value) const
452 return m_resourceAttributes.contains(key) == false
453 || m_resourceAttributes.at(key) != value;
456 void RCSResourceObject::setAutoNotifyPolicy(AutoNotifyPolicy policy)
458 m_autoNotifyPolicy = policy;
461 RCSResourceObject::AutoNotifyPolicy RCSResourceObject::getAutoNotifyPolicy() const
463 return m_autoNotifyPolicy;
466 void RCSResourceObject::setSetRequestHandlerPolicy(SetRequestHandlerPolicy policy)
468 m_setRequestHandlerPolicy = policy;
471 auto RCSResourceObject::getSetRequestHandlerPolicy() const -> SetRequestHandlerPolicy
473 return m_setRequestHandlerPolicy;
476 void RCSResourceObject::bindResource(const RCSResourceObject::Ptr& resource)
478 if (!resource || resource.get() == this)
480 throw RCSInvalidParameterException("The resource is invalid!");
483 invokeOCFunc(OC::OCPlatform::bindResource,
484 m_resourceHandle, resource->m_resourceHandle);
486 std::lock_guard< std:: mutex > lock{ m_mutexForBoundResources };
487 m_boundResources.push_back(resource);
490 void RCSResourceObject::unbindResource(const RCSResourceObject::Ptr& resource)
492 if (!resource || resource.get() == this)
494 throw RCSInvalidParameterException("The resource is invalid!");
497 invokeOCFunc(OC::OCPlatform::unbindResource,
498 m_resourceHandle, resource->m_resourceHandle);
500 std::lock_guard< std:: mutex > lock{ m_mutexForBoundResources };
501 m_boundResources.erase(std::find(m_boundResources.begin(), m_boundResources.end(),
505 std::vector< RCSResourceObject::Ptr > RCSResourceObject::getBoundResources() const
507 std::lock_guard< std:: mutex > lock{ m_mutexForBoundResources };
508 return m_boundResources;
511 std::string RCSResourceObject::getUri() const
516 std::string RCSResourceObject::getDefaultInterface() const
518 return m_defaultInterface;
521 std::vector< std::string > RCSResourceObject::getInterfaces() const
526 std::vector< std::string > RCSResourceObject::getTypes() const
531 RCSRepresentation RCSResourceObject::getRepresentation(const RCSRequest& request) const
533 if (request.getOCRequest()->getRequestType() == "GET")
535 return findInterfaceHandler(
536 request.getInterface()).getGetResponseBuilder()(request, *this);
539 if (request.getOCRequest()->getRequestType() == "POST")
541 return findInterfaceHandler(
542 request.getInterface()).getSetResponseBuilder()(request, *this);
545 throw RCSBadRequestException{ "Unsupported request type!" };
548 void RCSResourceObject::autoNotify(bool isAttributesChanged) const
550 autoNotify(isAttributesChanged, m_autoNotifyPolicy);
553 void RCSResourceObject::autoNotify(
554 bool isAttributesChanged, AutoNotifyPolicy autoNotifyPolicy) const
556 if(autoNotifyPolicy == AutoNotifyPolicy::NEVER) return;
557 if(autoNotifyPolicy == AutoNotifyPolicy::UPDATED &&
558 isAttributesChanged == false) return;
563 OCEntityHandlerResult RCSResourceObject::entityHandler(
564 const std::weak_ptr< RCSResourceObject >& weakRes,
565 const std::shared_ptr< OC::OCResourceRequest >& request)
567 auto resource = weakRes.lock();
569 if (!resource) return OC_EH_ERROR;
571 OIC_LOG(WARNING, LOG_TAG, "entityHandler");
579 if (request->getRequestHandlerFlag() & OC::RequestHandlerFlag::RequestFlag)
581 return resource->handleRequest(request);
584 if (request->getRequestHandlerFlag() & OC::RequestHandlerFlag::ObserverFlag)
586 return resource->handleObserve(request);
589 catch (const std::exception& e)
591 OIC_LOG_V(WARNING, LOG_TAG, "Failed to handle request : %s", e.what());
596 OIC_LOG(WARNING, LOG_TAG, "Failed to handle request.");
603 OCEntityHandlerResult RCSResourceObject::handleRequest(
604 const std::shared_ptr< OC::OCResourceRequest >& request)
606 assert(request != nullptr);
608 RCSRequest rcsRequest{ shared_from_this(), request };
610 if (rcsRequest.getInterface() != "" && m_interfaceHandlers.find(
611 rcsRequest.getInterface()) == m_interfaceHandlers.end())
616 if (request->getRequestType() == "GET")
618 return handleRequestGet(rcsRequest);
621 if (request->getRequestType() == "POST")
623 return handleRequestSet(rcsRequest);
629 OCEntityHandlerResult RCSResourceObject::handleRequestGet(
630 const RCSRequest& request)
632 if (!findInterfaceHandler(request.getInterface()).isGetSupported())
637 auto attrs = getAttributesFromOCRequest(request.getOCRequest());
638 auto response = invokeHandler(shared_from_this(), attrs, request.getOCRequest(),
639 m_getRequestHandler);
641 if (response.isSeparate()) return OC_EH_SLOW;
643 return sendResponse(request, response,
644 findInterfaceHandler(request.getInterface()).getGetResponseBuilder());
647 bool RCSResourceObject::applyAcceptanceMethod(
648 const RCSSetResponse& response, const RCSResourceAttributes& requestAttrs)
650 auto requestHandler = response.getHandler();
652 assert(requestHandler != nullptr);
654 RCSResourceAttributes result;
656 auto replaced = requestHandler->applyAcceptanceMethod(response.getAcceptanceMethod(),
657 *this, requestAttrs);
659 OIC_LOG_V(WARNING, LOG_TAG, "replaced num %zu", replaced.size());
660 for (const auto& attrKeyValPair : replaced)
662 std::shared_ptr< AttributeUpdatedListener > foundListener;
664 std::lock_guard< std::mutex > lock(m_mutexAttributeUpdatedListeners);
666 auto it = m_attributeUpdatedListeners.find(attrKeyValPair.first);
667 if (it != m_attributeUpdatedListeners.end())
669 foundListener = it->second;
675 (*foundListener)(attrKeyValPair.second, requestAttrs.at(attrKeyValPair.first));
679 return !replaced.empty();
682 OCEntityHandlerResult RCSResourceObject::handleRequestSet(
683 const RCSRequest& request)
685 if (!findInterfaceHandler(request.getInterface()).isSetSupported())
690 auto attrs = getAttributesFromOCRequest(request.getOCRequest());
692 auto response = invokeHandler(shared_from_this(), attrs, request.getOCRequest(),
693 m_setRequestHandler);
695 if (response.isSeparate()) return OC_EH_SLOW;
697 autoNotify(applyAcceptanceMethod(response, attrs), m_autoNotifyPolicy);
699 return sendResponse(request, response,
700 findInterfaceHandler(request.getInterface()).getSetResponseBuilder());
703 OCEntityHandlerResult RCSResourceObject::handleObserve(
704 const std::shared_ptr< OC::OCResourceRequest >&)
714 InterfaceHandler RCSResourceObject::findInterfaceHandler(
715 const std::string& interfaceName) const
717 auto it = m_interfaceHandlers.find(interfaceName);
719 if (it != m_interfaceHandlers.end()) return it->second;
721 assert(m_interfaceHandlers.find(m_defaultInterface) != m_interfaceHandlers.end());
723 return m_interfaceHandlers.find(m_defaultInterface)->second;
726 template <typename RESPONSE, typename RESPONSE_BUILDER>
727 OCEntityHandlerResult RCSResourceObject::sendResponse(
728 const RCSRequest& request, const RESPONSE& response,
729 const RESPONSE_BUILDER& resBuilder)
731 auto reqHandler = response.getHandler();
732 auto ocResponse = std::make_shared< OC::OCResourceResponse >();
734 ocResponse->setResponseResult(OC_EH_OK);
735 ocResponse->setErrorCode(reqHandler->getErrorCode());
737 if (reqHandler->hasCustomRepresentation())
739 ocResponse->setResourceRepresentation(reqHandler->getRepresentation());
743 ocResponse->setResourceRepresentation(
744 RCSRepresentation::toOCRepresentation(resBuilder(request, *this)));
747 return ::sendResponse(request.getOCRequest(), ocResponse);
751 RCSResourceObject::LockGuard::LockGuard(const RCSResourceObject::Ptr ptr) :
752 m_resourceObject(*ptr),
753 m_autoNotifyPolicy{ ptr->getAutoNotifyPolicy() },
754 m_isOwningLock{ false }
759 RCSResourceObject::LockGuard::LockGuard(
760 const RCSResourceObject& serverResource) :
761 m_resourceObject(serverResource),
762 m_autoNotifyPolicy{ serverResource.getAutoNotifyPolicy() },
763 m_isOwningLock{ false }
768 RCSResourceObject::LockGuard::LockGuard(
769 const RCSResourceObject::Ptr ptr, AutoNotifyPolicy autoNotifyPolicy) :
770 m_resourceObject(*ptr),
771 m_autoNotifyPolicy { autoNotifyPolicy },
772 m_isOwningLock{ false }
777 RCSResourceObject::LockGuard::LockGuard(
778 const RCSResourceObject& resourceObject, AutoNotifyPolicy autoNotifyPolicy) :
779 m_resourceObject(resourceObject),
780 m_autoNotifyPolicy { autoNotifyPolicy },
781 m_isOwningLock{ false }
786 RCSResourceObject::LockGuard::~LockGuard() noexcept(false)
788 if (!std::uncaught_exception() && m_autoNotifyFunc) m_autoNotifyFunc();
792 m_resourceObject.setLockOwner(std::thread::id{ });
793 m_resourceObject.m_mutex.unlock();
797 void RCSResourceObject::LockGuard::init()
799 if (m_resourceObject.getLockOwner() != std::this_thread::get_id())
801 m_resourceObject.m_mutex.lock();
802 m_resourceObject.setLockOwner(std::this_thread::get_id());
803 m_isOwningLock = true;
805 m_autoNotifyFunc = ::createAutoNotifyInvoker(&RCSResourceObject::autoNotify,
806 m_resourceObject, m_resourceObject.m_resourceAttributes, m_autoNotifyPolicy);
809 RCSResourceObject::WeakGuard::WeakGuard(
810 const RCSResourceObject& resourceObject) :
811 m_isOwningLock{ false },
812 m_resourceObject(resourceObject)
814 if (m_resourceObject.getLockOwner() != std::this_thread::get_id())
816 m_resourceObject.m_mutex.lock();
817 m_resourceObject.setLockOwner(std::this_thread::get_id());
818 m_isOwningLock = true;
822 RCSResourceObject::WeakGuard::~WeakGuard()
826 m_resourceObject.setLockOwner(std::thread::id{ });
827 m_resourceObject.m_mutex.unlock();
831 bool RCSResourceObject::WeakGuard::hasLocked() const
833 return m_isOwningLock;