1 # Copyright (c) 2010, 2011 Nicira, Inc.
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.
19 from ovs.db import error
23 def __init__(self, json, name):
26 if type(json) != dict:
27 self.__raise_error("Object expected.")
30 def __get(self, name, types, optional, default=None):
33 member = float_to_int(self.json[name])
34 if is_identifier(member) and "id" in types:
37 if len(types) and not isinstance(member, tuple(types)):
38 self.__raise_error("Type mismatch for member '%s'." % name)
40 self.__raise_error("Type mismatch for member '%s'." % name)
44 self.__raise_error("Required '%s' member is missing." % name)
47 def get(self, name, types):
48 return self.__get(name, types, False)
50 def get_optional(self, name, types, default=None):
51 return self.__get(name, types, True, default)
53 def __raise_error(self, message):
54 raise error.Error("Parsing %s failed: %s" % (self.name, message),
58 missing = set(self.json) - set(self.used)
62 present = "and %d other members are" % len(missing)
64 present = "and 1 other member are"
67 self.__raise_error("Member '%s' %s present but not allowed here" %
75 if integer == x and -2 ** 53 <= integer < 2 ** 53:
80 id_re = re.compile("[_a-zA-Z][_a-zA-Z0-9]*$")
84 return isinstance(s, six.string_types) and id_re.match(s)
87 def json_type_to_string(type_):
88 number_types = list(six.integer_types)
89 number_types.extend([float])
90 number_types = tuple(number_types)
93 elif issubclass(type_, bool):
95 elif issubclass(type_, dict):
97 elif issubclass(type_, list):
99 elif issubclass(type_, number_types):
101 elif issubclass(type_, six.string_types):
107 def unwrap_json(json, name, types, desc):
108 if (not isinstance(json, (list, tuple))
109 or len(json) != 2 or json[0] != name
110 or not isinstance(json[1], tuple(types))):
111 raise error.Error('expected ["%s", <%s>]' % (name, desc), json)
115 def parse_json_pair(json):
116 if type(json) != list or len(json) != 2:
117 raise error.Error("expected 2-element array", json)