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)
91 if (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 void insertValue(std::vector<std::string>& container, std::string value)
126 if (value.empty()) return;
128 if (std::find(container.begin(), container.end(), value) == container.end())
130 container.push_back(std::move(value));
134 } // unnamed namespace
141 RCSResourceObject::Builder::Builder(std::string uri, std::string type,
142 std::string interface) :
143 m_uri{ std::move(uri) },
144 m_types{ std::move(type) },
146 m_defaultInterface{ interface },
147 m_properties{ OC_DISCOVERABLE | OC_OBSERVABLE },
148 m_resourceAttributes{ }
150 addInterface(interface);
151 addInterface(BASELINE_INTERFACE);
153 if (m_defaultInterface.empty())
155 m_defaultInterface = BASELINE_INTERFACE;
159 RCSResourceObject::Builder& RCSResourceObject::Builder::addInterface(std::string interface)
161 insertValue(m_interfaces, std::move(interface));
165 RCSResourceObject::Builder& RCSResourceObject::Builder::addType(std::string type)
167 insertValue(m_types, std::move(type));
171 RCSResourceObject::Builder& RCSResourceObject::Builder::setDefaultInterface(
172 std::string interface)
174 if (std::find(m_interfaces.begin(), m_interfaces.end(), interface) ==
177 throw RCSBadRequestException{"The interface should be added, first."};
180 m_defaultInterface = std::move(interface);
185 RCSResourceObject::Builder& RCSResourceObject::Builder::setDiscoverable(
188 m_properties = ::makePropertyFlags(m_properties, OC_DISCOVERABLE, discoverable);
192 RCSResourceObject::Builder& RCSResourceObject::Builder::setObservable(
195 m_properties = ::makePropertyFlags(m_properties, OC_OBSERVABLE, observable);
199 RCSResourceObject::Builder& RCSResourceObject::Builder::setSecureFlag(
202 m_properties = ::makePropertyFlags(m_properties, OC_SECURE, secureFlag);
205 RCSResourceObject::Builder& RCSResourceObject::Builder::setAttributes(
206 const RCSResourceAttributes& attrs)
208 m_resourceAttributes = attrs;
212 RCSResourceObject::Builder& RCSResourceObject::Builder::setAttributes(
213 RCSResourceAttributes&& attrs)
215 m_resourceAttributes = std::move(attrs);
219 RCSResourceObject::Ptr RCSResourceObject::Builder::build()
221 OCResourceHandle handle{ nullptr };
223 RCSResourceObject::Ptr server {
224 new RCSResourceObject{ m_uri, m_properties, std::move(m_resourceAttributes) } };
226 OC::EntityHandler entityHandler{ std::bind(&RCSResourceObject::entityHandler,
227 std::weak_ptr< RCSResourceObject >{ server }, std::placeholders::_1) };
229 typedef OCStackResult (*RegisterResource)(OCResourceHandle&, std::string&,
230 const std::string&, const std::string&, OC::EntityHandler, uint8_t);
232 invokeOCFunc(static_cast<RegisterResource>(OC::OCPlatform::registerResource),
233 handle, m_uri, m_types[0], m_interfaces[0], entityHandler, m_properties);
235 std::for_each(m_interfaces.begin() + 1, m_interfaces.end(),
236 [&handle](const std::string& interfaceName){
237 invokeOCFunc(OC::OCPlatform::bindInterfaceToResource, handle, interfaceName);
240 std::for_each(m_types.begin() + 1, m_types.end(),
241 [&handle](const std::string& typeName){
242 invokeOCFunc(OC::OCPlatform::bindTypeToResource, handle, typeName);
245 server->init(handle, m_interfaces, m_types, m_defaultInterface);
251 RCSResourceObject::RCSResourceObject(const std::string& uri,
252 uint8_t properties, RCSResourceAttributes&& attrs) :
253 m_properties{ properties },
257 m_defaultInterface{ },
259 m_resourceAttributes{ std::move(attrs) },
260 m_getRequestHandler{ },
261 m_setRequestHandler{ },
262 m_autoNotifyPolicy{ AutoNotifyPolicy::UPDATED },
263 m_setRequestHandlerPolicy{ SetRequestHandlerPolicy::NEVER },
264 m_attributeUpdatedListeners{ },
267 m_mutexAttributeUpdatedListeners{ }
269 m_lockOwner.reset(new AtomicThreadId);
272 void RCSResourceObject::init(OCResourceHandle handle,
273 const std::vector< std::string >& interfaces,
274 const std::vector< std::string >& types,
275 const std::string& defaultInterface)
277 m_resourceHandle = handle;
278 m_interfaces = interfaces;
280 m_defaultInterface = defaultInterface;
282 for (const auto& itf : interfaces)
284 m_interfaceHandlers.insert({ itf, getDefaultInterfaceHandler(itf,
285 m_defaultInterface) });
289 RCSResourceObject::~RCSResourceObject()
291 if (m_resourceHandle)
295 invokeOCFunc(OC::OCPlatform::unregisterResource, m_resourceHandle);
299 OIC_LOG(WARNING, LOG_TAG, "Failed to unregister resource.");
304 template< typename K, typename V >
305 void RCSResourceObject::setAttributeInternal(K&& key, V&& value)
307 bool needToNotify = false;
308 bool valueUpdated = false;
311 WeakGuard lock(*this);
313 if (lock.hasLocked())
316 valueUpdated = testValueUpdated(key, value);
319 m_resourceAttributes[std::forward< K >(key)] = std::forward< V >(value);
322 if (needToNotify) autoNotify(valueUpdated);
324 void RCSResourceObject::setAttribute(const std::string& key,
325 const RCSResourceAttributes::Value& value)
327 setAttributeInternal(key, value);
330 void RCSResourceObject::setAttribute(const std::string& key,
331 RCSResourceAttributes::Value&& value)
333 setAttributeInternal(key, std::move(value));
336 void RCSResourceObject::setAttribute(std::string&& key,
337 const RCSResourceAttributes::Value& value)
339 setAttributeInternal(std::move(key), value);
342 void RCSResourceObject::setAttribute(std::string&& key,
343 RCSResourceAttributes::Value&& value)
345 setAttributeInternal(std::move(key), std::move(value));
348 RCSResourceAttributes::Value RCSResourceObject::getAttributeValue(
349 const std::string& key) const
351 WeakGuard lock(*this);
352 return m_resourceAttributes.at(key);
355 bool RCSResourceObject::removeAttribute(const std::string& key)
357 bool needToNotify = false;
360 WeakGuard lock(*this);
362 if (m_resourceAttributes.erase(key))
365 needToNotify = lock.hasLocked();
369 if (needToNotify) autoNotify(true);
374 bool RCSResourceObject::containsAttribute(const std::string& key) const
376 WeakGuard lock(*this);
377 return m_resourceAttributes.contains(key);
380 RCSResourceAttributes& RCSResourceObject::getAttributes()
383 return m_resourceAttributes;
386 const RCSResourceAttributes& RCSResourceObject::getAttributes() const
389 return m_resourceAttributes;
392 void RCSResourceObject::expectOwnLock() const
394 if (getLockOwner() != std::this_thread::get_id())
396 throw NoLockException{ "Must acquire the lock first using LockGuard." };
400 std::thread::id RCSResourceObject::getLockOwner() const noexcept
405 void RCSResourceObject::setLockOwner(std::thread::id&& id) const noexcept
407 m_lockOwner->store(std::move(id));
410 bool RCSResourceObject::isObservable() const
412 return ::hasProperty(m_properties, OC_OBSERVABLE);
415 bool RCSResourceObject::isDiscoverable() const
417 return ::hasProperty(m_properties, OC_DISCOVERABLE);
420 void RCSResourceObject::setGetRequestHandler(GetRequestHandler h)
422 m_getRequestHandler = std::make_shared< GetRequestHandler >(std::move(h));
425 void RCSResourceObject::setSetRequestHandler(SetRequestHandler h)
427 m_setRequestHandler = std::make_shared< SetRequestHandler >(std::move(h));
430 void RCSResourceObject::notify() const
432 typedef OCStackResult (*NotifyAllObservers)(OCResourceHandle);
434 invokeOCFuncWithResultExpect({ OC_STACK_OK, OC_STACK_NO_OBSERVERS },
435 static_cast< NotifyAllObservers >(OC::OCPlatform::notifyAllObservers),
439 void RCSResourceObject::addAttributeUpdatedListener(const std::string& key,
440 AttributeUpdatedListener h)
442 std::lock_guard< std::mutex > lock(m_mutexAttributeUpdatedListeners);
444 m_attributeUpdatedListeners[key] =
445 std::make_shared< AttributeUpdatedListener >(std::move(h));
448 void RCSResourceObject::addAttributeUpdatedListener(std::string&& key,
449 AttributeUpdatedListener h)
451 std::lock_guard< std::mutex > lock(m_mutexAttributeUpdatedListeners);
453 m_attributeUpdatedListeners[std::move(key)] =
454 std::make_shared< AttributeUpdatedListener >(std::move(h));
457 bool RCSResourceObject::removeAttributeUpdatedListener(const std::string& key)
459 std::lock_guard< std::mutex > lock(m_mutexAttributeUpdatedListeners);
461 return m_attributeUpdatedListeners.erase(key) != 0;
464 bool RCSResourceObject::testValueUpdated(const std::string& key,
465 const RCSResourceAttributes::Value& value) const
467 return m_resourceAttributes.contains(key) == false
468 || m_resourceAttributes.at(key) != value;
471 void RCSResourceObject::setAutoNotifyPolicy(AutoNotifyPolicy policy)
473 m_autoNotifyPolicy = policy;
476 RCSResourceObject::AutoNotifyPolicy RCSResourceObject::getAutoNotifyPolicy() const
478 return m_autoNotifyPolicy;
481 void RCSResourceObject::setSetRequestHandlerPolicy(SetRequestHandlerPolicy policy)
483 m_setRequestHandlerPolicy = policy;
486 auto RCSResourceObject::getSetRequestHandlerPolicy() const -> SetRequestHandlerPolicy
488 return m_setRequestHandlerPolicy;
491 void RCSResourceObject::bindResource(const RCSResourceObject::Ptr& resource)
493 if (!resource || resource.get() == this)
495 throw RCSInvalidParameterException("The resource is invalid!");
498 invokeOCFunc(OC::OCPlatform::bindResource,
499 m_resourceHandle, resource->m_resourceHandle);
501 std::lock_guard< std:: mutex > lock{ m_mutexForBoundResources };
502 m_boundResources.push_back(resource);
505 void RCSResourceObject::unbindResource(const RCSResourceObject::Ptr& resource)
507 if (!resource || resource.get() == this)
509 throw RCSInvalidParameterException("The resource is invalid!");
512 invokeOCFunc(OC::OCPlatform::unbindResource,
513 m_resourceHandle, resource->m_resourceHandle);
515 std::lock_guard< std:: mutex > lock{ m_mutexForBoundResources };
516 m_boundResources.erase(std::find(m_boundResources.begin(), m_boundResources.end(),
520 std::vector< RCSResourceObject::Ptr > RCSResourceObject::getBoundResources() const
522 std::lock_guard< std:: mutex > lock{ m_mutexForBoundResources };
523 return m_boundResources;
526 std::string RCSResourceObject::getUri() const
531 std::string RCSResourceObject::getDefaultInterface() const
533 return m_defaultInterface;
536 std::vector< std::string > RCSResourceObject::getInterfaces() const
541 std::vector< std::string > RCSResourceObject::getTypes() const
546 RCSRepresentation RCSResourceObject::getRepresentation(const RCSRequest& request) const
548 if (request.getOCRequest()->getRequestType() == "GET")
550 return findInterfaceHandler(
551 request.getInterface()).getGetResponseBuilder()(request, *this);
554 if (request.getOCRequest()->getRequestType() == "POST")
556 return findInterfaceHandler(
557 request.getInterface()).getSetResponseBuilder()(request, *this);
560 throw RCSBadRequestException{ "Unsupported request type!" };
563 void RCSResourceObject::autoNotify(bool isAttributesChanged) const
565 autoNotify(isAttributesChanged, m_autoNotifyPolicy);
568 void RCSResourceObject::autoNotify(
569 bool isAttributesChanged, AutoNotifyPolicy autoNotifyPolicy) const
571 if(autoNotifyPolicy == AutoNotifyPolicy::NEVER) return;
572 if(autoNotifyPolicy == AutoNotifyPolicy::UPDATED &&
573 isAttributesChanged == false) return;
578 OCEntityHandlerResult RCSResourceObject::entityHandler(
579 const std::weak_ptr< RCSResourceObject >& weakRes,
580 const std::shared_ptr< OC::OCResourceRequest >& request)
582 auto resource = weakRes.lock();
584 if (!resource) return OC_EH_ERROR;
586 OIC_LOG(WARNING, LOG_TAG, "entityHandler");
594 RCSRequest rcsRequest{ resource, request };
596 if (request->getRequestHandlerFlag() & OC::RequestHandlerFlag::RequestFlag)
598 return resource->handleRequest(rcsRequest);
601 if (request->getRequestHandlerFlag() & OC::RequestHandlerFlag::ObserverFlag)
603 return resource->handleObserve(rcsRequest);
606 catch (const std::exception& e)
608 OIC_LOG_V(WARNING, LOG_TAG, "Failed to handle request : %s", e.what());
613 OIC_LOG(WARNING, LOG_TAG, "Failed to handle request.");
620 OCEntityHandlerResult RCSResourceObject::handleRequest(
621 const RCSRequest& request)
623 if (request.getInterface() != "" &&
624 m_interfaceHandlers.find(request.getInterface()) == m_interfaceHandlers.end())
629 if (request.getOCRequest()->getRequestType() == "GET")
631 return handleRequestGet(request);
634 if (request.getOCRequest()->getRequestType() == "POST")
636 return handleRequestSet(request);
642 OCEntityHandlerResult RCSResourceObject::handleRequestGet(const RCSRequest& request)
644 if (!findInterfaceHandler(request.getInterface()).isGetSupported())
649 auto attrs = getAttributesFromOCRequest(request.getOCRequest());
651 auto response = invokeHandler(attrs, request, m_getRequestHandler);
653 if (response.isSeparate()) return OC_EH_SLOW;
655 return sendResponse(request, response,
656 findInterfaceHandler(request.getInterface()).getGetResponseBuilder());
659 bool RCSResourceObject::applyAcceptanceMethod(
660 const RCSSetResponse& response, const RCSResourceAttributes& requestAttrs)
662 auto requestHandler = response.getHandler();
664 assert(requestHandler != nullptr);
666 RCSResourceAttributes result;
668 auto replaced = requestHandler->applyAcceptanceMethod(response.getAcceptanceMethod(),
669 *this, requestAttrs);
671 OIC_LOG_V(WARNING, LOG_TAG, "replaced num %zu", replaced.size());
672 for (const auto& attrKeyValPair : replaced)
674 std::shared_ptr< AttributeUpdatedListener > foundListener;
676 std::lock_guard< std::mutex > lock(m_mutexAttributeUpdatedListeners);
678 auto it = m_attributeUpdatedListeners.find(attrKeyValPair.first);
679 if (it != m_attributeUpdatedListeners.end())
681 foundListener = it->second;
687 (*foundListener)(attrKeyValPair.second, requestAttrs.at(attrKeyValPair.first));
691 return !replaced.empty();
694 OCEntityHandlerResult RCSResourceObject::handleRequestSet(const RCSRequest& request)
696 if (!findInterfaceHandler(request.getInterface()).isSetSupported())
701 auto attrs = getAttributesFromOCRequest(request.getOCRequest());
703 auto response = invokeHandler(attrs, request, m_setRequestHandler);
705 if (response.isSeparate()) return OC_EH_SLOW;
707 autoNotify(applyAcceptanceMethod(response, attrs), m_autoNotifyPolicy);
709 return sendResponse(request, response,
710 findInterfaceHandler(request.getInterface()).getSetResponseBuilder());
713 OCEntityHandlerResult RCSResourceObject::handleObserve(const RCSRequest&)
723 InterfaceHandler RCSResourceObject::findInterfaceHandler(
724 const std::string& interfaceName) const
726 auto it = m_interfaceHandlers.find(interfaceName);
728 if (it != m_interfaceHandlers.end()) return it->second;
730 assert(m_interfaceHandlers.find(m_defaultInterface) != m_interfaceHandlers.end());
732 return m_interfaceHandlers.find(m_defaultInterface)->second;
735 template <typename RESPONSE, typename RESPONSE_BUILDER>
736 OCEntityHandlerResult RCSResourceObject::sendResponse(
737 const RCSRequest& request, const RESPONSE& response,
738 const RESPONSE_BUILDER& resBuilder)
740 auto reqHandler = response.getHandler();
741 auto ocResponse = std::make_shared< OC::OCResourceResponse >();
743 ocResponse->setResponseResult(OC_EH_OK);
744 ocResponse->setErrorCode(reqHandler->getErrorCode());
746 if (reqHandler->hasCustomRepresentation())
748 ocResponse->setResourceRepresentation(reqHandler->getRepresentation());
752 ocResponse->setResourceRepresentation(
753 RCSRepresentation::toOCRepresentation(resBuilder(request, *this)));
756 return ::sendResponse(request.getOCRequest(), ocResponse);
760 RCSResourceObject::LockGuard::LockGuard(const RCSResourceObject::Ptr ptr) :
761 m_resourceObject(*ptr),
762 m_autoNotifyPolicy{ ptr->getAutoNotifyPolicy() },
763 m_isOwningLock{ false }
768 RCSResourceObject::LockGuard::LockGuard(
769 const RCSResourceObject& serverResource) :
770 m_resourceObject(serverResource),
771 m_autoNotifyPolicy{ serverResource.getAutoNotifyPolicy() },
772 m_isOwningLock{ false }
777 RCSResourceObject::LockGuard::LockGuard(
778 const RCSResourceObject::Ptr ptr, AutoNotifyPolicy autoNotifyPolicy) :
779 m_resourceObject(*ptr),
780 m_autoNotifyPolicy { autoNotifyPolicy },
781 m_isOwningLock{ false }
786 RCSResourceObject::LockGuard::LockGuard(
787 const RCSResourceObject& resourceObject, AutoNotifyPolicy autoNotifyPolicy) :
788 m_resourceObject(resourceObject),
789 m_autoNotifyPolicy { autoNotifyPolicy },
790 m_isOwningLock{ false }
795 RCSResourceObject::LockGuard::~LockGuard() noexcept(false)
797 if (!std::uncaught_exception() && m_autoNotifyFunc) m_autoNotifyFunc();
801 m_resourceObject.setLockOwner(std::thread::id{ });
802 m_resourceObject.m_mutex.unlock();
806 void RCSResourceObject::LockGuard::init()
808 if (m_resourceObject.getLockOwner() != std::this_thread::get_id())
810 m_resourceObject.m_mutex.lock();
811 m_resourceObject.setLockOwner(std::this_thread::get_id());
812 m_isOwningLock = true;
814 m_autoNotifyFunc = ::createAutoNotifyInvoker(&RCSResourceObject::autoNotify,
815 m_resourceObject, m_resourceObject.m_resourceAttributes, m_autoNotifyPolicy);
818 RCSResourceObject::WeakGuard::WeakGuard(
819 const RCSResourceObject& resourceObject) :
820 m_isOwningLock{ false },
821 m_resourceObject(resourceObject)
823 if (m_resourceObject.getLockOwner() != std::this_thread::get_id())
825 m_resourceObject.m_mutex.lock();
826 m_resourceObject.setLockOwner(std::this_thread::get_id());
827 m_isOwningLock = true;
831 RCSResourceObject::WeakGuard::~WeakGuard()
835 m_resourceObject.setLockOwner(std::thread::id{ });
836 m_resourceObject.m_mutex.unlock();
840 bool RCSResourceObject::WeakGuard::hasLocked() const
842 return m_isOwningLock;