4d4b8e23d104f8354f56bcf2a49c16b8262d6681
[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     const XMLCh* value=domNode->getTextContent();
180     if (!value || !*value)
181         return nullptr;
182
183     int i;
184     if ((i=XMLString::indexOf(value,chColon))>0) {
185         XMLCh* prefix=new XMLCh[i+1];
186         XMLString::subString(prefix,value,0,i);
187         prefix[i]=chNull;
188         xmltooling::QName* ret=new xmltooling::QName(domNode->lookupNamespaceURI(prefix), value + i + 1, prefix);
189         delete[] prefix;
190         return ret;
191     }
192     
193     return new xmltooling::QName(domNode->lookupNamespaceURI(nullptr), value);
194 }
195
196 bool XMLHelper::getNodeValueAsBool(const xercesc::DOMNode* domNode, bool def)
197 {
198     if (!domNode)
199         return def;
200     const XMLCh* value = domNode->getNodeValue();
201     if (!value || !*value)
202         return def;
203     if (*value == chLatin_t || *value == chDigit_1)
204         return true;
205     else if (*value == chLatin_f || *value == chDigit_0)
206         return false;
207     return def;
208 }
209
210 DOMElement* XMLHelper::appendChildElement(DOMElement* parentElement, DOMElement* childElement)
211 {
212     DOMDocument* parentDocument = parentElement->getOwnerDocument();
213     if (childElement->getOwnerDocument() != parentDocument) {
214         childElement = static_cast<DOMElement*>(parentDocument->importNode(childElement, true));
215     }
216
217     parentElement->appendChild(childElement);
218     return childElement;
219 }
220
221 bool XMLHelper::isNodeNamed(const xercesc::DOMNode* n, const XMLCh* ns, const XMLCh* local)
222 {
223     return (n && XMLString::equals(local,n->getLocalName()) && XMLString::equals(ns,n->getNamespaceURI()));
224 }
225
226 const XMLCh* XMLHelper::getTextContent(const DOMElement* e)
227 {
228     DOMNode* child = e ? e->getFirstChild() : nullptr;
229     while (child) {
230         if (child->getNodeType() == DOMNode::TEXT_NODE)
231             return child->getNodeValue();
232         child = child->getNextSibling();
233     }
234     return nullptr;
235 }
236
237 DOMElement* XMLHelper::getFirstChildElement(const DOMNode* n, const XMLCh* localName)
238 {
239     DOMNode* child = n ? n->getFirstChild() : nullptr;
240     while (child && child->getNodeType() != DOMNode::ELEMENT_NODE)
241         child = child->getNextSibling();
242     if (child && localName) {
243         if (!XMLString::equals(localName,child->getLocalName()))
244             return getNextSiblingElement(child, localName);
245     }
246     return static_cast<DOMElement*>(child);
247 }    
248
249 DOMElement* XMLHelper::getLastChildElement(const DOMNode* n, const XMLCh* localName)
250 {
251     DOMNode* child = n ? n->getLastChild() : nullptr;
252     while (child && child->getNodeType() != DOMNode::ELEMENT_NODE)
253         child = child->getPreviousSibling();
254     if (child && localName) {
255         if (!XMLString::equals(localName,child->getLocalName()))
256             return getPreviousSiblingElement(child, localName);
257     }
258     return static_cast<DOMElement*>(child);
259 }    
260
261 DOMElement* XMLHelper::getFirstChildElement(const DOMNode* n, const XMLCh* ns, const XMLCh* localName)
262 {
263     DOMElement* e = getFirstChildElement(n, localName);
264     while (e && !XMLString::equals(e->getNamespaceURI(),ns))
265         e = getNextSiblingElement(e, localName);
266     return e;
267 }
268
269 DOMElement* XMLHelper::getLastChildElement(const DOMNode* n, const XMLCh* ns, const XMLCh* localName)
270 {
271     DOMElement* e = getLastChildElement(n, localName);
272     while (e && !XMLString::equals(e->getNamespaceURI(),ns))
273         e = getPreviousSiblingElement(e, localName);
274     return e;
275 }
276
277 DOMElement* XMLHelper::getNextSiblingElement(const DOMNode* n, const XMLCh* localName)
278 {
279     DOMNode* sib = n ? n->getNextSibling() : nullptr;
280     while (sib && sib->getNodeType() != DOMNode::ELEMENT_NODE)
281         sib = sib->getNextSibling();
282     if (sib && localName) {
283         if (!XMLString::equals(localName,sib->getLocalName()))
284             return getNextSiblingElement(sib, localName);
285     }   
286     return static_cast<DOMElement*>(sib);
287 }
288
289 DOMElement* XMLHelper::getPreviousSiblingElement(const DOMNode* n, const XMLCh* localName)
290 {
291     DOMNode* sib = n ? n->getPreviousSibling() : nullptr;
292     while (sib && sib->getNodeType() != DOMNode::ELEMENT_NODE)
293         sib = sib->getPreviousSibling();
294     if (sib && localName) {
295         if (!XMLString::equals(localName,sib->getLocalName()))
296             return getPreviousSiblingElement(sib, localName);
297     }   
298     return static_cast<DOMElement*>(sib);
299 }
300
301 DOMElement* XMLHelper::getNextSiblingElement(const DOMNode* n, const XMLCh* ns, const XMLCh* localName)
302 {
303     DOMElement* e = getNextSiblingElement(n, localName);
304     while (e && !XMLString::equals(e->getNamespaceURI(),ns))
305         e = getNextSiblingElement(e, localName);
306     return e;
307 }
308
309 DOMElement* XMLHelper::getPreviousSiblingElement(const DOMNode* n, const XMLCh* ns, const XMLCh* localName)
310 {
311     DOMElement* e = getPreviousSiblingElement(n, localName);
312     while (e && !XMLString::equals(e->getNamespaceURI(),ns))
313         e = getPreviousSiblingElement(e, localName);
314     return e;
315 }
316
317 string XMLHelper::getAttrString(const DOMElement* e, const char* defValue, const XMLCh* localName, const XMLCh* ns)
318 {
319     if (e) {
320         auto_ptr_char val(e->getAttributeNS(ns, localName));
321         if (val.get() && *val.get())
322             return val.get();
323     }
324     return defValue ? defValue : "";
325 }
326
327 int XMLHelper::getAttrInt(const DOMElement* e, int defValue, const XMLCh* localName, const XMLCh* ns)
328 {
329     if (e) {
330         const XMLCh* val = e->getAttributeNS(ns, localName);
331         if (val && *val) {
332             int i = XMLString::parseInt(val);
333             if (i)
334                 return i;
335         }
336     }
337     return defValue;
338 }
339
340 bool XMLHelper::getAttrBool(const DOMElement* e, bool defValue, const XMLCh* localName, const XMLCh* ns)
341 {
342     if (e) {
343         const XMLCh* val = e->getAttributeNS(ns, localName);
344         if (val) {
345             if (*val == chLatin_t || *val == chDigit_1)
346                 return true;
347             if (*val == chLatin_f || *val == chDigit_0)
348                 return false;
349         }
350     }
351     return defValue;
352 }
353
354 void XMLHelper::serialize(const DOMNode* n, std::string& buf, bool pretty)
355 {
356     static const XMLCh impltype[] = { chLatin_L, chLatin_S, chNull };
357     static const XMLCh UTF8[]={ chLatin_U, chLatin_T, chLatin_F, chDash, chDigit_8, chNull };
358
359     MemBufFormatTarget target;
360     DOMImplementation* impl=DOMImplementationRegistry::getDOMImplementation(impltype);
361
362 #ifdef XMLTOOLING_XERCESC_COMPLIANT_DOMLS
363     DOMLSSerializer* serializer = static_cast<DOMImplementationLS*>(impl)->createLSSerializer();
364     XercesJanitor<DOMLSSerializer> janitor(serializer);
365     if (pretty && serializer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, pretty))
366         serializer->getDomConfig()->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, pretty);
367     DOMLSOutput *theOutput = static_cast<DOMImplementationLS*>(impl)->createLSOutput();
368     XercesJanitor<DOMLSOutput> j_theOutput(theOutput);
369     theOutput->setEncoding(UTF8);
370     theOutput->setByteStream(&target);
371     if (!serializer->write(n, theOutput))
372         throw XMLParserException("unable to serialize XML");
373 #else
374     DOMWriter* serializer = static_cast<DOMImplementationLS*>(impl)->createDOMWriter();
375     XercesJanitor<DOMWriter> janitor(serializer);
376     serializer->setEncoding(UTF8);
377     if (pretty && serializer->canSetFeature(XMLUni::fgDOMWRTFormatPrettyPrint, pretty))
378         serializer->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, pretty);
379     if (!serializer->writeNode(&target, *n))
380         throw XMLParserException("unable to serialize XML");
381 #endif
382
383     buf.erase();
384     buf.append(reinterpret_cast<const char*>(target.getRawBuffer()),target.getLen());
385 }
386
387 namespace {
388     class StreamFormatTarget : public XMLFormatTarget
389     {
390     public:
391         StreamFormatTarget(std::ostream& out) : m_out(out) {}
392         ~StreamFormatTarget() {}
393
394         void writeChars(const XMLByte *const toWrite, const xsecsize_t count, XMLFormatter *const formatter) {
395             m_out.write(reinterpret_cast<const char*>(toWrite),count);
396         }
397
398         void flush() {
399             m_out.flush();
400         }
401
402     private:
403         std::ostream& m_out;
404     };
405 };
406
407 ostream& XMLHelper::serialize(const DOMNode* n, ostream& out, bool pretty)
408 {
409     static const XMLCh impltype[] = { chLatin_L, chLatin_S, chNull };
410     static const XMLCh UTF8[]={ chLatin_U, chLatin_T, chLatin_F, chDash, chDigit_8, chNull };
411
412     StreamFormatTarget target(out);
413     DOMImplementation* impl=DOMImplementationRegistry::getDOMImplementation(impltype);
414
415 #ifdef XMLTOOLING_XERCESC_COMPLIANT_DOMLS
416     DOMLSSerializer* serializer = static_cast<DOMImplementationLS*>(impl)->createLSSerializer();
417     XercesJanitor<DOMLSSerializer> janitor(serializer);
418     if (pretty && serializer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, pretty))
419         serializer->getDomConfig()->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, pretty);
420     DOMLSOutput *theOutput = static_cast<DOMImplementationLS*>(impl)->createLSOutput();
421     XercesJanitor<DOMLSOutput> j_theOutput(theOutput);
422     theOutput->setEncoding(UTF8);
423     theOutput->setByteStream(&target);
424     if (!serializer->write(n, theOutput))
425         throw XMLParserException("unable to serialize XML");
426 #else
427     DOMWriter* serializer=(static_cast<DOMImplementationLS*>(impl))->createDOMWriter();
428     XercesJanitor<DOMWriter> janitor(serializer);
429     serializer->setEncoding(UTF8);
430     if (pretty && serializer->canSetFeature(XMLUni::fgDOMWRTFormatPrettyPrint, pretty))
431         serializer->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, pretty);
432     if (!serializer->writeNode(&target,*n))
433         throw XMLParserException("unable to serialize XML");
434 #endif
435
436     return out;
437 }
438
439 ostream& xmltooling::operator<<(ostream& ostr, const DOMNode& node)
440 {
441     return XMLHelper::serialize(&node, ostr);
442 }
443
444 ostream& xmltooling::operator<<(ostream& ostr, const XMLObject& obj)
445 {
446     return ostr << *(obj.marshall());
447 }