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