blob: b1bf78906ecc5387a4182970d91708af6b3c7f9f [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
17
Dan Smithba6cb162012-08-14 07:22:42 -070018XMLNS_11 = "http://docs.openstack.org/compute/api/v1.1"
ivan-zhu8f992be2013-07-31 14:56:58 +080019XMLNS_V3 = "http://docs.openstack.org/compute/api/v1.1"
Dan Smithba6cb162012-08-14 07:22:42 -070020
Ann Kamyshnikova26111542013-12-26 12:25:43 +040021NEUTRON_NAMESPACES = {
Elena Ezhova1ec6e182013-12-24 17:45:59 +040022 'binding': "http://docs.openstack.org/ext/binding/api/v1.0",
Ann Kamyshnikova26111542013-12-26 12:25:43 +040023 'router': "http://docs.openstack.org/ext/neutron/router/api/v1.0",
24 'provider': 'http://docs.openstack.org/ext/provider/api/v1.0',
25}
26
Dan Smithba6cb162012-08-14 07:22:42 -070027
28# NOTE(danms): This is just a silly implementation to help make generating
29# XML faster for prototyping. Could be replaced with proper etree gorp
30# if desired
31class Element(object):
32 def __init__(self, element_name, *args, **kwargs):
33 self.element_name = element_name
34 self._attrs = kwargs
35 self._elements = list(args)
36
37 def add_attr(self, name, value):
38 self._attrs[name] = value
39
40 def append(self, element):
41 self._elements.append(element)
42
43 def __str__(self):
ivan-zhuae5f98a2013-10-18 15:57:54 +080044 args = " ".join(['%s="%s"' %
45 (k, v if v is not None else "")
46 for k, v in self._attrs.items()])
Dan Smithba6cb162012-08-14 07:22:42 -070047 string = '<%s %s' % (self.element_name, args)
48 if not self._elements:
49 string += '/>'
50 return string
51
52 string += '>'
53
54 for element in self._elements:
55 string += str(element)
56
57 string += '</%s>' % self.element_name
58
59 return string
60
61 def __getitem__(self, name):
62 for element in self._elements:
63 if element.element_name == name:
64 return element
65 raise KeyError("No such element `%s'" % name)
66
67 def __getattr__(self, name):
68 if name in self._attrs:
69 return self._attrs[name]
70 return object.__getattr__(self, name)
71
72 def attributes(self):
73 return self._attrs.items()
74
75 def children(self):
76 return self._elements
77
78
79class Document(Element):
80 def __init__(self, *args, **kwargs):
81 if 'version' not in kwargs:
82 kwargs['version'] = '1.0'
83 if 'encoding' not in kwargs:
84 kwargs['encoding'] = 'UTF-8'
85 Element.__init__(self, '?xml', *args, **kwargs)
86
87 def __str__(self):
ivan-zhuae5f98a2013-10-18 15:57:54 +080088 args = " ".join(['%s="%s"' %
89 (k, v if v is not None else "")
90 for k, v in self._attrs.items()])
Dan Smithba6cb162012-08-14 07:22:42 -070091 string = '<?xml %s?>\n' % args
92 for element in self._elements:
93 string += str(element)
94 return string
95
96
97class Text(Element):
98 def __init__(self, content=""):
99 Element.__init__(self, None)
100 self.__content = content
101
102 def __str__(self):
103 return self.__content
104
105
Rossella Sblendidoc1724112013-11-28 14:16:48 +0100106def parse_array(node, plurals=None):
107 array = []
108 for child in node.getchildren():
109 array.append(xml_to_json(child,
110 plurals))
111 return array
112
113
114def xml_to_json(node, plurals=None):
Dan Smithba6cb162012-08-14 07:22:42 -0700115 """This does a really braindead conversion of an XML tree to
116 something that looks like a json dump. In cases where the XML
117 and json structures are the same, then this "just works". In
Attila Fazekasb2902af2013-02-16 16:22:44 +0100118 others, it requires a little hand-editing of the result.
119 """
Dan Smithba6cb162012-08-14 07:22:42 -0700120 json = {}
Ann Kamyshnikovaf6bd5782014-01-13 14:08:04 +0400121 bool_flag = False
122 int_flag = False
123 long_flag = False
Dan Smithba6cb162012-08-14 07:22:42 -0700124 for attr in node.keys():
Davanum Srinivas8d226cc2013-03-08 09:35:36 -0500125 if not attr.startswith("xmlns"):
126 json[attr] = node.get(attr)
Ann Kamyshnikovaf6bd5782014-01-13 14:08:04 +0400127 if json[attr] == 'bool':
128 bool_flag = True
129 elif json[attr] == 'int':
130 int_flag = True
131 elif json[attr] == 'long':
132 long_flag = True
Dan Smithba6cb162012-08-14 07:22:42 -0700133 if not node.getchildren():
Ann Kamyshnikovaf6bd5782014-01-13 14:08:04 +0400134 if bool_flag:
135 return node.text == 'True'
136 elif int_flag:
137 return int(node.text)
138 elif long_flag:
139 return long(node.text)
140 else:
141 return node.text or json
Dan Smithba6cb162012-08-14 07:22:42 -0700142 for child in node.getchildren():
143 tag = child.tag
144 if tag.startswith("{"):
145 ns, tag = tag.split("}", 1)
Ann Kamyshnikova26111542013-12-26 12:25:43 +0400146 for key, uri in NEUTRON_NAMESPACES.iteritems():
147 if uri == ns[1:]:
148 tag = key + ":" + tag
Rossella Sblendidoc1724112013-11-28 14:16:48 +0100149 if plurals is not None and tag in plurals:
Andrea Frittoli513c8392014-01-10 14:16:34 +0000150 json[tag] = parse_array(child, plurals)
Rossella Sblendidoc1724112013-11-28 14:16:48 +0100151 else:
Andrea Frittoli513c8392014-01-10 14:16:34 +0000152 json[tag] = xml_to_json(child, plurals)
Dan Smithba6cb162012-08-14 07:22:42 -0700153 return json
Attila Fazekasc74aede2013-09-11 13:04:02 +0200154
155
156def deep_dict_to_xml(dest, source):
157 """Populates the ``dest`` xml element with the ``source`` ``Mapping``
158 elements, if the source Mapping's value is also a ``Mapping``
159 they will be recursively added as a child elements.
160 :param source: A python ``Mapping`` (dict)
161 :param dest: XML child element will be added to the ``dest``
162 """
163 for element, content in source.iteritems():
164 if isinstance(content, collections.Mapping):
165 xml_element = Element(element)
166 deep_dict_to_xml(xml_element, content)
167 dest.append(xml_element)
168 else:
169 dest.append(Element(element, content))