summaryrefslogtreecommitdiffstats
path: root/src/examples/sudo
diff options
context:
space:
mode:
Diffstat (limited to 'src/examples/sudo')
0 files changed, 0 insertions, 0 deletions
f='#n105'>105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
# vim: tabstop=4 shiftwidth=4 softtabstop=4

# Copyright 2012 OpenStack LLC
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

"""
Dict <--> XML de/serializer.

The identity API prefers attributes over elements, so we serialize that way
by convention, with a few hardcoded exceptions.

"""

from lxml import etree
import re


DOCTYPE = '<?xml version="1.0" encoding="UTF-8"?>'
XMLNS = 'http://docs.openstack.org/identity/api/v2.0'
XMLNS_LIST = [
    {
        'value': 'http://docs.openstack.org/identity/api/v2.0'
    },
    {
        'prefix': 'OS-KSADM',
        'value': 'http://docs.openstack.org/identity/api/ext/OS-KSADM/v1.0',
    },
]


def from_xml(xml):
    """Deserialize XML to a dictionary."""
    if xml is None:
        return None

    deserializer = XmlDeserializer()
    return deserializer(xml)


def to_xml(d, xmlns=None):
    """Serialize a dictionary to XML."""
    if d is None:
        return None

    serialize = XmlSerializer()
    return serialize(d, xmlns)


class XmlDeserializer(object):
    def __call__(self, xml_str):
        """Returns a dictionary populated by decoding the given xml string."""
        dom = etree.fromstring(xml_str.strip())
        return self.walk_element(dom, True)

    @staticmethod
    def _tag_name(tag, namespace):
        """Returns a tag name.

        The tag name may contain the namespace prefix or not, which can
        be determined by specifying the parameter namespace.

        """
        m = re.search('[^}]+$', tag)
        tag_name = m.string[m.start():]
        if not namespace:
            return tag_name
        bracket = re.search('[^{]+$', tag)
        ns = m.string[bracket.start():m.start() - 1]
        #If the namespace is
        #http://docs.openstack.org/identity/api/ext/OS-KSADM/v1.0
        #for the root element, a prefix needs to add in front of the tag name.
        prefix = None
        for xmlns in XMLNS_LIST:
            if xmlns['value'] == ns:
                prefix = xmlns.get('prefix', None)
                break
        if prefix is not None:
            return '%(PREFIX)s:%(tag_name)s' \
                % {'PREFIX': prefix, 'tag_name': tag_name}
        else:
            return tag_name

    def walk_element(self, element, namespace=False):
        """Populates a dictionary by walking an etree element."""
        values = {}
        for k, v in element.attrib.iteritems():
            # boolean-looking attributes become booleans in JSON
            if k in ['enabled']:
                if v in ['true']:
                    v = True
                elif v in ['false']:
                    v = False

            values[k] = v

        text = None
        if element.text is not None:
            text = element.text.strip()

        # current spec does not have attributes on an element with text
        values = values or text or {}

        for child in [self.walk_element(x) for x in element]:
            values = dict(values.items() + child.items())

        return {XmlDeserializer._tag_name(element.tag, namespace): values}


class XmlSerializer(object):
    def __call__(self, d, xmlns=None):
        """Returns an xml etree populated by the given dictionary.

        Optionally, namespace the etree by specifying an ``xmlns``.

        """
        # FIXME(dolph): skipping links for now
        for key in d.keys():
            if '_links' in key:
                d.pop(key)

        assert len(d.keys()) == 1, ('Cannot encode more than one root '
                                    'element: %s' % d.keys())

        # name the root dom element
        name = d.keys()[0]