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 <cereal/cereal.hpp>
30 #include <cereal/types/map.hpp>
31 #include <cereal/types/vector.hpp>
32 #include <cereal/types/utility.hpp>
33 #include <OicJsonSerializer.hpp>
36 // code needed to serialize a string=>Attribute value map
41 template<class Archive>
42 class WriteAttributeValue : public boost::static_visitor<>
45 WriteAttributeValue(const std::string& name, Archive& ar)
46 :m_name(name), m_archive(ar)
50 void operator()(const T& value) const
52 m_archive(cereal::make_nvp(m_name, value));
63 // take no action when serializing the null type, because the 'save' below
64 // doesn't use the visitor for this type.
65 template <class Archive>
66 void serialize(Archive&, OC::NullType t)
69 template<class Archive>
70 void save(Archive& ar, const std::map<std::string, OC::AttributeValue>& vals)
72 for(const auto& kv : vals)
74 const auto& k = kv.first;
75 const auto& v = kv.second;
77 if(v.which() != OC::AttributeValueNullIndex)
79 OC::detail::WriteAttributeValue<Archive> writer(k,ar);
80 boost::apply_visitor(writer, v);
84 ar.setNextName(k.c_str());
91 template<class Archive>
92 void load(Archive& ar, std::map<std::string, OC::AttributeValue>& vals)
94 ar.loadAttributeValues(vals);
100 typedef cereal::JSONOutputArchive OutputArchiveType;
101 typedef cereal::JSONInputArchive InputArchiveType;
103 void MessageContainer::setJSONRepresentation(const std::string& payload)
105 std::stringstream os(payload);
107 InputArchiveType archive(os);
108 archive(cereal::make_nvp(OC::Key::OCKEY, m_reps));
112 void MessageContainer::setJSONRepresentation(const unsigned char* payload)
114 setJSONRepresentation(std::string(reinterpret_cast<const char*>(payload)));
117 std::string MessageContainer::getJSONRepresentation(OCInfoFormat f) const
119 std::stringstream os;
121 // note: the block is required because cereal closes the JSON string
122 // upon destruction, so the archive needs to be destroyed before accessing
125 if(f == OCInfoFormat::IncludeOC)
127 OutputArchiveType archive(os);
128 archive(cereal::make_nvp(OC::Key::OCKEY, m_reps));
130 else if(f== OCInfoFormat::ExcludeOC)
132 bool firstPrinted = false;
133 for(std::vector<OCRepresentation>::size_type i = 0; i< m_reps.size();++i)
135 if(!m_reps[i].empty())
142 os << m_reps[i].getJSONRepresentation();
150 const std::vector<OCRepresentation>& MessageContainer::representations() const
155 void MessageContainer::addRepresentation(const OCRepresentation& rep)
157 m_reps.push_back(rep);
163 OCRepresentation::OCRepresentation()
164 :m_interfaceType(InterfaceType::None)
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::empty() 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);