[IOT-3055]Fixed Handle collection resource payload
[iotivity.git] / resource / include / OCRepresentation.h
1 //******************************************************************
2 //
3 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
4 //
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
6 //
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
10 //
11 //      http://www.apache.org/licenses/LICENSE-2.0
12 //
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.
18 //
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
20
21 /**
22  * @file
23  *
24  * This file contains the declaration of classes and its members related
25  * to OCRepresentation.
26  */
27
28 #ifndef OC_REPRESENTATION_H_
29 #define OC_REPRESENTATION_H_
30
31 #include <string>
32 #include <sstream>
33 #include <vector>
34 #include <map>
35
36 #include <AttributeValue.h>
37 #include <StringConstants.h>
38
39 #ifdef __ANDROID__
40 #include "OCAndroid.h"
41 #endif
42
43 #include <OCException.h>
44
45 namespace OC
46 {
47
48     enum class InterfaceType
49     {
50         None,
51         LinkParent,
52         BatchParent,
53         DefaultParent,
54         LinkChild,
55         BatchChild,
56         DefaultChild
57     };
58
59     class MessageContainer
60     {
61         public:
62             void setPayload(const OCPayload* rep);
63
64             void setPayload(const OCRepPayload* rep);
65
66             OCRepPayload* getPayload() const;
67
68             const std::vector<OCRepresentation>& representations() const;
69
70             void addRepresentation(const OCRepresentation& rep);
71
72             const OCRepresentation& operator[](int index) const
73             {
74                 return m_reps[index];
75             }
76
77             const OCRepresentation& back() const
78             {
79                 return m_reps.back();
80             }
81         private:
82             std::vector<OCRepresentation> m_reps;
83     };
84     class OCRepresentation
85     {
86         public:
87             friend bool operator==(const OC::OCRepresentation&, const OC::OCRepresentation&);
88             // Note: Implementation of all constructors and destructors
89             // are all placed in the same location due to a crash that
90             // was observed in Android, where merely constructing/destructing
91             // an OCRepresentation object was enough to cause an invalid 'free'.
92             // It is believed that this is a result of incompatible compiler
93             // options between the gradle JNI and armeabi scons build, however
94             // this fix will work in the meantime.
95             OCRepresentation(): m_interfaceType(InterfaceType::None){}
96
97             virtual ~OCRepresentation(){}
98
99             void setDevAddr(const OCDevAddr&);
100
101             const std::string getHost() const;
102
103             OCRepPayload* getPayload() const;
104
105             void setInterfaceType(const InterfaceType&);
106
107             InterfaceType getInterfaceType() const;
108
109             void setIsCollectionResource(bool isColResource);
110
111             bool isCollectionResource() const;
112
113             void addChild(const OCRepresentation&);
114
115             void clearChildren();
116
117             const std::vector<OCRepresentation>& getChildren() const;
118
119             void setChildren(const std::vector<OCRepresentation>& children);
120
121             void setUri(const char* uri);
122
123             void setUri(const std::string& uri);
124
125             std::string getUri() const;
126
127             const std::vector<std::string>& getResourceTypes() const;
128
129             const std::vector<std::string>& getDataModelVersions() const;
130
131             void setResourceTypes(const std::vector<std::string>& resourceTypes);
132
133             void addResourceType(const std::string& str);
134
135             const std::vector<std::string>& getResourceInterfaces() const;
136
137             void setResourceInterfaces(const std::vector<std::string>& resourceInterfaces);
138
139             void addResourceInterface(const std::string& str);
140
141             void addDataModelVersion(const std::string& str);
142
143             bool emptyData() const;
144
145             size_t numberOfAttributes() const;
146
147             bool erase(const std::string& str);
148
149             template <typename T>
150             void setValue(const std::string& str, const T& val)
151             {
152                 m_values[str] = val;
153             }
154
155             // using R-value(or universal ref depending) to move string and vector<uint8_t>
156             template <typename T>
157             void setValue(const std::string& str, T&& val)
158             {
159                 m_values[str] = std::forward<T>(val);
160             }
161
162             const std::map<std::string, AttributeValue>& getValues() const {
163                 return m_values;
164             }
165
166             /**
167              *  Retrieve the attribute value associated with the supplied name
168              *
169              *  @param str Name of the attribute
170              *  @param val Value of the attribute
171              *  @return The getValue method returns true if the attribute was
172              *        found in the representation.  Otherwise it returns false.
173              */
174             template <typename T>
175             bool getValue(const std::string& str, T& val) const
176             {
177                 auto x = m_values.find(str);
178
179                 if(x!= m_values.end())
180                 {
181                     try
182                     {
183                         val = boost::get<T>(x->second);
184                         return true;
185                     }
186                     catch (boost::bad_get&)
187                     {
188                         val = T();
189                         return false;
190                     }
191                 }
192                 else
193                 {
194                     val = T();
195                     return false;
196                 }
197             }
198
199             /**
200              *  Return the attribute value associated with the supplied name
201              *
202              *  @param str Name of the attribute
203              *  @return When the representation contains the attribute, the
204              *       the associated value is returned.  Otherwise, getValue
205              *       returns the default contructed value for the type.
206              */
207             template <typename T>
208             T getValue(const std::string& str) const
209             {
210                 T val = T();
211                 auto x = m_values.find(str);
212                 if(x != m_values.end())
213                 {
214                     try
215                     {
216                         val = boost::get<T>(x->second);
217                     }
218                     catch (boost::bad_get&)
219                     {
220                         return val;
221                     }
222                 }
223                 return val;
224             }
225
226            /**
227             *  Retrieve the attributevalue structure associated with the supplied name
228             *
229             *  @param str Name of the attribute
230             *  @param attrValue Attribute Value structure
231             *  @return The getAttributeValue method returns true if the attribute was
232             *        found in the representation.  Otherwise it returns false.
233             */
234             bool getAttributeValue(const std::string& str, AttributeValue& attrValue) const
235             {
236                 auto x = m_values.find(str);
237
238                 if (x != m_values.end())
239                 {
240                     attrValue = x->second;
241                     return true;
242                 }
243                 else
244                 {
245                     return false;
246                 }
247             }
248
249             std::string getValueToString(const std::string& key) const;
250             bool hasAttribute(const std::string& str) const;
251
252             void setNULL(const std::string& str);
253
254             bool isNULL(const std::string& str) const;
255
256         private:
257             std::string m_host;
258
259             // STL Container stuff
260         public:
261             class iterator;
262             class const_iterator;
263             // Shim class to allow iterating and indexing of the OCRepresentation
264             // object.
265             class AttributeItem
266             {
267                 friend class OCRepresentation;
268                 friend class iterator;
269                 friend class const_iterator;
270                 public:
271                     const std::string& attrname() const;
272                     AttributeType type() const;
273                     AttributeType base_type() const;
274                     size_t depth() const;
275                     template<typename T>
276                     T getValue() const
277                     {
278                         try
279                         {
280                             return boost::get<T>(m_values[m_attrName]);
281                         }
282                         catch (boost::bad_get&)
283                         {
284                             T val = T();
285                             return val;
286                         }
287                     }
288
289                     std::string getValueToString() const;
290
291                     template<typename T>
292                     AttributeItem& operator=(T&& rhs)
293                     {
294                         m_values[m_attrName] = std::forward<T>(rhs);
295                         return *this;
296                     }
297
298                     AttributeItem& operator=(std::nullptr_t /*rhs*/)
299                     {
300                         NullType t;
301                         m_values[m_attrName] = t;
302                         return *this;
303                     }
304
305                     // Enable-if required to prevent conversions to alternate types.  This prevents
306                     // ambigious conversions in the case where conversions can include a number of
307                     // types, such as the string constructor.
308 #if (defined(_MSC_VER) ) || (defined(__GNUC__) && (__GNUC__ <= 5))
309                     template<typename T, typename std::enable_if<
310                      std::is_same<T, int>::value ||
311                      std::is_same<T, double>::value ||
312                      std::is_same<T, bool>::value ||
313                      std::is_same<T, std::string>::value ||
314                      std::is_same<T, OCRepresentation>::value ||
315                      std::is_same<T, OCByteString>::value ||
316                      std::is_same<T, std::vector<int>>::value ||
317                      std::is_same<T, std::vector<std::vector<int>>>::value ||
318                      std::is_same<T, std::vector<std::vector<std::vector<int>>>>::value ||
319                      std::is_same<T, std::vector<double>>::value ||
320                      std::is_same<T, std::vector<std::vector<double>>>::value ||
321                      std::is_same<T, std::vector<std::vector<std::vector<double>>>>::value ||
322                      std::is_same<T, std::vector<bool>>::value ||
323                      std::is_same<T, std::vector<std::vector<bool>>>::value ||
324                      std::is_same<T, std::vector<std::vector<std::vector<bool>>>>::value ||
325                      std::is_same<T, std::vector<std::string>>::value ||
326                      std::is_same<T, std::vector<std::vector<std::string>>>::value ||
327                      std::is_same<T, std::vector<std::vector<std::vector<std::string>>>>::value ||
328                      std::is_same<T, std::vector<OCRepresentation>>::value ||
329                      std::is_same<T, std::vector<std::vector<OCRepresentation>>>::value ||
330                      std::is_same<T, std::vector<std::vector<std::vector<OCRepresentation>>>>::value ||
331                      std::is_same<T, std::vector<OCByteString>>::value ||
332                      std::is_same<T, std::vector<std::vector<OCByteString>>>::value ||
333                      std::is_same<T, std::vector<std::vector<std::vector<OCByteString>>>>::value
334                      , int>::type = 0// enable_if
335                     >
336 #else
337                     template<typename T, typename std::enable_if<
338                         is_component<T,
339                             remove_first<AttributeValue>::type
340                             >::value
341                         , int>::type = 0
342                     >
343 #endif
344                     operator T() const
345                     {
346                         return this->getValue<T>();
347                     }
348
349                     template<typename T, typename std::enable_if<
350                         std::is_same<T, std::nullptr_t>::value
351                         , int>::type = 0
352                     >
353                     operator T() const
354                     {
355                         this->getValue<NullType>();
356                         return nullptr;
357                     }
358
359                 private:
360                     AttributeItem(const std::string& name,
361                             std::map<std::string, AttributeValue>& vals);
362                     AttributeItem(const AttributeItem&) = default;
363                     std::string m_attrName;
364                     std::map<std::string, AttributeValue>& m_values;
365             };
366
367             // Iterator to allow iteration via STL containers/methods
368             class iterator
369             {
370                 friend class OCRepresentation;
371                 public:
372                     typedef iterator self_type;
373                     typedef AttributeItem value_type;
374                     typedef value_type& reference;
375                     typedef value_type* pointer;
376                     typedef std::forward_iterator_tag iterator_category;
377                     typedef int difference_type;
378
379                     iterator(const iterator&) = default;
380                     ~iterator() = default;
381
382                     bool operator ==(const iterator&) const;
383                     bool operator !=(const iterator&) const;
384
385                     iterator& operator++();
386                     iterator operator++(int);
387
388                     reference operator*();
389                     pointer operator->();
390                 private:
391                     iterator(std::map<std::string, AttributeValue>::iterator&& itr,
392                             std::map<std::string, AttributeValue>& vals)
393                         : m_iterator(std::move(itr)),
394                         m_item(m_iterator != vals.end() ? m_iterator->first:"", vals){}
395                     std::map<std::string, AttributeValue>::iterator m_iterator;
396                     AttributeItem m_item;
397             };
398
399             class const_iterator
400             {
401                 friend class OCRepresentation;
402                 public:
403                     typedef iterator self_type;
404                     typedef const AttributeItem value_type;
405                     typedef value_type& const_reference;
406                     typedef value_type* const_pointer;
407                     typedef std::forward_iterator_tag iterator_category;
408                     typedef int difference_type;
409
410                     const_iterator(const iterator& rhs)
411                         :m_iterator(rhs.m_iterator), m_item(rhs.m_item){}
412                     const_iterator(const const_iterator&) = default;
413                     ~const_iterator() = default;
414
415                     bool operator ==(const const_iterator&) const;
416                     bool operator !=(const const_iterator&) const;
417
418                     const_iterator& operator++();
419                     const_iterator operator++(int);
420
421                     const_reference operator*() const;
422                     const_pointer operator->() const;
423                 private:
424                     const_iterator(std::map<std::string, AttributeValue>::const_iterator&& itr,
425                             std::map<std::string, AttributeValue>& vals)
426                         : m_iterator(std::move(itr)),
427                         m_item(m_iterator != vals.end() ? m_iterator->first: "", vals){}
428                     std::map<std::string, AttributeValue>::const_iterator m_iterator;
429                     AttributeItem m_item;
430             };
431
432             iterator begin();
433             const_iterator begin() const;
434             const_iterator cbegin() const;
435             iterator end();
436             const_iterator end() const;
437             const_iterator cend() const;
438             size_t size() const;
439             bool empty() const;
440
441             AttributeItem operator[](const std::string& key);
442             const AttributeItem operator[](const std::string& key) const;
443         private:
444             friend class OCResourceResponse;
445             friend class MessageContainer;
446
447             template<typename T>
448             void payload_array_helper(const OCRepPayloadValue* pl, size_t depth);
449             template<typename T>
450             T payload_array_helper_copy(size_t index, const OCRepPayloadValue* pl);
451             void setPayload(const OCRepPayload* payload);
452             void setPayloadArray(const OCRepPayloadValue* pl);
453             void getPayloadArray(OCRepPayload* payload,
454                     const OCRepresentation::AttributeItem& item) const;
455             // the root node has a slightly different JSON version
456             // based on the interface type configured in ResourceResponse.
457             // This allows ResourceResponse to set it, so that the save function
458             // doesn't serialize things that it isn't supposed to serialize.
459
460             // class used to wrap the 'prop' feature of the save/load
461             class Prop
462             {
463                 public:
464                     Prop(std::vector<std::string>& resourceTypes,
465                             std::vector<std::string>& interfaces)
466                     : m_types(resourceTypes), m_interfaces(interfaces)
467                     {}
468
469                  /*   Prop(const std::vector<std::string>& resourceTypes,
470                             const std::vector<std::string>& interfaces)
471                     :m_types(resourceTypes),
472                     m_interfaces(interfaces)
473                     {}*/
474                 private:
475                     std::vector<std::string>& m_types;
476                     std::vector<std::string>& m_interfaces;
477             };
478         private:
479             std::string m_uri;
480             std::vector<OCRepresentation> m_children;
481             mutable std::map<std::string, AttributeValue> m_values;
482             std::vector<std::string> m_resourceTypes;
483             std::vector<std::string> m_interfaces;
484             std::vector<std::string> m_dataModelVersions;
485
486             InterfaceType m_interfaceType;
487             bool m_isCollectionResource;
488     };
489
490     std::ostream& operator <<(std::ostream& os, const OCRepresentation::AttributeItem& ai);
491 } // namespace OC
492
493
494 #endif // OC_REPRESENTATION_H_