]> granicus.if.org Git - icinga2/blob - lib/base/serializer.cpp
Update copyright header.
[icinga2] / lib / base / serializer.cpp
1 /******************************************************************************
2 * Icinga 2                                                                   *
3 * Copyright (C) 2012-present Icinga Development Team (http://www.icinga.org) *
4 *                                                                            *
5 * This program is free software; you can redistribute it and/or              *
6 * modify it under the terms of the GNU General Public License                *
7 * as published by the Free Software Foundation; either version 2             *
8 * of the License, or (at your option) any later version.                     *
9 *                                                                            *
10 * This program is distributed in the hope that it will be useful,            *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of             *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the              *
13 * GNU General Public License for more details.                               *
14 *                                                                            *
15 * You should have received a copy of the GNU General Public License          *
16 * along with this program; if not, write to the Free Software Foundation     *
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.             *
18 ******************************************************************************/
19
20 #include "base/serializer.h"
21 #include "base/type.h"
22 #include "base/application.h"
23 #include "base/objectlock.h"
24 #include <boost/foreach.hpp>
25 #include <cJSON.h>
26
27 using namespace icinga;
28
29 /**
30  * Serializes a Value into a JSON string.
31  *
32  * @returns A string representing the Value.
33  */
34 String icinga::JsonSerialize(const Value& value)
35 {
36         cJSON *json = value.ToJson();
37
38         char *jsonString;
39
40         if (Application::IsDebugging())
41                 jsonString = cJSON_Print(json);
42         else
43                 jsonString = cJSON_PrintUnformatted(json);
44
45         cJSON_Delete(json);
46
47         String result = jsonString;
48
49         free(jsonString);
50
51         return result;
52 }
53
54 /**
55  * Deserializes the string representation of a Value.
56  *
57  * @param data A JSON string obtained from JsonSerialize
58  * @returns The newly deserialized Value.
59  */
60 Value icinga::JsonDeserialize(const String& data)
61 {
62         cJSON *json = cJSON_Parse(data.CStr());
63
64         if (!json)
65                 BOOST_THROW_EXCEPTION(std::runtime_error("Invalid JSON String: " + data));
66
67         Value value = Value::FromJson(json);
68         cJSON_Delete(json);
69
70         return value;
71 }
72
73 static Array::Ptr SerializeArray(const Array::Ptr& input, int attributeTypes)
74 {
75         Array::Ptr result = make_shared<Array>();
76
77         ObjectLock olock(input);
78
79         BOOST_FOREACH(const Value& value, input) {
80                 result->Add(Serialize(value, attributeTypes));
81         }
82
83         return result;
84 }
85
86 static Dictionary::Ptr SerializeDictionary(const Dictionary::Ptr& input, int attributeTypes)
87 {
88         Dictionary::Ptr result = make_shared<Dictionary>();
89
90         ObjectLock olock(input);
91
92         BOOST_FOREACH(const Dictionary::Pair& kv, input) {
93                 result->Set(kv.first, Serialize(kv.second, attributeTypes));
94         }
95
96         return result;
97 }
98
99 static Object::Ptr SerializeObject(const Object::Ptr& input, int attributeTypes)
100 {
101         const Type *type = input->GetReflectionType();
102
103         VERIFY(type);
104
105         Dictionary::Ptr fields = make_shared<Dictionary>();
106
107         for (int i = 0; i < type->GetFieldCount(); i++) {
108                 Field field = type->GetFieldInfo(i);
109
110                 if ((field.Attributes & attributeTypes) == 0)
111                         continue;
112
113                 fields->Set(field.Name, Serialize(input->GetField(i), attributeTypes));
114         }
115
116         fields->Set("__type", type->GetName());
117
118         return fields;
119 }
120
121 static Array::Ptr DeserializeArray(const Array::Ptr& input, bool safe_mode, int attributeTypes)
122 {
123         Array::Ptr result = make_shared<Array>();
124
125         ObjectLock olock(input);
126
127         BOOST_FOREACH(const Value& value, input) {
128                 result->Add(Deserialize(value, safe_mode, attributeTypes));
129         }
130
131         return result;
132 }
133
134 static Dictionary::Ptr DeserializeDictionary(const Dictionary::Ptr& input, bool safe_mode, int attributeTypes)
135 {
136         Dictionary::Ptr result = make_shared<Dictionary>();
137
138         ObjectLock olock(input);
139
140         BOOST_FOREACH(const Dictionary::Pair& kv, input) {
141                 result->Set(kv.first, Deserialize(kv.second, attributeTypes));
142         }
143
144         return result;
145 }
146
147 static Object::Ptr DeserializeObject(const Object::Ptr& object, const Dictionary::Ptr& input, bool safe_mode, int attributeTypes)
148 {
149         const Type *type;
150
151         if (object)
152                 type = object->GetReflectionType();
153         else
154                 type = Type::GetByName(input->Get("__type"));
155
156         if (!type)
157                 return object;
158
159         Object::Ptr instance = object;
160
161         if (!instance) {
162                 if (safe_mode && !type->IsSafe())
163                         BOOST_THROW_EXCEPTION(std::runtime_error("Tried to instantiate type '" + type->GetName() + "' which is not marked as safe."));
164
165                 instance = type->Instantiate();
166         }
167
168         BOOST_FOREACH(const Dictionary::Pair& kv, input) {
169                 if (kv.first.IsEmpty())
170                         continue;
171
172                 int fid = type->GetFieldId(kv.first);
173         
174                 if (fid < 0)
175                         continue;
176
177                 Field field = type->GetFieldInfo(fid);
178
179                 if ((field.Attributes & attributeTypes) == 0)
180                         continue;
181
182                 try {
183                         instance->SetField(fid, Deserialize(kv.second, safe_mode, attributeTypes));
184                 } catch (const std::exception&) {
185                         instance->SetField(fid, Empty);
186                 }
187         }
188
189         return instance;
190 }
191
192 Value icinga::Serialize(const Value& value, int attributeTypes)
193 {
194         if (!value.IsObject())
195                 return value;
196
197         Object::Ptr input = value;
198
199         Array::Ptr array = dynamic_pointer_cast<Array>(input);
200
201         if (array != NULL)
202                 return SerializeArray(array, attributeTypes);
203
204         Dictionary::Ptr dict = dynamic_pointer_cast<Dictionary>(input);
205
206         if (dict != NULL)
207                 return SerializeDictionary(dict, attributeTypes);
208
209         return SerializeObject(input, attributeTypes);
210 }
211
212 Value icinga::Deserialize(const Value& value, bool safe_mode, int attributeTypes)
213 {
214         return Deserialize(Object::Ptr(), value, safe_mode, attributeTypes);
215 }
216
217 Value icinga::Deserialize(const Object::Ptr& object, const Value& value, bool safe_mode, int attributeTypes)
218 {
219         if (!value.IsObject())
220                 return value;
221
222         Object::Ptr input = value;
223
224         Array::Ptr array = dynamic_pointer_cast<Array>(input);
225
226         if (array != NULL)
227                 return DeserializeArray(array, safe_mode, attributeTypes);
228
229         Dictionary::Ptr dict = dynamic_pointer_cast<Dictionary>(input);
230
231         ASSERT(dict != NULL);
232
233         if (!dict->Contains("__type"))
234                 return DeserializeDictionary(dict, safe_mode, attributeTypes);
235
236         return DeserializeObject(object, dict, safe_mode, attributeTypes);
237 }