Add method to compute non-visibly used prefixes in a tree.
[shibboleth/cpp-xmltooling.git] / xmltooling / util / XMLHelper.cpp
1 /*
2  *  Copyright 2001-2009 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(NULL), attributeValue);
61             }
62         }
63     }
64
65     return NULL;
66 }
67
68 DOMAttr* XMLHelper::getIdAttribute(const DOMElement* domElement)
69 {
70     if(!domElement->hasAttributes()) {
71         return NULL;
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 NULL;
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 NULL;
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 NULL;
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 NULL; 
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 NULL;
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(NULL), value);
178 }
179
180 DOMElement* XMLHelper::appendChildElement(DOMElement* parentElement, DOMElement* childElement)
181 {
182     DOMDocument* parentDocument = parentElement->getOwnerDocument();
183     if (childElement->getOwnerDocument() != parentDocument) {
184         childElement = static_cast<DOMElement*>(parentDocument->importNode(childElement, true));
185     }
186
187     parentElement->appendChild(childElement);
188     return childElement;
189 }
190
191 bool XMLHelper::isNodeNamed(const xercesc::DOMNode* n, const XMLCh* ns, const XMLCh* local)
192 {
193     return (n && XMLString::equals(local,n->getLocalName()) && XMLString::equals(ns,n->getNamespaceURI()));
194 }
195
196 const XMLCh* XMLHelper::getTextContent(const DOMElement* e)
197 {
198     DOMNode* child=e->getFirstChild();
199     while (child) {
200         if (child->getNodeType()==DOMNode::TEXT_NODE)
201             return child->getNodeValue();
202         child=child->getNextSibling();
203     }
204     return NULL;
205 }
206
207 DOMElement* XMLHelper::getFirstChildElement(const DOMNode* n, const XMLCh* localName)
208 {
209     DOMNode* child = n->getFirstChild();
210     while (child && child->getNodeType() != DOMNode::ELEMENT_NODE)
211         child = child->getNextSibling();
212     if (child && localName) {
213         if (!XMLString::equals(localName,child->getLocalName()))
214             return getNextSiblingElement(child, localName);
215     }
216     return static_cast<DOMElement*>(child);
217 }    
218
219 DOMElement* XMLHelper::getLastChildElement(const DOMNode* n, const XMLCh* localName)
220 {
221     DOMNode* child = n->getLastChild();
222     while (child && child->getNodeType() != DOMNode::ELEMENT_NODE)
223         child = child->getPreviousSibling();
224     if (child && localName) {
225         if (!XMLString::equals(localName,child->getLocalName()))
226             return getPreviousSiblingElement(child, localName);
227     }
228     return static_cast<DOMElement*>(child);
229 }    
230
231 DOMElement* XMLHelper::getFirstChildElement(const DOMNode* n, const XMLCh* ns, const XMLCh* localName)
232 {
233     DOMElement* e = getFirstChildElement(n, localName);
234     while (e && !XMLString::equals(e->getNamespaceURI(),ns))
235         e = getNextSiblingElement(e, localName);
236     return e;
237 }
238
239 DOMElement* XMLHelper::getLastChildElement(const DOMNode* n, const XMLCh* ns, const XMLCh* localName)
240 {
241     DOMElement* e = getLastChildElement(n, localName);
242     while (e && !XMLString::equals(e->getNamespaceURI(),ns))
243         e = getPreviousSiblingElement(e, localName);
244     return e;
245 }
246
247 DOMElement* XMLHelper::getNextSiblingElement(const DOMNode* n, const XMLCh* localName)
248 {
249     DOMNode* sib = n->getNextSibling();
250     while (sib && sib->getNodeType() != DOMNode::ELEMENT_NODE)
251         sib = sib->getNextSibling();
252     if (sib && localName) {
253         if (!XMLString::equals(localName,sib->getLocalName()))
254             return getNextSiblingElement(sib, localName);
255     }   
256     return static_cast<DOMElement*>(sib);
257 }
258
259 DOMElement* XMLHelper::getPreviousSiblingElement(const DOMNode* n, const XMLCh* localName)
260 {
261     DOMNode* sib = n->getPreviousSibling();
262     while (sib && sib->getNodeType() != DOMNode::ELEMENT_NODE)
263         sib = sib->getPreviousSibling();
264     if (sib && localName) {
265         if (!XMLString::equals(localName,sib->getLocalName()))
266             return getPreviousSiblingElement(sib, localName);
267     }   
268     return static_cast<DOMElement*>(sib);
269 }
270
271 DOMElement* XMLHelper::getNextSiblingElement(const DOMNode* n, const XMLCh* ns, const XMLCh* localName)
272 {
273     DOMElement* e = getNextSiblingElement(n, localName);
274     while (e && !XMLString::equals(e->getNamespaceURI(),ns))
275         e = getNextSiblingElement(e, localName);
276     return e;
277 }
278
279 DOMElement* XMLHelper::getPreviousSiblingElement(const DOMNode* n, const XMLCh* ns, const XMLCh* localName)
280 {
281     DOMElement* e = getPreviousSiblingElement(n, localName);
282     while (e && !XMLString::equals(e->getNamespaceURI(),ns))
283         e = getPreviousSiblingElement(e, localName);
284     return e;
285 }
286
287 void XMLHelper::serialize(const DOMNode* n, std::string& buf, bool pretty)
288 {
289     static const XMLCh impltype[] = { chLatin_L, chLatin_S, chNull };
290     static const XMLCh UTF8[]={ chLatin_U, chLatin_T, chLatin_F, chDash, chDigit_8, chNull };
291
292     MemBufFormatTarget target;
293     DOMImplementation* impl=DOMImplementationRegistry::getDOMImplementation(impltype);
294
295 #ifdef XMLTOOLING_XERCESC_COMPLIANT_DOMLS
296     DOMLSSerializer* serializer = static_cast<DOMImplementationLS*>(impl)->createLSSerializer();
297     XercesJanitor<DOMLSSerializer> janitor(serializer);
298     if (pretty && serializer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, pretty))
299         serializer->getDomConfig()->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, pretty);
300     DOMLSOutput *theOutput = static_cast<DOMImplementationLS*>(impl)->createLSOutput();
301     XercesJanitor<DOMLSOutput> j_theOutput(theOutput);
302     theOutput->setEncoding(UTF8);
303     theOutput->setByteStream(&target);
304     if (!serializer->write(n, theOutput))
305         throw XMLParserException("unable to serialize XML");
306 #else
307     DOMWriter* serializer = static_cast<DOMImplementationLS*>(impl)->createDOMWriter();
308     XercesJanitor<DOMWriter> janitor(serializer);
309     serializer->setEncoding(UTF8);
310     if (pretty && serializer->canSetFeature(XMLUni::fgDOMWRTFormatPrettyPrint, pretty))
311         serializer->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, pretty);
312     if (!serializer->writeNode(&target, *n))
313         throw XMLParserException("unable to serialize XML");
314 #endif
315
316     buf.erase();
317     buf.append(reinterpret_cast<const char*>(target.getRawBuffer()),target.getLen());
318 }
319
320 namespace {
321     class StreamFormatTarget : public XMLFormatTarget
322     {
323     public:
324         StreamFormatTarget(std::ostream& out) : m_out(out) {}
325         ~StreamFormatTarget() {}
326
327         void writeChars(const XMLByte *const toWrite, const xsecsize_t count, XMLFormatter *const formatter) {
328             m_out.write(reinterpret_cast<const char*>(toWrite),count);
329         }
330
331         void flush() {
332             m_out.flush();
333         }
334
335     private:
336         std::ostream& m_out;
337     };
338 };
339
340 ostream& XMLHelper::serialize(const DOMNode* n, ostream& out, bool pretty)
341 {
342     static const XMLCh impltype[] = { chLatin_L, chLatin_S, chNull };
343     static const XMLCh UTF8[]={ chLatin_U, chLatin_T, chLatin_F, chDash, chDigit_8, chNull };
344
345     StreamFormatTarget target(out);
346     DOMImplementation* impl=DOMImplementationRegistry::getDOMImplementation(impltype);
347
348 #ifdef XMLTOOLING_XERCESC_COMPLIANT_DOMLS
349     DOMLSSerializer* serializer = static_cast<DOMImplementationLS*>(impl)->createLSSerializer();
350     XercesJanitor<DOMLSSerializer> janitor(serializer);
351     if (pretty && serializer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, pretty))
352         serializer->getDomConfig()->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, pretty);
353     DOMLSOutput *theOutput = static_cast<DOMImplementationLS*>(impl)->createLSOutput();
354     XercesJanitor<DOMLSOutput> j_theOutput(theOutput);
355     theOutput->setEncoding(UTF8);
356     theOutput->setByteStream(&target);
357     if (!serializer->write(n, theOutput))
358         throw XMLParserException("unable to serialize XML");
359 #else
360     DOMWriter* serializer=(static_cast<DOMImplementationLS*>(impl))->createDOMWriter();
361     XercesJanitor<DOMWriter> janitor(serializer);
362     serializer->setEncoding(UTF8);
363     if (pretty && serializer->canSetFeature(XMLUni::fgDOMWRTFormatPrettyPrint, pretty))
364         serializer->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, pretty);
365     if (!serializer->writeNode(&target,*n))
366         throw XMLParserException("unable to serialize XML");
367 #endif
368
369     return out;
370 }
371
372 ostream& xmltooling::operator<<(ostream& ostr, const DOMNode& node)
373 {
374     return XMLHelper::serialize(&node, ostr);
375 }
376
377 ostream& xmltooling::operator<<(ostream& ostr, const XMLObject& obj)
378 {
379     return ostr << *(obj.marshall());
380 }