More boostisms
[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_each(
135         tree.getOrderedChildren().begin(), tree.getOrderedChildren().end(),
136         if_(_1 != nullptr)[lambda::bind(&getNonVisiblyUsedPrefixes, boost::ref(*_1), boost::ref(child_prefixes))]
137         );
138     const set<Namespace>& nsset = tree.getNamespaces();
139     for (set<Namespace>::const_iterator ns = nsset.begin(); ns != nsset.end(); ++ns) {
140         // Check for xmlns:xml.
141         if (XMLString::equals(ns->getNamespacePrefix(), xmlconstants::XML_PREFIX) && XMLString::equals(ns->getNamespaceURI(), xmlconstants::XML_NS))
142             continue;
143         switch (ns->usage()) {
144             case Namespace::Indeterminate:
145                 break;
146             case Namespace::VisiblyUsed:
147             {
148                 // See if the prefix was noted as non-visible below.
149                 const XMLCh* p = ns->getNamespacePrefix() ? ns->getNamespacePrefix() : &chNull;
150                 map<xstring,xstring>::iterator decl = child_prefixes.find(p);
151                 if (decl != child_prefixes.end()) {
152                     // It's declared below, see if it's the same namespace. If so, pull it from the set,
153                     // otherwise leave it in the set.
154                     if (decl->second == (ns->getNamespaceURI() ? ns->getNamespaceURI() : &chNull))
155                         child_prefixes.erase(decl);
156                 }
157                 break;
158             }
159             case Namespace::NonVisiblyUsed:
160                 // It may already be in the map from another branch of the tree, but as long
161                 // as it's set to something so the parent knows about it, we're good.
162                 prefixes[ns->getNamespacePrefix() ? ns->getNamespacePrefix() : &chNull] = (ns->getNamespaceURI() ? ns->getNamespaceURI() : &chNull);
163                 break;
164         }
165     }
166
167     prefixes.insert(child_prefixes.begin(), child_prefixes.end());
168 }
169
170 xmltooling::QName* XMLHelper::getNodeQName(const DOMNode* domNode)
171 {
172     if (domNode)
173         return new xmltooling::QName(domNode->getNamespaceURI(), domNode->getLocalName(), domNode->getPrefix());
174     return nullptr; 
175 }
176
177 xmltooling::QName* XMLHelper::getAttributeValueAsQName(const DOMAttr* attribute)
178 {
179     return getNodeValueAsQName(attribute);
180 }
181
182 xmltooling::QName* XMLHelper::getNodeValueAsQName(const DOMNode* domNode)
183 {
184     if (!domNode)
185         return nullptr;
186     
187     const XMLCh* value=domNode->getTextContent();
188     if (!value || !*value)
189         return nullptr;
190
191     int i;
192     if ((i=XMLString::indexOf(value,chColon))>0) {
193         XMLCh* prefix=new XMLCh[i+1];
194         XMLString::subString(prefix,value,0,i);
195         prefix[i]=chNull;
196         xmltooling::QName* ret=new xmltooling::QName(domNode->lookupNamespaceURI(prefix), value + i + 1, prefix);
197         delete[] prefix;
198         return ret;
199     }
200     
201     return new xmltooling::QName(domNode->lookupNamespaceURI(nullptr), value);
202 }
203
204 bool XMLHelper::getNodeValueAsBool(const xercesc::DOMNode* domNode, bool def)
205 {
206     if (!domNode)
207         return def;
208     const XMLCh* value = domNode->getNodeValue();
209     if (!value || !*value)
210         return def;
211     if (*value == chLatin_t || *value == chDigit_1)
212         return true;
213     else if (*value == chLatin_f || *value == chDigit_0)
214         return false;
215     return def;
216 }
217
218 DOMElement* XMLHelper::appendChildElement(DOMElement* parentElement, DOMElement* childElement)
219 {
220     DOMDocument* parentDocument = parentElement->getOwnerDocument();
221     if (childElement->getOwnerDocument() != parentDocument) {
222         childElement = static_cast<DOMElement*>(parentDocument->importNode(childElement, true));
223     }
224
225     parentElement->appendChild(childElement);
226     return childElement;
227 }
228
229 bool XMLHelper::isNodeNamed(const xercesc::DOMNode* n, const XMLCh* ns, const XMLCh* local)
230 {
231     return (n && XMLString::equals(local,n->getLocalName()) && XMLString::equals(ns,n->getNamespaceURI()));
232 }
233
234 const XMLCh* XMLHelper::getTextContent(const DOMElement* e)
235 {
236     DOMNode* child = e ? e->getFirstChild() : nullptr;
237     while (child) {
238         if (child->getNodeType() == DOMNode::TEXT_NODE)
239             return child->getNodeValue();
240         child = child->getNextSibling();
241     }
242     return nullptr;
243 }
244
245 DOMElement* XMLHelper::getFirstChildElement(const DOMNode* n, const XMLCh* localName)
246 {
247     DOMNode* child = n ? n->getFirstChild() : nullptr;
248     while (child && child->getNodeType() != DOMNode::ELEMENT_NODE)
249         child = child->getNextSibling();
250     if (child && localName) {
251         if (!XMLString::equals(localName,child->getLocalName()))
252             return getNextSiblingElement(child, localName);
253     }
254     return static_cast<DOMElement*>(child);
255 }    
256
257 DOMElement* XMLHelper::getLastChildElement(const DOMNode* n, const XMLCh* localName)
258 {
259     DOMNode* child = n ? n->getLastChild() : nullptr;
260     while (child && child->getNodeType() != DOMNode::ELEMENT_NODE)
261         child = child->getPreviousSibling();
262     if (child && localName) {
263         if (!XMLString::equals(localName,child->getLocalName()))
264             return getPreviousSiblingElement(child, localName);
265     }
266     return static_cast<DOMElement*>(child);
267 }    
268
269 DOMElement* XMLHelper::getFirstChildElement(const DOMNode* n, const XMLCh* ns, const XMLCh* localName)
270 {
271     DOMElement* e = getFirstChildElement(n, localName);
272     while (e && !XMLString::equals(e->getNamespaceURI(),ns))
273         e = getNextSiblingElement(e, localName);
274     return e;
275 }
276
277 DOMElement* XMLHelper::getLastChildElement(const DOMNode* n, const XMLCh* ns, const XMLCh* localName)
278 {
279     DOMElement* e = getLastChildElement(n, localName);
280     while (e && !XMLString::equals(e->getNamespaceURI(),ns))
281         e = getPreviousSiblingElement(e, localName);
282     return e;
283 }
284
285 DOMElement* XMLHelper::getNextSiblingElement(const DOMNode* n, const XMLCh* localName)
286 {
287     DOMNode* sib = n ? n->getNextSibling() : nullptr;
288     while (sib && sib->getNodeType() != DOMNode::ELEMENT_NODE)
289         sib = sib->getNextSibling();
290     if (sib && localName) {
291         if (!XMLString::equals(localName,sib->getLocalName()))
292             return getNextSiblingElement(sib, localName);
293     }   
294     return static_cast<DOMElement*>(sib);
295 }
296
297 DOMElement* XMLHelper::getPreviousSiblingElement(const DOMNode* n, const XMLCh* localName)
298 {
299     DOMNode* sib = n ? n->getPreviousSibling() : nullptr;
300     while (sib && sib->getNodeType() != DOMNode::ELEMENT_NODE)
301         sib = sib->getPreviousSibling();
302     if (sib && localName) {
303         if (!XMLString::equals(localName,sib->getLocalName()))
304             return getPreviousSiblingElement(sib, localName);
305     }   
306     return static_cast<DOMElement*>(sib);
307 }
308
309 DOMElement* XMLHelper::getNextSiblingElement(const DOMNode* n, const XMLCh* ns, const XMLCh* localName)
310 {
311     DOMElement* e = getNextSiblingElement(n, localName);
312     while (e && !XMLString::equals(e->getNamespaceURI(),ns))
313         e = getNextSiblingElement(e, localName);
314     return e;
315 }
316
317 DOMElement* XMLHelper::getPreviousSiblingElement(const DOMNode* n, const XMLCh* ns, const XMLCh* localName)
318 {
319     DOMElement* e = getPreviousSiblingElement(n, localName);
320     while (e && !XMLString::equals(e->getNamespaceURI(),ns))
321         e = getPreviousSiblingElement(e, localName);
322     return e;
323 }
324
325 string XMLHelper::getAttrString(const DOMElement* e, const char* defValue, const XMLCh* localName, const XMLCh* ns)
326 {
327     if (e) {
328         auto_ptr_char val(e->getAttributeNS(ns, localName));
329         if (val.get() && *val.get())
330             return val.get();
331     }
332     return defValue ? defValue : "";
333 }
334
335 int XMLHelper::getAttrInt(const DOMElement* e, int defValue, const XMLCh* localName, const XMLCh* ns)
336 {
337     if (e) {
338         const XMLCh* val = e->getAttributeNS(ns, localName);
339         if (val && *val) {
340             int i = XMLString::parseInt(val);
341             if (i)
342                 return i;
343         }
344     }
345     return defValue;
346 }
347
348 bool XMLHelper::getAttrBool(const DOMElement* e, bool defValue, const XMLCh* localName, const XMLCh* ns)
349 {
350     if (e) {
351         const XMLCh* val = e->getAttributeNS(ns, localName);
352         if (val) {
353             if (*val == chLatin_t || *val == chDigit_1)
354                 return true;
355             if (*val == chLatin_f || *val == chDigit_0)
356                 return false;
357         }
358     }
359     return defValue;
360 }
361
362 void XMLHelper::serialize(const DOMNode* n, std::string& buf, bool pretty)
363 {
364     static const XMLCh impltype[] = { chLatin_L, chLatin_S, chNull };
365     static const XMLCh UTF8[]={ chLatin_U, chLatin_T, chLatin_F, chDash, chDigit_8, chNull };
366
367     MemBufFormatTarget target;
368     DOMImplementation* impl=DOMImplementationRegistry::getDOMImplementation(impltype);
369
370 #ifdef XMLTOOLING_XERCESC_COMPLIANT_DOMLS
371     DOMLSSerializer* serializer = static_cast<DOMImplementationLS*>(impl)->createLSSerializer();
372     XercesJanitor<DOMLSSerializer> janitor(serializer);
373     if (pretty && serializer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, pretty))
374         serializer->getDomConfig()->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, pretty);
375     DOMLSOutput *theOutput = static_cast<DOMImplementationLS*>(impl)->createLSOutput();
376     XercesJanitor<DOMLSOutput> j_theOutput(theOutput);
377     theOutput->setEncoding(UTF8);
378     theOutput->setByteStream(&target);
379     if (!serializer->write(n, theOutput))
380         throw XMLParserException("unable to serialize XML");
381 #else
382     DOMWriter* serializer = static_cast<DOMImplementationLS*>(impl)->createDOMWriter();
383     XercesJanitor<DOMWriter> janitor(serializer);
384     serializer->setEncoding(UTF8);
385     if (pretty && serializer->canSetFeature(XMLUni::fgDOMWRTFormatPrettyPrint, pretty))
386         serializer->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, pretty);
387     if (!serializer->writeNode(&target, *n))
388         throw XMLParserException("unable to serialize XML");
389 #endif
390
391     buf.erase();
392     buf.append(reinterpret_cast<const char*>(target.getRawBuffer()),target.getLen());
393 }
394
395 namespace {
396     class StreamFormatTarget : public XMLFormatTarget
397     {
398     public:
399         StreamFormatTarget(std::ostream& out) : m_out(out) {}
400         ~StreamFormatTarget() {}
401
402         void writeChars(const XMLByte *const toWrite, const xsecsize_t count, XMLFormatter *const formatter) {
403             m_out.write(reinterpret_cast<const char*>(toWrite),count);
404         }
405
406         void flush() {
407             m_out.flush();
408         }
409
410     private:
411         std::ostream& m_out;
412     };
413 };
414
415 ostream& XMLHelper::serialize(const DOMNode* n, ostream& out, bool pretty)
416 {
417     static const XMLCh impltype[] = { chLatin_L, chLatin_S, chNull };
418     static const XMLCh UTF8[]={ chLatin_U, chLatin_T, chLatin_F, chDash, chDigit_8, chNull };
419
420     StreamFormatTarget target(out);
421     DOMImplementation* impl=DOMImplementationRegistry::getDOMImplementation(impltype);
422
423 #ifdef XMLTOOLING_XERCESC_COMPLIANT_DOMLS
424     DOMLSSerializer* serializer = static_cast<DOMImplementationLS*>(impl)->createLSSerializer();
425     XercesJanitor<DOMLSSerializer> janitor(serializer);
426     if (pretty && serializer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, pretty))
427         serializer->getDomConfig()->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, pretty);
428     DOMLSOutput *theOutput = static_cast<DOMImplementationLS*>(impl)->createLSOutput();
429     XercesJanitor<DOMLSOutput> j_theOutput(theOutput);
430     theOutput->setEncoding(UTF8);
431     theOutput->setByteStream(&target);
432     if (!serializer->write(n, theOutput))
433         throw XMLParserException("unable to serialize XML");
434 #else
435     DOMWriter* serializer=(static_cast<DOMImplementationLS*>(impl))->createDOMWriter();
436     XercesJanitor<DOMWriter> janitor(serializer);
437     serializer->setEncoding(UTF8);
438     if (pretty && serializer->canSetFeature(XMLUni::fgDOMWRTFormatPrettyPrint, pretty))
439         serializer->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, pretty);
440     if (!serializer->writeNode(&target,*n))
441         throw XMLParserException("unable to serialize XML");
442 #endif
443
444     return out;
445 }
446
447 ostream& xmltooling::operator<<(ostream& ostr, const DOMNode& node)
448 {
449     return XMLHelper::serialize(&node, ostr);
450 }
451
452 ostream& xmltooling::operator<<(ostream& ostr, const XMLObject& obj)
453 {
454     return ostr << *(obj.marshall());
455 }