1 # Copyright (C) 2013 Nippon Telegraph and Telephone Corporation.
2 # Copyright (C) 2013 YAMAMOTO Takashi <yamamoto at valinux co jp>
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
8 # http://www.apache.org/licenses/LICENSE-2.0
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
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
17 # convenient classes to manipulate OF-Config XML
18 # in a little more pythonic way.
19 # currently assuming OF-Config 1.1.1.
21 from ryu.lib import stringify
23 from lxml import objectify
24 import lxml.etree as ET
27 _ns_of111 = 'urn:onf:of111:config:yang'
28 _ns_netconf = 'urn:ietf:params:xml:ns:netconf:base:1.0'
36 return name.replace('-', '_')
40 def __init__(self, name, is_list):
43 self.is_list = is_list
48 def __init__(self, name, cls, is_list):
49 super(_ct, self).__init__(name, is_list)
53 class _Base(stringify.StringifyMixin):
54 _M = objectify.ElementMaker(annotate=False,
58 def __init__(self, **kwargs):
59 for e in self._ELEMENTS:
60 k = _pythonify(e.name)
63 assert e.name not in kwargs
75 raise TypeError('unknown kwargs %s' % kwargs)
79 if isinstance(v, _Base):
80 return v.to_et(e.name)
81 elif isinstance(v, objectify.ObjectifiedElement):
82 assert ET.QName(v.tag).localname == itag
84 return self._M(itag, v)
87 for e in self._ELEMENTS:
93 if isinstance(v, list):
95 ele = list(map(convert, v))
100 return self._M(tag, *args)
102 def to_xml(self, tag):
104 return ET.tostring(e, pretty_print=True)
107 def from_xml(cls, xmlstring):
108 et = objectify.fromstring(xmlstring)
109 return cls.from_et(et)
112 def from_et(cls, et):
114 if e.cls is not None:
115 return e.cls.from_et(v)
119 for e in cls._ELEMENTS:
122 except AttributeError:
124 assert isinstance(v, objectify.ObjectifiedElement)
131 v = list(map(convert, v))
132 k = _pythonify(e.name)
133 assert k not in kwargs
137 def __getattribute__(self, k):
138 return stringify.StringifyMixin.__getattribute__(self, _pythonify(k))
140 def __setattr__(self, k, v):
141 stringify.StringifyMixin.__setattr__(self, _pythonify(k), v)
144 class _Unimpl(_Base):
146 _e('raw_et', is_list=False),
149 def to_et(self, tag):
150 assert self.raw_et.tag == tag
154 def from_et(cls, et):
155 return cls(raw_et=et)