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