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