1 # Copyright (c) 2010 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 self.__raise_error("Member '%s' and %d other members "
57 "are present but not allowed here"
58 % (name, len(missing)))
60 self.__raise_error("Member '%s' and 1 other member "
61 "are present but not allowed here" % name)
63 self.__raise_error("Member '%s' is present but not "
64 "allowed here" % name)
70 if integer == x and integer >= -2**53 and integer < 2**53:
74 id_re = re.compile("[_a-zA-Z][_a-zA-Z0-9]*$")
76 return type(s) in [str, unicode] and id_re.match(s)
78 def json_type_to_string(type):
87 elif type in [int, long, float]:
89 elif type in [str, unicode]:
94 def unwrap_json(json, name, need_type):
95 if (type(json) != list or len(json) != 2 or json[0] != name or
96 type(json[1]) != need_type):
97 raise error.Error("expected [\"%s\", <%s>]"
98 % (name, json_type_to_string(need_type)), json)
101 def parse_json_pair(json):
102 if type(json) != list or len(json) != 2:
103 raise error.Error("expected 2-element array", json)