CPPXT-104 - Add exception handling to integer conversions
[shibboleth/cpp-xmltooling.git] / xmltooling / util / XMLHelper.cpp
1 /**
2  * Licensed to the University Corporation for Advanced Internet
3  * Development, Inc. (UCAID) under one or more contributor license
4  * agreements. See the NOTICE file distributed with this work for
5  * additional information regarding copyright ownership.
6  *
7  * UCAID licenses this file to you under the Apache License,
8  * Version 2.0 (the "License"); you may not use this file except
9  * in compliance with the License. You may obtain a copy of the
10  * License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing,
15  * software distributed under the License is distributed on an
16  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17  * either express or implied. See the License for the specific
18  * language governing permissions and limitations under the License.
19  */
20
21 /**
22  * XMLHelper.cpp
23  * 
24  * A helper class for working with W3C DOM objects. 
25  */
26
27 #include "internal.h"
28 #include "exceptions.h"
29 #include "QName.h"
30 #include "XMLObject.h"
31 #include "util/XMLHelper.h"
32 #include "util/XMLConstants.h"
33
34 #include <boost/lambda/bind.hpp>
35 #include <boost/lambda/if.hpp>
36 #include <boost/lambda/lambda.hpp>
37 #include <xercesc/framework/MemBufFormatTarget.hpp>
38 #include <xercesc/util/XMLUniDefs.hpp>
39
40 using namespace xmltooling;
41 using namespace xercesc;
42 using namespace boost::lambda;
43 using namespace boost;
44 using namespace std;
45
46 static const XMLCh type[]={chLatin_t, chLatin_y, chLatin_p, chLatin_e, chNull };
47     
48 bool XMLHelper::hasXSIType(const DOMElement* e)
49 {
50     return (e && e->hasAttributeNS(xmlconstants::XSI_NS, type));
51 }
52
53 xmltooling::QName* XMLHelper::getXSIType(const DOMElement* e)
54 {
55     DOMAttr* attribute = e->getAttributeNodeNS(xmlconstants::XSI_NS, type);
56     if (attribute) {
57         const XMLCh* attributeValue = attribute->getTextContent();
58         if (attributeValue && *attributeValue) {
59             int i;
60             if ((i=XMLString::indexOf(attributeValue,chColon))>0) {
61                 XMLCh* prefix=new XMLCh[i+1];
62                 XMLString::subString(prefix,attributeValue,0,i);
63                 prefix[i]=chNull;
64                 xmltooling::QName* ret=new xmltooling::QName(e->lookupNamespaceURI(prefix), attributeValue + i + 1, prefix);
65                 delete[] prefix;
66                 return ret;
67             }
68             else {
69                 return new xmltooling::QName(e->lookupNamespaceURI(nullptr), attributeValue);
70             }
71         }
72     }
73
74     return nullptr;
75 }
76
77 DOMAttr* XMLHelper::getIdAttribute(const DOMElement* domElement)
78 {
79     if(!domElement->hasAttributes()) {
80         return nullptr;
81     }
82     
83     DOMNamedNodeMap* attributes = domElement->getAttributes();
84     DOMAttr* attribute;
85     for(XMLSize_t i = 0; i < attributes->getLength(); ++i) {
86         attribute = static_cast<DOMAttr*>(attributes->item(i));
87         if(attribute->isId()) {
88             return attribute;
89         }
90     }
91     
92     return nullptr;
93 }
94
95 const XMLObject* XMLHelper::getXMLObjectById(const XMLObject& tree, const XMLCh* id)
96 {
97     if (XMLString::equals(id, tree.getXMLID()))
98         return &tree;
99     
100     const XMLObject* ret;
101     const list<XMLObject*>& children = tree.getOrderedChildren();
102     for (list<XMLObject*>::const_iterator i = children.begin(); i != children.end(); ++i) {
103         if (*i) {
104             ret = getXMLObjectById(*(*i), id);
105             if (ret)
106                 return ret;
107         }
108     }
109     
110     return nullptr;
111 }
112
113 XMLObject* XMLHelper::getXMLObjectById(XMLObject& tree, const XMLCh* id)
114 {
115     if (XMLString::equals(id, tree.getXMLID()))
116         return &tree;
117
118     XMLObject* ret;
119     const list<XMLObject*>& children = tree.getOrderedChildren();
120     for (list<XMLObject*>::const_iterator i = children.begin(); i != children.end(); ++i) {
121         if (*i) {
122             ret = getXMLObjectById(*(*i), id);
123             if (ret)
124                 return ret;
125         }
126     }
127     
128     return nullptr;
129 }
130
131 void XMLHelper::getNonVisiblyUsedPrefixes(const XMLObject& tree, map<xstring,xstring>& prefixes)
132 {
133     map<xstring,xstring> child_prefixes;
134     for(list<XMLObject*>::const_iterator i = tree.getOrderedChildren().begin(); i != tree.getOrderedChildren().end(); ++i) {
135         if (*i) {
136             getNonVisiblyUsedPrefixes(*(*i), child_prefixes);
137         }
138     }
139     const set<Namespace>& nsset = tree.getNamespaces();
140     for (set<Namespace>::const_iterator ns = nsset.begin(); ns != nsset.end(); ++ns) {
141         // Check for xmlns:xml.
142         if (XMLString::equals(ns->getNamespacePrefix(), xmlconstants::XML_PREFIX) && XMLString::equals(ns->getNamespaceURI(), xmlconstants::XML_NS))
143             continue;
144         switch (ns->usage()) {
145             case Namespace::Indeterminate:
146                 break;
147             case Namespace::VisiblyUsed:
148             {
149                 // See if the prefix was noted as non-visible below.
150                 const XMLCh* p = ns->getNamespacePrefix() ? ns->getNamespacePrefix() : &chNull;
151                 map<xstring,xstring>::iterator decl = child_prefixes.find(p);
152                 if (decl != child_prefixes.end()) {
153                     // It's declared below, see if it's the same namespace. If so, pull it from the set,
154                     // otherwise leave it in the set.
155                     if (decl->second == (ns->getNamespaceURI() ? ns->getNamespaceURI() : &chNull))
156                         child_prefixes.erase(decl);
157                 }
158                 break;
159             }
160             case Namespace::NonVisiblyUsed:
161                 // It may already be in the map from another branch of the tree, but as long
162                 // as it's set to something so the parent knows about it, we're good.
163                 prefixes[ns->getNamespacePrefix() ? ns->getNamespacePrefix() : &chNull] = (ns->getNamespaceURI() ? ns->getNamespaceURI() : &chNull);
164                 break;
165         }
166     }
167
168     prefixes.insert(child_prefixes.begin(), child_prefixes.end());
169 }
170
171 xmltooling::QName* XMLHelper::getNodeQName(const DOMNode* domNode)
172 {
173     if (domNode)
174         return new xmltooling::QName(domNode->getNamespaceURI(), domNode->getLocalName(), domNode->getPrefix());
175     return nullptr; 
176 }
177
178 xmltooling::QName* XMLHelper::getAttributeValueAsQName(const DOMAttr* attribute)
179 {
180     return getNodeValueAsQName(attribute);
181 }
182
183 xmltooling::QName* XMLHelper::getNodeValueAsQName(const DOMNode* domNode)
184 {
185     if (!domNode)
186         return nullptr;
187     
188     const XMLCh* value=domNode->getTextContent();
189     if (!value || !*value)
190         return nullptr;
191
192     int i;
193     if ((i=XMLString::indexOf(value,chColon))>0) {
194         XMLCh* prefix=new XMLCh[i+1];
195         XMLString::subString(prefix,value,0,i);
196         prefix[i]=chNull;
197         xmltooling::QName* ret=new xmltooling::QName(domNode->lookupNamespaceURI(prefix), value + i + 1, prefix);
198         delete[] prefix;
199         return ret;
200     }
201     
202     return new xmltooling::QName(domNode->lookupNamespaceURI(nullptr), value);
203 }
204
205 bool XMLHelper::getNodeValueAsBool(const xercesc::DOMNode* domNode, bool def)
206 {
207     if (!domNode)
208         return def;
209     const XMLCh* value = domNode->getNodeValue();
210     if (!value || !*value)
211         return def;
212     if (*value == chLatin_t || *value == chDigit_1)
213         return true;
214     else if (*value == chLatin_f || *value == chDigit_0)
215         return false;
216     return def;
217 }
218
219 DOMElement* XMLHelper::appendChildElement(DOMElement* parentElement, DOMElement* childElement)
220 {
221     DOMDocument* parentDocument = parentElement->getOwnerDocument();
222     if (childElement->getOwnerDocument() != parentDocument) {
223         childElement = static_cast<DOMElement*>(parentDocument->importNode(childElement, true));
224     }
225
226     parentElement->appendChild(childElement);
227     return childElement;
228 }
229
230 bool XMLHelper::isNodeNamed(const xercesc::DOMNode* n, const XMLCh* ns, const XMLCh* local)
231 {
232     return (n && XMLString::equals(local,n->getLocalName()) && XMLString::equals(ns,n->getNamespaceURI()));
233 }
234
235 const XMLCh* XMLHelper::getTextContent(const DOMElement* e)
236 {
237     DOMNode* child = e ? e->getFirstChild() : nullptr;
238     while (child) {
239         if (child->getNodeType() == DOMNode::TEXT_NODE)
240             return child->getNodeValue();
241         child = child->getNextSibling();
242     }
243     return nullptr;
244 }
245
246 DOMElement* XMLHelper::getFirstChildElement(const DOMNode* n, const XMLCh* localName)
247 {
248     DOMNode* child = n ? n->getFirstChild() : nullptr;
249     while (child && child->getNodeType() != DOMNode::ELEMENT_NODE)
250         child = child->getNextSibling();
251     if (child && localName) {
252         if (!XMLString::equals(localName,child->getLocalName()))
253             return getNextSiblingElement(child, localName);
254     }
255     return static_cast<DOMElement*>(child);
256 }    
257
258 DOMElement* XMLHelper::getLastChildElement(const DOMNode* n, const XMLCh* localName)
259 {
260     DOMNode* child = n ? n->getLastChild() : nullptr;
261     while (child && child->getNodeType() != DOMNode::ELEMENT_NODE)
262         child = child->getPreviousSibling();
263     if (child && localName) {
264         if (!XMLString::equals(localName,child->getLocalName()))
265             return getPreviousSiblingElement(child, localName);
266     }
267     return static_cast<DOMElement*>(child);
268 }    
269
270 DOMElement* XMLHelper::getFirstChildElement(const DOMNode* n, const XMLCh* ns, const XMLCh* localName)
271 {
272     DOMElement* e = getFirstChildElement(n, localName);
273     while (e && !XMLString::equals(e->getNamespaceURI(),ns))
274         e = getNextSiblingElement(e, localName);
275     return e;
276 }
277
278 DOMElement* XMLHelper::getLastChildElement(const DOMNode* n, const XMLCh* ns, const XMLCh* localName)
279 {
280     DOMElement* e = getLastChildElement(n, localName);
281     while (e && !XMLString::equals(e->getNamespaceURI(),ns))
282         e = getPreviousSiblingElement(e, localName);
283     return e;
284 }
285
286 DOMElement* XMLHelper::getNextSiblingElement(const DOMNode* n, const XMLCh* localName)
287 {
288     DOMNode* sib = n ? n->getNextSibling() : nullptr;
289     while (sib && sib->getNodeType() != DOMNode::ELEMENT_NODE)
290         sib = sib->getNextSibling();
291     if (sib && localName) {
292         if (!XMLString::equals(localName,sib->getLocalName()))
293             return getNextSiblingElement(sib, localName);
294     }   
295     return static_cast<DOMElement*>(sib);
296 }
297
298 DOMElement* XMLHelper::getPreviousSiblingElement(const DOMNode* n, const XMLCh* localName)
299 {
300     DOMNode* sib = n ? n->getPreviousSibling() : nullptr;
301     while (sib && sib->getNodeType() != DOMNode::ELEMENT_NODE)
302         sib = sib->getPreviousSibling();
303     if (sib && localName) {
304         if (!XMLString::equals(localName,sib->getLocalName()))
305             return getPreviousSiblingElement(sib, localName);
306     }   
307     return static_cast<DOMElement*>(sib);
308 }
309
310 DOMElement* XMLHelper::getNextSiblingElement(const DOMNode* n, const XMLCh* ns, const XMLCh* localName)
311 {
312     DOMElement* e = getNextSiblingElement(n, localName);
313     while (e && !XMLString::equals(e->getNamespaceURI(),ns))
314         e = getNextSiblingElement(e, localName);
315     return e;
316 }
317
318 DOMElement* XMLHelper::getPreviousSiblingElement(const DOMNode* n, const XMLCh* ns, const XMLCh* localName)
319 {
320     DOMElement* e = getPreviousSiblingElement(n, localName);
321     while (e && !XMLString::equals(e->getNamespaceURI(),ns))
322         e = getPreviousSiblingElement(e, localName);
323     return e;
324 }
325
326 string XMLHelper::getAttrString(const DOMElement* e, const char* defValue, const XMLCh* localName, const XMLCh* ns)
327 {
328     if (e) {
329         auto_ptr_char val(e->getAttributeNS(ns, localName));
330         if (val.get() && *val.get())
331             return val.get();
332     }
333     return defValue ? defValue : "";
334 }
335
336 int XMLHelper::getAttrInt(const DOMElement* e, int defValue, const XMLCh* localName, const XMLCh* ns)
337 {
338     if (e) {
339         const XMLCh* val = e->getAttributeNS(ns, localName);
340         if (val && *val) {
341             try {
342                 return XMLString::parseInt(val);
343             }
344             catch (XMLException&) {
345             }
346         }
347     }
348     return defValue;
349 }
350
351 bool XMLHelper::getAttrBool(const DOMElement* e, bool defValue, const XMLCh* localName, const XMLCh* ns)
352 {
353     if (e) {
354         const XMLCh* val = e->getAttributeNS(ns, localName);
355         if (val) {
356             if (*val == chLatin_t || *val == chDigit_1)
357                 return true;
358             if (*val == chLatin_f || *val == chDigit_0)
359                 return false;
360         }
361     }
362     return defValue;
363 }
364
365 void XMLHelper::serialize(const DOMNode* n, std::string& buf, bool pretty)
366 {
367     static const XMLCh impltype[] = { chLatin_L, chLatin_S, chNull };
368     static const XMLCh UTF8[]={ chLatin_U, chLatin_T, chLatin_F, chDash, chDigit_8, chNull };
369
370     MemBufFormatTarget target;
371     DOMImplementation* impl=DOMImplementationRegistry::getDOMImplementation(impltype);
372
373 #ifdef XMLTOOLING_XERCESC_COMPLIANT_DOMLS
374     DOMLSSerializer* serializer = static_cast<DOMImplementationLS*>(impl)->createLSSerializer();
375     XercesJanitor<DOMLSSerializer> janitor(serializer);
376     if (pretty && serializer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, pretty))
377         serializer->getDomConfig()->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, pretty);
378     DOMLSOutput *theOutput = static_cast<DOMImplementationLS*>(impl)->createLSOutput();
379     XercesJanitor<DOMLSOutput> j_theOutput(theOutput);
380     theOutput->setEncoding(UTF8);
381     theOutput->setByteStream(&target);
382     if (!serializer->write(n, theOutput))
383         throw XMLParserException("unable to serialize XML");
384 #else
385     DOMWriter* serializer = static_cast<DOMImplementationLS*>(impl)->createDOMWriter();
386     XercesJanitor<DOMWriter> janitor(serializer);
387     serializer->setEncoding(UTF8);
388     if (pretty && serializer->canSetFeature(XMLUni::fgDOMWRTFormatPrettyPrint, pretty))
389         serializer->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, pretty);
390     if (!serializer->writeNode(&target, *n))
391         throw XMLParserException("unable to serialize XML");
392 #endif
393
394     buf.erase();
395     buf.append(reinterpret_cast<const char*>(target.getRawBuffer()),target.getLen());
396 }
397
398 namespace {
399     class StreamFormatTarget : public XMLFormatTarget
400     {
401     public:
402         StreamFormatTarget(std::ostream& out) : m_out(out) {}
403         ~StreamFormatTarget() {}
404
405         void writeChars(const XMLByte *const toWrite, const xsecsize_t count, XMLFormatter *const formatter) {
406             m_out.write(reinterpret_cast<const char*>(toWrite),count);
407         }
408
409         void flush() {
410             m_out.flush();
411         }
412
413     private:
414         std::ostream& m_out;
415     };
416 };
417
418 ostream& XMLHelper::serialize(const DOMNode* n, ostream& out, bool pretty)
419 {
420     static const XMLCh impltype[] = { chLatin_L, chLatin_S, chNull };
421     static const XMLCh UTF8[]={ chLatin_U, chLatin_T, chLatin_F, chDash, chDigit_8, chNull };
422
423     StreamFormatTarget target(out);
424     DOMImplementation* impl=DOMImplementationRegistry::getDOMImplementation(impltype);
425
426 #ifdef XMLTOOLING_XERCESC_COMPLIANT_DOMLS
427     DOMLSSerializer* serializer = static_cast<DOMImplementationLS*>(impl)->createLSSerializer();
428     XercesJanitor<DOMLSSerializer> janitor(serializer);
429     if (pretty && serializer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, pretty))
430         serializer->getDomConfig()->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, pretty);
431     DOMLSOutput *theOutput = static_cast<DOMImplementationLS*>(impl)->createLSOutput();
432     XercesJanitor<DOMLSOutput> j_theOutput(theOutput);
433     theOutput->setEncoding(UTF8);
434     theOutput->setByteStream(&target);
435     if (!serializer->write(n, theOutput))
436         throw XMLParserException("unable to serialize XML");
437 #else
438     DOMWriter* serializer=(static_cast<DOMImplementationLS*>(impl))->createDOMWriter();
439     XercesJanitor<DOMWriter> janitor(serializer);
440     serializer->setEncoding(UTF8);
441     if (pretty && serializer->canSetFeature(XMLUni::fgDOMWRTFormatPrettyPrint, pretty))
442         serializer->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, pretty);
443     if (!serializer->writeNode(&target,*n))
444         throw XMLParserException("unable to serialize XML");
445 #endif
446
447     return out;
448 }
449
450 ostream& xmltooling::operator<<(ostream& ostr, const DOMNode& node)
451 {
452     return XMLHelper::serialize(&node, ostr);
453 }
454
455 ostream& xmltooling::operator<<(ostream& ostr, const XMLObject& obj)
456 {
457     try {
458         return ostr << *(obj.marshall());
459     }
460     catch (DOMException& ex) {
461         auto_ptr_char msg(ex.getMessage());
462         throw XMLParserException(msg.get());
463     }
464 }