Add same-doc KeyInfoReference support, with option to disable.
[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 void XMLHelper::serialize(const DOMNode* n, std::string& buf, bool pretty)
302 {
303     static const XMLCh impltype[] = { chLatin_L, chLatin_S, chNull };
304     static const XMLCh UTF8[]={ chLatin_U, chLatin_T, chLatin_F, chDash, chDigit_8, chNull };
305
306     MemBufFormatTarget target;
307     DOMImplementation* impl=DOMImplementationRegistry::getDOMImplementation(impltype);
308
309 #ifdef XMLTOOLING_XERCESC_COMPLIANT_DOMLS
310     DOMLSSerializer* serializer = static_cast<DOMImplementationLS*>(impl)->createLSSerializer();
311     XercesJanitor<DOMLSSerializer> janitor(serializer);
312     if (pretty && serializer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, pretty))
313         serializer->getDomConfig()->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, pretty);
314     DOMLSOutput *theOutput = static_cast<DOMImplementationLS*>(impl)->createLSOutput();
315     XercesJanitor<DOMLSOutput> j_theOutput(theOutput);
316     theOutput->setEncoding(UTF8);
317     theOutput->setByteStream(&target);
318     if (!serializer->write(n, theOutput))
319         throw XMLParserException("unable to serialize XML");
320 #else
321     DOMWriter* serializer = static_cast<DOMImplementationLS*>(impl)->createDOMWriter();
322     XercesJanitor<DOMWriter> janitor(serializer);
323     serializer->setEncoding(UTF8);
324     if (pretty && serializer->canSetFeature(XMLUni::fgDOMWRTFormatPrettyPrint, pretty))
325         serializer->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, pretty);
326     if (!serializer->writeNode(&target, *n))
327         throw XMLParserException("unable to serialize XML");
328 #endif
329
330     buf.erase();
331     buf.append(reinterpret_cast<const char*>(target.getRawBuffer()),target.getLen());
332 }
333
334 namespace {
335     class StreamFormatTarget : public XMLFormatTarget
336     {
337     public:
338         StreamFormatTarget(std::ostream& out) : m_out(out) {}
339         ~StreamFormatTarget() {}
340
341         void writeChars(const XMLByte *const toWrite, const xsecsize_t count, XMLFormatter *const formatter) {
342             m_out.write(reinterpret_cast<const char*>(toWrite),count);
343         }
344
345         void flush() {
346             m_out.flush();
347         }
348
349     private:
350         std::ostream& m_out;
351     };
352 };
353
354 ostream& XMLHelper::serialize(const DOMNode* n, ostream& out, 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     StreamFormatTarget target(out);
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     return out;
384 }
385
386 ostream& xmltooling::operator<<(ostream& ostr, const DOMNode& node)
387 {
388     return XMLHelper::serialize(&node, ostr);
389 }
390
391 ostream& xmltooling::operator<<(ostream& ostr, const XMLObject& obj)
392 {
393     return ostr << *(obj.marshall());
394 }