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"
25 #include "RequestHandler.h"
26 #include "AssertUtils.h"
27 #include "AtomicHelper.h"
28 #include "ResourceAttributesConverter.h"
29 #include "ResourceAttributesUtils.h"
30 #include "RCSRequest.h"
31 #include "RCSRepresentation.h"
32 #include "InterfaceHandler.h"
35 #include "OCPlatform.h"
37 #define LOG_TAG "RCSResourceObject"
41 using namespace OIC::Service;
43 inline bool hasProperty(uint8_t base, uint8_t target)
45 return (base & target) == target;
48 inline uint8_t makePropertyFlags(uint8_t base, uint8_t target, bool add)
55 return base & ~target;
58 OCEntityHandlerResult sendResponse(const std::shared_ptr< OC::OCResourceRequest >& ocRequest,
59 const std::shared_ptr< OC::OCResourceResponse >& ocResponse)
61 ocResponse->setRequestHandle(ocRequest->getRequestHandle());
62 ocResponse->setResourceHandle(ocRequest->getResourceHandle());
66 if (OC::OCPlatform::sendResponse(ocResponse) == OC_STACK_OK)
71 catch (const OC::OCException& e)
73 OIC_LOG_V(WARNING, LOG_TAG, "Error (%s)", e.what());
79 RCSResourceAttributes getAttributesFromOCRequest(
80 const std::shared_ptr< OC::OCResourceRequest >& request)
82 return ResourceAttributesConverter::fromOCRepresentation(
83 request->getResourceRepresentation());
86 template< typename HANDLER, typename RESPONSE =
87 typename std::decay<HANDLER>::type::result_type >
88 RESPONSE invokeHandler(RCSResourceAttributes& attrs, const RCSRequest& request,
89 std::shared_ptr< HANDLER > handler)
93 return (*handler)(request, attrs);
96 return RESPONSE::defaultAction();
99 typedef void (RCSResourceObject::* AutoNotifyFunc)
100 (bool, RCSResourceObject::AutoNotifyPolicy) const;
102 std::function<void()> createAutoNotifyInvoker(AutoNotifyFunc autoNotifyFunc,
103 const RCSResourceObject& resourceObject,
104 const RCSResourceAttributes& resourceAttributes,
105 RCSResourceObject::AutoNotifyPolicy autoNotifyPolicy)
107 if(autoNotifyPolicy == RCSResourceObject::AutoNotifyPolicy::UPDATED)
109 auto&& compareAttributesFunc =
110 std::bind(std::not_equal_to<RCSResourceAttributes>(),
112 std::cref(resourceAttributes));
113 return std::bind(autoNotifyFunc,
114 &resourceObject, std::move(compareAttributesFunc), autoNotifyPolicy);
116 else if(autoNotifyPolicy == RCSResourceObject::AutoNotifyPolicy::ALWAYS)
118 return std::bind(autoNotifyFunc,
119 &resourceObject, true, autoNotifyPolicy);
124 } // unnamed namespace
131 RCSResourceObject::Builder::Builder(std::string uri, std::string type,
132 std::string interface) :
133 m_uri{ std::move(uri) },
134 m_types{ std::move(type) },
135 m_interfaces{ std::move(interface) },
136 m_defaultInterface { BASELINE_INTERFACE },
137 m_properties{ OC_DISCOVERABLE | OC_OBSERVABLE },
138 m_resourceAttributes{ }
142 RCSResourceObject::Builder& RCSResourceObject::Builder::addInterface(std::string interface)
144 m_interfaces.push_back(std::move(interface));
148 RCSResourceObject::Builder& RCSResourceObject::Builder::addType(std::string type)
150 m_types.push_back(std::move(type));
154 RCSResourceObject::Builder& RCSResourceObject::Builder::setDefaultInterface(
155 std::string interface)
157 if (std::find(m_interfaces.begin(), m_interfaces.end(), interface) ==
160 throw RCSBadRequestException{"The interface should be added, first."};
163 m_defaultInterface = std::move(interface);
168 RCSResourceObject::Builder& RCSResourceObject::Builder::setDiscoverable(
171 m_properties = ::makePropertyFlags(m_properties, OC_DISCOVERABLE, discoverable);
175 RCSResourceObject::Builder& RCSResourceObject::Builder::setObservable(
178 m_properties = ::makePropertyFlags(m_properties, OC_OBSERVABLE, observable);
182 RCSResourceObject::Builder& RCSResourceObject::Builder::setSecureFlag(
185 m_properties = ::makePropertyFlags(m_properties, OC_SECURE, secureFlag);
188 RCSResourceObject::Builder& RCSResourceObject::Builder::setAttributes(
189 const RCSResourceAttributes& attrs)
191 m_resourceAttributes = attrs;
195 RCSResourceObject::Builder& RCSResourceObject::Builder::setAttributes(
196 RCSResourceAttributes&& attrs)
198 m_resourceAttributes = std::move(attrs);
202 RCSResourceObject::Ptr RCSResourceObject::Builder::build()
204 OCResourceHandle handle{ nullptr };
206 RCSResourceObject::Ptr server {
207 new RCSResourceObject{ m_uri, m_properties, std::move(m_resourceAttributes) } };
209 OC::EntityHandler entityHandler{ std::bind(&RCSResourceObject::entityHandler,
210 std::weak_ptr< RCSResourceObject >{ server }, std::placeholders::_1) };
212 typedef OCStackResult (*RegisterResource)(OCResourceHandle&, std::string&,
213 const std::string&, const std::string&, OC::EntityHandler, uint8_t);
215 invokeOCFunc(static_cast<RegisterResource>(OC::OCPlatform::registerResource),
216 handle, m_uri, m_types[0], m_interfaces[0], entityHandler, m_properties);
218 std::for_each(m_interfaces.begin() + 1, m_interfaces.end(),
219 [&handle](const std::string& interfaceName){
220 invokeOCFunc(OC::OCPlatform::bindInterfaceToResource, handle, interfaceName);
223 std::for_each(m_types.begin() + 1, m_types.end(),
224 [&handle](const std::string& typeName){
225 invokeOCFunc(OC::OCPlatform::bindTypeToResource, handle, typeName);
228 server->init(handle, m_interfaces, m_types, m_defaultInterface);
234 RCSResourceObject::RCSResourceObject(const std::string& uri,
235 uint8_t properties, RCSResourceAttributes&& attrs) :
236 m_properties{ properties },
240 m_defaultInterface{ },
242 m_resourceAttributes{ std::move(attrs) },
243 m_getRequestHandler{ },
244 m_setRequestHandler{ },
245 m_autoNotifyPolicy{ AutoNotifyPolicy::UPDATED },
246 m_setRequestHandlerPolicy{ SetRequestHandlerPolicy::NEVER },
247 m_attributeUpdatedListeners{ },
250 m_mutexAttributeUpdatedListeners{ }
252 m_lockOwner.reset(new AtomicThreadId);
255 void RCSResourceObject::init(OCResourceHandle handle,
256 const std::vector< std::string >& interfaces,
257 const std::vector< std::string >& types,
258 const std::string& defaultInterface)
260 m_resourceHandle = handle;
261 m_interfaces = interfaces;
263 m_defaultInterface = defaultInterface;
265 for (const auto& itf : interfaces)
267 m_interfaceHandlers.insert({ itf, getDefaultInterfaceHandler(itf,
268 m_defaultInterface) });
272 RCSResourceObject::~RCSResourceObject()
274 if (m_resourceHandle)
278 invokeOCFunc(OC::OCPlatform::unregisterResource, m_resourceHandle);
282 OIC_LOG(WARNING, LOG_TAG, "Failed to unregister resource.");
287 template< typename K, typename V >
288 void RCSResourceObject::setAttributeInternal(K&& key, V&& value)
290 bool needToNotify = false;
291 bool valueUpdated = false;
294 WeakGuard lock(*this);
296 if (lock.hasLocked())
299 valueUpdated = testValueUpdated(key, value);
302 m_resourceAttributes[std::forward< K >(key)] = std::forward< V >(value);
305 if (needToNotify) autoNotify(valueUpdated);
307 void RCSResourceObject::setAttribute(const std::string& key,
308 const RCSResourceAttributes::Value& value)
310 setAttributeInternal(key, value);
313 void RCSResourceObject::setAttribute(const std::string& key,
314 RCSResourceAttributes::Value&& value)
316 setAttributeInternal(key, std::move(value));
319 void RCSResourceObject::setAttribute(std::string&& key,
320 const RCSResourceAttributes::Value& value)
322 setAttributeInternal(std::move(key), value);
325 void RCSResourceObject::setAttribute(std::string&& key,
326 RCSResourceAttributes::Value&& value)
328 setAttributeInternal(std::move(key), std::move(value));
331 RCSResourceAttributes::Value RCSResourceObject::getAttributeValue(
332 const std::string& key) const
334 WeakGuard lock(*this);
335 return m_resourceAttributes.at(key);
338 bool RCSResourceObject::removeAttribute(const std::string& key)
340 bool needToNotify = false;
343 WeakGuard lock(*this);
345 if (m_resourceAttributes.erase(key))
348 needToNotify = lock.hasLocked();
352 if (needToNotify) autoNotify(true);
357 bool RCSResourceObject::containsAttribute(const std::string& key) const
359 WeakGuard lock(*this);
360 return m_resourceAttributes.contains(key);
363 RCSResourceAttributes& RCSResourceObject::getAttributes()
366 return m_resourceAttributes;
369 const RCSResourceAttributes& RCSResourceObject::getAttributes() const
372 return m_resourceAttributes;
375 void RCSResourceObject::expectOwnLock() const
377 if (getLockOwner() != std::this_thread::get_id())
379 throw NoLockException{ "Must acquire the lock first using LockGuard." };
383 std::thread::id RCSResourceObject::getLockOwner() const noexcept
388 void RCSResourceObject::setLockOwner(std::thread::id&& id) const noexcept
390 m_lockOwner->store(std::move(id));
393 bool RCSResourceObject::isObservable() const
395 return ::hasProperty(m_properties, OC_OBSERVABLE);
398 bool RCSResourceObject::isDiscoverable() const
400 return ::hasProperty(m_properties, OC_DISCOVERABLE);
403 void RCSResourceObject::setGetRequestHandler(GetRequestHandler h)
405 m_getRequestHandler = std::make_shared< GetRequestHandler >(std::move(h));
408 void RCSResourceObject::setSetRequestHandler(SetRequestHandler h)
410 m_setRequestHandler = std::make_shared< SetRequestHandler >(std::move(h));
413 void RCSResourceObject::notify() const
415 typedef OCStackResult (*NotifyAllObservers)(OCResourceHandle);
417 invokeOCFuncWithResultExpect({ OC_STACK_OK, OC_STACK_NO_OBSERVERS },
418 static_cast< NotifyAllObservers >(OC::OCPlatform::notifyAllObservers),
422 void RCSResourceObject::addAttributeUpdatedListener(const std::string& key,
423 AttributeUpdatedListener h)
425 std::lock_guard< std::mutex > lock(m_mutexAttributeUpdatedListeners);
427 m_attributeUpdatedListeners[key] =
428 std::make_shared< AttributeUpdatedListener >(std::move(h));
431 void RCSResourceObject::addAttributeUpdatedListener(std::string&& key,
432 AttributeUpdatedListener h)
434 std::lock_guard< std::mutex > lock(m_mutexAttributeUpdatedListeners);
436 m_attributeUpdatedListeners[std::move(key)] =
437 std::make_shared< AttributeUpdatedListener >(std::move(h));
440 bool RCSResourceObject::removeAttributeUpdatedListener(const std::string& key)
442 std::lock_guard< std::mutex > lock(m_mutexAttributeUpdatedListeners);
444 return m_attributeUpdatedListeners.erase(key) != 0;
447 bool RCSResourceObject::testValueUpdated(const std::string& key,
448 const RCSResourceAttributes::Value& value) const
450 return m_resourceAttributes.contains(key) == false
451 || m_resourceAttributes.at(key) != value;
454 void RCSResourceObject::setAutoNotifyPolicy(AutoNotifyPolicy policy)
456 m_autoNotifyPolicy = policy;
459 RCSResourceObject::AutoNotifyPolicy RCSResourceObject::getAutoNotifyPolicy() const
461 return m_autoNotifyPolicy;
464 void RCSResourceObject::setSetRequestHandlerPolicy(SetRequestHandlerPolicy policy)
466 m_setRequestHandlerPolicy = policy;
469 auto RCSResourceObject::getSetRequestHandlerPolicy() const -> SetRequestHandlerPolicy
471 return m_setRequestHandlerPolicy;
474 void RCSResourceObject::bindResource(const RCSResourceObject::Ptr& resource)
476 if (!resource || resource.get() == this)
478 throw RCSInvalidParameterException("The resource is invalid!");
481 invokeOCFunc(OC::OCPlatform::bindResource,
482 m_resourceHandle, resource->m_resourceHandle);
484 std::lock_guard< std:: mutex > lock{ m_mutexForBoundResources };
485 m_boundResources.push_back(resource);
488 void RCSResourceObject::unbindResource(const RCSResourceObject::Ptr& resource)
490 if (!resource || resource.get() == this)
492 throw RCSInvalidParameterException("The resource is invalid!");
495 invokeOCFunc(OC::OCPlatform::unbindResource,
496 m_resourceHandle, resource->m_resourceHandle);
498 std::lock_guard< std:: mutex > lock{ m_mutexForBoundResources };
499 m_boundResources.erase(std::find(m_boundResources.begin(), m_boundResources.end(),
503 std::vector< RCSResourceObject::Ptr > RCSResourceObject::getBoundResources() const
505 std::lock_guard< std:: mutex > lock{ m_mutexForBoundResources };
506 return m_boundResources;
509 std::string RCSResourceObject::getUri() const
514 std::string RCSResourceObject::getDefaultInterface() const
516 return m_defaultInterface;
519 std::vector< std::string > RCSResourceObject::getInterfaces() const
524 std::vector< std::string > RCSResourceObject::getTypes() const
529 RCSRepresentation RCSResourceObject::getRepresentation(const RCSRequest& request) const
531 if (request.getOCRequest()->getRequestType() == "GET")
533 return findInterfaceHandler(
534 request.getInterface()).getGetResponseBuilder()(request, *this);
537 if (request.getOCRequest()->getRequestType() == "POST")
539 return findInterfaceHandler(
540 request.getInterface()).getSetResponseBuilder()(request, *this);
543 throw RCSBadRequestException{ "Unsupported request type!" };
546 void RCSResourceObject::autoNotify(bool isAttributesChanged) const
548 autoNotify(isAttributesChanged, m_autoNotifyPolicy);
551 void RCSResourceObject::autoNotify(
552 bool isAttributesChanged, AutoNotifyPolicy autoNotifyPolicy) const
554 if(autoNotifyPolicy == AutoNotifyPolicy::NEVER) return;
555 if(autoNotifyPolicy == AutoNotifyPolicy::UPDATED &&
556 isAttributesChanged == false) return;
561 OCEntityHandlerResult RCSResourceObject::entityHandler(
562 const std::weak_ptr< RCSResourceObject >& weakRes,
563 const std::shared_ptr< OC::OCResourceRequest >& request)
565 auto resource = weakRes.lock();
567 if (!resource) return OC_EH_ERROR;
569 OIC_LOG(WARNING, LOG_TAG, "entityHandler");
577 RCSRequest rcsRequest{ resource, request };
579 if (request->getRequestHandlerFlag() & OC::RequestHandlerFlag::RequestFlag)
581 return resource->handleRequest(rcsRequest);
584 if (request->getRequestHandlerFlag() & OC::RequestHandlerFlag::ObserverFlag)
586 return resource->handleObserve(rcsRequest);
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 RCSRequest& request)
606 if (request.getInterface() != "" &&
607 m_interfaceHandlers.find(request.getInterface()) == m_interfaceHandlers.end())
612 if (request.getOCRequest()->getRequestType() == "GET")
614 return handleRequestGet(request);
617 if (request.getOCRequest()->getRequestType() == "POST")
619 return handleRequestSet(request);
625 OCEntityHandlerResult RCSResourceObject::handleRequestGet(const RCSRequest& request)
627 if (!findInterfaceHandler(request.getInterface()).isGetSupported())
632 auto attrs = getAttributesFromOCRequest(request.getOCRequest());
634 auto response = invokeHandler(attrs, request, m_getRequestHandler);
636 if (response.isSeparate()) return OC_EH_SLOW;
638 return sendResponse(request, response,
639 findInterfaceHandler(request.getInterface()).getGetResponseBuilder());
642 bool RCSResourceObject::applyAcceptanceMethod(
643 const RCSSetResponse& response, const RCSResourceAttributes& requestAttrs)
645 auto requestHandler = response.getHandler();
647 assert(requestHandler != nullptr);
649 RCSResourceAttributes result;
651 auto replaced = requestHandler->applyAcceptanceMethod(response.getAcceptanceMethod(),
652 *this, requestAttrs);
654 OIC_LOG_V(WARNING, LOG_TAG, "replaced num %zu", replaced.size());
655 for (const auto& attrKeyValPair : replaced)
657 std::shared_ptr< AttributeUpdatedListener > foundListener;
659 std::lock_guard< std::mutex > lock(m_mutexAttributeUpdatedListeners);
661 auto it = m_attributeUpdatedListeners.find(attrKeyValPair.first);
662 if (it != m_attributeUpdatedListeners.end())
664 foundListener = it->second;
670 (*foundListener)(attrKeyValPair.second, requestAttrs.at(attrKeyValPair.first));
674 return !replaced.empty();
677 OCEntityHandlerResult RCSResourceObject::handleRequestSet(const RCSRequest& request)
679 if (!findInterfaceHandler(request.getInterface()).isSetSupported())
684 auto attrs = getAttributesFromOCRequest(request.getOCRequest());
686 auto response = invokeHandler(attrs, request, m_setRequestHandler);
688 if (response.isSeparate()) return OC_EH_SLOW;
690 autoNotify(applyAcceptanceMethod(response, attrs), m_autoNotifyPolicy);
692 return sendResponse(request, response,
693 findInterfaceHandler(request.getInterface()).getSetResponseBuilder());
696 OCEntityHandlerResult RCSResourceObject::handleObserve(const RCSRequest&)
706 InterfaceHandler RCSResourceObject::findInterfaceHandler(
707 const std::string& interfaceName) const
709 auto it = m_interfaceHandlers.find(interfaceName);
711 if (it != m_interfaceHandlers.end()) return it->second;
713 assert(m_interfaceHandlers.find(m_defaultInterface) != m_interfaceHandlers.end());
715 return m_interfaceHandlers.find(m_defaultInterface)->second;
718 template <typename RESPONSE, typename RESPONSE_BUILDER>
719 OCEntityHandlerResult RCSResourceObject::sendResponse(
720 const RCSRequest& request, const RESPONSE& response,
721 const RESPONSE_BUILDER& resBuilder)
723 auto reqHandler = response.getHandler();
724 auto ocResponse = std::make_shared< OC::OCResourceResponse >();
726 ocResponse->setResponseResult(OC_EH_OK);
727 ocResponse->setErrorCode(reqHandler->getErrorCode());
729 if (reqHandler->hasCustomRepresentation())
731 ocResponse->setResourceRepresentation(reqHandler->getRepresentation());
735 ocResponse->setResourceRepresentation(
736 RCSRepresentation::toOCRepresentation(resBuilder(request, *this)));
739 return ::sendResponse(request.getOCRequest(), ocResponse);
743 RCSResourceObject::LockGuard::LockGuard(const RCSResourceObject::Ptr ptr) :
744 m_resourceObject(*ptr),
745 m_autoNotifyPolicy{ ptr->getAutoNotifyPolicy() },
746 m_isOwningLock{ false }
751 RCSResourceObject::LockGuard::LockGuard(
752 const RCSResourceObject& serverResource) :
753 m_resourceObject(serverResource),
754 m_autoNotifyPolicy{ serverResource.getAutoNotifyPolicy() },
755 m_isOwningLock{ false }
760 RCSResourceObject::LockGuard::LockGuard(
761 const RCSResourceObject::Ptr ptr, AutoNotifyPolicy autoNotifyPolicy) :
762 m_resourceObject(*ptr),
763 m_autoNotifyPolicy { autoNotifyPolicy },
764 m_isOwningLock{ false }
769 RCSResourceObject::LockGuard::LockGuard(
770 const RCSResourceObject& resourceObject, AutoNotifyPolicy autoNotifyPolicy) :
771 m_resourceObject(resourceObject),
772 m_autoNotifyPolicy { autoNotifyPolicy },
773 m_isOwningLock{ false }
778 RCSResourceObject::LockGuard::~LockGuard() noexcept(false)
780 if (!std::uncaught_exception() && m_autoNotifyFunc) m_autoNotifyFunc();
784 m_resourceObject.setLockOwner(std::thread::id{ });
785 m_resourceObject.m_mutex.unlock();
789 void RCSResourceObject::LockGuard::init()
791 if (m_resourceObject.getLockOwner() != std::this_thread::get_id())
793 m_resourceObject.m_mutex.lock();
794 m_resourceObject.setLockOwner(std::this_thread::get_id());
795 m_isOwningLock = true;
797 m_autoNotifyFunc = ::createAutoNotifyInvoker(&RCSResourceObject::autoNotify,
798 m_resourceObject, m_resourceObject.m_resourceAttributes, m_autoNotifyPolicy);
801 RCSResourceObject::WeakGuard::WeakGuard(
802 const RCSResourceObject& resourceObject) :
803 m_isOwningLock{ false },
804 m_resourceObject(resourceObject)
806 if (m_resourceObject.getLockOwner() != std::this_thread::get_id())
808 m_resourceObject.m_mutex.lock();
809 m_resourceObject.setLockOwner(std::this_thread::get_id());
810 m_isOwningLock = true;
814 RCSResourceObject::WeakGuard::~WeakGuard()
818 m_resourceObject.setLockOwner(std::thread::id{ });
819 m_resourceObject.m_mutex.unlock();
823 bool RCSResourceObject::WeakGuard::hasLocked() const
825 return m_isOwningLock;