summaryrefslogtreecommitdiffstats
path: root/cpp/sca/kernel/xml.hpp
blob: b4a3b87ad18568162187668b059ddb96ad12e06d (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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 */

/* $Rev$ $Date$ */

#ifndef tuscany_xml_hpp
#define tuscany_xml_hpp

/**
 * XML read/write functions.
 */

#include <libxml/xmlreader.h>
#include <libxml/xmlwriter.h>
#include <libxml/xmlschemas.h>
#include <libxml/globals.h>
#include <iostream>
#include <fstream>
#include <string>
#include "list.hpp"

namespace tuscany {

/**
 * Encapsulates a libxml2 xmlTextReader and its state.
 */
class XmlReader {
public:
    enum TokenType {
        None = 0, Element = 1, Attribute = 2, EndElement = 15, Identifier = 100, Text = 101, End = 103
    };

    explicit XmlReader(xmlTextReaderPtr xml) : xml(xml), tokenType(None) {
        xmlTextReaderSetParserProp(xml, XML_PARSER_DEFAULTATTRS, 1);
        xmlTextReaderSetParserProp(xml, XML_PARSER_SUBST_ENTITIES, 1);
    }

    ~XmlReader() {
        xmlFreeTextReader(xml);
    }

    /**
     * Read the next token and return its type.
     */
    int read() {
        if (tokenType == End)
            return tokenType;
        if (tokenType == Element) {
            isEmptyElement = xmlTextReaderIsEmptyElement(xml);
            hasValue = xmlTextReaderHasValue(xml);
            hasAttributes = xmlTextReaderHasAttributes(xml);
            return tokenType = Identifier;
        }
        if (hasValue && tokenType == Identifier)
            return tokenType = Text;
        if (hasAttributes && (tokenType == Identifier || tokenType == Text) && xmlTextReaderMoveToFirstAttribute(xml) == 1)
            return tokenType = Attribute;
        if (tokenType == Attribute && xmlTextReaderMoveToNextAttribute(xml) == 1)
            return tokenType = Attribute;
        if (isEmptyElement && (tokenType == Identifier || tokenType == Text || tokenType == Attribute))
            return tokenType = EndElement;
        if (!xmlTextReaderRead(xml))
            return tokenType = End;
        return tokenType = xmlTextReaderNodeType(xml);
    }

    operator xmlTextReaderPtr() const {
        return xml;
    }

private:
    const xmlTextReaderPtr xml;
    int tokenType;
    bool isEmptyElement;
    bool hasValue;
    bool hasAttributes;
};

/**
 * Constants used to tag XML tokens.
 */
const value endElement("<");
const value startElement(">");
const value attribute("attribute");
const value element("element");

/**
 * Read an XML identifier.
 */
const value readIdentifier(XmlReader& reader) {
    const char* name = (const char*)xmlTextReaderConstName(reader);
    return value(name);
}

/**
 * Read XML text.
 */
const value readText(XmlReader& reader) {
    const char *val = (const char*)xmlTextReaderConstValue(reader);
    return value(std::string(val));
}

/**
 * Read an XML attribute.
 */
const value readAttribute(XmlReader& reader) {
    const char *name = (const char*)xmlTextReaderConstName(reader);
    const char *val = (const char*)xmlTextReaderConstValue(reader);
    return value(makeList(attribute, value(name), value(std::string(val))));
}

/**
 * Read an XML token.
 */
const value readToken(XmlReader& reader) {
    const int tokenType = reader.read();
    if (tokenType == XmlReader::End)
        return value();
    if (tokenType == XmlReader::Element)
        return startElement;
    if (tokenType == XmlReader::Identifier)
        return readIdentifier(reader);
    if (tokenType == XmlReader::Attribute)
        return readAttribute(reader);
    if (tokenType == XmlReader::Text)
        return readText(reader);
    if (tokenType == XmlReader::EndElement)
        return endElement;
    return readToken(reader);
}

/**
 * Read a list of XML tokens.
 */
const list<value> readList(const list<value>& listSoFar, XmlReader& reader) {
    const value token = readToken(reader);
    if(isNil(token) || endElement == token)
        return reverse(listSoFar);
    if(startElement == token)
        return readList(cons(value(readList(makeList(element), reader)), listSoFar), reader);
    return readList(cons(token, listSoFar), reader);
}

/**
 * Read an XML document from a libxml2 XML reader.
 */
const list<value> read(XmlReader& reader) {
    value nextToken = readToken(reader);
    if (startElement == nextToken)
        return makeList(value(readList(makeList(element), reader)));
    return list<value>();
}

/**
 * Callback function called by libxml2 to read the XML input stream.
 */
int readCallback(void *context, char* buffer, int len) {
    std::istream* is = static_cast<std::istream*>(context);
    is->read(buffer, len);
    if (!is->eof() && (is->fail() || is->bad()))
        return -1;
    const int n = is->gcount();
    return n;
}

/**
 * Read an XML document from an input stream.
 */
const list<value> readXML(std::istream& is) {
    xmlTextReaderPtr xml = xmlReaderForIO(readCallback, NULL, &is, NULL, NULL, XML_PARSE_NONET);
    if (xml == NULL)
        return list<value>();
    XmlReader reader(xml);
    return read(reader);
}

/**
 * Callback function called by libxml2 to read the XML file input stream.
 */
int readFileCallback(void *context, char* buffer, int len) {
    std::ifstream* is = static_cast<std::ifstream*>(context);
    is->read(buffer, len);
    if (is->fail() || is->bad())
        return -1;
    return is->gcount();
}

/**
 * Callback function called by libxml2 to close the XML file input stream.
 */
int readCloseFileCallback(void *context) {
    std::ifstream* fis = static_cast<std::ifstream*>(context);
    fis->close();
    return 0;
}

/**
 * Read an XML document from a file input stream.
 */
const list<value> readXML(std::ifstream& is) {
    xmlTextReaderPtr xml = xmlReaderForIO(readFileCallback, readCloseFileCallback, &is, NULL, NULL, XML_PARSE_NONET);
    if (xml == NULL)
        return list<value>();
    XmlReader reader(xml);
    return read(reader);
}

/**
 * Returns true if a value is an XML attribute.
 */
const bool isAttribute(const list<value>& l) {
    return !isNil(l) && car(l) == attribute;
}

/**
 * Returns the name of an XML attribute.
 */
const std::string attributeName(const list<value>& l) {
    return cadr(l);
}

/**
 * Returns the text value of an XML attribute.
 */
const std::string attributeText(const list<value>& l) {
    return caddr(l);
}

/**
 * Returns true if a value is an XML element.
 */
const bool isElement(const list<value>& l) {
    return !isNil(l) && car(l) == element;
}

/**
 * Returns the name of an XML element.
 */
const std::string elementName(const list<value>& l) {
    return cadr(l);
}

/**
 * Returns true if an XML element contains text content.
 */
const bool elementHasText(const list<value>& l) {
    if (isNil(cddr(l)))
        return false;
    return isString(caddr(l));
}

/**
 * Returns the text content of an XML element.
 */
const std::string elementText(const list<value>& l) {
    return caddr(l);
}

/**
 * Returns the children of an XML element.
 */
const list<value> elementChildren(const list<value>& l) {
    return cddr(l);
}

/**
 * Default encoding used to write XML documents.
 */
const char* encoding = "UTF-8";

/**
 * Write a list of XML element or attribute tokens.
 */
const bool writeList(const list<value>& l, const xmlTextWriterPtr xml) {
    if (isNil(l))
        return true;

    // Write an attribute
    const list<value> token(car(l));
    if (isAttribute(token)) {
        if (xmlTextWriterWriteAttribute(xml, (const xmlChar*)attributeName(token).c_str(), (const xmlChar*)attributeText(token).c_str()) < 0)
            return false;

    } else if (isElement(token)) {

        // Write an element
        if (xmlTextWriterStartElement(xml, (const xmlChar*)elementName(token).c_str()) < 0)
            return false;
        if (elementHasText(token) && xmlTextWriterWriteString(xml, (const xmlChar*)elementText(token).c_str()) < 0)
            return false;

        // Write its children
        writeList(elementChildren(token), xml);

        if (xmlTextWriterEndElement(xml) < 0)
            return false;
    }

    // Go on
    return writeList(cdr(l), xml);
}

/**
 * Write an XML document to a libxml2 XML writer.
 */
const bool write(const list<value>& l, const xmlTextWriterPtr xml) {
    if (xmlTextWriterStartDocument(xml, NULL, encoding, NULL) < 0)
        return false;
    writeList(l, xml);
    if (xmlTextWriterEndDocument(xml) < 0)
        return false;
    return true;
}

/**
 * Callback function called by libxml2 to write to the XML output stream.
 */
int writeCallback(void *context, const char* buffer, int len) {
    std::ostream* os = static_cast<std::ostream*>(context);
    os->write(buffer, len);
    if (os->fail() || os->bad())
        return -1;
    return len;
}

/**
 * Write an XML document to an output stream.
 */
const bool writeXML(const list<value>& l, std::ostream& os) {
    xmlOutputBufferPtr out = xmlOutputBufferCreateIO(writeCallback, NULL, &os, NULL);
    xmlTextWriterPtr xml = xmlNewTextWriter(out);
    if (xml == NULL)
        return false;
    return write(l, xml);
}

/**
 * Callback function called by libxml2 to write to the XML file output stream.
 */
int writeFileCallback(void *context, const char* buffer, int len) {
    std::ofstream* os = static_cast<std::ofstream*>(context);
    os->write(buffer, len);
    if (os->fail() || os->bad())
        return -1;
    return len;
}

/**
 * Callback function called by libxml2 to close the XML file output stream.
 */
int writeCloseFileCallback(void *context) {
    std::ofstream* fos = static_cast<std::ofstream*>(context);
    fos->close();
    return 0;
}

/**
 * Write an XML document to a file output stream.
 */
const bool writeXML(const list<value>& l, std::ofstream& os) {
    xmlOutputBufferPtr out = xmlOutputBufferCreateIO(writeFileCallback, writeCloseFileCallback, &os, NULL);
    xmlTextWriterPtr xml = xmlNewTextWriter(out);
    if (xml == NULL)
        return false;
    return write(l, xml);
}

}
#endif /* tuscany_xml_hpp */