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 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
24 * This file contains the implementation of classes and its members related
25 * to OCRepresentation.
29 #include <OCRepresentation.h>
31 #include <boost/lexical_cast.hpp>
32 #include <cereal/cereal.hpp>
33 #include <cereal/types/map.hpp>
34 #include <cereal/types/vector.hpp>
35 #include <cereal/types/utility.hpp>
36 #include <OicJsonSerializer.hpp>
39 // code needed to serialize a string=>Attribute value map
44 template<class Archive>
45 class WriteAttributeValue : public boost::static_visitor<>
48 WriteAttributeValue(const std::string& name, Archive& ar)
49 :m_name(name), m_archive(ar)
53 void operator()(const T& value) const
55 m_archive(cereal::make_nvp(m_name, value));
66 // take no action when serializing the null type, because the 'save' below
67 // doesn't use the visitor for this type.
68 template <class Archive>
69 void serialize(Archive&, OC::NullType t)
72 template<class Archive>
73 void save(Archive& ar, const std::map<std::string, OC::AttributeValue>& vals)
75 for(const auto& kv : vals)
77 const auto& k = kv.first;
78 const auto& v = kv.second;
80 if(v.which() != OC::AttributeValueNullIndex)
82 OC::detail::WriteAttributeValue<Archive> writer(k,ar);
83 boost::apply_visitor(writer, v);
87 ar.setNextName(k.c_str());
94 template<class Archive>
95 void load(Archive& ar, std::map<std::string, OC::AttributeValue>& vals)
97 ar.loadAttributeValues(vals);
103 typedef cereal::JSONOutputArchive OutputArchiveType;
104 typedef cereal::JSONInputArchive InputArchiveType;
106 void MessageContainer::setJSONRepresentation(const std::string& payload)
108 std::stringstream os(payload);
110 InputArchiveType archive(os);
111 archive(cereal::make_nvp(OC::Key::OCKEY, m_reps));
115 void MessageContainer::setJSONRepresentation(const char* payload)
117 setJSONRepresentation(std::string(payload));
120 std::string MessageContainer::getJSONRepresentation(OCInfoFormat f) const
122 std::stringstream os;
124 // note: the block is required because cereal closes the JSON string
125 // upon destruction, so the archive needs to be destroyed before accessing
128 if(f == OCInfoFormat::IncludeOC)
130 OutputArchiveType archive(os);
131 archive(cereal::make_nvp(OC::Key::OCKEY, m_reps));
133 else if(f== OCInfoFormat::ExcludeOC)
135 bool firstPrinted = false;
136 for(std::vector<OCRepresentation>::size_type i = 0; i< m_reps.size();++i)
138 if(!m_reps[i].emptyData())
145 os << m_reps[i].getJSONRepresentation();
153 const std::vector<OCRepresentation>& MessageContainer::representations() const
158 void MessageContainer::addRepresentation(const OCRepresentation& rep)
160 m_reps.push_back(rep);
166 std::string OCRepresentation::getJSONRepresentation() const
173 std::stringstream os;
175 // note: the block is required because cereal closes the JSON string
176 // upon destruction, so the archive needs to be destroyed before accessing
179 OutputArchiveType archive (os);
186 void OCRepresentation::addChild(const OCRepresentation& rep)
188 m_children.push_back(rep);
191 void OCRepresentation::clearChildren()
196 const std::vector<OCRepresentation>& OCRepresentation::getChildren() const
201 void OCRepresentation::setUri(const std::string& uri)
206 std::string OCRepresentation::getUri() const
211 const std::vector<std::string>& OCRepresentation::getResourceTypes() const
213 return m_resourceTypes;
216 void OCRepresentation::setResourceTypes(const std::vector<std::string>& resourceTypes)
218 m_resourceTypes = resourceTypes;
221 const std::vector<std::string>& OCRepresentation::getResourceInterfaces() const
226 void OCRepresentation::setResourceInterfaces(const std::vector<std::string>& resourceInterfaces)
228 m_interfaces = resourceInterfaces;
231 bool OCRepresentation::hasAttribute(const std::string& str) const
233 return m_values.find(str) != m_values.end();
236 bool OCRepresentation::emptyData() const
238 // This logic is meant to determine whether based on the JSON serialization rules
239 // if this object will result in empty JSON. URI is only serialized if there is valid
240 // data, ResourceType and Interfaces are only serialized if we are a nothing, a
241 // child of a default or link item.
242 // Our values array is only printed in the if we are the child of a Batch resource,
243 // the parent in a 'default' situation, or not in a child/parent relationship.
248 else if ((m_interfaceType == InterfaceType::None
249 || m_interfaceType==InterfaceType::DefaultChild
250 || m_interfaceType==InterfaceType::LinkChild)
251 && (m_resourceTypes.size()>0 || m_interfaces.size()>0))
255 else if((m_interfaceType == InterfaceType::None
256 || m_interfaceType == InterfaceType::BatchChild
257 || m_interfaceType == InterfaceType::DefaultParent)
258 && m_values.size()>0)
263 if(m_children.size() > 0)
271 int OCRepresentation::numberOfAttributes() const
273 return m_values.size();
276 bool OCRepresentation::erase(const std::string& str)
278 return m_values.erase(str);
281 void OCRepresentation::setNULL(const std::string& str)
283 m_values[str] = OC::NullType();
286 bool OCRepresentation::isNULL(const std::string& str) const
288 auto x = m_values.find(str);
290 if(m_values.end() != x)
292 return x->second.which() == AttributeValueNullIndex;
296 throw OCException(OC::Exception::INVALID_ATTRIBUTE+ str);
303 template <class Archive, class Val>
304 void OCRepresentation::optional_load(Archive& ar, Val&& v)
310 catch(cereal::Exception& e)
312 ar.setNextName(nullptr);
313 // Loading a key that doesn't exist results in an exception
314 // Since "Not Found" is a valid condition for us, we swallow
315 // this exception and the archive will not load anything
319 template<class Archive>
320 void OCRepresentation::save(Archive& ar) const
322 // printed for all interface types
325 ar(cereal::make_nvp(Key::URIKEY, m_uri));
328 if((m_interfaceType == InterfaceType::None
329 || m_interfaceType==InterfaceType::DefaultChild
330 || m_interfaceType==InterfaceType::LinkChild)
331 && (m_resourceTypes.size()>0 || m_interfaces.size()>0))
333 // The Prop object requires that it refer to non-const vectors
334 // so that it can alter them in the 'load' case. In the save case
335 // (initiated here) it will not modify the object. So, to keep the
336 // compiler happy, removing the 'const' context here is necessary.
337 const std::vector<std::string>& rt(m_resourceTypes);
338 const std::vector<std::string>& intf(m_interfaces);
339 Prop temp(const_cast<std::vector<std::string>&>(rt),
340 const_cast<std::vector<std::string>&>(intf));
341 ar(cereal::make_nvp(Key::PROPERTYKEY, temp));
344 // printed only for BatchChildren and DefaultParent
345 if((m_interfaceType == InterfaceType::None
346 || m_interfaceType == InterfaceType::BatchChild
347 || m_interfaceType == InterfaceType::DefaultParent)
348 && m_values.size()>0)
350 ar(cereal::make_nvp(Key::REPKEY, m_values));
354 template<class Archive>
355 void OCRepresentation::load(Archive& ar)
357 optional_load(ar, cereal::make_nvp(Key::URIKEY, m_uri));
359 Prop temp(m_resourceTypes, m_interfaces);
360 optional_load(ar, cereal::make_nvp(Key::PROPERTYKEY, temp));
362 optional_load(ar, cereal::make_nvp(Key::REPKEY, m_values));
365 template<class Archive>
366 void OCRepresentation::Prop::save(Archive& ar) const
368 if(m_types.size() > 0)
370 ar(cereal::make_nvp(Key::RESOURCETYPESKEY, m_types));
373 if(m_interfaces.size()>0)
375 ar(cereal::make_nvp(Key::INTERFACESKEY, m_interfaces));
379 template<class Archive>
380 void OCRepresentation::Prop::load(Archive& ar)
382 optional_load(ar, cereal::make_nvp(Key::RESOURCETYPESKEY, m_types));
383 optional_load(ar, cereal::make_nvp(Key::INTERFACESKEY, m_interfaces));
387 // note: the below is used to load an AttributeValue map out of JSON
392 enum class typeTag:uint8_t
402 typedef rapidjson::Document::GenericValue GenericValue;
404 AttributeValue parseAttributeValue(const GenericValue& v);
405 AttributeValue parseAttributeValue(const GenericValue& v,
406 const unsigned int curLevel, unsigned int& maxDepth, typeTag& t);
407 AttributeValue parseAttributeValueObject(const GenericValue& v, typeTag& t);
408 AttributeValue parseAttributeValueArray(const GenericValue& v,
409 const unsigned int curLevel, unsigned int& maxDepth, typeTag& t);
410 AttributeValue parseAttributeValuePrimitive(const GenericValue& v, typeTag& t);
412 AttributeValue parseAttributeValue(const GenericValue& v)
414 // base entrance, start everything at '0'
415 unsigned int max_depth {0};
416 typeTag t {typeTag::NOTHING};
418 return parseAttributeValue(v, 0, max_depth, t);
421 AttributeValue parseAttributeValue(const GenericValue& v,
422 const unsigned int curLevel, unsigned int& maxDepth, typeTag& t)
426 return parseAttributeValueObject(v, t);
430 return parseAttributeValueArray(v, curLevel + 1, maxDepth, t);
434 return parseAttributeValuePrimitive(v,t);
438 AttributeValue parseAttributeValueObject(const GenericValue& v, typeTag& t)
440 typedef rapidjson::Value::ConstMemberIterator CMI;
441 t = typeTag::_representation;
442 OC::OCRepresentation rep;
444 for(CMI itr = v.MemberBegin(); itr!= v.MemberEnd(); ++itr)
446 std::string keyName = itr->name.GetString();
448 if(keyName == OC::Key::URIKEY)
450 rep.setUri(boost::get<std::string>(parseAttributeValue(itr->value)));
452 else if (keyName == OC::Key::PROPERTYKEY)
454 for(CMI itr2 = itr->value.MemberBegin();
455 itr->value.MemberEnd()!=itr2;
458 if(keyName == OC::Key::RESOURCETYPESKEY)
460 rep.setResourceTypes(
461 boost::get<std::vector<std::string>>(
462 parseAttributeValue(itr->value)));
464 else if(keyName == OC::Key::PROPERTYKEY)
466 rep.setResourceInterfaces(
467 boost::get<std::vector<std::string>>(
468 parseAttributeValue(itr->value)));
472 else if (keyName == OC::Key::REPKEY)
474 for(CMI itr2 = itr->value.MemberBegin();
475 itr->value.MemberEnd()!=itr2;
478 rep.setValue(itr2->name.GetString(),
479 parseAttributeValue(itr2->value));
487 AttributeValue parseAttributeValuePrimitive(const GenericValue& v, typeTag& t)
491 t = typeTag::_string;
492 return std::string(v.GetString());
494 else if (v.IsNumber())
498 t = typeTag::_double;
499 return double(v.GetDouble());
504 return int(v.GetInt());
508 throw OC::OCException(OC::Exception::INVALID_JSON_NUMERIC
509 + std::to_string(v.GetType()));
515 return bool(v.GetBool_());
519 return OC::NullType();
523 throw OC::OCException(OC::Exception::INVALID_JSON_TYPE
524 + std::to_string(v.GetType()));
528 std::vector<AttributeValue> gatherArrayContents(const GenericValue& v,
529 const unsigned int curLevel, unsigned int& maxDepth, typeTag& t)
531 std::vector<AttributeValue> out;
533 std::transform(v.Begin(), v.End(), back_inserter(out),
534 [curLevel, &maxDepth, &t](const GenericValue& x)
536 return parseAttributeValue(x, curLevel, maxDepth, t);
542 struct valueToConcrete
544 OutT operator()(const AttributeValue& v)
546 return boost::get<OutT>(v);
551 template <class OutSeqT>
552 OutSeqT valuesToConcreteVectors(const std::vector<AttributeValue>& vs)
556 std::transform(begin(vs),end(vs), back_inserter(ret),
557 valueToConcrete<typename OutSeqT::value_type>());
561 template<class valueType>
562 AttributeValue remapArrayDepth(const unsigned int curLevel,
563 const std::vector<OC::AttributeValue>& vs)
568 throw OC::OCException(OC::Exception::INVALID_JSON_ARRAY_DEPTH);
571 return valuesToConcreteVectors<std::vector<valueType>>(vs);
574 return valuesToConcreteVectors<std::vector<std::vector<valueType>>>(vs);
577 return valuesToConcreteVectors
578 <std::vector<std::vector<std::vector<valueType>>>>(vs);
583 AttributeValue convertArrayToConcretes(const typeTag t,
584 const unsigned int curLevel, const std::vector<OC::AttributeValue>& vs)
586 // This function converts a std::vector of AttributeValue to a std::vector
587 // of concrete types. Since we don't use a recursive Variant, we need
588 // to get back to a 'base' primitive type
592 case typeTag::NOTHING:
593 throw OC::OCException(OC::Exception::INVALID_JSON_TYPE_TAG);
595 case typeTag::_string:
596 return remapArrayDepth<std::string>(curLevel, vs);
599 return remapArrayDepth<int>(curLevel, vs);
601 case typeTag::_double:
602 return remapArrayDepth<double>(curLevel, vs);
605 return remapArrayDepth<bool>(curLevel, vs);
607 case typeTag::_representation:
608 return remapArrayDepth<OCRepresentation>(curLevel, vs);
613 AttributeValue parseAttributeValueArray(const GenericValue& v,
614 const unsigned int curLevel, unsigned int& maxDepth, typeTag& t)
616 const unsigned int max_level = 3;
618 if(curLevel > max_level)
620 throw OC::OCException(OC::Exception::INVALID_JSON_ARRAY_DEPTH);
623 if(curLevel > maxDepth)
628 auto arrayItems = gatherArrayContents(v, curLevel, maxDepth, t);
629 const int remapLevel = maxDepth - (curLevel -1);
630 return convertArrayToConcretes(t, remapLevel, arrayItems);
637 void JSONInputArchive::loadAttributeValues(std::map<std::string, OC::AttributeValue>& map)
639 for(auto&b = itsIteratorStack.back();
640 b.Member && b.itsMemberItEnd != b.itsMemberItBegin+b.itsIndex;
643 std::string key = b.itsMemberItBegin[b.itsIndex].name.GetString();
644 const GenericValue& v = itsIteratorStack.back().value();
645 map[key] = OC::detail::parseAttributeValue(v);
652 std::ostream& operator <<(std::ostream& os, const AttributeType at)
656 case AttributeType::Null:
659 case AttributeType::Integer:
662 case AttributeType::Double:
665 case AttributeType::Boolean:
668 case AttributeType::String:
671 case AttributeType::OCRepresentation:
672 os << "OCRepresentation";
674 case AttributeType::Vector:
682 // STL Container For OCRepresentation
685 OCRepresentation::AttributeItem::AttributeItem(const std::string& name,
686 std::map<std::string, AttributeValue>& vals):
687 m_attrName(name), m_values(vals){}
689 OCRepresentation::AttributeItem OCRepresentation::operator[](const std::string& key)
691 OCRepresentation::AttributeItem attr{key, m_values};
692 return std::move(attr);
695 const OCRepresentation::AttributeItem OCRepresentation::operator[](const std::string& key) const
697 OCRepresentation::AttributeItem attr{key, m_values};
698 return std::move(attr);
701 const std::string& OCRepresentation::AttributeItem::attrname() const
706 template<typename T, typename = void>
709 // contains the actual type
711 // contains the inner most vector-type
713 // contains the AttributeType for this item
714 constexpr static AttributeType enum_type =
715 AttributeTypeConvert<T>::type;
716 // contains the AttributeType for this base-type
717 constexpr static AttributeType enum_base_type =
718 AttributeTypeConvert<T>::type;
719 // depth of the vector
720 constexpr static size_t depth = 0;
724 struct type_info<T, typename std::enable_if<is_vector<T>::value>::type>
727 typedef typename type_info<typename T::value_type>::base_type base_type;
728 constexpr static AttributeType enum_type = AttributeType::Vector;
729 constexpr static AttributeType enum_base_type =
730 type_info<typename T::value_type>::enum_base_type;
731 constexpr static size_t depth = 1 +
732 type_info<typename T::value_type>::depth;
735 struct type_introspection_visitor : boost::static_visitor<>
738 AttributeType base_type;
741 type_introspection_visitor() : boost::static_visitor<>(),
742 type(AttributeType::Null), base_type(AttributeType::Null), depth(0){}
744 template <typename T>
745 void operator()(T const& item)
747 type = type_info<T>::enum_type;
748 base_type = type_info<T>::enum_base_type;
749 depth = type_info<T>::depth;
753 AttributeType OCRepresentation::AttributeItem::type() const
755 type_introspection_visitor vis;
756 boost::apply_visitor(vis, m_values[m_attrName]);
760 AttributeType OCRepresentation::AttributeItem::base_type() const
762 type_introspection_visitor vis;
763 boost::apply_visitor(vis, m_values[m_attrName]);
764 return vis.base_type;
767 size_t OCRepresentation::AttributeItem::depth() const
769 type_introspection_visitor vis;
770 boost::apply_visitor(vis, m_values[m_attrName]);
774 OCRepresentation::iterator OCRepresentation::begin()
776 return OCRepresentation::iterator(m_values.begin(), m_values);
779 OCRepresentation::const_iterator OCRepresentation::begin() const
781 return OCRepresentation::const_iterator(m_values.begin(), m_values);
784 OCRepresentation::const_iterator OCRepresentation::cbegin() const
786 return OCRepresentation::const_iterator(m_values.cbegin(), m_values);
789 OCRepresentation::iterator OCRepresentation::end()
791 return OCRepresentation::iterator(m_values.end(), m_values);
794 OCRepresentation::const_iterator OCRepresentation::end() const
796 return OCRepresentation::const_iterator(m_values.end(), m_values);
799 OCRepresentation::const_iterator OCRepresentation::cend() const
801 return OCRepresentation::const_iterator(m_values.cend(), m_values);
804 size_t OCRepresentation::size() const
806 return m_values.size();
809 bool OCRepresentation::empty() const
811 return m_values.empty();
814 bool OCRepresentation::iterator::operator==(const OCRepresentation::iterator& rhs) const
816 return m_iterator == rhs.m_iterator;
819 bool OCRepresentation::iterator::operator!=(const OCRepresentation::iterator& rhs) const
821 return m_iterator != rhs.m_iterator;
824 bool OCRepresentation::const_iterator::operator==(
825 const OCRepresentation::const_iterator& rhs) const
827 return m_iterator == rhs.m_iterator;
830 bool OCRepresentation::const_iterator::operator!=(
831 const OCRepresentation::const_iterator& rhs) const
833 return m_iterator != rhs.m_iterator;
836 OCRepresentation::iterator::reference OCRepresentation::iterator::operator*()
841 OCRepresentation::const_iterator::const_reference
842 OCRepresentation::const_iterator::operator*() const
847 OCRepresentation::iterator::pointer OCRepresentation::iterator::operator->()
852 OCRepresentation::const_iterator::const_pointer
853 OCRepresentation::const_iterator::operator->() const
858 OCRepresentation::iterator& OCRepresentation::iterator::operator++()
861 if(m_iterator != m_item.m_values.end())
863 m_item.m_attrName = m_iterator->first;
867 m_item.m_attrName = "";
872 OCRepresentation::const_iterator& OCRepresentation::const_iterator::operator++()
875 if(m_iterator != m_item.m_values.end())
877 m_item.m_attrName = m_iterator->first;
881 m_item.m_attrName = "";
886 OCRepresentation::iterator OCRepresentation::iterator::operator++(int)
888 OCRepresentation::iterator itr(*this);
893 OCRepresentation::const_iterator OCRepresentation::const_iterator::operator++(int)
895 OCRepresentation::const_iterator itr(*this);
900 struct to_string_visitor : boost::static_visitor<>
903 template <typename T>
904 void operator()(T const& item)
906 str = boost::lexical_cast<std::string>(item);
909 template <typename T>
910 void operator()(std::vector<T> const& item)
912 to_string_visitor vis;
913 std::ostringstream stream;
916 for(const auto& i : item)
919 stream << vis.str << " ";
927 void to_string_visitor::operator()(bool const& item)
929 str = item ? "true" : "false";
933 void to_string_visitor::operator()(std::string const& item)
939 void to_string_visitor::operator()(NullType const& item)
945 void to_string_visitor::operator()(OCRepresentation const& item)
947 str = "OC::OCRepresentation";
950 std::string OCRepresentation::getValueToString(const std::string& key) const
952 auto x = m_values.find(key);
953 if(x != m_values.end())
955 to_string_visitor vis;
956 boost::apply_visitor(vis, x->second);
957 return std::move(vis.str);
963 std::string OCRepresentation::AttributeItem::getValueToString() const
965 to_string_visitor vis;
966 boost::apply_visitor(vis, m_values[m_attrName]);
967 return std::move(vis.str);
970 std::ostream& operator<<(std::ostream& os, const OCRepresentation::AttributeItem& ai)
972 os << ai.getValueToString();