1 //******************************************************************
3 // Copyright 2014 Intel Mobile Communications GmbH 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 /// @file OCRepresentation.cpp
23 /// @brief This file contains the implementation of classes and its members
24 /// related to OCRepresentation
27 #include <OCRepresentation.h>
29 #include <boost/lexical_cast.hpp>
30 #include <cereal/cereal.hpp>
31 #include <cereal/types/map.hpp>
32 #include <cereal/types/vector.hpp>
33 #include <cereal/types/utility.hpp>
34 #include <OicJsonSerializer.hpp>
37 // code needed to serialize a string=>Attribute value map
42 template<class Archive>
43 class WriteAttributeValue : public boost::static_visitor<>
46 WriteAttributeValue(const std::string& name, Archive& ar)
47 :m_name(name), m_archive(ar)
51 void operator()(const T& value) const
53 m_archive(cereal::make_nvp(m_name, value));
64 // take no action when serializing the null type, because the 'save' below
65 // doesn't use the visitor for this type.
66 template <class Archive>
67 void serialize(Archive&, OC::NullType t)
70 template<class Archive>
71 void save(Archive& ar, const std::map<std::string, OC::AttributeValue>& vals)
73 for(const auto& kv : vals)
75 const auto& k = kv.first;
76 const auto& v = kv.second;
78 if(v.which() != OC::AttributeValueNullIndex)
80 OC::detail::WriteAttributeValue<Archive> writer(k,ar);
81 boost::apply_visitor(writer, v);
85 ar.setNextName(k.c_str());
92 template<class Archive>
93 void load(Archive& ar, std::map<std::string, OC::AttributeValue>& vals)
95 ar.loadAttributeValues(vals);
101 typedef cereal::JSONOutputArchive OutputArchiveType;
102 typedef cereal::JSONInputArchive InputArchiveType;
104 void MessageContainer::setJSONRepresentation(const std::string& payload)
106 std::stringstream os(payload);
108 InputArchiveType archive(os);
109 archive(cereal::make_nvp(OC::Key::OCKEY, m_reps));
113 void MessageContainer::setJSONRepresentation(const unsigned char* payload)
115 setJSONRepresentation(std::string(reinterpret_cast<const char*>(payload)));
118 std::string MessageContainer::getJSONRepresentation(OCInfoFormat f) const
120 std::stringstream os;
122 // note: the block is required because cereal closes the JSON string
123 // upon destruction, so the archive needs to be destroyed before accessing
126 if(f == OCInfoFormat::IncludeOC)
128 OutputArchiveType archive(os);
129 archive(cereal::make_nvp(OC::Key::OCKEY, m_reps));
131 else if(f== OCInfoFormat::ExcludeOC)
133 bool firstPrinted = false;
134 for(std::vector<OCRepresentation>::size_type i = 0; i< m_reps.size();++i)
136 if(!m_reps[i].emptyData())
143 os << m_reps[i].getJSONRepresentation();
151 const std::vector<OCRepresentation>& MessageContainer::representations() const
156 void MessageContainer::addRepresentation(const OCRepresentation& rep)
158 m_reps.push_back(rep);
164 std::string OCRepresentation::getJSONRepresentation() const
171 std::stringstream os;
173 // note: the block is required because cereal closes the JSON string
174 // upon destruction, so the archive needs to be destroyed before accessing
177 OutputArchiveType archive (os);
184 void OCRepresentation::addChild(const OCRepresentation& rep)
186 m_children.push_back(rep);
189 void OCRepresentation::clearChildren()
194 const std::vector<OCRepresentation>& OCRepresentation::getChildren() const
199 void OCRepresentation::setUri(const std::string& uri)
204 std::string OCRepresentation::getUri() const
209 const std::vector<std::string>& OCRepresentation::getResourceTypes() const
211 return m_resourceTypes;
214 void OCRepresentation::setResourceTypes(const std::vector<std::string>& resourceTypes)
216 m_resourceTypes = resourceTypes;
219 const std::vector<std::string>& OCRepresentation::getResourceInterfaces() const
224 void OCRepresentation::setResourceInterfaces(const std::vector<std::string>& resourceInterfaces)
226 m_interfaces = resourceInterfaces;
229 bool OCRepresentation::hasAttribute(const std::string& str) const
231 return m_values.find(str) != m_values.end();
234 bool OCRepresentation::emptyData() const
236 // This logic is meant to determine whether based on the JSON serialization rules
237 // if this object will result in empty JSON. URI is only serialized if there is valid
238 // data, ResourceType and Interfaces are only serialized if we are a nothing, a
239 // child of a default or link item.
240 // Our values array is only printed in the if we are the child of a Batch resource,
241 // the parent in a 'default' situation, or not in a child/parent relationship.
246 else if ((m_interfaceType == InterfaceType::None
247 || m_interfaceType==InterfaceType::DefaultChild
248 || m_interfaceType==InterfaceType::LinkChild)
249 && (m_resourceTypes.size()>0 || m_interfaces.size()>0))
253 else if((m_interfaceType == InterfaceType::None
254 || m_interfaceType == InterfaceType::BatchChild
255 || m_interfaceType == InterfaceType::DefaultParent)
256 && m_values.size()>0)
261 if(m_children.size() > 0)
269 int OCRepresentation::numberOfAttributes() const
271 return m_values.size();
274 bool OCRepresentation::erase(const std::string& str)
276 return m_values.erase(str);
279 void OCRepresentation::setNULL(const std::string& str)
281 m_values[str] = OC::NullType();
284 bool OCRepresentation::isNULL(const std::string& str) const
286 auto x = m_values.find(str);
288 if(m_values.end() != x)
290 return x->second.which() == AttributeValueNullIndex;
294 throw OCException(OC::Exception::INVALID_ATTRIBUTE+ str);
301 template <class Archive, class Val>
302 void OCRepresentation::optional_load(Archive& ar, Val&& v)
308 catch(cereal::Exception& e)
310 ar.setNextName(nullptr);
311 // Loading a key that doesn't exist results in an exception
312 // Since "Not Found" is a valid condition for us, we swallow
313 // this exception and the archive will not load anything
317 template<class Archive>
318 void OCRepresentation::save(Archive& ar) const
320 // printed for all interface types
323 ar(cereal::make_nvp(Key::URIKEY, m_uri));
326 if((m_interfaceType == InterfaceType::None
327 || m_interfaceType==InterfaceType::DefaultChild
328 || m_interfaceType==InterfaceType::LinkChild)
329 && (m_resourceTypes.size()>0 || m_interfaces.size()>0))
331 // The Prop object requires that it refer to non-const vectors
332 // so that it can alter them in the 'load' case. In the save case
333 // (initiated here) it will not modify the object. So, to keep the
334 // compiler happy, removing the 'const' context here is necessary.
335 const std::vector<std::string>& rt(m_resourceTypes);
336 const std::vector<std::string>& intf(m_interfaces);
337 Prop temp(const_cast<std::vector<std::string>&>(rt),
338 const_cast<std::vector<std::string>&>(intf));
339 ar(cereal::make_nvp(Key::PROPERTYKEY, temp));
342 // printed only for BatchChildren and DefaultParent
343 if((m_interfaceType == InterfaceType::None
344 || m_interfaceType == InterfaceType::BatchChild
345 || m_interfaceType == InterfaceType::DefaultParent)
346 && m_values.size()>0)
348 ar(cereal::make_nvp(Key::REPKEY, m_values));
352 template<class Archive>
353 void OCRepresentation::load(Archive& ar)
355 optional_load(ar, cereal::make_nvp(Key::URIKEY, m_uri));
357 Prop temp(m_resourceTypes, m_interfaces);
358 optional_load(ar, cereal::make_nvp(Key::PROPERTYKEY, temp));
360 optional_load(ar, cereal::make_nvp(Key::REPKEY, m_values));
363 template<class Archive>
364 void OCRepresentation::Prop::save(Archive& ar) const
366 if(m_types.size() > 0)
368 ar(cereal::make_nvp(Key::RESOURCETYPESKEY, m_types));
371 if(m_interfaces.size()>0)
373 ar(cereal::make_nvp(Key::INTERFACESKEY, m_interfaces));
377 template<class Archive>
378 void OCRepresentation::Prop::load(Archive& ar)
380 optional_load(ar, cereal::make_nvp(Key::RESOURCETYPESKEY, m_types));
381 optional_load(ar, cereal::make_nvp(Key::INTERFACESKEY, m_interfaces));
385 // note: the below is used to load an AttributeValue map out of JSON
390 enum class typeTag:uint8_t
400 typedef rapidjson::Document::GenericValue GenericValue;
402 AttributeValue parseAttributeValue(const GenericValue& v);
403 AttributeValue parseAttributeValue(const GenericValue& v,
404 const unsigned int curLevel, unsigned int& maxDepth, typeTag& t);
405 AttributeValue parseAttributeValueObject(const GenericValue& v, typeTag& t);
406 AttributeValue parseAttributeValueArray(const GenericValue& v,
407 const unsigned int curLevel, unsigned int& maxDepth, typeTag& t);
408 AttributeValue parseAttributeValuePrimitive(const GenericValue& v, typeTag& t);
410 AttributeValue parseAttributeValue(const GenericValue& v)
412 // base entrance, start everything at '0'
413 unsigned int max_depth {0};
414 typeTag t {typeTag::NOTHING};
416 return parseAttributeValue(v, 0, max_depth, t);
419 AttributeValue parseAttributeValue(const GenericValue& v,
420 const unsigned int curLevel, unsigned int& maxDepth, typeTag& t)
424 return parseAttributeValueObject(v, t);
428 return parseAttributeValueArray(v, curLevel + 1, maxDepth, t);
432 return parseAttributeValuePrimitive(v,t);
436 AttributeValue parseAttributeValueObject(const GenericValue& v, typeTag& t)
438 typedef rapidjson::Value::ConstMemberIterator CMI;
439 t = typeTag::_representation;
440 OC::OCRepresentation rep;
442 for(CMI itr = v.MemberBegin(); itr!= v.MemberEnd(); ++itr)
444 std::string keyName = itr->name.GetString();
446 if(keyName == OC::Key::URIKEY)
448 rep.setUri(boost::get<std::string>(parseAttributeValue(itr->value)));
450 else if (keyName == OC::Key::PROPERTYKEY)
452 for(CMI itr2 = itr->value.MemberBegin();
453 itr->value.MemberEnd()!=itr2;
456 if(keyName == OC::Key::RESOURCETYPESKEY)
458 rep.setResourceTypes(
459 boost::get<std::vector<std::string>>(
460 parseAttributeValue(itr->value)));
462 else if(keyName == OC::Key::PROPERTYKEY)
464 rep.setResourceInterfaces(
465 boost::get<std::vector<std::string>>(
466 parseAttributeValue(itr->value)));
470 else if (keyName == OC::Key::REPKEY)
472 for(CMI itr2 = itr->value.MemberBegin();
473 itr->value.MemberEnd()!=itr2;
476 rep.setValue(itr2->name.GetString(),
477 parseAttributeValue(itr2->value));
485 AttributeValue parseAttributeValuePrimitive(const GenericValue& v, typeTag& t)
489 t = typeTag::_string;
490 return std::string(v.GetString());
492 else if (v.IsNumber())
496 t = typeTag::_double;
497 return double(v.GetDouble());
502 return int(v.GetInt());
506 throw OC::OCException(OC::Exception::INVALID_JSON_NUMERIC
507 + std::to_string(v.GetType()));
513 return bool(v.GetBool_());
517 return OC::NullType();
521 throw OC::OCException(OC::Exception::INVALID_JSON_TYPE
522 + std::to_string(v.GetType()));
526 std::vector<AttributeValue> gatherArrayContents(const GenericValue& v,
527 const unsigned int curLevel, unsigned int& maxDepth, typeTag& t)
529 std::vector<AttributeValue> out;
531 std::transform(v.Begin(), v.End(), back_inserter(out),
532 [curLevel, &maxDepth, &t](const GenericValue& x)
534 return parseAttributeValue(x, curLevel, maxDepth, t);
540 struct valueToConcrete
542 OutT operator()(const AttributeValue& v)
544 return boost::get<OutT>(v);
549 template <class OutSeqT>
550 OutSeqT valuesToConcreteVectors(const std::vector<AttributeValue>& vs)
554 std::transform(begin(vs),end(vs), back_inserter(ret),
555 valueToConcrete<typename OutSeqT::value_type>());
559 template<class valueType>
560 AttributeValue remapArrayDepth(const unsigned int curLevel,
561 const std::vector<OC::AttributeValue>& vs)
566 throw OC::OCException(OC::Exception::INVALID_JSON_ARRAY_DEPTH);
569 return valuesToConcreteVectors<std::vector<valueType>>(vs);
572 return valuesToConcreteVectors<std::vector<std::vector<valueType>>>(vs);
575 return valuesToConcreteVectors
576 <std::vector<std::vector<std::vector<valueType>>>>(vs);
581 AttributeValue convertArrayToConcretes(const typeTag t,
582 const unsigned int curLevel, const std::vector<OC::AttributeValue>& vs)
584 // This function converts a std::vector of AttributeValue to a std::vector
585 // of concrete types. Since we don't use a recursive Variant, we need
586 // to get back to a 'base' primitive type
590 case typeTag::NOTHING:
591 throw OC::OCException(OC::Exception::INVALID_JSON_TYPE_TAG);
593 case typeTag::_string:
594 return remapArrayDepth<std::string>(curLevel, vs);
597 return remapArrayDepth<int>(curLevel, vs);
599 case typeTag::_double:
600 return remapArrayDepth<double>(curLevel, vs);
603 return remapArrayDepth<bool>(curLevel, vs);
605 case typeTag::_representation:
606 return remapArrayDepth<OCRepresentation>(curLevel, vs);
611 AttributeValue parseAttributeValueArray(const GenericValue& v,
612 const unsigned int curLevel, unsigned int& maxDepth, typeTag& t)
614 const unsigned int max_level = 3;
616 if(curLevel > max_level)
618 throw OC::OCException(OC::Exception::INVALID_JSON_ARRAY_DEPTH);
621 if(curLevel > maxDepth)
626 auto arrayItems = gatherArrayContents(v, curLevel, maxDepth, t);
627 const int remapLevel = maxDepth - (curLevel -1);
628 return convertArrayToConcretes(t, remapLevel, arrayItems);
635 void JSONInputArchive::loadAttributeValues(std::map<std::string, OC::AttributeValue>& map)
637 for(auto&b = itsIteratorStack.back();
638 b.Member && b.itsMemberItEnd != b.itsMemberItBegin+b.itsIndex;
641 std::string key = b.itsMemberItBegin[b.itsIndex].name.GetString();
642 const GenericValue& v = itsIteratorStack.back().value();
643 map[key] = OC::detail::parseAttributeValue(v);
650 std::ostream& operator <<(std::ostream& os, const AttributeType at)
654 case AttributeType::Null:
657 case AttributeType::Integer:
660 case AttributeType::Double:
663 case AttributeType::Boolean:
666 case AttributeType::String:
669 case AttributeType::OCRepresentation:
670 os << "OCRepresentation";
672 case AttributeType::Vector:
680 // STL Container For OCRepresentation
683 OCRepresentation::AttributeItem::AttributeItem(const std::string& name,
684 std::map<std::string, AttributeValue>& vals):
685 m_attrName(name), m_values(vals){}
687 OCRepresentation::AttributeItem OCRepresentation::operator[](const std::string& key)
689 OCRepresentation::AttributeItem attr{key, m_values};
690 return std::move(attr);
693 const OCRepresentation::AttributeItem OCRepresentation::operator[](const std::string& key) const
695 OCRepresentation::AttributeItem attr{key, m_values};
696 return std::move(attr);
699 const std::string& OCRepresentation::AttributeItem::attrname() const
704 template<typename T, typename = void>
707 // contains the actual type
709 // contains the inner most vector-type
711 // contains the AttributeType for this item
712 constexpr static AttributeType enum_type =
713 AttributeTypeConvert<T>::type;
714 // contains the AttributeType for this base-type
715 constexpr static AttributeType enum_base_type =
716 AttributeTypeConvert<T>::type;
717 // depth of the vector
718 constexpr static size_t depth = 0;
722 struct type_info<T, typename std::enable_if<is_vector<T>::value>::type>
725 typedef typename type_info<typename T::value_type>::base_type base_type;
726 constexpr static AttributeType enum_type = AttributeType::Vector;
727 constexpr static AttributeType enum_base_type =
728 type_info<typename T::value_type>::enum_base_type;
729 constexpr static size_t depth = 1 +
730 type_info<typename T::value_type>::depth;
733 struct type_introspection_visitor : boost::static_visitor<>
736 AttributeType base_type;
739 type_introspection_visitor() : boost::static_visitor<>(),
740 type(AttributeType::Null), base_type(AttributeType::Null), depth(0){}
742 template <typename T>
743 void operator()(T const& item)
745 type = type_info<T>::enum_type;
746 base_type = type_info<T>::enum_base_type;
747 depth = type_info<T>::depth;
751 AttributeType OCRepresentation::AttributeItem::type() const
753 type_introspection_visitor vis;
754 boost::apply_visitor(vis, m_values[m_attrName]);
758 AttributeType OCRepresentation::AttributeItem::base_type() const
760 type_introspection_visitor vis;
761 boost::apply_visitor(vis, m_values[m_attrName]);
762 return vis.base_type;
765 size_t OCRepresentation::AttributeItem::depth() const
767 type_introspection_visitor vis;
768 boost::apply_visitor(vis, m_values[m_attrName]);
772 OCRepresentation::iterator OCRepresentation::begin()
774 return OCRepresentation::iterator(m_values.begin(), m_values);
777 OCRepresentation::const_iterator OCRepresentation::begin() const
779 return OCRepresentation::const_iterator(m_values.begin(), m_values);
782 OCRepresentation::const_iterator OCRepresentation::cbegin() const
784 return OCRepresentation::const_iterator(m_values.cbegin(), m_values);
787 OCRepresentation::iterator OCRepresentation::end()
789 return OCRepresentation::iterator(m_values.end(), m_values);
792 OCRepresentation::const_iterator OCRepresentation::end() const
794 return OCRepresentation::const_iterator(m_values.end(), m_values);
797 OCRepresentation::const_iterator OCRepresentation::cend() const
799 return OCRepresentation::const_iterator(m_values.cend(), m_values);
802 size_t OCRepresentation::size() const
804 return m_values.size();
807 bool OCRepresentation::empty() const
809 return m_values.empty();
812 bool OCRepresentation::iterator::operator==(const OCRepresentation::iterator& rhs) const
814 return m_iterator == rhs.m_iterator;
817 bool OCRepresentation::iterator::operator!=(const OCRepresentation::iterator& rhs) const
819 return m_iterator != rhs.m_iterator;
822 bool OCRepresentation::const_iterator::operator==(
823 const OCRepresentation::const_iterator& rhs) const
825 return m_iterator == rhs.m_iterator;
828 bool OCRepresentation::const_iterator::operator!=(
829 const OCRepresentation::const_iterator& rhs) const
831 return m_iterator != rhs.m_iterator;
834 OCRepresentation::iterator::reference OCRepresentation::iterator::operator*()
839 OCRepresentation::const_iterator::const_reference
840 OCRepresentation::const_iterator::operator*() const
845 OCRepresentation::iterator::pointer OCRepresentation::iterator::operator->()
850 OCRepresentation::const_iterator::const_pointer
851 OCRepresentation::const_iterator::operator->() const
856 OCRepresentation::iterator& OCRepresentation::iterator::operator++()
859 if(m_iterator != m_item.m_values.end())
861 m_item.m_attrName = m_iterator->first;
865 m_item.m_attrName = "";
870 OCRepresentation::const_iterator& OCRepresentation::const_iterator::operator++()
873 if(m_iterator != m_item.m_values.end())
875 m_item.m_attrName = m_iterator->first;
879 m_item.m_attrName = "";
884 OCRepresentation::iterator OCRepresentation::iterator::operator++(int)
886 OCRepresentation::iterator itr(*this);
891 OCRepresentation::const_iterator OCRepresentation::const_iterator::operator++(int)
893 OCRepresentation::const_iterator itr(*this);
898 struct to_string_visitor : boost::static_visitor<>
901 template <typename T>
902 void operator()(T const& item)
904 str = boost::lexical_cast<std::string>(item);
907 template <typename T>
908 void operator()(std::vector<T> const& item)
910 to_string_visitor vis;
911 std::ostringstream stream;
914 for(const auto& i : item)
917 stream << vis.str << " ";
925 void to_string_visitor::operator()(bool const& item)
927 str = item ? "true" : "false";
931 void to_string_visitor::operator()(std::string const& item)
937 void to_string_visitor::operator()(NullType const& item)
943 void to_string_visitor::operator()(OCRepresentation const& item)
945 str = "OC::OCRepresentation";
948 std::string OCRepresentation::getValueToString(const std::string& key) const
950 auto x = m_values.find(key);
951 if(x != m_values.end())
953 to_string_visitor vis;
954 boost::apply_visitor(vis, x->second);
955 return std::move(vis.str);
961 std::string OCRepresentation::AttributeItem::getValueToString() const
963 to_string_visitor vis;
964 boost::apply_visitor(vis, m_values[m_attrName]);
965 return std::move(vis.str);
968 std::ostream& operator<<(std::ostream& os, const OCRepresentation::AttributeItem& ai)
970 os << ai.getValueToString();