blob: 7d460a497f7c5782c6c8dffc6921b5a4c3fe0db9 [file] [log] [blame]
Kurt Taylor6a6f5be2013-04-02 18:53:47 -04001# Copyright 2012 IBM Corp.
Dan Smithba6cb162012-08-14 07:22:42 -07002# All Rights Reserved.
3#
4# Licensed under the Apache License, Version 2.0 (the "License"); you may
5# not use this file except in compliance with the License. You may obtain
6# 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, WITHOUT
12# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13# License for the specific language governing permissions and limitations
14# under the License.
15
Attila Fazekasc74aede2013-09-11 13:04:02 +020016import collections
Adam Gandelman7f606042014-08-21 17:52:09 -070017import copy
Attila Fazekasc74aede2013-09-11 13:04:02 +020018
Dan Smithba6cb162012-08-14 07:22:42 -070019XMLNS_11 = "http://docs.openstack.org/compute/api/v1.1"
ivan-zhu8f992be2013-07-31 14:56:58 +080020XMLNS_V3 = "http://docs.openstack.org/compute/api/v1.1"
Dan Smithba6cb162012-08-14 07:22:42 -070021
Ann Kamyshnikova26111542013-12-26 12:25:43 +040022NEUTRON_NAMESPACES = {
Elena Ezhova1ec6e182013-12-24 17:45:59 +040023 'binding': "http://docs.openstack.org/ext/binding/api/v1.0",
Ann Kamyshnikova26111542013-12-26 12:25:43 +040024 'router': "http://docs.openstack.org/ext/neutron/router/api/v1.0",
25 'provider': 'http://docs.openstack.org/ext/provider/api/v1.0',
26}
27
Dan Smithba6cb162012-08-14 07:22:42 -070028
29# NOTE(danms): This is just a silly implementation to help make generating
30# XML faster for prototyping. Could be replaced with proper etree gorp
31# if desired
32class Element(object):
33 def __init__(self, element_name, *args, **kwargs):
34 self.element_name = element_name
35 self._attrs = kwargs
36 self._elements = list(args)
37
38 def add_attr(self, name, value):
39 self._attrs[name] = value
40
41 def append(self, element):
42 self._elements.append(element)
43
44 def __str__(self):
ivan-zhuae5f98a2013-10-18 15:57:54 +080045 args = " ".join(['%s="%s"' %
46 (k, v if v is not None else "")
47 for k, v in self._attrs.items()])
Dan Smithba6cb162012-08-14 07:22:42 -070048 string = '<%s %s' % (self.element_name, args)
49 if not self._elements:
50 string += '/>'
51 return string
52
53 string += '>'
54
55 for element in self._elements:
56 string += str(element)
57
58 string += '</%s>' % self.element_name
59
60 return string
61
62 def __getitem__(self, name):
63 for element in self._elements:
64 if element.element_name == name:
65 return element
66 raise KeyError("No such element `%s'" % name)
67
68 def __getattr__(self, name):
69 if name in self._attrs:
70 return self._attrs[name]
71 return object.__getattr__(self, name)
72
73 def attributes(self):
74 return self._attrs.items()
75
76 def children(self):
77 return self._elements
78
79
80class Document(Element):
81 def __init__(self, *args, **kwargs):
Dan Smithba6cb162012-08-14 07:22:42 -070082 Element.__init__(self, '?xml', *args, **kwargs)
83
84 def __str__(self):
Adam Gandelman7f606042014-08-21 17:52:09 -070085 attrs = copy.copy(self._attrs)
86 # pop the required standard attrs out and render in required
87 # order.
88 vers = attrs.pop('version', '1.0')
89 enc = attrs.pop('encoding', 'UTF-8')
90 args = 'version="%s" encoding="%s"' % (vers, enc)
91 if attrs:
92 args = " ".join([args] + ['%s="%s"' %
93 (k, v if v is not None else "")
94 for k, v in attrs.items()])
Dan Smithba6cb162012-08-14 07:22:42 -070095 string = '<?xml %s?>\n' % args
96 for element in self._elements:
97 string += str(element)
98 return string
99
100
101class Text(Element):
102 def __init__(self, content=""):
103 Element.__init__(self, None)
104 self.__content = content
105
106 def __str__(self):
107 return self.__content
108
109
Rossella Sblendidoc1724112013-11-28 14:16:48 +0100110def parse_array(node, plurals=None):
111 array = []
112 for child in node.getchildren():
113 array.append(xml_to_json(child,
114 plurals))
115 return array
116
117
118def xml_to_json(node, plurals=None):
Dan Smithba6cb162012-08-14 07:22:42 -0700119 """This does a really braindead conversion of an XML tree to
120 something that looks like a json dump. In cases where the XML
121 and json structures are the same, then this "just works". In
Attila Fazekasb2902af2013-02-16 16:22:44 +0100122 others, it requires a little hand-editing of the result.
123 """
Dan Smithba6cb162012-08-14 07:22:42 -0700124 json = {}
Ann Kamyshnikovaf6bd5782014-01-13 14:08:04 +0400125 bool_flag = False
126 int_flag = False
127 long_flag = False
Dan Smithba6cb162012-08-14 07:22:42 -0700128 for attr in node.keys():
Davanum Srinivas8d226cc2013-03-08 09:35:36 -0500129 if not attr.startswith("xmlns"):
130 json[attr] = node.get(attr)
Ann Kamyshnikovaf6bd5782014-01-13 14:08:04 +0400131 if json[attr] == 'bool':
132 bool_flag = True
133 elif json[attr] == 'int':
134 int_flag = True
135 elif json[attr] == 'long':
136 long_flag = True
Dan Smithba6cb162012-08-14 07:22:42 -0700137 if not node.getchildren():
Ann Kamyshnikovaf6bd5782014-01-13 14:08:04 +0400138 if bool_flag:
139 return node.text == 'True'
140 elif int_flag:
141 return int(node.text)
142 elif long_flag:
143 return long(node.text)
144 else:
145 return node.text or json
Dan Smithba6cb162012-08-14 07:22:42 -0700146 for child in node.getchildren():
147 tag = child.tag
148 if tag.startswith("{"):
149 ns, tag = tag.split("}", 1)
Ann Kamyshnikova26111542013-12-26 12:25:43 +0400150 for key, uri in NEUTRON_NAMESPACES.iteritems():
151 if uri == ns[1:]:
152 tag = key + ":" + tag
Rossella Sblendidoc1724112013-11-28 14:16:48 +0100153 if plurals is not None and tag in plurals:
Andrea Frittoli513c8392014-01-10 14:16:34 +0000154 json[tag] = parse_array(child, plurals)
Rossella Sblendidoc1724112013-11-28 14:16:48 +0100155 else:
Andrea Frittoli513c8392014-01-10 14:16:34 +0000156 json[tag] = xml_to_json(child, plurals)
Dan Smithba6cb162012-08-14 07:22:42 -0700157 return json
Attila Fazekasc74aede2013-09-11 13:04:02 +0200158
159
160def deep_dict_to_xml(dest, source):
161 """Populates the ``dest`` xml element with the ``source`` ``Mapping``
162 elements, if the source Mapping's value is also a ``Mapping``
163 they will be recursively added as a child elements.
164 :param source: A python ``Mapping`` (dict)
165 :param dest: XML child element will be added to the ``dest``
166 """
167 for element, content in source.iteritems():
168 if isinstance(content, collections.Mapping):
169 xml_element = Element(element)
170 deep_dict_to_xml(xml_element, content)
171 dest.append(xml_element)
172 else:
173 dest.append(Element(element, content))