Merged marshalling/unmarshalling methods into core interface.
[shibboleth/cpp-xmltooling.git] / xmltooling / io / AbstractXMLObjectMarshaller.cpp
1 /*\r
2 *  Copyright 2001-2006 Internet2\r
3  * \r
4 * Licensed under the Apache License, Version 2.0 (the "License");\r
5  * you may not use this file except in compliance with the License.\r
6  * You may obtain a copy of the License at\r
7  *\r
8  *     http://www.apache.org/licenses/LICENSE-2.0\r
9  *\r
10  * Unless required by applicable law or agreed to in writing, software\r
11  * distributed under the License is distributed on an "AS IS" BASIS,\r
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
13  * See the License for the specific language governing permissions and\r
14  * limitations under the License.\r
15  */\r
16 \r
17 /**\r
18  * AbstractXMLObjectMarshaller.cpp\r
19  * \r
20  * A thread-safe abstract marshaller.\r
21  */\r
22 \r
23 #include "internal.h"\r
24 #include "exceptions.h"\r
25 #include "io/AbstractXMLObjectMarshaller.h"\r
26 #ifndef XMLTOOLING_NO_XMLSEC\r
27     #include "signature/Signature.h"\r
28 #endif\r
29 #include "util/NDC.h"\r
30 #include "util/XMLConstants.h"\r
31 #include "util/XMLHelper.h"\r
32 \r
33 #include <algorithm>\r
34 #include <functional>\r
35 #include <xercesc/util/XMLUniDefs.hpp>\r
36 #include <log4cpp/Category.hh>\r
37 \r
38 using namespace xmltooling;\r
39 using namespace log4cpp;\r
40 using namespace std;\r
41 \r
42 #define XT_log (*static_cast<Category*>(m_log))\r
43 \r
44 DOMElement* AbstractXMLObjectMarshaller::marshall(DOMDocument* document, MarshallingContext* ctx) const\r
45 {\r
46 #ifdef _DEBUG\r
47     xmltooling::NDC ndc("marshall");\r
48 #endif\r
49 \r
50     if (XT_log.isDebugEnabled()) {\r
51         XT_log.debug("starting to marshal %s", getElementQName().toString().c_str());\r
52     }\r
53 \r
54     DOMElement* cachedDOM=getDOM();\r
55     if (cachedDOM) {\r
56         if (!document || document==cachedDOM->getOwnerDocument()) {\r
57             XT_log.debug("XMLObject has a usable cached DOM, reusing it");\r
58             if (document)\r
59                 setDocumentElement(cachedDOM->getOwnerDocument(),cachedDOM);\r
60             releaseParentDOM(true);\r
61             return cachedDOM;\r
62         }\r
63         \r
64         // We have a DOM but it doesn't match the document we were given. This both sucks and blows.\r
65         // Without an adoptNode option to maintain the child pointers, we have to either import the\r
66         // DOM while somehow reassigning all the nested references (which amounts to a complete\r
67         // *unmarshall* operation), or we just release the existing DOM and hope that we can get\r
68         // it back. This depends on all objects being able to preserve their DOM at all costs.\r
69         releaseChildrenDOM(true);\r
70         releaseDOM();\r
71     }\r
72     \r
73     // If we get here, we didn't have a usable DOM (and/or we released the one we had).\r
74     // We may need to create our own document.\r
75     bool bindDocument=false;\r
76     if (!document) {\r
77         document=DOMImplementationRegistry::getDOMImplementation(NULL)->createDocument();\r
78         bindDocument=true;\r
79     }\r
80 \r
81     try {\r
82         XT_log.debug("creating root element to marshall");\r
83         DOMElement* domElement = document->createElementNS(\r
84             getElementQName().getNamespaceURI(), getElementQName().getLocalPart()\r
85             );\r
86         setDocumentElement(document, domElement);\r
87         marshallInto(domElement, ctx);\r
88 \r
89         //Recache the DOM.\r
90         XT_log.debug("caching DOM for XMLObject (document is %sbound)", bindDocument ? "" : "not ");\r
91         setDOM(domElement, bindDocument);\r
92         releaseParentDOM(true);\r
93 \r
94         return domElement;\r
95     }\r
96     catch (...) {\r
97         // Delete the document if need be, and rethrow.\r
98         if (bindDocument) {\r
99             document->release();\r
100         }\r
101         throw;\r
102     }\r
103 }\r
104 \r
105 DOMElement* AbstractXMLObjectMarshaller::marshall(DOMElement* parentElement, MarshallingContext* ctx) const\r
106 {\r
107 #ifdef _DEBUG\r
108     xmltooling::NDC ndc("marshall");\r
109 #endif\r
110 \r
111     if (XT_log.isDebugEnabled()) {\r
112         XT_log.debug("starting to marshalling %s", getElementQName().toString().c_str());\r
113     }\r
114 \r
115     DOMElement* cachedDOM=getDOM();\r
116     if (cachedDOM) {\r
117         if (parentElement->getOwnerDocument()==cachedDOM->getOwnerDocument()) {\r
118             XT_log.debug("XMLObject has a usable cached DOM, reusing it");\r
119             if (parentElement!=cachedDOM->getParentNode()) {\r
120                 parentElement->appendChild(cachedDOM);\r
121                 releaseParentDOM(true);\r
122             }\r
123             return cachedDOM;\r
124         }\r
125         \r
126         // We have a DOM but it doesn't match the document we were given. This both sucks and blows.\r
127         // Without an adoptNode option to maintain the child pointers, we have to either import the\r
128         // DOM while somehow reassigning all the nested references (which amounts to a complete\r
129         // *unmarshall* operation), or we just release the existing DOM and hope that we can get\r
130         // it back. This depends on all objects being able to preserve their DOM at all costs.\r
131         releaseChildrenDOM(true);\r
132         releaseDOM();\r
133     }\r
134     \r
135     // If we get here, we didn't have a usable DOM (and/or we released the one we had).\r
136     XT_log.debug("creating root element to marshall");\r
137     DOMElement* domElement = parentElement->getOwnerDocument()->createElementNS(\r
138         getElementQName().getNamespaceURI(), getElementQName().getLocalPart()\r
139         );\r
140     parentElement->appendChild(domElement);\r
141     marshallInto(domElement, ctx);\r
142 \r
143     //Recache the DOM.\r
144     XT_log.debug("caching DOM for XMLObject");\r
145     setDOM(domElement, false);\r
146     releaseParentDOM(true);\r
147 \r
148     return domElement;\r
149 }\r
150 \r
151 #ifndef XMLTOOLING_NO_XMLSEC\r
152     class _signit : public unary_function<const pair<Signature*,const SigningContext*>&, void> {\r
153     public:\r
154         void operator()(const pair<Signature*,const SigningContext*>& p) const {\r
155             p.first->sign(*(p.second));\r
156         }\r
157     };\r
158 #endif\r
159 \r
160 void AbstractXMLObjectMarshaller::marshallInto(DOMElement* targetElement, MarshallingContext* ctx) const\r
161 {\r
162     if (getElementQName().hasPrefix())\r
163         targetElement->setPrefix(getElementQName().getPrefix());\r
164     marshallElementType(targetElement);\r
165     marshallNamespaces(targetElement);\r
166     marshallAttributes(targetElement);\r
167     marshallChildElements(targetElement);\r
168     marshallElementContent(targetElement);\r
169 \r
170 #ifndef XMLTOOLING_NO_XMLSEC\r
171     if (ctx) {\r
172         for_each(ctx->m_signingContexts.begin(),ctx->m_signingContexts.end(),_signit());\r
173     }\r
174 #endif\r
175 }\r
176 \r
177 void AbstractXMLObjectMarshaller::marshallElementType(DOMElement* domElement) const\r
178 {\r
179     const QName* type = getSchemaType();\r
180     if (type) {\r
181         XT_log.debug("setting xsi:type attribute for XMLObject");\r
182         \r
183         const XMLCh* typeLocalName = type->getLocalPart();\r
184         if (!typeLocalName || !*typeLocalName) {\r
185             throw MarshallingException("Schema type of XMLObject may not have an empty local name.");\r
186         }\r
187 \r
188         static const XMLCh xsitype[] = {\r
189             chLatin_x, chLatin_s, chLatin_i, chColon, chLatin_t, chLatin_y, chLatin_p, chLatin_e, chNull\r
190             };\r
191         \r
192         XMLCh* xsivalue=const_cast<XMLCh*>(typeLocalName);\r
193         const XMLCh* prefix=type->getPrefix();\r
194         if (prefix && *prefix) {\r
195             xsivalue=new XMLCh[XMLString::stringLen(typeLocalName) + XMLString::stringLen(prefix) + 2*sizeof(XMLCh)];\r
196             *xsivalue=chNull;\r
197             XMLString::catString(xsivalue,prefix);\r
198             static const XMLCh colon[] = {chColon, chNull};\r
199             XMLString::catString(xsivalue,colon);\r
200             XMLString::catString(xsivalue,typeLocalName);\r
201         }   \r
202         domElement->setAttributeNS(XMLConstants::XSI_NS, xsitype, xsivalue);\r
203         if (xsivalue != typeLocalName)\r
204             XMLString::release(&xsivalue);\r
205 \r
206         XT_log.debug("Adding XSI namespace to list of namespaces used by XMLObject");\r
207         addNamespace(Namespace(XMLConstants::XSI_NS, XMLConstants::XSI_PREFIX));\r
208     }\r
209 }\r
210 \r
211 class _addns : public binary_function<DOMElement*,Namespace,void> {\r
212 public:\r
213     void operator()(DOMElement* domElement, const Namespace& ns) const {\r
214         const XMLCh* prefix=ns.getNamespacePrefix();\r
215         const XMLCh* uri=ns.getNamespaceURI();\r
216         \r
217         // Check to see if the prefix is already declared properly above this node.\r
218         if (!ns.alwaysDeclare()) {\r
219             const XMLCh* declared=lookupNamespaceURI(domElement->getParentNode(),prefix);\r
220             if (declared && XMLString::equals(declared,uri))\r
221                 return;\r
222         }\r
223             \r
224         if (prefix && *prefix) {\r
225             XMLCh* xmlns=new XMLCh[XMLString::stringLen(XMLConstants::XMLNS_PREFIX) + XMLString::stringLen(prefix) + 2*sizeof(XMLCh)];\r
226             *xmlns=chNull;\r
227             XMLString::catString(xmlns,XMLConstants::XMLNS_PREFIX);\r
228             static const XMLCh colon[] = {chColon, chNull};\r
229             XMLString::catString(xmlns,colon);\r
230             XMLString::catString(xmlns,prefix);\r
231             domElement->setAttributeNS(XMLConstants::XMLNS_NS, xmlns, uri);\r
232         }\r
233         else {\r
234             domElement->setAttributeNS(XMLConstants::XMLNS_NS, XMLConstants::XMLNS_PREFIX, uri);\r
235         }\r
236     }\r
237 \r
238     const XMLCh* lookupNamespaceURI(const DOMNode* n, const XMLCh* prefix) const {\r
239         // Return NULL if no declaration in effect. The empty string signifies the null namespace.\r
240         if (!n || n->getNodeType()!=DOMNode::ELEMENT_NODE) {\r
241             // At the root, the default namespace is set to the null namespace.\r
242             if (!prefix || !*prefix)\r
243                 return &chNull;\r
244             return NULL;    // we're done\r
245         }\r
246         DOMNamedNodeMap* attributes = static_cast<const DOMElement*>(n)->getAttributes();\r
247         if (!attributes)\r
248             return lookupNamespaceURI(n->getParentNode(),prefix);   // defer to parent\r
249         DOMNode* childNode;\r
250         DOMAttr* attribute;\r
251         for (XMLSize_t i=0; i<attributes->getLength(); i++) {\r
252             childNode = attributes->item(i);\r
253             if (childNode->getNodeType() != DOMNode::ATTRIBUTE_NODE)    // not an attribute?\r
254                 continue;\r
255             attribute = static_cast<DOMAttr*>(childNode);\r
256             if (!XMLString::equals(attribute->getNamespaceURI(),XMLConstants::XMLNS_NS))\r
257                 continue;   // not a namespace declaration\r
258             // Local name should be the prefix and the value would be the URI, except for the default namespace.\r
259             if ((!prefix || !*prefix) && XMLString::equals(attribute->getLocalName(),XMLConstants::XMLNS_PREFIX))\r
260                 return attribute->getNodeValue();\r
261             else if (XMLString::equals(prefix,attribute->getLocalName()))\r
262                 return attribute->getNodeValue();\r
263         }\r
264         // Defer to parent.\r
265         return lookupNamespaceURI(n->getParentNode(),prefix);\r
266     }\r
267 };\r
268 \r
269 void AbstractXMLObjectMarshaller::marshallNamespaces(DOMElement* domElement) const\r
270 {\r
271     XT_log.debug("marshalling namespace attributes for XMLObject");\r
272     const set<Namespace>& namespaces = getNamespaces();\r
273     for_each(namespaces.begin(),namespaces.end(),bind1st(_addns(),domElement));\r
274 }\r
275 \r
276 class _marshallit : public binary_function<const XMLObject*,DOMElement*,void> {\r
277 public:\r
278     void operator()(const XMLObject* xo, DOMElement* e) const {\r
279         if (xo) xo->marshall(e);\r
280     }\r
281 };\r
282 \r
283 void AbstractXMLObjectMarshaller::marshallChildElements(DOMElement* domElement) const\r
284 {\r
285     XT_log.debug("marshalling child elements for XMLObject");\r
286 \r
287     const list<XMLObject*>& children=getOrderedChildren();\r
288     for_each(children.begin(),children.end(),bind2nd(_marshallit(),domElement));\r
289 }\r