summaryrefslogtreecommitdiff
path: root/src/manager/initial-values/parser.cpp
blob: 6b393d4b26db2663d1fe294cee6bf0edb21fe0d7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
/*
 *  Copyright (c) 2000 - 2015 Samsung Electronics Co., Ltd All Rights Reserved
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License
 *
 *
 * @file        parser.cpp
 * @author      Maciej Karpiuk (m.karpiuk2@samsung.com)
 * @version     1.0
 * @brief       XML parser class implementation.
 */

#include <string>
#include <string.h>
#include <algorithm>
#include <exception>
#include <libxml/parser.h>
#include <libxml/valid.h>
#include <libxml/xmlschemas.h>
#include <parser.h>
#include <xml-utils.h>
#include <dpl/log/log.h>

namespace CKM {
namespace XML {

namespace {

struct LibXmlCleanup {
	~LibXmlCleanup()
	{
		xmlCleanupParser();
	}
} cleanup;

} // namespace anonymous

Parser::Parser(const std::string &XML_filename) :
	m_errorCb(0)
{
	m_XMLfile = XML_filename;
	memset(&m_saxHandler, 0, sizeof(m_saxHandler));
	m_saxHandler.startElement = &Parser::StartElement;
	m_saxHandler.endElement = &Parser::EndElement;
	m_saxHandler.characters = &Parser::Characters;
	m_saxHandler.error = &Parser::Error;
	m_saxHandler.warning = &Parser::Warning;
}
Parser::~Parser()
{
}

using SchemaParserCtxt =
	std::unique_ptr<xmlSchemaParserCtxt, void(*)(xmlSchemaParserCtxtPtr)>;
using Schema = std::unique_ptr<xmlSchema, void(*)(xmlSchemaPtr)>;
using SchemaValidCtxt =
	std::unique_ptr<xmlSchemaValidCtxt, void(*)(xmlSchemaValidCtxtPtr)>;
int Parser::Validate(const std::string &XSD_schema)
{
	if (XSD_schema.empty()) {
		LogError("no XSD file path given");
		return ERROR_INVALID_ARGUMENT;
	}

	int retCode;
	SchemaParserCtxt parserCtxt(xmlSchemaNewParserCtxt(XSD_schema.c_str()),
	[](xmlSchemaParserCtxtPtr ctx) {
		xmlSchemaFreeParserCtxt(ctx);
	});

	if (!parserCtxt) {
		LogError("XSD file path is invalid");
		return ERROR_INVALID_ARGUMENT;
	}

	Schema schema(xmlSchemaParse(parserCtxt.get()), [](xmlSchemaPtr schemaPtr) {
		xmlSchemaFree(schemaPtr);
	});

	if (!schema) {
		LogError("Parsing XSD file failed");
		return ERROR_XSD_PARSE_FAILED;
	}

	SchemaValidCtxt validCtxt(xmlSchemaNewValidCtxt(schema.get()), [](
	xmlSchemaValidCtxtPtr validCtxPtr) {
		xmlSchemaFreeValidCtxt(validCtxPtr);
	});

	if (!validCtxt) {
		LogError("Internal parser error");
		return ERROR_INTERNAL;
	}

	xmlSetStructuredErrorFunc(NULL, NULL);
	xmlSetGenericErrorFunc(this, &Parser::ErrorValidate);
	xmlThrDefSetStructuredErrorFunc(NULL, NULL);
	xmlThrDefSetGenericErrorFunc(this, &Parser::ErrorValidate);

	retCode = xmlSchemaValidateFile(validCtxt.get(), m_XMLfile.c_str(), 0);

	if (0 != retCode) {
		LogWarning("Validating XML file failed, ec: " << retCode);
		retCode = ERROR_XML_VALIDATION_FAILED;
	} else {
		retCode = PARSE_SUCCESS;
	}

	return retCode;
}

int Parser::Parse()
{
	if (m_elementListenerMap.empty()) {
		LogError("Can not parse XML file: no registered element callbacks.");
		return ERROR_INVALID_ARGUMENT;
	}

	int retCode = xmlSAXUserParseFile(&m_saxHandler, this, m_XMLfile.c_str());

	if (0 != retCode) {
		LogWarning("Parsing XML file failed, ec: " << retCode);
		return ERROR_XML_PARSE_FAILED;
	}

	// if error detected while parsing
	if (m_elementListenerMap.empty()) {
		LogError("Critical error detected while parsing.");
		return ERROR_INTERNAL;
	}

	return PARSE_SUCCESS;
}

int Parser::RegisterErrorCb(const ErrorCb newCb)
{
	if (m_errorCb) {
		LogError("Callback already registered!");
		return ERROR_CALLBACK_PRESENT;
	}

	m_errorCb = newCb;
	return PARSE_SUCCESS;
}

int Parser::RegisterElementCb(const char *elementName,
							  const StartCb startCb,
							  const EndCb endCb)
{
	if (!elementName)
		return ERROR_INVALID_ARGUMENT;

	std::string key(elementName);

	if (m_elementListenerMap.find(elementName) != m_elementListenerMap.end()) {
		LogError("Callback for element " << elementName << " already registered!");
		return ERROR_CALLBACK_PRESENT;
	}

	m_elementListenerMap[key] = {startCb, endCb};
	return PARSE_SUCCESS;
}

void Parser::StartElement(const xmlChar *name,
						  const xmlChar **attrs)
{
	std::string key(reinterpret_cast<const char *>(name));

	if (m_elementListenerMap.find(key) == m_elementListenerMap.end())
		return;

	ElementHandlerPtr newHandler;
	const ElementListener &current = m_elementListenerMap[key];

	if (current.startCb) {
		Attributes attribs;

		size_t numAttrs = 0;
		std::string _key;

		while (attrs && attrs[numAttrs]) {
			const char *attrChr = reinterpret_cast<const char *>(attrs[numAttrs]);

			if ((numAttrs % 2) == 0)
				_key = std::string(attrChr);
			else
				attribs[_key] = std::string(attrChr);

			numAttrs++;
		}

		newHandler = current.startCb();

		if (newHandler)
			newHandler->Start(attribs);
	}

	// always put a handler, even if it's empty. This will not break
	// the sequence of queued elements when popping from the queue.
	m_elementHandlerStack.push(newHandler);
}

void Parser::EndElement(const xmlChar *name)
{
	std::string key(reinterpret_cast<const char *>(name));

	if (m_elementListenerMap.find(key) == m_elementListenerMap.end())
		return;

	// this should never ever happen
	if (m_elementHandlerStack.empty())
		throw std::runtime_error("internal error: element queue desynchronized!");

	ElementHandlerPtr &currentHandler = m_elementHandlerStack.top();

	if (currentHandler)
		currentHandler->End();

	const ElementListener &current = m_elementListenerMap[key];

	if (current.endCb)
		current.endCb(currentHandler);

	m_elementHandlerStack.pop();
}

void Parser::Characters(const xmlChar *ch, size_t chLen)
{
	std::string chars(reinterpret_cast<const char *>(ch), chLen);

	if (chars.empty())
		return;

	if (!m_elementHandlerStack.empty()) {
		ElementHandlerPtr &currentHandler = m_elementHandlerStack.top();

		if (currentHandler)
			currentHandler->Characters(chars);
	}
}

void Parser::Error(const ErrorType errorType, const char *msg, va_list &args)
{
	if (!m_errorCb)
		return;

	va_list args2;

	try {
		va_copy(args2, args);
		std::vector<char> buf(1 + std::vsnprintf(NULL, 0, msg, args));
		std::vsnprintf(buf.data(), buf.size(), msg, args2);
		m_errorCb(errorType, trim(std::string(buf.begin(), buf.end())));
	} catch (...) {
		LogError("Error callback throwed an exception.");
		// if an error handler throwed exception,
		// do not call further callbacks
		m_elementListenerMap.clear();
	}

	va_end(args2);
}

//
// -------------------------- start of static wrappers --------------------------
//
void Parser::CallbackHelper(std::function<void(void)> func)
{
	try {
		func();
		return;
	} catch (const std::exception &e) {
		LogError("parser error: " << e.what());

		if (m_errorCb)
			m_errorCb(PARSE_ERROR, e.what());
	} catch (...) {
		LogError("unknown parser error");

		if (m_errorCb)
			m_errorCb(PARSE_ERROR, "unknown parser error");
	}

	// raise error flag - unregister listeners
	m_elementListenerMap.clear();
}
void Parser::StartElement(void *userData,
						  const xmlChar *name,
						  const xmlChar **attrs)
{
	Parser *parser = static_cast<Parser *>(userData);
	parser->CallbackHelper([&parser, &name, &attrs] { parser->StartElement(name, attrs); });
}
void Parser::EndElement(void *userData,
						const xmlChar *name)
{
	Parser *parser = static_cast<Parser *>(userData);
	parser->CallbackHelper([&parser, &name] { parser->EndElement(name); });
}
void Parser::Characters(void *userData,
						const xmlChar *ch,
						int len)
{
	Parser *parser = static_cast<Parser *>(userData);
	parser->CallbackHelper([&parser, &ch, &len] { parser->Characters(ch, static_cast<size_t>(len)); });
}

void Parser::ErrorValidate(void *userData,
						   const char *msg,
						   ...)
{
	va_list args;
	va_start(args, msg);
	Parser *parser = static_cast<Parser *>(userData);
	parser->Error(VALIDATION_ERROR, msg, args);
	va_end(args);
}

void Parser::Error(void *userData,
				   const char *msg,
				   ...)
{
	va_list args;
	va_start(args, msg);
	Parser *parser = static_cast<Parser *>(userData);
	parser->Error(PARSE_ERROR, msg, args);
	va_end(args);
}

void Parser::Warning(void *userData,
					 const char *msg,
					 ...)
{
	va_list args;
	va_start(args, msg);
	Parser &parser = *(static_cast<Parser *>(userData));
	parser.Error(PARSE_WARNING, msg, args);
	va_end(args);
}
//
// -------------------------- end of static wrappers --------------------------
//
}
}