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"
27 #include "RequestHandler.h"
28 #include "AssertUtils.h"
29 #include "AtomicHelper.h"
30 #include "ResourceAttributesConverter.h"
31 #include "ResourceAttributesUtils.h"
32 #include "RCSRequest.h"
33 #include "RCSRepresentation.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 inline bool requestContainsInterface(const std::shared_ptr< OC::OCResourceRequest >& request,
60 const std::string& interface)
62 return request->getQueryParameters().find(interface) != request->getQueryParameters().end();
65 OCEntityHandlerResult sendResponse(const std::shared_ptr< OC::OCResourceRequest >& ocRequest,
66 const std::shared_ptr< OC::OCResourceResponse >& ocResponse)
68 ocResponse->setRequestHandle(ocRequest->getRequestHandle());
69 ocResponse->setResourceHandle(ocRequest->getResourceHandle());
73 if (OC::OCPlatform::sendResponse(ocResponse) == OC_STACK_OK)
78 catch (const OC::OCException& e)
80 OIC_LOG_V(WARNING, LOG_TAG, "Error (%s)", e.what());
87 template <typename RESPONSE>
88 OCEntityHandlerResult sendResponse(RCSResourceObject& resource,
89 const std::shared_ptr< OC::OCResourceRequest >& ocRequest, RESPONSE&& response)
91 return sendResponse(ocRequest, response.getHandler()->buildResponse(resource));
94 RCSResourceAttributes getAttributesFromOCRequest(
95 const std::shared_ptr< OC::OCResourceRequest >& request)
97 return ResourceAttributesConverter::fromOCRepresentation(
98 request->getResourceRepresentation());
101 template< typename HANDLER, typename RESPONSE =
102 typename std::decay<HANDLER>::type::result_type >
103 RESPONSE invokeHandler(RCSResourceAttributes& attrs,
104 const std::shared_ptr< OC::OCResourceRequest >& ocRequest,
105 std::shared_ptr< HANDLER > handler)
109 return (*handler)(RCSRequest{ ocRequest }, attrs);
112 return RESPONSE::defaultAction();
115 typedef void (RCSResourceObject::* AutoNotifyFunc)
116 (bool, RCSResourceObject::AutoNotifyPolicy) const;
118 std::function<void()> createAutoNotifyInvoker(AutoNotifyFunc autoNotifyFunc,
119 const RCSResourceObject& resourceObject, const RCSResourceAttributes& resourceAttributes,
120 RCSResourceObject::AutoNotifyPolicy autoNotifyPolicy)
122 if(autoNotifyPolicy == RCSResourceObject::AutoNotifyPolicy::UPDATED)
124 auto&& compareAttributesFunc =
125 std::bind(std::not_equal_to<RCSResourceAttributes>(),
127 std::cref(resourceAttributes));
128 return std::bind(autoNotifyFunc,
129 &resourceObject, std::move(compareAttributesFunc), autoNotifyPolicy);
131 else if(autoNotifyPolicy == RCSResourceObject::AutoNotifyPolicy::ALWAYS)
133 return std::bind(autoNotifyFunc,
134 &resourceObject, true, autoNotifyPolicy);
139 OCEntityHandlerResult handleBatchInterfaceGetRequest(
140 const std::shared_ptr< OC::OCResourceRequest >& request,
141 const RCSResourceObject* resourceObject)
143 auto rcsRep = resourceObject->toRepresentation();
145 for (const auto& bound : resourceObject->getBoundResources())
147 rcsRep.addChild(bound->toRepresentation());
150 auto response = std::make_shared< OC::OCResourceResponse >();
152 response->setResponseResult(OC_EH_OK);
153 response->setErrorCode(200);
154 response->setResourceRepresentation(
155 RCSRepresentation::toOCRepresentation(std::move(rcsRep)));
157 return sendResponse(request, response);
160 } // unnamed namespace
167 RCSResourceObject::Builder::Builder(const std::string& uri, const std::string& type,
168 const std::string& interface) :
171 m_interfaces{ interface },
172 m_properties{ OC_DISCOVERABLE | OC_OBSERVABLE },
173 m_resourceAttributes{ }
177 RCSResourceObject::Builder& RCSResourceObject::Builder::addInterface(
178 const std::string& interface)
180 return addInterface(std::string{ interface });
183 RCSResourceObject::Builder& RCSResourceObject::Builder::addInterface(
184 std::string&& interface)
186 m_interfaces.push_back(std::move(interface));
190 RCSResourceObject::Builder& RCSResourceObject::Builder::addType(const std::string& type)
192 return addType(std::string{ type });
195 RCSResourceObject::Builder& RCSResourceObject::Builder::addType(std::string&& type)
197 m_types.push_back(std::move(type));
201 RCSResourceObject::Builder& RCSResourceObject::Builder::setDiscoverable(
204 m_properties = ::makePropertyFlags(m_properties, OC_DISCOVERABLE, discoverable);
208 RCSResourceObject::Builder& RCSResourceObject::Builder::setObservable(
211 m_properties = ::makePropertyFlags(m_properties, OC_OBSERVABLE, observable);
215 RCSResourceObject::Builder& RCSResourceObject::Builder::setSecureFlag(
218 m_properties = ::makePropertyFlags(m_properties, OC_SECURE, secureFlag);
221 RCSResourceObject::Builder& RCSResourceObject::Builder::setAttributes(
222 const RCSResourceAttributes& attrs)
224 m_resourceAttributes = attrs;
228 RCSResourceObject::Builder& RCSResourceObject::Builder::setAttributes(
229 RCSResourceAttributes&& attrs)
231 m_resourceAttributes = std::move(attrs);
235 RCSResourceObject::Ptr RCSResourceObject::Builder::build()
237 OCResourceHandle handle{ nullptr };
239 RCSResourceObject::Ptr server {
240 new RCSResourceObject{ m_uri, m_properties, std::move(m_resourceAttributes) } };
242 OC::EntityHandler entityHandler{ std::bind(&RCSResourceObject::entityHandler,
243 server.get(), std::placeholders::_1) };
245 typedef OCStackResult (*RegisterResource)(OCResourceHandle&, std::string&,
246 const std::string&, const std::string&, OC::EntityHandler, uint8_t);
248 invokeOCFunc(static_cast<RegisterResource>(OC::OCPlatform::registerResource),
249 handle, m_uri, m_types[0], m_interfaces[0], entityHandler, m_properties);
251 std::for_each(m_interfaces.begin() + 1, m_interfaces.end(),
252 [&handle](const std::string& interfaceName){
253 invokeOCFunc(OC::OCPlatform::bindInterfaceToResource, handle, interfaceName);
256 std::for_each(m_types.begin() + 1, m_types.end(),
257 [&handle](const std::string& typeName){
258 invokeOCFunc(OC::OCPlatform::bindTypeToResource, handle, typeName);
261 server->m_resourceHandle = handle;
262 server->m_interfaces = m_interfaces;
263 server->m_types = m_types;
269 RCSResourceObject::RCSResourceObject(const std::string& uri,
270 uint8_t properties, RCSResourceAttributes&& attrs) :
271 m_properties{ properties },
276 m_resourceAttributes{ std::move(attrs) },
277 m_getRequestHandler{ },
278 m_setRequestHandler{ },
279 m_autoNotifyPolicy{ AutoNotifyPolicy::UPDATED },
280 m_setRequestHandlerPolicy{ SetRequestHandlerPolicy::NEVER },
281 m_attributeUpdatedListeners{ },
284 m_mutexAttributeUpdatedListeners{ }
286 m_lockOwner.reset(new AtomicThreadId);
289 RCSResourceObject::~RCSResourceObject()
291 if (m_resourceHandle)
295 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::vector< std::string > RCSResourceObject::getInterfaces() const
531 std::vector< std::string > RCSResourceObject::getTypes() const
536 RCSRepresentation RCSResourceObject::toRepresentation() const
538 return RCSRepresentation{ m_uri, m_interfaces, m_types, m_resourceAttributes };
541 void RCSResourceObject::autoNotify(bool isAttributesChanged) const
543 autoNotify(isAttributesChanged, m_autoNotifyPolicy);
546 void RCSResourceObject::autoNotify(
547 bool isAttributesChanged, AutoNotifyPolicy autoNotifyPolicy) const
549 if(autoNotifyPolicy == AutoNotifyPolicy::NEVER) return;
550 if(autoNotifyPolicy == AutoNotifyPolicy::UPDATED &&
551 isAttributesChanged == false) return;
556 OCEntityHandlerResult RCSResourceObject::entityHandler(
557 const std::shared_ptr< OC::OCResourceRequest >& request)
559 OIC_LOG(WARNING, LOG_TAG, "entityHandler");
567 if (request->getRequestHandlerFlag() & OC::RequestHandlerFlag::RequestFlag)
569 return handleRequest(request);
572 if (request->getRequestHandlerFlag() & OC::RequestHandlerFlag::ObserverFlag)
574 return handleObserve(request);
577 catch (const std::exception& e)
579 OIC_LOG_V(WARNING, LOG_TAG, "Failed to handle request : %s", e.what());
584 OIC_LOG(WARNING, LOG_TAG, "Failed to handle request.");
591 OCEntityHandlerResult RCSResourceObject::handleRequest(
592 const std::shared_ptr< OC::OCResourceRequest >& request)
594 assert(request != nullptr);
596 if (request->getRequestType() == "GET")
598 return handleRequestGet(request);
601 if (request->getRequestType() == "POST")
603 return handleRequestSet(request);
609 OCEntityHandlerResult RCSResourceObject::handleRequestGet(
610 const std::shared_ptr< OC::OCResourceRequest >& request)
612 assert(request != nullptr);
614 if (requestContainsInterface(request, OC::BATCH_INTERFACE))
616 return handleBatchInterfaceGetRequest(request, this);
619 auto attrs = getAttributesFromOCRequest(request);
621 return sendResponse(*this, request, invokeHandler(attrs, request, m_getRequestHandler));
624 bool RCSResourceObject::applyAcceptanceMethod(const RCSSetResponse& response,
625 const RCSResourceAttributes& requstAttrs)
627 auto requestHandler = response.getHandler();
629 assert(requestHandler != nullptr);
631 auto replaced = requestHandler->applyAcceptanceMethod(response.getAcceptanceMethod(),
634 OIC_LOG_V(WARNING, LOG_TAG, "replaced num %zu", replaced.size());
635 for (const auto& attrKeyValPair : replaced)
637 std::shared_ptr< AttributeUpdatedListener > foundListener;
639 std::lock_guard< std::mutex > lock(m_mutexAttributeUpdatedListeners);
641 auto it = m_attributeUpdatedListeners.find(attrKeyValPair.first);
642 if (it != m_attributeUpdatedListeners.end())
644 foundListener = it->second;
650 (*foundListener)(attrKeyValPair.second, requstAttrs.at(attrKeyValPair.first));
654 return !replaced.empty();
657 OCEntityHandlerResult RCSResourceObject::handleRequestSet(
658 const std::shared_ptr< OC::OCResourceRequest >& request)
660 assert(request != nullptr);
662 auto attrs = getAttributesFromOCRequest(request);
663 auto response = invokeHandler(attrs, request, m_setRequestHandler);
665 auto attrsChanged = applyAcceptanceMethod(response, attrs);
669 autoNotify(attrsChanged, m_autoNotifyPolicy);
670 return sendResponse(*this, request, response);
671 } catch (const RCSPlatformException& e) {
672 OIC_LOG_V(ERROR, LOG_TAG, "Error : %s ", e.what());
677 OCEntityHandlerResult RCSResourceObject::handleObserve(
678 const std::shared_ptr< OC::OCResourceRequest >&)
688 RCSResourceObject::LockGuard::LockGuard(const RCSResourceObject::Ptr ptr) :
689 m_resourceObject(*ptr),
690 m_autoNotifyPolicy{ ptr->getAutoNotifyPolicy() },
691 m_isOwningLock{ false }
696 RCSResourceObject::LockGuard::LockGuard(
697 const RCSResourceObject& serverResource) :
698 m_resourceObject(serverResource),
699 m_autoNotifyPolicy{ serverResource.getAutoNotifyPolicy() },
700 m_isOwningLock{ false }
705 RCSResourceObject::LockGuard::LockGuard(
706 const RCSResourceObject::Ptr ptr, AutoNotifyPolicy autoNotifyPolicy) :
707 m_resourceObject(*ptr),
708 m_autoNotifyPolicy { autoNotifyPolicy },
709 m_isOwningLock{ false }
714 RCSResourceObject::LockGuard::LockGuard(
715 const RCSResourceObject& resourceObject, AutoNotifyPolicy autoNotifyPolicy) :
716 m_resourceObject(resourceObject),
717 m_autoNotifyPolicy { autoNotifyPolicy },
718 m_isOwningLock{ false }
723 RCSResourceObject::LockGuard::~LockGuard() noexcept(false)
725 if (!std::uncaught_exception() && m_autoNotifyFunc) m_autoNotifyFunc();
729 m_resourceObject.setLockOwner(std::thread::id{ });
730 m_resourceObject.m_mutex.unlock();
734 void RCSResourceObject::LockGuard::init()
736 if (m_resourceObject.getLockOwner() != std::this_thread::get_id())
738 m_resourceObject.m_mutex.lock();
739 m_resourceObject.setLockOwner(std::this_thread::get_id());
740 m_isOwningLock = true;
742 m_autoNotifyFunc = ::createAutoNotifyInvoker(&RCSResourceObject::autoNotify,
743 m_resourceObject, m_resourceObject.m_resourceAttributes, m_autoNotifyPolicy);
746 RCSResourceObject::WeakGuard::WeakGuard(
747 const RCSResourceObject& resourceObject) :
748 m_isOwningLock{ false },
749 m_resourceObject(resourceObject)
751 if (m_resourceObject.getLockOwner() != std::this_thread::get_id())
753 m_resourceObject.m_mutex.lock();
754 m_resourceObject.setLockOwner(std::this_thread::get_id());
755 m_isOwningLock = true;
759 RCSResourceObject::WeakGuard::~WeakGuard()
763 m_resourceObject.setLockOwner(std::thread::id{ });
764 m_resourceObject.m_mutex.unlock();
768 bool RCSResourceObject::WeakGuard::hasLocked() const
770 return m_isOwningLock;