1 # Copyright (c) 2010, 2011 Nicira Networks
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at:
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
17 from ovs.db import error
20 def __init__(self, json, name):
23 if type(json) != dict:
24 self.__raise_error("Object expected.")
27 def __get(self, name, types, optional, default=None):
30 member = float_to_int(self.json[name])
31 if is_identifier(member) and "id" in types:
33 if len(types) and type(member) not in types:
34 self.__raise_error("Type mismatch for member '%s'." % name)
38 self.__raise_error("Required '%s' member is missing." % name)
41 def get(self, name, types):
42 return self.__get(name, types, False)
44 def get_optional(self, name, types, default=None):
45 return self.__get(name, types, True, default)
47 def __raise_error(self, message):
48 raise error.Error("Parsing %s failed: %s" % (self.name, message),
52 missing = set(self.json) - set(self.used)
56 present = "and %d other members are" % len(missing)
58 present = "and 1 other member are"
61 self.__raise_error("Member '%s' %s present but not allowed here" %
68 if integer == x and -2**53 <= integer < 2**53:
72 id_re = re.compile("[_a-zA-Z][_a-zA-Z0-9]*$")
74 return type(s) in [str, unicode] and id_re.match(s)
76 def json_type_to_string(type_):
85 elif type_ in [int, long, float]:
87 elif type_ in [str, unicode]:
92 def unwrap_json(json, name, need_type):
93 if (type(json) != list or len(json) != 2 or json[0] != name or
94 type(json[1]) != need_type):
95 raise error.Error('expected ["%s", <%s>]'
96 % (name, json_type_to_string(need_type)), json)
99 def parse_json_pair(json):
100 if type(json) != list or len(json) != 2:
101 raise error.Error("expected 2-element array", json)