a270de4edcabc187ae18b723cbc9cf472eff501c
[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             int i = XMLString::parseInt(val);
342             if (i)
343                 return i;
344         }
345     }
346     return defValue;
347 }
348
349 bool XMLHelper::getAttrBool(const DOMElement* e, bool defValue, const XMLCh* localName, const XMLCh* ns)
350 {
351     if (e) {
352         const XMLCh* val = e->getAttributeNS(ns, localName);
353         if (val) {
354             if (*val == chLatin_t || *val == chDigit_1)
355                 return true;
356             if (*val == chLatin_f || *val == chDigit_0)
357                 return false;
358         }
359     }
360     return defValue;
361 }
362
363 void XMLHelper::serialize(const DOMNode* n, std::string& buf, bool pretty)
364 {
365     static const XMLCh impltype[] = { chLatin_L, chLatin_S, chNull };
366     static const XMLCh UTF8[]={ chLatin_U, chLatin_T, chLatin_F, chDash, chDigit_8, chNull };
367
368     MemBufFormatTarget target;
369     DOMImplementation* impl=DOMImplementationRegistry::getDOMImplementation(impltype);
370
371 #ifdef XMLTOOLING_XERCESC_COMPLIANT_DOMLS
372     DOMLSSerializer* serializer = static_cast<DOMImplementationLS*>(impl)->createLSSerializer();
373     XercesJanitor<DOMLSSerializer> janitor(serializer);
374     if (pretty && serializer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, pretty))
375         serializer->getDomConfig()->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, pretty);
376     DOMLSOutput *theOutput = static_cast<DOMImplementationLS*>(impl)->createLSOutput();
377     XercesJanitor<DOMLSOutput> j_theOutput(theOutput);
378     theOutput->setEncoding(UTF8);
379     theOutput->setByteStream(&target);
380     if (!serializer->write(n, theOutput))
381         throw XMLParserException("unable to serialize XML");
382 #else
383     DOMWriter* serializer = static_cast<DOMImplementationLS*>(impl)->createDOMWriter();
384     XercesJanitor<DOMWriter> janitor(serializer);
385     serializer->setEncoding(UTF8);
386     if (pretty && serializer->canSetFeature(XMLUni::fgDOMWRTFormatPrettyPrint, pretty))
387         serializer->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, pretty);
388     if (!serializer->writeNode(&target, *n))
389         throw XMLParserException("unable to serialize XML");
390 #endif
391
392     buf.erase();
393     buf.append(reinterpret_cast<const char*>(target.getRawBuffer()),target.getLen());
394 }
395
396 namespace {
397     class StreamFormatTarget : public XMLFormatTarget
398     {
399     public:
400         StreamFormatTarget(std::ostream& out) : m_out(out) {}
401         ~StreamFormatTarget() {}
402
403         void writeChars(const XMLByte *const toWrite, const xsecsize_t count, XMLFormatter *const formatter) {
404             m_out.write(reinterpret_cast<const char*>(toWrite),count);
405         }
406
407         void flush() {
408             m_out.flush();
409         }
410
411     private:
412         std::ostream& m_out;
413     };
414 };
415
416 ostream& XMLHelper::serialize(const DOMNode* n, ostream& out, bool pretty)
417 {
418     static const XMLCh impltype[] = { chLatin_L, chLatin_S, chNull };
419     static const XMLCh UTF8[]={ chLatin_U, chLatin_T, chLatin_F, chDash, chDigit_8, chNull };
420
421     StreamFormatTarget target(out);
422     DOMImplementation* impl=DOMImplementationRegistry::getDOMImplementation(impltype);
423
424 #ifdef XMLTOOLING_XERCESC_COMPLIANT_DOMLS
425     DOMLSSerializer* serializer = static_cast<DOMImplementationLS*>(impl)->createLSSerializer();
426     XercesJanitor<DOMLSSerializer> janitor(serializer);
427     if (pretty && serializer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, pretty))
428         serializer->getDomConfig()->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, pretty);
429     DOMLSOutput *theOutput = static_cast<DOMImplementationLS*>(impl)->createLSOutput();
430     XercesJanitor<DOMLSOutput> j_theOutput(theOutput);
431     theOutput->setEncoding(UTF8);
432     theOutput->setByteStream(&target);
433     if (!serializer->write(n, theOutput))
434         throw XMLParserException("unable to serialize XML");
435 #else
436     DOMWriter* serializer=(static_cast<DOMImplementationLS*>(impl))->createDOMWriter();
437     XercesJanitor<DOMWriter> janitor(serializer);
438     serializer->setEncoding(UTF8);
439     if (pretty && serializer->canSetFeature(XMLUni::fgDOMWRTFormatPrettyPrint, pretty))
440         serializer->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, pretty);
441     if (!serializer->writeNode(&target,*n))
442         throw XMLParserException("unable to serialize XML");
443 #endif
444
445     return out;
446 }
447
448 ostream& xmltooling::operator<<(ostream& ostr, const DOMNode& node)
449 {
450     return XMLHelper::serialize(&node, ostr);
451 }
452
453 ostream& xmltooling::operator<<(ostream& ostr, const XMLObject& obj)
454 {
455     try {
456         return ostr << *(obj.marshall());
457     }
458     catch (DOMException& ex) {
459         auto_ptr_char msg(ex.getMessage());
460         throw XMLParserException(msg.get());
461     }
462 }