author | lbessard |
Mon, 28 Jan 2008 10:31:29 +0100 | |
changeset 156 | 2a2e974302fe |
parent 153 | f0e8e7f58a5a |
permissions | -rw-r--r-- |
2 | 1 |
#!/usr/bin/env python |
2 |
# -*- coding: utf-8 -*- |
|
3 |
||
4 |
#This file is part of PLCOpenEditor, a library implementing an IEC 61131-3 editor |
|
5 |
#based on the plcopen standard. |
|
6 |
# |
|
58 | 7 |
#Copyright (C) 2007: Edouard TISSERANT and Laurent BESSARD |
2 | 8 |
# |
9 |
#See COPYING file for copyrights details. |
|
10 |
# |
|
11 |
#This library is free software; you can redistribute it and/or |
|
12 |
#modify it under the terms of the GNU General Public |
|
13 |
#License as published by the Free Software Foundation; either |
|
14 |
#version 2.1 of the License, or (at your option) any later version. |
|
15 |
# |
|
16 |
#This library is distributed in the hope that it will be useful, |
|
17 |
#but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
18 |
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
|
58 | 19 |
#General Public License for more details. |
2 | 20 |
# |
21 |
#You should have received a copy of the GNU General Public |
|
22 |
#License along with this library; if not, write to the Free Software |
|
23 |
#Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA |
|
24 |
||
25 |
from xml.dom import minidom |
|
151 | 26 |
import sys, re, datetime |
2 | 27 |
from types import * |
75
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
28 |
from new import classobj |
2 | 29 |
|
151 | 30 |
LANGUAGES = ["en-US", "fr-FR", "en", "fr"] |
31 |
||
32 |
""" |
|
33 |
Regular expression models for check all kind of string |
|
34 |
""" |
|
35 |
Name_model = re.compile('([a-zA-Z_\:][\w\.\-\:]*)$') |
|
36 |
Names_model = re.compile('([a-zA-Z_\:][\w\.\-\:]*(?: [a-zA-Z_\:][\w\.\-\:]*)*)$') |
|
37 |
NMToken_model = re.compile('([\w\.\-\:]*)$') |
|
38 |
NMTokens_model = re.compile('([\w\.\-\:]*(?: [\w\.\-\:]*)*)$') |
|
39 |
QName_model = re.compile('((?:[a-zA-Z_][\w]*:)?[a-zA-Z_][\w]*)$') |
|
40 |
QNames_model = re.compile('((?:[a-zA-Z_][\w]*:)?[a-zA-Z_][\w]*(?: (?:[a-zA-Z_][\w]*:)?[a-zA-Z_][\w]*)*)$') |
|
41 |
NCName_model = re.compile('([a-zA-Z_][\w]*)$') |
|
42 |
URI_model = re.compile('((?:http://|/)?(?:[\w.]*/?)*)$') |
|
43 |
||
44 |
ONLY_ANNOTATION = re.compile("((?:annotation )?)") |
|
45 |
||
2 | 46 |
""" |
47 |
Regular expression models for extracting dates and times from a string |
|
48 |
""" |
|
151 | 49 |
time_model = re.compile('([0-9]{2}):([0-9]{2}):([0-9]{2}(?:\.[0-9]*)?)(?:Z)?$') |
50 |
date_model = re.compile('([0-9]{4})-([0-9]{2})-([0-9]{2})((?:[\-\+][0-9]{2}:[0-9]{2})|Z)?$') |
|
51 |
datetime_model = re.compile('([0-9]{4})-([0-9]{2})-([0-9]{2})[ T]([0-9]{2}):([0-9]{2}):([0-9]{2}(?:\.[0-9]*)?)((?:[\-\+][0-9]{2}:[0-9]{2})|Z)?$') |
|
52 |
||
53 |
class xml_timezone(datetime.tzinfo): |
|
116
58b9b84e385f
Adding support in xmlclass for timezone in datetime and for not paying attention to xml comments
lbessard
parents:
92
diff
changeset
|
54 |
|
58b9b84e385f
Adding support in xmlclass for timezone in datetime and for not paying attention to xml comments
lbessard
parents:
92
diff
changeset
|
55 |
def SetOffset(self, offset): |
58b9b84e385f
Adding support in xmlclass for timezone in datetime and for not paying attention to xml comments
lbessard
parents:
92
diff
changeset
|
56 |
if offset == "Z": |
58b9b84e385f
Adding support in xmlclass for timezone in datetime and for not paying attention to xml comments
lbessard
parents:
92
diff
changeset
|
57 |
self.__offset = timedelta(minutes = 0) |
58b9b84e385f
Adding support in xmlclass for timezone in datetime and for not paying attention to xml comments
lbessard
parents:
92
diff
changeset
|
58 |
self.__name = "UTC" |
58b9b84e385f
Adding support in xmlclass for timezone in datetime and for not paying attention to xml comments
lbessard
parents:
92
diff
changeset
|
59 |
else: |
58b9b84e385f
Adding support in xmlclass for timezone in datetime and for not paying attention to xml comments
lbessard
parents:
92
diff
changeset
|
60 |
sign = {"-" : -1, "+" : 1}[offset[0]] |
58b9b84e385f
Adding support in xmlclass for timezone in datetime and for not paying attention to xml comments
lbessard
parents:
92
diff
changeset
|
61 |
hours, minutes = [int(val) for val in offset[1:].split(":")] |
58b9b84e385f
Adding support in xmlclass for timezone in datetime and for not paying attention to xml comments
lbessard
parents:
92
diff
changeset
|
62 |
self.__offset = timedelta(minutes = sign * (hours * 60 + minutes)) |
58b9b84e385f
Adding support in xmlclass for timezone in datetime and for not paying attention to xml comments
lbessard
parents:
92
diff
changeset
|
63 |
self.__name = "" |
58b9b84e385f
Adding support in xmlclass for timezone in datetime and for not paying attention to xml comments
lbessard
parents:
92
diff
changeset
|
64 |
|
58b9b84e385f
Adding support in xmlclass for timezone in datetime and for not paying attention to xml comments
lbessard
parents:
92
diff
changeset
|
65 |
def utcoffset(self, dt): |
58b9b84e385f
Adding support in xmlclass for timezone in datetime and for not paying attention to xml comments
lbessard
parents:
92
diff
changeset
|
66 |
return self.__offset |
58b9b84e385f
Adding support in xmlclass for timezone in datetime and for not paying attention to xml comments
lbessard
parents:
92
diff
changeset
|
67 |
|
58b9b84e385f
Adding support in xmlclass for timezone in datetime and for not paying attention to xml comments
lbessard
parents:
92
diff
changeset
|
68 |
def tzname(self, dt): |
58b9b84e385f
Adding support in xmlclass for timezone in datetime and for not paying attention to xml comments
lbessard
parents:
92
diff
changeset
|
69 |
return self.__name |
58b9b84e385f
Adding support in xmlclass for timezone in datetime and for not paying attention to xml comments
lbessard
parents:
92
diff
changeset
|
70 |
|
58b9b84e385f
Adding support in xmlclass for timezone in datetime and for not paying attention to xml comments
lbessard
parents:
92
diff
changeset
|
71 |
def dst(self, dt): |
58b9b84e385f
Adding support in xmlclass for timezone in datetime and for not paying attention to xml comments
lbessard
parents:
92
diff
changeset
|
72 |
return ZERO |
2 | 73 |
|
151 | 74 |
[SYNTAXELEMENT, SYNTAXATTRIBUTE, SIMPLETYPE, COMPLEXTYPE, COMPILEDCOMPLEXTYPE, |
75 |
ATTRIBUTESGROUP, ELEMENTSGROUP, ATTRIBUTE, ELEMENT, CHOICE, ANY, TAG |
|
76 |
] = range(12) |
|
77 |
||
78 |
def NotSupportedYet(type): |
|
79 |
""" |
|
80 |
Function that generates a function that point out to user that datatype asked |
|
81 |
are not yet supported by xmlclass |
|
82 |
@param type: data type |
|
83 |
@return: function generated |
|
84 |
""" |
|
85 |
def GetUnknownValue(attr): |
|
86 |
raise ValueError, "\"%s\" type isn't supported by \"xmlclass\" yet!"%type |
|
87 |
return GetUnknownValue |
|
90
2245e8776086
Adding support support for using PLCOpenEditor with Beremiz
lbessard
parents:
88
diff
changeset
|
88 |
|
2 | 89 |
""" |
90 |
This function calculates the number of whitespace for indentation |
|
91 |
""" |
|
92 |
def getIndent(indent, balise): |
|
93 |
first = indent * 2 |
|
94 |
second = first + len(balise) + 1 |
|
95 |
return "\t".expandtabs(first), "\t".expandtabs(second) |
|
96 |
||
151 | 97 |
|
98 |
def GetAttributeValue(attr, extract = True): |
|
99 |
""" |
|
100 |
Function that extracts data from a tree node |
|
101 |
@param attr: tree node containing data to extract |
|
102 |
@param extract: attr is a tree node or not |
|
103 |
@return: data extracted as string |
|
104 |
""" |
|
105 |
if not extract: |
|
106 |
return attr |
|
2 | 107 |
if len(attr.childNodes) == 1: |
108 |
return attr.childNodes[0].data.encode() |
|
109 |
else: |
|
151 | 110 |
# content is a CDATA |
67
3a1b0afdaf84
Adding support for automatically generate function blocks in interface when a block is added
lbessard
parents:
58
diff
changeset
|
111 |
text = "" |
3a1b0afdaf84
Adding support for automatically generate function blocks in interface when a block is added
lbessard
parents:
58
diff
changeset
|
112 |
for node in attr.childNodes: |
3a1b0afdaf84
Adding support for automatically generate function blocks in interface when a block is added
lbessard
parents:
58
diff
changeset
|
113 |
if node.nodeName != "#text": |
3a1b0afdaf84
Adding support for automatically generate function blocks in interface when a block is added
lbessard
parents:
58
diff
changeset
|
114 |
text += node.data.encode() |
3a1b0afdaf84
Adding support for automatically generate function blocks in interface when a block is added
lbessard
parents:
58
diff
changeset
|
115 |
return text |
2 | 116 |
|
151 | 117 |
|
118 |
def GetNormalizedString(attr, extract = True): |
|
119 |
""" |
|
120 |
Function that normalizes a string according to XML 1.0. Replace tabulations, |
|
121 |
line feed and carriage return by white space |
|
122 |
@param attr: tree node containing data to extract or data to normalize |
|
123 |
@param extract: attr is a tree node or not |
|
124 |
@return: data normalized as string |
|
125 |
""" |
|
126 |
if extract: |
|
127 |
return GetAttributeValue(attr).replace("\n", " ").replace("\t", " ") |
|
2 | 128 |
else: |
151 | 129 |
return attr.replace("\n", " ").replace("\t", " ") |
130 |
||
131 |
||
132 |
def GetToken(attr, extract = True): |
|
133 |
""" |
|
134 |
Function that tokenizes a string according to XML 1.0. Remove any leading and |
|
135 |
trailing white space and replace internal sequence of two or more spaces by |
|
136 |
only one white space |
|
137 |
@param attr: tree node containing data to extract or data to tokenize |
|
138 |
@param extract: attr is a tree node or not |
|
139 |
@return: data tokenized as string |
|
140 |
""" |
|
141 |
return " ".join([part for part in GetNormalizedString(attr, extract).split(" ") if part]) |
|
142 |
||
143 |
||
144 |
def GetHexInteger(attr, extract = True): |
|
145 |
""" |
|
146 |
Function that extracts an hexadecimal integer from a tree node or a string |
|
147 |
@param attr: tree node containing data to extract or data as a string |
|
148 |
@param extract: attr is a tree node or not |
|
149 |
@return: data as an integer |
|
150 |
""" |
|
151 |
if extract: |
|
152 |
value = GetAttributeValue(attr) |
|
153 |
else: |
|
154 |
value = attr |
|
155 |
try: |
|
156 |
return int(value, 16) |
|
157 |
except: |
|
158 |
raise ValueError, "\"%s\" isn't a valid hexadecimal integer!"%value |
|
159 |
||
160 |
||
161 |
def GenerateIntegerExtraction(minInclusive = None, maxInclusive = None, minExclusive = None, maxExclusive = None): |
|
162 |
""" |
|
163 |
Function that generates an extraction function for integer defining min and max |
|
164 |
of integer value |
|
165 |
@param minInclusive: inclusive minimum |
|
166 |
@param maxInclusive: inclusive maximum |
|
167 |
@param minExclusive: exclusive minimum |
|
168 |
@param maxExclusive: exclusive maximum |
|
169 |
@return: function generated |
|
170 |
""" |
|
171 |
def GetInteger(attr, extract = True): |
|
172 |
""" |
|
173 |
Function that extracts an integer from a tree node or a string |
|
174 |
@param attr: tree node containing data to extract or data as a string |
|
175 |
@param extract: attr is a tree node or not |
|
176 |
@return: data as an integer |
|
177 |
""" |
|
178 |
||
179 |
if extract: |
|
180 |
value = GetAttributeValue(attr) |
|
181 |
else: |
|
182 |
value = attr |
|
183 |
try: |
|
184 |
# TODO: permit to write value like 1E2 |
|
185 |
value = int(value) |
|
186 |
except: |
|
187 |
raise ValueError, "\"%s\" isn't a valid integer!"%value |
|
188 |
if minInclusive is not None and value < minInclusive: |
|
189 |
raise ValueError, "%d isn't greater or equal to %d!"%(value, minInclusive) |
|
190 |
if maxInclusive is not None and value > maxInclusive: |
|
191 |
raise ValueError, "%d isn't lesser or equal to %d!"%(value, maxInclusive) |
|
192 |
if minExclusive is not None and value <= minExclusive: |
|
193 |
raise ValueError, "%d isn't greater than %d!"%(value, minExclusive) |
|
194 |
if maxExclusive is not None and value >= maxExclusive: |
|
195 |
raise ValueError, "%d isn't lesser than %d!"%(value, maxExclusive) |
|
2 | 196 |
return value |
151 | 197 |
return GetInteger |
198 |
||
199 |
||
200 |
def GenerateFloatExtraction(type, extra_values = []): |
|
201 |
""" |
|
202 |
Function that generates an extraction function for float |
|
203 |
@param type: name of the type of float |
|
204 |
@return: function generated |
|
205 |
""" |
|
206 |
def GetFloat(attr, extract = True): |
|
207 |
""" |
|
208 |
Function that extracts a float from a tree node or a string |
|
209 |
@param attr: tree node containing data to extract or data as a string |
|
210 |
@param extract: attr is a tree node or not |
|
211 |
@return: data as a float |
|
212 |
""" |
|
213 |
if extract: |
|
214 |
value = GetAttributeValue(attr) |
|
215 |
else: |
|
216 |
value = attr |
|
217 |
try: |
|
218 |
if value in extra_values: |
|
219 |
return value |
|
220 |
return float(value) |
|
221 |
except: |
|
222 |
raise ValueError, "\"%s\" isn't a valid %s!"%(value, type) |
|
223 |
return GetFloat |
|
224 |
||
225 |
||
226 |
def GetBoolean(attr, extract = True): |
|
227 |
""" |
|
228 |
Function that extracts a boolean from a tree node or a string |
|
229 |
@param attr: tree node containing data to extract or data as a string |
|
230 |
@param extract: attr is a tree node or not |
|
231 |
@return: data as a boolean |
|
232 |
""" |
|
233 |
if extract: |
|
234 |
value = GetAttributeValue(attr) |
|
2 | 235 |
else: |
151 | 236 |
value = attr |
237 |
if value == "true" or value == "1": |
|
238 |
return True |
|
239 |
elif value == "false" or value == "0": |
|
240 |
return False |
|
241 |
else: |
|
242 |
raise ValueError, "\"%s\" isn't a valid boolean!"%value |
|
243 |
||
244 |
||
245 |
def GetTime(attr, extract = True): |
|
246 |
""" |
|
247 |
Function that extracts a time from a tree node or a string |
|
248 |
@param attr: tree node containing data to extract or data as a string |
|
249 |
@param extract: attr is a tree node or not |
|
250 |
@return: data as a time |
|
251 |
""" |
|
252 |
if extract: |
|
253 |
result = time_model.match(GetAttributeValue(attr)) |
|
254 |
else: |
|
255 |
result = time_model.match(attr) |
|
256 |
if result: |
|
257 |
values = result.groups() |
|
258 |
time_values = [int(v) for v in values[:2]] |
|
259 |
seconds = float(values[2]) |
|
260 |
time_values.extend([int(seconds), int((seconds % 1) * 1000000)]) |
|
261 |
return datetime.time(*time_values) |
|
262 |
else: |
|
263 |
raise ValueError, "\"%s\" is not a valid time!"%value |
|
264 |
||
265 |
||
266 |
def GetDate(attr, extract = True): |
|
267 |
""" |
|
268 |
Function that extracts a date from a tree node or a string |
|
269 |
@param attr: tree node containing data to extract or data as a string |
|
270 |
@param extract: attr is a tree node or not |
|
271 |
@return: data as a date |
|
272 |
""" |
|
273 |
if extract: |
|
274 |
result = date_model.match(GetAttributeValue(attr)) |
|
275 |
else: |
|
276 |
result = date_model.match(attr) |
|
277 |
if result: |
|
278 |
values = result.groups() |
|
279 |
date_values = [int(v) for v in values[:3]] |
|
280 |
if values[3] is not None: |
|
281 |
tz = xml_timezone() |
|
282 |
tz.SetOffset(values[3]) |
|
283 |
date_values.append(tz) |
|
284 |
return datetime.date(*date_values) |
|
285 |
else: |
|
286 |
raise ValueError, "\"%s\" is not a valid date!"%value |
|
287 |
||
288 |
||
289 |
def GetDateTime(attr, extract = True): |
|
290 |
""" |
|
291 |
Function that extracts date and time from a tree node or a string |
|
292 |
@param attr: tree node containing data to extract or data as a string |
|
293 |
@param extract: attr is a tree node or not |
|
294 |
@return: data as date and time |
|
295 |
""" |
|
296 |
if extract: |
|
297 |
result = datetime_model.match(GetAttributeValue(attr)) |
|
298 |
else: |
|
299 |
result = datetime_model.match(attr) |
|
300 |
if result: |
|
301 |
values = result.groups() |
|
302 |
datetime_values = [int(v) for v in values[:5]] |
|
303 |
seconds = float(values[5]) |
|
304 |
datetime_values.extend([int(seconds), int((seconds % 1) * 1000000)]) |
|
305 |
if values[6] is not None: |
|
306 |
tz = xml_timezone() |
|
307 |
tz.SetOffset(values[6]) |
|
308 |
datetime_values.append(tz) |
|
309 |
return datetime.datetime(*datetime_values) |
|
310 |
else: |
|
311 |
raise ValueError, "\"%s\" is not a valid datetime!"%value |
|
312 |
||
313 |
||
314 |
def GenerateModelNameExtraction(type, model): |
|
315 |
""" |
|
316 |
Function that generates an extraction function for string matching a model |
|
317 |
@param type: name of the data type |
|
318 |
@param model: model that data must match |
|
319 |
@return: function generated |
|
320 |
""" |
|
321 |
def GetModelName(attr, extract = True): |
|
322 |
""" |
|
323 |
Function that extracts a string from a tree node or not and check that |
|
324 |
string extracted or given match the model |
|
325 |
@param attr: tree node containing data to extract or data as a string |
|
326 |
@param extract: attr is a tree node or not |
|
327 |
@return: data as a string if matching |
|
328 |
""" |
|
329 |
if extract: |
|
330 |
value = GetAttributeValue(attr) |
|
331 |
else: |
|
332 |
value = attr |
|
333 |
result = model.match(value) |
|
334 |
if not result: |
|
335 |
raise ValueError, "\"%s\" is not a valid %s!"%(value, type) |
|
336 |
return value |
|
337 |
return GetModelName |
|
338 |
||
339 |
||
340 |
def GenerateLimitExtraction(min = None, max = None, unbounded = True): |
|
341 |
""" |
|
342 |
Function that generates an extraction function for integer defining min and max |
|
343 |
of integer value |
|
344 |
@param min: minimum limit value |
|
345 |
@param max: maximum limit value |
|
346 |
@param unbounded: value can be "unbounded" or not |
|
347 |
@return: function generated |
|
348 |
""" |
|
349 |
def GetLimit(attr, extract = True): |
|
350 |
""" |
|
351 |
Function that extracts a string from a tree node or not and check that |
|
352 |
string extracted or given is in a list of values |
|
353 |
@param attr: tree node containing data to extract or data as a string |
|
354 |
@param extract: attr is a tree node or not |
|
355 |
@return: data as a string |
|
356 |
""" |
|
357 |
if extract: |
|
358 |
value = GetAttributeValue(attr) |
|
359 |
else: |
|
360 |
value = attr |
|
361 |
if value == "unbounded": |
|
362 |
if unbounded: |
|
363 |
return value |
|
364 |
else: |
|
365 |
raise "\"%s\" isn't a valid value for this member limit!"%value |
|
366 |
try: |
|
367 |
limit = int(value) |
|
368 |
except: |
|
369 |
raise "\"%s\" isn't a valid value for this member limit!"%value |
|
370 |
if limit < 0: |
|
371 |
raise "\"%s\" isn't a valid value for this member limit!"%value |
|
372 |
elif min is not None and limit < min: |
|
373 |
raise "\"%s\" isn't a valid value for this member limit!"%value |
|
374 |
elif max is not None and limit > max: |
|
375 |
raise "\"%s\" isn't a valid value for this member limit!"%value |
|
376 |
return limit |
|
377 |
return GetLimit |
|
378 |
||
379 |
||
380 |
def GenerateEnumeratedExtraction(type, list): |
|
381 |
""" |
|
382 |
Function that generates an extraction function for enumerated values |
|
383 |
@param type: name of the data type |
|
384 |
@param list: list of possible values |
|
385 |
@return: function generated |
|
386 |
""" |
|
387 |
def GetEnumerated(attr, extract = True): |
|
388 |
""" |
|
389 |
Function that extracts a string from a tree node or not and check that |
|
390 |
string extracted or given is in a list of values |
|
391 |
@param attr: tree node containing data to extract or data as a string |
|
392 |
@param extract: attr is a tree node or not |
|
393 |
@return: data as a string |
|
394 |
""" |
|
395 |
if extract: |
|
396 |
value = GetAttributeValue(attr) |
|
397 |
else: |
|
398 |
value = attr |
|
399 |
if value in list: |
|
400 |
return value |
|
401 |
else: |
|
402 |
raise ValueError, "\"%s\" isn't a valid value for %s!"%(value, type) |
|
403 |
return GetEnumerated |
|
404 |
||
405 |
||
406 |
def GetNamespaces(attr, extract = True): |
|
407 |
""" |
|
408 |
Function that extracts a list of namespaces from a tree node or a string |
|
409 |
@param attr: tree node containing data to extract or data as a string |
|
410 |
@param extract: attr is a tree node or not |
|
411 |
@return: list of namespaces |
|
412 |
""" |
|
413 |
if extract: |
|
414 |
value = GetAttributeValue(attr) |
|
415 |
else: |
|
416 |
value = attr |
|
417 |
if value == "": |
|
418 |
return [] |
|
419 |
elif value == "##any" or value == "##other": |
|
420 |
namespaces = [value] |
|
421 |
else: |
|
422 |
namespaces = [] |
|
423 |
for item in value.split(" "): |
|
424 |
if item == "##targetNamespace" or item == "##local": |
|
425 |
namespaces.append(item) |
|
426 |
else: |
|
427 |
result = URI_model.match(item) |
|
428 |
if result is not None: |
|
429 |
namespaces.append(item) |
|
430 |
else: |
|
431 |
raise ValueError, "\"%s\" isn't a valid value for namespace!"%value |
|
432 |
return namespaces |
|
433 |
||
434 |
||
435 |
def GenerateGetList(type, list): |
|
436 |
""" |
|
437 |
Function that generates an extraction function for a list of values |
|
438 |
@param type: name of the data type |
|
439 |
@param list: list of possible values |
|
440 |
@return: function generated |
|
441 |
""" |
|
442 |
def GetLists(attr, extract = True): |
|
443 |
""" |
|
444 |
Function that extracts a list of values from a tree node or a string |
|
445 |
@param attr: tree node containing data to extract or data as a string |
|
446 |
@param extract: attr is a tree node or not |
|
447 |
@return: list of values |
|
448 |
""" |
|
449 |
if extract: |
|
450 |
value = GetAttributeValue(attr) |
|
451 |
else: |
|
452 |
value = attr |
|
453 |
if value == "": |
|
454 |
return [] |
|
455 |
elif value == "#all": |
|
456 |
return [value] |
|
457 |
else: |
|
458 |
values = [] |
|
459 |
for item in value.split(" "): |
|
460 |
if item in list: |
|
461 |
values.append(item) |
|
462 |
else: |
|
463 |
raise ValueError, "\"%s\" isn't a valid value for %s!"%(value, type) |
|
464 |
return values |
|
465 |
return GetLists |
|
466 |
||
467 |
||
468 |
def GenerateModelNameListExtraction(type, model): |
|
469 |
""" |
|
470 |
Function that generates an extraction function for list of string matching a model |
|
471 |
@param type: name of the data type |
|
472 |
@param model: model that list elements must match |
|
473 |
@return: function generated |
|
474 |
""" |
|
475 |
def GetModelNameList(attr, extract = True): |
|
476 |
""" |
|
477 |
Function that extracts a list of string from a tree node or not and check |
|
478 |
that all the items extracted match the model |
|
479 |
@param attr: tree node containing data to extract or data as a string |
|
480 |
@param extract: attr is a tree node or not |
|
481 |
@return: data as a list of string if matching |
|
482 |
""" |
|
483 |
if extract: |
|
484 |
value = GetAttributeValue(attr) |
|
485 |
else: |
|
486 |
value = attr |
|
487 |
values = [] |
|
488 |
for item in value.split(" "): |
|
489 |
result = model.match(item) |
|
490 |
if result is not None: |
|
491 |
values.append(item) |
|
492 |
else: |
|
493 |
raise ValueError, "\"%s\" isn't a valid value for %s!"%(value, type) |
|
494 |
return values |
|
495 |
return GetModelNameList |
|
496 |
||
497 |
def GenerateAnyInfos(): |
|
498 |
def ExtractAny(tree): |
|
499 |
return tree.data.encode() |
|
500 |
||
501 |
def GenerateAny(value, name = None, indent = 0): |
|
502 |
return "<![CDATA[%s]]>\n"%str(value) |
|
503 |
||
504 |
return { |
|
505 |
"type" : COMPLEXTYPE, |
|
506 |
"extract" : ExtractAny, |
|
507 |
"generate" : GenerateAny, |
|
508 |
"initial" : lambda: "", |
|
509 |
"check" : lambda x: isinstance(x, (StringType, UnicodeType)) |
|
510 |
} |
|
511 |
||
512 |
def GenerateTagInfos(name): |
|
513 |
def ExtractTag(tree): |
|
514 |
if len(tree._attrs) > 0: |
|
515 |
raise ValueError, "\"%s\" musn't have attributes!"%name |
|
516 |
if len(tree.childNodes) > 0: |
|
517 |
raise ValueError, "\"%s\" musn't have children!"%name |
|
2 | 518 |
return None |
151 | 519 |
|
520 |
def GenerateTag(value, name = None, indent = 0): |
|
521 |
if name is not None: |
|
522 |
ind1, ind2 = getIndent(indent, name) |
|
523 |
return ind1 + "<%s/>\n"%name |
|
524 |
else: |
|
525 |
return "" |
|
526 |
||
527 |
return { |
|
528 |
"type" : TAG, |
|
529 |
"extract" : ExtractTag, |
|
530 |
"generate" : GenerateTag, |
|
531 |
"initial" : lambda: None, |
|
532 |
"check" : lambda x: x == None |
|
533 |
} |
|
534 |
||
535 |
def GenerateContentInfos(factory, choices): |
|
536 |
def GetContentInitial(): |
|
537 |
content_name, infos = choices[0] |
|
538 |
if isinstance(infos["elmt_type"], (UnicodeType, StringType)): |
|
539 |
namespace, name = DecomposeQualifiedName(infos["elmt_type"]) |
|
540 |
infos["elmt_type"] = factory.GetQualifiedNameInfos(name, namespace) |
|
541 |
if infos["maxOccurs"] == "unbounded" or infos["maxOccurs"] > 1: |
|
542 |
return {"name" : content_name, "value" : map(infos["elmt_type"]["initial"], range(infos["minOccurs"]))} |
|
543 |
else: |
|
544 |
return {"name" : content_name, "value" : infos["elmt_type"]["initial"]()} |
|
545 |
||
546 |
def CheckContent(value): |
|
547 |
for content_name, infos in choices: |
|
548 |
if content_name == value["name"]: |
|
549 |
if isinstance(infos["elmt_type"], (UnicodeType, StringType)): |
|
550 |
namespace, name = DecomposeQualifiedName(infos["elmt_type"]) |
|
551 |
infos["elmt_type"] = factory.GetQualifiedNameInfos(name, namespace) |
|
552 |
if infos["maxOccurs"] == "unbounded" or infos["maxOccurs"] > 1: |
|
553 |
if isinstance(value["value"], ListType) and infos["minOccurs"] <= len(value["value"]) <= infos["maxOccurs"]: |
|
554 |
return reduce(lambda x, y: x and y, map(infos["elmt_type"]["check"], value["value"]), True) |
|
555 |
else: |
|
556 |
return infos["elmt_type"]["check"](value["value"]) |
|
557 |
return False |
|
558 |
||
559 |
def ExtractContent(tree, content): |
|
560 |
for content_name, infos in choices: |
|
561 |
if content_name == tree.nodeName: |
|
562 |
if isinstance(infos["elmt_type"], (UnicodeType, StringType)): |
|
563 |
namespace, name = DecomposeQualifiedName(infos["elmt_type"]) |
|
564 |
infos["elmt_type"] = factory.GetQualifiedNameInfos(name, namespace) |
|
565 |
if infos["maxOccurs"] == "unbounded" or infos["maxOccurs"] > 1: |
|
566 |
if isinstance(content, ListType) and len(content) > 0 and content[-1]["name"] == content_name: |
|
567 |
content_item = content.pop(-1) |
|
568 |
content_item["value"].append(infos["elmt_type"]["extract"](tree)) |
|
569 |
return content_item |
|
570 |
elif not isinstance(content, ListType) and content is not None and content["name"] == content_name: |
|
571 |
return {"name" : content_name, "value" : content["value"] + [infos["elmt_type"]["extract"](tree)]} |
|
572 |
else: |
|
573 |
return {"name" : content_name, "value" : [infos["elmt_type"]["extract"](tree)]} |
|
574 |
else: |
|
575 |
return {"name" : content_name, "value" : infos["elmt_type"]["extract"](tree)} |
|
576 |
raise ValueError, "Invalid element \"%s\" for content!"%tree.nodeName |
|
577 |
||
578 |
def GenerateContent(value, name = None, indent = 0): |
|
579 |
for content_name, infos in choices: |
|
580 |
if content_name == value["name"]: |
|
581 |
if isinstance(infos["elmt_type"], (UnicodeType, StringType)): |
|
582 |
namespace, name = DecomposeQualifiedName(infos["elmt_type"]) |
|
583 |
infos["elmt_type"] = factory.GetQualifiedNameInfos(name, namespace) |
|
584 |
if infos["maxOccurs"] == "unbounded" or infos["maxOccurs"] > 1: |
|
585 |
text = "" |
|
586 |
for item in value["value"]: |
|
587 |
text += infos["elmt_type"]["generate"](item, content_name, indent) |
|
588 |
return text |
|
589 |
else: |
|
590 |
return infos["elmt_type"]["generate"](value["value"], content_name, indent) |
|
591 |
return "" |
|
592 |
||
593 |
return { |
|
594 |
"initial" : GetContentInitial, |
|
595 |
"check" : CheckContent, |
|
596 |
"extract" : ExtractContent, |
|
597 |
"generate" : GenerateContent |
|
598 |
} |
|
599 |
||
600 |
#------------------------------------------------------------------------------- |
|
601 |
# Structure extraction functions |
|
602 |
#------------------------------------------------------------------------------- |
|
603 |
||
604 |
||
605 |
def DecomposeQualifiedName(name): |
|
606 |
result = QName_model.match(name) |
|
607 |
if not result: |
|
608 |
raise ValueError, "\"%s\" isn't a valid QName value!"%name |
|
609 |
parts = result.groups()[0].split(':') |
|
610 |
if len(parts) == 1: |
|
611 |
return None, parts[0] |
|
612 |
return parts |
|
613 |
||
614 |
def GenerateElement(element_name, attributes, elements_model, accept_text = False): |
|
615 |
def ExtractElement(factory, node): |
|
616 |
attrs = factory.ExtractNodeAttrs(element_name, node, attributes) |
|
617 |
children_structure = "" |
|
618 |
children_infos = [] |
|
619 |
children = [] |
|
620 |
for child in node.childNodes: |
|
621 |
if child.nodeName not in ["#comment", "#text"]: |
|
622 |
namespace, childname = DecomposeQualifiedName(child.nodeName) |
|
623 |
children_structure += "%s "%childname |
|
624 |
result = elements_model.match(children_structure) |
|
625 |
if not result: |
|
626 |
raise ValueError, "Invalid structure for \"%s\" children!. First element invalid."%node.nodeName |
|
627 |
valid = result.groups()[0] |
|
628 |
if len(valid) < len(children_structure): |
|
629 |
raise ValueError, "Invalid structure for \"%s\" children!. Element number %d invalid."%(node.nodeName, len(valid.split(" ")) - 1) |
|
630 |
for child in node.childNodes: |
|
631 |
if child.nodeName != "#comment" and (accept_text or child.nodeName != "#text"): |
|
632 |
if child.nodeName == "#text": |
|
633 |
children.append(GetAttributeValue(node)) |
|
634 |
else: |
|
635 |
namespace, childname = DecomposeQualifiedName(child.nodeName) |
|
636 |
infos = factory.GetQualifiedNameInfos(childname, namespace) |
|
637 |
if infos["type"] != SYNTAXELEMENT: |
|
638 |
raise ValueError, "\"%s\" can't be a member child!"%name |
|
639 |
if element_name in infos["extract"]: |
|
640 |
children.append(infos["extract"][element_name](factory, child)) |
|
641 |
else: |
|
642 |
children.append(infos["extract"]["default"](factory, child)) |
|
643 |
return node.nodeName, attrs, children |
|
644 |
return ExtractElement |
|
645 |
||
646 |
||
647 |
""" |
|
648 |
Class that generate class from an XML Tree |
|
76
5bac3213fea1
xmlclass modified for allowing class definitions for multiple XSD files and indicating which classes are the base classes
lbessard
parents:
75
diff
changeset
|
649 |
""" |
5bac3213fea1
xmlclass modified for allowing class definitions for multiple XSD files and indicating which classes are the base classes
lbessard
parents:
75
diff
changeset
|
650 |
class ClassFactory: |
5bac3213fea1
xmlclass modified for allowing class definitions for multiple XSD files and indicating which classes are the base classes
lbessard
parents:
75
diff
changeset
|
651 |
|
151 | 652 |
def __init__(self, document, debug = False): |
653 |
self.Document = document |
|
654 |
self.Debug = debug |
|
76
5bac3213fea1
xmlclass modified for allowing class definitions for multiple XSD files and indicating which classes are the base classes
lbessard
parents:
75
diff
changeset
|
655 |
|
5bac3213fea1
xmlclass modified for allowing class definitions for multiple XSD files and indicating which classes are the base classes
lbessard
parents:
75
diff
changeset
|
656 |
# Dictionary for stocking Classes and Types definitions created from the XML tree |
5bac3213fea1
xmlclass modified for allowing class definitions for multiple XSD files and indicating which classes are the base classes
lbessard
parents:
75
diff
changeset
|
657 |
self.XMLClassDefinitions = {} |
5bac3213fea1
xmlclass modified for allowing class definitions for multiple XSD files and indicating which classes are the base classes
lbessard
parents:
75
diff
changeset
|
658 |
|
151 | 659 |
self.DefinedNamespaces = {} |
660 |
self.Namespaces = {} |
|
661 |
self.SchemaNamespace = None |
|
662 |
self.TargetNamespace = None |
|
663 |
||
664 |
self.CurrentCompilations = [] |
|
665 |
||
76
5bac3213fea1
xmlclass modified for allowing class definitions for multiple XSD files and indicating which classes are the base classes
lbessard
parents:
75
diff
changeset
|
666 |
# Dictionaries for stocking Classes and Types generated |
151 | 667 |
self.ComputeAfter = [] |
76
5bac3213fea1
xmlclass modified for allowing class definitions for multiple XSD files and indicating which classes are the base classes
lbessard
parents:
75
diff
changeset
|
668 |
self.ComputedClasses = {} |
5bac3213fea1
xmlclass modified for allowing class definitions for multiple XSD files and indicating which classes are the base classes
lbessard
parents:
75
diff
changeset
|
669 |
self.AlreadyComputed = {} |
5bac3213fea1
xmlclass modified for allowing class definitions for multiple XSD files and indicating which classes are the base classes
lbessard
parents:
75
diff
changeset
|
670 |
|
151 | 671 |
def GetQualifiedNameInfos(self, name, namespace = None, canbenone = False): |
672 |
if namespace is None: |
|
673 |
if name in self.Namespaces[self.SchemaNamespace]: |
|
674 |
return self.Namespaces[self.SchemaNamespace][name] |
|
675 |
for space, elements in self.Namespaces.items(): |
|
676 |
if space != self.SchemaNamespace and name in elements: |
|
677 |
return elements[name] |
|
678 |
parts = name.split("_", 1) |
|
679 |
if len(parts) > 1: |
|
680 |
group = self.GetQualifiedNameInfos(parts[0], namespace) |
|
681 |
if group is not None and group["type"] == ELEMENTSGROUP: |
|
682 |
elements = [] |
|
683 |
if "elements" in group: |
|
684 |
elements = group["elements"] |
|
685 |
elif "choices" in group: |
|
686 |
elements = group["choices"] |
|
687 |
for element in elements: |
|
688 |
if element["name"] == parts[1]: |
|
689 |
return element |
|
690 |
if not canbenone: |
|
691 |
raise ValueError, "Unknown element \"%s\" for any defined namespaces!"%name |
|
692 |
elif namespace in self.Namespaces: |
|
693 |
if name in self.Namespaces[namespace]: |
|
694 |
return self.Namespaces[namespace][name] |
|
695 |
parts = name.split("_", 1) |
|
696 |
if len(parts) > 1: |
|
697 |
group = self.GetQualifiedNameInfos(parts[0], namespace) |
|
698 |
if group is not None and group["type"] == ELEMENTSGROUP: |
|
699 |
elements = [] |
|
700 |
if "elements" in group: |
|
701 |
elements = group["elements"] |
|
702 |
elif "choices" in group: |
|
703 |
elements = group["choices"] |
|
704 |
for element in elements: |
|
705 |
if element["name"] == parts[1]: |
|
706 |
return element |
|
707 |
if not canbenone: |
|
708 |
raise ValueError, "Unknown element \"%s\" for namespace \"%s\"!"%(name, namespace) |
|
709 |
elif not canbenone: |
|
710 |
raise ValueError, "Unknown namespace \"%s\"!"%namespace |
|
711 |
return None |
|
712 |
||
713 |
def SplitQualifiedName(self, name, namespace = None, canbenone = False): |
|
714 |
if namespace is None: |
|
715 |
if name in self.Namespaces[self.SchemaNamespace]: |
|
716 |
return name, None |
|
717 |
for space, elements in self.Namespaces.items(): |
|
718 |
if space != self.SchemaNamespace and name in elements: |
|
719 |
return name, None |
|
720 |
parts = name.split("_", 1) |
|
721 |
if len(parts) > 1: |
|
722 |
group = self.GetQualifiedNameInfos(parts[0], namespace) |
|
723 |
if group is not None and group["type"] == ELEMENTSGROUP: |
|
724 |
elements = [] |
|
725 |
if "elements" in group: |
|
726 |
elements = group["elements"] |
|
727 |
elif "choices" in group: |
|
728 |
elements = group["choices"] |
|
729 |
for element in elements: |
|
730 |
if element["name"] == parts[1]: |
|
731 |
return part[1], part[0] |
|
732 |
if not canbenone: |
|
733 |
raise ValueError, "Unknown element \"%s\" for any defined namespaces!"%name |
|
734 |
elif namespace in self.Namespaces: |
|
735 |
if name in self.Namespaces[namespace]: |
|
736 |
return name, None |
|
737 |
parts = name.split("_", 1) |
|
738 |
if len(parts) > 1: |
|
739 |
group = self.GetQualifiedNameInfos(parts[0], namespace) |
|
740 |
if group is not None and group["type"] == ELEMENTSGROUP: |
|
741 |
elements = [] |
|
742 |
if "elements" in group: |
|
743 |
elements = group["elements"] |
|
744 |
elif "choices" in group: |
|
745 |
elements = group["choices"] |
|
746 |
for element in elements: |
|
747 |
if element["name"] == parts[1]: |
|
748 |
return parts[1], parts[0] |
|
749 |
if not canbenone: |
|
750 |
raise ValueError, "Unknown element \"%s\" for namespace \"%s\"!"%(name, namespace) |
|
751 |
elif not canbenone: |
|
752 |
raise ValueError, "Unknown namespace \"%s\"!"%namespace |
|
753 |
return None, None |
|
754 |
||
755 |
def ExtractNodeAttrs(self, element_name, node, valid_attrs): |
|
756 |
attrs = {} |
|
757 |
for qualified_name, attr in node._attrs.items(): |
|
758 |
namespace, name = DecomposeQualifiedName(qualified_name) |
|
759 |
if name in valid_attrs: |
|
760 |
infos = self.GetQualifiedNameInfos(name, namespace) |
|
761 |
if infos["type"] != SYNTAXATTRIBUTE: |
|
762 |
raise ValueError, "\"%s\" can't be a member attribute!"%name |
|
763 |
elif name in attrs: |
|
764 |
raise ValueError, "\"%s\" attribute has been twice!"%name |
|
765 |
elif element_name in infos["extract"]: |
|
766 |
attrs[name] = infos["extract"][element_name](attr) |
|
767 |
else: |
|
768 |
attrs[name] = infos["extract"]["default"](attr) |
|
769 |
elif namespace == "xmlns": |
|
770 |
infos = self.GetQualifiedNameInfos("anyURI", self.SchemaNamespace) |
|
771 |
self.DefinedNamespaces[infos["extract"](attr)] = name |
|
772 |
else: |
|
773 |
raise ValueError, "Invalid attribute \"%s\" for member \"%s\"!"%(qualified_name, node.nodeName) |
|
774 |
for attr in valid_attrs: |
|
775 |
if attr not in attrs and attr in self.Namespaces[self.SchemaNamespace] and "default" in self.Namespaces[self.SchemaNamespace][attr]: |
|
776 |
if element_name in self.Namespaces[self.SchemaNamespace][attr]["default"]: |
|
777 |
default = self.Namespaces[self.SchemaNamespace][attr]["default"][element_name] |
|
778 |
else: |
|
779 |
default = self.Namespaces[self.SchemaNamespace][attr]["default"]["default"] |
|
780 |
if default is not None: |
|
781 |
attrs[attr] = default |
|
782 |
return attrs |
|
783 |
||
784 |
def ReduceElements(self, elements, schema=False): |
|
785 |
result = [] |
|
786 |
for child_infos in elements: |
|
787 |
if "name" in child_infos[1] and schema: |
|
788 |
self.CurrentCompilations.append(child_infos[1]["name"]) |
|
789 |
namespace, name = DecomposeQualifiedName(child_infos[0]) |
|
790 |
infos = self.GetQualifiedNameInfos(name, namespace) |
|
791 |
if infos["type"] != SYNTAXELEMENT: |
|
792 |
raise ValueError, "\"%s\" can't be a member child!"%name |
|
793 |
result.append(infos["reduce"](self, child_infos[1], child_infos[2])) |
|
794 |
if "name" in child_infos[1] and schema: |
|
795 |
self.CurrentCompilations.pop(-1) |
|
796 |
annotations = [] |
|
797 |
children = [] |
|
798 |
for element in result: |
|
799 |
if element["type"] == "annotation": |
|
800 |
annotations.append(element) |
|
801 |
else: |
|
802 |
children.append(element) |
|
803 |
return annotations, children |
|
804 |
||
805 |
def AddComplexType(self, typename, infos): |
|
806 |
if typename not in self.XMLClassDefinitions: |
|
807 |
self.XMLClassDefinitions[typename] = infos |
|
808 |
else: |
|
809 |
raise ValueError, "\"%s\" class already defined. Choose another name!"%typename |
|
810 |
||
811 |
def ParseSchema(self): |
|
812 |
pass |
|
813 |
||
814 |
def ExtractTypeInfos(self, name, parent, typeinfos): |
|
815 |
if isinstance(typeinfos, (StringType, UnicodeType)): |
|
816 |
namespace, name = DecomposeQualifiedName(typeinfos) |
|
817 |
infos = self.GetQualifiedNameInfos(name, namespace) |
|
818 |
if infos["type"] == COMPLEXTYPE: |
|
819 |
name, parent = self.SplitQualifiedName(name, namespace) |
|
820 |
result = self.CreateClass(name, parent, infos) |
|
821 |
if result is not None and not isinstance(result, (UnicodeType, StringType)): |
|
822 |
self.Namespaces[self.TargetNamespace][result["name"]] = result |
|
823 |
return result |
|
824 |
elif infos["type"] == ELEMENT and infos["elmt_type"]["type"] == COMPLEXTYPE: |
|
825 |
name, parent = self.SplitQualifiedName(name, namespace) |
|
826 |
result = self.CreateClass(name, parent, infos["elmt_type"]) |
|
827 |
if result is not None and not isinstance(result, (UnicodeType, StringType)): |
|
828 |
self.Namespaces[self.TargetNamespace][result["name"]] = result |
|
829 |
return result |
|
830 |
else: |
|
831 |
return infos |
|
832 |
elif typeinfos["type"] == COMPLEXTYPE: |
|
833 |
return self.CreateClass(name, parent, typeinfos) |
|
834 |
elif typeinfos["type"] == SIMPLETYPE: |
|
835 |
return typeinfos |
|
836 |
||
837 |
""" |
|
838 |
Methods that generates the classes |
|
839 |
""" |
|
840 |
def CreateClasses(self): |
|
841 |
self.ParseSchema() |
|
842 |
for name, infos in self.Namespaces[self.TargetNamespace].items(): |
|
843 |
if infos["type"] == ELEMENT: |
|
844 |
if not isinstance(infos["elmt_type"], (UnicodeType, StringType)) and infos["elmt_type"]["type"] == COMPLEXTYPE: |
|
845 |
self.ComputeAfter.append((name, None, infos["elmt_type"], True)) |
|
846 |
while len(self.ComputeAfter) > 0: |
|
847 |
result = self.CreateClass(*self.ComputeAfter.pop(0)) |
|
848 |
if result is not None and not isinstance(result, (UnicodeType, StringType)): |
|
849 |
self.Namespaces[self.TargetNamespace][result["name"]] = result |
|
850 |
elif infos["type"] == COMPLEXTYPE: |
|
851 |
self.ComputeAfter.append((name, None, infos)) |
|
852 |
while len(self.ComputeAfter) > 0: |
|
853 |
result = self.CreateClass(*self.ComputeAfter.pop(0)) |
|
854 |
if result is not None and not isinstance(result, (UnicodeType, StringType)): |
|
855 |
self.Namespaces[self.TargetNamespace][result["name"]] = result |
|
856 |
elif infos["type"] == ELEMENTSGROUP: |
|
857 |
elements = [] |
|
858 |
if "elements" in infos: |
|
859 |
elements = infos["elements"] |
|
860 |
elif "choices" in infos: |
|
861 |
elements = infos["choices"] |
|
862 |
for element in elements: |
|
863 |
if not isinstance(element["elmt_type"], (UnicodeType, StringType)) and element["elmt_type"]["type"] == COMPLEXTYPE: |
|
864 |
self.ComputeAfter.append((element["name"], infos["name"], element["elmt_type"])) |
|
865 |
while len(self.ComputeAfter) > 0: |
|
866 |
result = self.CreateClass(*self.ComputeAfter.pop(0)) |
|
867 |
if result is not None and not isinstance(result, (UnicodeType, StringType)): |
|
868 |
self.Namespaces[self.TargetNamespace][result["name"]] = result |
|
869 |
return self.ComputedClasses |
|
870 |
||
871 |
def CreateClass(self, name, parent, classinfos, baseclass = False): |
|
872 |
if parent is not None: |
|
873 |
classname = "%s_%s"%(parent, name) |
|
874 |
else: |
|
875 |
classname = name |
|
876 |
||
877 |
# Checks that classe haven't been generated yet |
|
878 |
if self.AlreadyComputed.get(classname, False): |
|
879 |
if baseclass: |
|
880 |
self.AlreadyComputed[classname].IsBaseClass = baseclass |
|
881 |
return None |
|
882 |
||
883 |
# If base classes haven't been generated |
|
884 |
bases = [] |
|
885 |
if "base" in classinfos: |
|
886 |
result = self.ExtractTypeInfos("base", name, classinfos["base"]) |
|
887 |
if result is None: |
|
888 |
namespace, base_name = DecomposeQualifiedName(classinfos["base"]) |
|
889 |
if self.AlreadyComputed.get(base_name, False): |
|
890 |
self.ComputeAfter.append((name, parent, classinfos)) |
|
891 |
if self.TargetNamespace is not None: |
|
892 |
return "%s:%s"%(self.TargetNamespace, classname) |
|
76
5bac3213fea1
xmlclass modified for allowing class definitions for multiple XSD files and indicating which classes are the base classes
lbessard
parents:
75
diff
changeset
|
893 |
else: |
151 | 894 |
return classname |
895 |
elif result is not None: |
|
896 |
classinfos["base"] = self.ComputedClasses[result["name"]] |
|
897 |
bases.append(self.ComputedClasses[result["name"]]) |
|
898 |
bases.append(object) |
|
899 |
bases = tuple(bases) |
|
900 |
classmembers = {"__doc__" : classinfos.get("doc", ""), "IsBaseClass" : baseclass} |
|
901 |
||
902 |
self.AlreadyComputed[classname] = True |
|
903 |
||
904 |
for attribute in classinfos["attributes"]: |
|
905 |
infos = self.ExtractTypeInfos(attribute["name"], name, attribute["attr_type"]) |
|
906 |
if infos is not None: |
|
907 |
if infos["type"] != SIMPLETYPE: |
|
908 |
raise ValueError, "\"%s\" type is not a simple type!"%attribute["attr_type"] |
|
909 |
attrname = attribute["name"] |
|
910 |
if attribute["use"] == "optional": |
|
911 |
classmembers[attrname] = None |
|
912 |
classmembers["add%s"%attrname] = generateAddMethod(attrname, self, attribute) |
|
913 |
classmembers["delete%s"%attrname] = generateDeleteMethod(attrname) |
|
914 |
else: |
|
915 |
classmembers[attrname] = infos["initial"]() |
|
916 |
classmembers["set%s"%attrname] = generateSetMethod(attrname) |
|
917 |
classmembers["get%s"%attrname] = generateGetMethod(attrname) |
|
918 |
else: |
|
919 |
raise ValueError, "\"%s\" type unrecognized!"%attribute["attr_type"] |
|
920 |
attribute["attr_type"] = infos |
|
921 |
||
922 |
for element in classinfos["elements"]: |
|
923 |
if element["type"] == CHOICE: |
|
924 |
elmtname = element["name"] |
|
925 |
choices = [] |
|
926 |
for choice in element["choices"]: |
|
927 |
if choice["elmt_type"] == "tag": |
|
928 |
choice["elmt_type"] = GenerateTagInfos(choice["name"]) |
|
76
5bac3213fea1
xmlclass modified for allowing class definitions for multiple XSD files and indicating which classes are the base classes
lbessard
parents:
75
diff
changeset
|
929 |
else: |
151 | 930 |
infos = self.ExtractTypeInfos(choice["name"], name, choice["elmt_type"]) |
931 |
if infos is not None: |
|
932 |
choice["elmt_type"] = infos |
|
933 |
choices.append((choice["name"], choice)) |
|
934 |
classmembers["get%schoices"%elmtname] = generateGetChoicesMethod(element["choices"]) |
|
935 |
classmembers["add%sbytype"%elmtname] = generateAddChoiceByTypeMethod(element["choices"]) |
|
936 |
infos = GenerateContentInfos(self, choices) |
|
937 |
elif element["type"] == ANY: |
|
938 |
elmtname = element["name"] = "text" |
|
939 |
element["minOccurs"] = element["maxOccurs"] = 1 |
|
940 |
infos = GenerateAnyInfos() |
|
941 |
else: |
|
942 |
elmtname = element["name"] |
|
943 |
infos = self.ExtractTypeInfos(element["name"], name, element["elmt_type"]) |
|
944 |
if infos is not None: |
|
945 |
element["elmt_type"] = infos |
|
946 |
if element["maxOccurs"] == "unbounded" or element["maxOccurs"] > 1: |
|
947 |
classmembers[elmtname] = [] |
|
948 |
classmembers["append%s"%elmtname] = generateAppendMethod(elmtname, element["maxOccurs"], self, element) |
|
949 |
classmembers["insert%s"%elmtname] = generateInsertMethod(elmtname, element["maxOccurs"], self, element) |
|
950 |
classmembers["remove%s"%elmtname] = generateRemoveMethod(elmtname, element["minOccurs"]) |
|
951 |
classmembers["count%s"%elmtname] = generateCountMethod(elmtname) |
|
952 |
else: |
|
953 |
if element["minOccurs"] == 0: |
|
954 |
classmembers[elmtname] = None |
|
955 |
classmembers["add%s"%elmtname] = generateAddMethod(elmtname, self, element) |
|
956 |
classmembers["delete%s"%elmtname] = generateDeleteMethod(elmtname) |
|
957 |
elif not isinstance(element["elmt_type"], (UnicodeType, StringType)): |
|
958 |
classmembers[elmtname] = element["elmt_type"]["initial"]() |
|
959 |
else: |
|
960 |
classmembers[elmtname] = None |
|
961 |
classmembers["set%s"%elmtname] = generateSetMethod(elmtname) |
|
962 |
classmembers["get%s"%elmtname] = generateGetMethod(elmtname) |
|
76
5bac3213fea1
xmlclass modified for allowing class definitions for multiple XSD files and indicating which classes are the base classes
lbessard
parents:
75
diff
changeset
|
963 |
|
151 | 964 |
classmembers["__init__"] = generateInitMethod(self, classinfos) |
965 |
classmembers["__setattr__"] = generateSetattrMethod(self, classinfos) |
|
966 |
classmembers["getStructure"] = generateStructureMethod(classinfos) |
|
967 |
classmembers["loadXMLTree"] = generateLoadXMLTree(self, classinfos) |
|
968 |
classmembers["generateXMLText"] = generateGenerateXMLText(self, classinfos) |
|
969 |
classmembers["getElementAttributes"] = generateGetElementAttributes(self, classinfos) |
|
970 |
classmembers["getElementInfos"] = generateGetElementInfos(self, classinfos) |
|
971 |
classmembers["setElementValue"] = generateSetElementValue(self, classinfos) |
|
972 |
classmembers["singleLineAttributes"] = True |
|
973 |
||
974 |
class_definition = classobj(str(classname), bases, classmembers) |
|
975 |
||
976 |
self.ComputedClasses[classname] = class_definition |
|
977 |
||
978 |
return {"type" : COMPILEDCOMPLEXTYPE, |
|
979 |
"name" : classname, |
|
980 |
"check" : generateClassCheckFunction(class_definition), |
|
981 |
"initial" : generateClassCreateFunction(class_definition), |
|
982 |
"extract" : generateClassExtractFunction(class_definition), |
|
983 |
"generate" : class_definition.generateXMLText} |
|
76
5bac3213fea1
xmlclass modified for allowing class definitions for multiple XSD files and indicating which classes are the base classes
lbessard
parents:
75
diff
changeset
|
984 |
|
5bac3213fea1
xmlclass modified for allowing class definitions for multiple XSD files and indicating which classes are the base classes
lbessard
parents:
75
diff
changeset
|
985 |
""" |
5bac3213fea1
xmlclass modified for allowing class definitions for multiple XSD files and indicating which classes are the base classes
lbessard
parents:
75
diff
changeset
|
986 |
Methods that print the classes generated |
5bac3213fea1
xmlclass modified for allowing class definitions for multiple XSD files and indicating which classes are the base classes
lbessard
parents:
75
diff
changeset
|
987 |
""" |
5bac3213fea1
xmlclass modified for allowing class definitions for multiple XSD files and indicating which classes are the base classes
lbessard
parents:
75
diff
changeset
|
988 |
def PrintClasses(self): |
151 | 989 |
items = self.ComputedClasses.items() |
990 |
items.sort() |
|
991 |
for classname, xmlclass in items: |
|
76
5bac3213fea1
xmlclass modified for allowing class definitions for multiple XSD files and indicating which classes are the base classes
lbessard
parents:
75
diff
changeset
|
992 |
print "%s : %s"%(classname, str(xmlclass)) |
5bac3213fea1
xmlclass modified for allowing class definitions for multiple XSD files and indicating which classes are the base classes
lbessard
parents:
75
diff
changeset
|
993 |
|
5bac3213fea1
xmlclass modified for allowing class definitions for multiple XSD files and indicating which classes are the base classes
lbessard
parents:
75
diff
changeset
|
994 |
def PrintClassNames(self): |
5bac3213fea1
xmlclass modified for allowing class definitions for multiple XSD files and indicating which classes are the base classes
lbessard
parents:
75
diff
changeset
|
995 |
classnames = self.XMLClassDefinitions.keys() |
5bac3213fea1
xmlclass modified for allowing class definitions for multiple XSD files and indicating which classes are the base classes
lbessard
parents:
75
diff
changeset
|
996 |
classnames.sort() |
5bac3213fea1
xmlclass modified for allowing class definitions for multiple XSD files and indicating which classes are the base classes
lbessard
parents:
75
diff
changeset
|
997 |
for classname in classnames: |
5bac3213fea1
xmlclass modified for allowing class definitions for multiple XSD files and indicating which classes are the base classes
lbessard
parents:
75
diff
changeset
|
998 |
print classname |
5bac3213fea1
xmlclass modified for allowing class definitions for multiple XSD files and indicating which classes are the base classes
lbessard
parents:
75
diff
changeset
|
999 |
|
5bac3213fea1
xmlclass modified for allowing class definitions for multiple XSD files and indicating which classes are the base classes
lbessard
parents:
75
diff
changeset
|
1000 |
""" |
151 | 1001 |
Method that generate the method for checking a class instance |
1002 |
""" |
|
1003 |
def generateClassCheckFunction(class_definition): |
|
1004 |
def classCheckfunction(instance): |
|
1005 |
return isinstance(instance, class_definition) |
|
1006 |
return classCheckfunction |
|
1007 |
||
1008 |
""" |
|
1009 |
Method that generate the method for creating a class instance |
|
1010 |
""" |
|
1011 |
def generateClassCreateFunction(class_definition): |
|
1012 |
def classCreatefunction(): |
|
1013 |
return class_definition() |
|
1014 |
return classCreatefunction |
|
1015 |
||
1016 |
""" |
|
1017 |
Method that generate the method for extracting a class instance |
|
1018 |
""" |
|
1019 |
def generateClassExtractFunction(class_definition): |
|
1020 |
def classExtractfunction(node): |
|
1021 |
instance = class_definition() |
|
1022 |
instance.loadXMLTree(node) |
|
1023 |
return instance |
|
1024 |
return classExtractfunction |
|
1025 |
||
1026 |
""" |
|
75
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1027 |
Method that generate the method for loading an xml tree by following the |
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1028 |
attributes list defined |
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1029 |
""" |
151 | 1030 |
def generateSetattrMethod(factory, classinfos): |
1031 |
attributes = dict([(attr["name"], attr) for attr in classinfos["attributes"] if attr["use"] != "prohibited"]) |
|
1032 |
optional_attributes = [attr["name"] for attr in classinfos["attributes"] if attr["use"] == "optional"] |
|
1033 |
elements = dict([(element["name"], element) for element in classinfos["elements"]]) |
|
1034 |
||
1035 |
def setattrMethod(self, name, value): |
|
1036 |
if name in attributes: |
|
1037 |
if isinstance(attributes[name]["attr_type"], (UnicodeType, StringType)): |
|
1038 |
namespace, name = DecomposeQualifiedName(infos) |
|
1039 |
attributes[name]["attr_type"] = factory.GetQualifiedNameInfos(name, namespace) |
|
1040 |
if value is None: |
|
1041 |
if name in optional_attributes: |
|
1042 |
return object.__setattr__(self, name, None) |
|
1043 |
else: |
|
1044 |
raise ValueError, "Attribute '%s' isn't optional."%name |
|
1045 |
elif "fixed" in attributes[name] and value != attributes[name]["fixed"]: |
|
1046 |
raise ValueError, "Value of attribute '%s' can only be '%s'."%(name, str(attributes[name]["fixed"])) |
|
1047 |
elif attributes[name]["attr_type"]["check"](value): |
|
1048 |
return object.__setattr__(self, name, value) |
|
1049 |
else: |
|
1050 |
raise ValueError, "Invalid value for attribute '%s'."%(name) |
|
1051 |
elif name in elements: |
|
1052 |
if isinstance(elements[name]["elmt_type"], (UnicodeType, StringType)): |
|
1053 |
namespace, name = DecomposeQualifiedName(infos) |
|
1054 |
elements[name]["elmt_type"] = factory.GetQualifiedNameInfos(name, namespace) |
|
1055 |
if value is None: |
|
1056 |
if elements[name]["minOccurs"] == 0 and elements[name]["maxOccurs"] == 1: |
|
1057 |
return object.__setattr__(self, name, None) |
|
1058 |
else: |
|
1059 |
raise ValueError, "Attribute '%s' isn't optional."%name |
|
1060 |
elif elements[name]["maxOccurs"] == "unbounded" or elements[name]["maxOccurs"] > 1: |
|
1061 |
if isinstance(value, ListType) and elements[name]["minOccurs"] <= len(value) <= elements[name]["maxOccurs"]: |
|
1062 |
if reduce(lambda x, y: x and y, map(elements[name]["elmt_type"]["check"], value), True): |
|
1063 |
return object.__setattr__(self, name, value) |
|
1064 |
raise ValueError, "Attribute '%s' must be a list of valid elements."%name |
|
1065 |
elif "fixed" in elements[name] and value != elements[name]["fixed"]: |
|
1066 |
raise ValueError, "Value of attribute '%s' can only be '%s'."%(name, str(elements[name]["fixed"])) |
|
1067 |
elif elements[name]["elmt_type"]["check"](value): |
|
1068 |
return object.__setattr__(self, name, value) |
|
1069 |
else: |
|
1070 |
raise ValueError, "Invalid value for attribute '%s'."%(name) |
|
1071 |
elif "base" in classinfos: |
|
1072 |
return classinfos["base"].__setattr__(self, name, value) |
|
1073 |
else: |
|
1074 |
raise AttributeError, "'%s' can't have an attribute '%s'."%(classinfos["name"], name) |
|
1075 |
||
1076 |
return setattrMethod |
|
1077 |
||
1078 |
""" |
|
1079 |
Method that generate the method for generating the xml tree structure model by |
|
1080 |
following the attributes list defined |
|
1081 |
""" |
|
1082 |
def ComputeMultiplicity(name, infos): |
|
1083 |
if infos["minOccurs"] == 0: |
|
1084 |
if infos["maxOccurs"] == "unbounded": |
|
1085 |
return "(?:%s)*"%name |
|
1086 |
elif infos["maxOccurs"] == 1: |
|
1087 |
return "(?:%s)?"%name |
|
1088 |
else: |
|
1089 |
return "(?:%s){0, %d}"%(name, infos["maxOccurs"]) |
|
1090 |
elif infos["minOccurs"] == 1: |
|
1091 |
if infos["maxOccurs"] == "unbounded": |
|
1092 |
return "(?:%s)+"%name |
|
1093 |
elif infos["maxOccurs"] == 1: |
|
1094 |
return name |
|
1095 |
else: |
|
1096 |
return "(?:%s){1, %d}"%(name, infos["maxOccurs"]) |
|
1097 |
else: |
|
1098 |
if infos["maxOccurs"] == "unbounded": |
|
1099 |
return "(?:%s){%d}(?:%s )*"%(name, infos["minOccurs"], name) |
|
1100 |
else: |
|
1101 |
return "(?:%s){%d, %d}"%(name, infos["minOccurs"], infos["maxOccurs"]) |
|
1102 |
||
1103 |
def generateStructureMethod(classinfos): |
|
1104 |
elements = [] |
|
1105 |
for element in classinfos["elements"]: |
|
1106 |
if element["type"] == ANY: |
|
1107 |
elements.append(ComputeMultiplicity("(?:#cdata-section )?", element)) |
|
1108 |
elif element["type"] == CHOICE: |
|
1109 |
elements.append(ComputeMultiplicity( |
|
1110 |
"|".join([ComputeMultiplicity("%s "%infos["name"], infos) for infos in element["choices"]]), |
|
1111 |
element)) |
|
1112 |
else: |
|
1113 |
elements.append(ComputeMultiplicity("%s "%element["name"], element)) |
|
1114 |
if classinfos.get("order") or len(elements) == 0: |
|
1115 |
structure = "".join(elements) |
|
1116 |
else: |
|
1117 |
raise ValueError, "XSD structure not yet supported!" |
|
1118 |
||
1119 |
def getStructureMethod(self): |
|
1120 |
if "base" in classinfos: |
|
1121 |
return classinfos["base"].getStructure(self) + structure |
|
1122 |
return structure |
|
1123 |
return getStructureMethod |
|
1124 |
||
1125 |
""" |
|
1126 |
Method that generate the method for loading an xml tree by following the |
|
1127 |
attributes list defined |
|
1128 |
""" |
|
1129 |
def generateLoadXMLTree(factory, classinfos): |
|
1130 |
attributes = dict([(attr["name"], attr) for attr in classinfos["attributes"] if attr["use"] != "prohibited"]) |
|
1131 |
elements = dict([(element["name"], element) for element in classinfos["elements"]]) |
|
1132 |
||
1133 |
def loadXMLTreeMethod(self, tree, extras = [], derived = False): |
|
1134 |
if not derived: |
|
1135 |
children_structure = "" |
|
75
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1136 |
for node in tree.childNodes: |
151 | 1137 |
if node.nodeName not in ["#comment", "#text"]: |
1138 |
children_structure += "%s "%node.nodeName |
|
1139 |
structure_model = re.compile("(%s)$"%self.getStructure()) |
|
1140 |
result = structure_model.match(children_structure) |
|
1141 |
if not result: |
|
1142 |
raise ValueError, "Invalid structure for \"%s\" children!."%tree.nodeName |
|
1143 |
required_attributes = [attr["name"] for attr in classinfos["attributes"] if attr["use"] == "required"] |
|
1144 |
if "base" in classinfos: |
|
1145 |
extras.extend([attr["name"] for attr in classinfos["attributes"] if attr["use"] != "prohibited"]) |
|
1146 |
classinfos["base"].loadXMLTree(self, tree, extras, True) |
|
1147 |
for attrname, attr in tree._attrs.items(): |
|
1148 |
if attrname in attributes: |
|
1149 |
if isinstance(attributes[attrname]["attr_type"], (UnicodeType, StringType)): |
|
1150 |
namespace, name = DecomposeQualifiedName(infos) |
|
1151 |
attributes[attrname]["attr_type"] = factory.GetQualifiedNameInfos(name, namespace) |
|
1152 |
setattr(self, attrname, attributes[attrname]["attr_type"]["extract"](attr)) |
|
1153 |
elif "base" not in classinfos and attrname not in extras: |
|
1154 |
raise ValueError, "Invalid attribute \"%s\" for \"%s\" element!"%(attrname, tree.nodeName) |
|
1155 |
if attrname in required_attributes: |
|
1156 |
required_attributes.remove(attrname) |
|
1157 |
if len(required_attributes) > 0: |
|
1158 |
raise ValueError, "Required attributes %s missing for \"%s\" element!"%(", ".join(["\"%s\""%name for name in required_attributes]), tree.nodeName) |
|
1159 |
first = {} |
|
1160 |
for node in tree.childNodes: |
|
1161 |
name = node.nodeName |
|
1162 |
if name in ["#text", "#comment"]: |
|
1163 |
continue |
|
1164 |
if name in elements: |
|
1165 |
if isinstance(elements[name]["elmt_type"], (UnicodeType, StringType)): |
|
1166 |
namespace, name = DecomposeQualifiedName(infos) |
|
1167 |
elements[name]["elmt_type"] = factory.GetQualifiedNameInfos(name, namespace) |
|
1168 |
if elements[name]["maxOccurs"] == "unbounded" or elements[name]["maxOccurs"] > 1: |
|
1169 |
if first.get(name, True): |
|
1170 |
setattr(self, name, [elements[name]["elmt_type"]["extract"](node)]) |
|
1171 |
first[name] = False |
|
1172 |
else: |
|
1173 |
getattr(self, name).append(elements[name]["elmt_type"]["extract"](node)) |
|
1174 |
else: |
|
1175 |
setattr(self, name, elements[name]["elmt_type"]["extract"](node)) |
|
1176 |
elif name == "#cdata-section" and "text" in elements: |
|
1177 |
if elements["text"]["maxOccurs"] == "unbounded" or elements["text"]["maxOccurs"] > 1: |
|
1178 |
if first.get("text", True): |
|
1179 |
setattr(self, "text", [elements["text"]["elmt_type"]["extract"](node)]) |
|
1180 |
first["text"] = False |
|
1181 |
else: |
|
1182 |
getattr(self, "text").append(elements["text"]["elmt_type"]["extract"](node)) |
|
1183 |
else: |
|
1184 |
setattr(self, "text", elements["text"]["elmt_type"]["extract"](node)) |
|
1185 |
elif "content" in elements: |
|
1186 |
content = getattr(self, "content") |
|
1187 |
if elements["content"]["maxOccurs"] == "unbounded" or elements["content"]["maxOccurs"] > 1: |
|
1188 |
if first.get("content", True): |
|
1189 |
setattr(self, "content", [elements["content"]["elmt_type"]["extract"](node, None)]) |
|
1190 |
first["content"] = False |
|
1191 |
else: |
|
1192 |
content.append(elements["content"]["elmt_type"]["extract"](node, content)) |
|
1193 |
else: |
|
1194 |
setattr(self, "content", elements["content"]["elmt_type"]["extract"](node, content)) |
|
75
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1195 |
return loadXMLTreeMethod |
151 | 1196 |
|
75
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1197 |
|
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1198 |
""" |
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1199 |
Method that generates the method for generating an xml text by following the |
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1200 |
attributes list defined |
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1201 |
""" |
151 | 1202 |
def generateGenerateXMLText(factory, classinfos): |
1203 |
def generateXMLTextMethod(self, name, indent = 0, extras = {}, derived = False): |
|
75
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1204 |
ind1, ind2 = getIndent(indent, name) |
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1205 |
if not derived: |
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1206 |
text = ind1 + "<%s"%name |
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1207 |
else: |
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1208 |
text = "" |
151 | 1209 |
|
75
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1210 |
first = True |
151 | 1211 |
if "base" not in classinfos: |
1212 |
for attr, value in extras.items(): |
|
1213 |
if not first and not self.singleLineAttributes: |
|
1214 |
text += "\n%s"%(ind2) |
|
1215 |
text += " %s=\"%s\""%(attr, value) |
|
1216 |
first = False |
|
1217 |
extras.clear() |
|
1218 |
for attr in classinfos["attributes"]: |
|
1219 |
if attr["use"] != "prohibited": |
|
1220 |
if isinstance(attr["attr_type"], (UnicodeType, StringType)): |
|
1221 |
namespace, name = DecomposeQualifiedName(infos) |
|
1222 |
attr["attr_type"] = factory.GetQualifiedNameInfos(name, namespace) |
|
1223 |
value = getattr(self, attr["name"], None) |
|
86
4f1dbdb0bed2
Bug on xmlclass XML file attributes generation fixed
lbessard
parents:
85
diff
changeset
|
1224 |
if value != None: |
151 | 1225 |
computed_value = attr["attr_type"]["generate"](value) |
86
4f1dbdb0bed2
Bug on xmlclass XML file attributes generation fixed
lbessard
parents:
85
diff
changeset
|
1226 |
else: |
4f1dbdb0bed2
Bug on xmlclass XML file attributes generation fixed
lbessard
parents:
85
diff
changeset
|
1227 |
computed_value = None |
151 | 1228 |
if attr["use"] != "optional" or (value != None and computed_value != attr.get("default", attr["attr_type"]["generate"](attr["attr_type"]["initial"]()))): |
1229 |
if "base" in classinfos: |
|
1230 |
extras[attr["name"]] = computed_value |
|
75
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1231 |
else: |
83 | 1232 |
if not first and not self.singleLineAttributes: |
1233 |
text += "\n%s"%(ind2) |
|
151 | 1234 |
text += " %s=\"%s\""%(attr["name"], computed_value) |
75
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1235 |
first = False |
151 | 1236 |
if "base" in classinfos: |
1237 |
first, new_text = classinfos["base"].generateXMLText(self, name, indent, extras, True) |
|
75
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1238 |
text += new_text |
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1239 |
else: |
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1240 |
first = True |
151 | 1241 |
for element in classinfos["elements"]: |
1242 |
if isinstance(element["elmt_type"], (UnicodeType, StringType)): |
|
1243 |
namespace, name = DecomposeQualifiedName(infos) |
|
1244 |
element["elmt_type"] = factory.GetQualifiedNameInfos(name, namespace) |
|
1245 |
value = getattr(self, element["name"], None) |
|
1246 |
if element["minOccurs"] == 0 and element["maxOccurs"] == 1: |
|
1247 |
if value is not None: |
|
75
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1248 |
if first: |
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1249 |
text += ">\n" |
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1250 |
first = False |
151 | 1251 |
text += element["elmt_type"]["generate"](value, element["name"], indent + 1) |
1252 |
elif element["minOccurs"] == 1 and element["maxOccurs"] == 1: |
|
1253 |
if first: |
|
1254 |
text += ">\n" |
|
1255 |
first = False |
|
1256 |
text += element["elmt_type"]["generate"](value, element["name"], indent + 1) |
|
1257 |
else: |
|
1258 |
if first and len(value) > 0: |
|
1259 |
text += ">\n" |
|
1260 |
first = False |
|
1261 |
for item in value: |
|
1262 |
text += element["elmt_type"]["generate"](item, element["name"], indent + 1) |
|
75
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1263 |
if not derived: |
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1264 |
if first: |
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1265 |
text += "/>\n" |
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1266 |
else: |
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1267 |
text += ind1 + "</%s>\n"%(name) |
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1268 |
return text |
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1269 |
else: |
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1270 |
return first, text |
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1271 |
return generateXMLTextMethod |
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1272 |
|
151 | 1273 |
def gettypeinfos(name, facets): |
1274 |
if "enumeration" in facets and facets["enumeration"][0] is not None: |
|
1275 |
return facets["enumeration"][0] |
|
1276 |
elif "maxInclusive" in facets: |
|
1277 |
limits = {"max" : None, "min" : None} |
|
1278 |
if facets["maxInclusive"][0] is not None: |
|
1279 |
limits["max"] = facets["maxInclusive"][0] |
|
1280 |
elif facets["maxExclusive"][0] is not None: |
|
1281 |
limits["max"] = facets["maxExclusive"][0] - 1 |
|
1282 |
if facets["minInclusive"][0] is not None: |
|
1283 |
limits["min"] = facets["minInclusive"][0] |
|
1284 |
elif facets["minExclusive"][0] is not None: |
|
1285 |
limits["min"] = facets["minExclusive"][0] + 1 |
|
1286 |
if limits["max"] is not None or limits["min"] is not None: |
|
1287 |
return limits |
|
1288 |
return name |
|
1289 |
||
1290 |
def generateGetElementAttributes(factory, classinfos): |
|
75
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1291 |
def getElementAttributes(self): |
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1292 |
attr_list = [] |
151 | 1293 |
for attr in classinfos["attributes"]: |
1294 |
if attr["use"] != "prohibited": |
|
1295 |
attr_params = {"name" : attr["name"], "require" : attr["use"] == "required", |
|
1296 |
"type" : gettypeinfos(attr["attr_type"]["basename"], attr["attr_type"]["facets"]), |
|
1297 |
"value" : getattr(self, attr["name"], "")} |
|
83 | 1298 |
attr_list.append(attr_params) |
75
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1299 |
return attr_list |
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1300 |
return getElementAttributes |
85
fd17b0e0fd7e
Adding members to classes for automatically generate infos and set the value of an element with its path
lbessard
parents:
84
diff
changeset
|
1301 |
|
151 | 1302 |
def generateGetElementInfos(factory, classinfos): |
1303 |
attributes = dict([(attr["name"], attr) for attr in classinfos["attributes"] if attr["use"] != "prohibited"]) |
|
1304 |
elements = dict([(element["name"], element) for element in classinfos["elements"]]) |
|
1305 |
||
85
fd17b0e0fd7e
Adding members to classes for automatically generate infos and set the value of an element with its path
lbessard
parents:
84
diff
changeset
|
1306 |
def getElementInfos(self, name, path = None): |
fd17b0e0fd7e
Adding members to classes for automatically generate infos and set the value of an element with its path
lbessard
parents:
84
diff
changeset
|
1307 |
attr_type = "element" |
fd17b0e0fd7e
Adding members to classes for automatically generate infos and set the value of an element with its path
lbessard
parents:
84
diff
changeset
|
1308 |
value = None |
fd17b0e0fd7e
Adding members to classes for automatically generate infos and set the value of an element with its path
lbessard
parents:
84
diff
changeset
|
1309 |
children = [] |
151 | 1310 |
if path is not None: |
1311 |
parts = path.split(".", 1) |
|
1312 |
if parts[0] in attributes: |
|
1313 |
if len(parts) != 0: |
|
1314 |
raise ValueError, "Wrong path!" |
|
1315 |
attr_type = gettypeinfos(attributes[parts[0]]["attr_type"]["basename"], |
|
1316 |
attributes[parts[0]]["attr_type"]["facets"]) |
|
1317 |
value = getattr(self, parts[0], "") |
|
1318 |
elif parts[0] in elements: |
|
1319 |
if element["elmt_type"]["type"] == SIMPLETYPE: |
|
1320 |
if len(parts) != 0: |
|
1321 |
raise ValueError, "Wrong path!" |
|
1322 |
attr_type = gettypeinfos(elements[parts[0]]["elmt_type"]["basename"], |
|
1323 |
elements[parts[0]]["elmt_type"]["facets"]) |
|
1324 |
value = getattr(self, parts[0], "") |
|
1325 |
elif parts[0] == "content": |
|
1326 |
return self.content["value"].getElementInfos(self.content["name"], path) |
|
1327 |
elif len(parts) == 1: |
|
1328 |
return attr.getElementInfos(parts[0]) |
|
1329 |
else: |
|
1330 |
return attr.getElementInfos(parts[0], parts[1]) |
|
1331 |
else: |
|
1332 |
raise ValueError, "Wrong path!" |
|
1333 |
else: |
|
1334 |
children.extend(self.getElementAttributes()) |
|
1335 |
for element_name, element in elements.items(): |
|
1336 |
if element_name == "content": |
|
1337 |
attr_type = [(choice["name"], None) for choice in element["choices"]] |
|
1338 |
value = self.content["name"] |
|
1339 |
children.extend(self.content["value"].getElementInfos(self.content["name"])["children"]) |
|
1340 |
elif element["elmt_type"]["type"] == SIMPLETYPE: |
|
1341 |
children.append({"name" : element_name, "require" : element["minOccurs"] != 0, |
|
1342 |
"type" : gettypeinfos(element["elmt_type"]["basename"], |
|
1343 |
element["elmt_type"]["facets"]), |
|
1344 |
"value" : getattr(self, element_name, None)}) |
|
1345 |
else: |
|
1346 |
instance = getattr(self, element_name, None) |
|
1347 |
if instance is None: |
|
1348 |
instance = elmt_type["elmt_type"]["initial"]() |
|
1349 |
children.append(instance.getElementInfos(element_name)) |
|
85
fd17b0e0fd7e
Adding members to classes for automatically generate infos and set the value of an element with its path
lbessard
parents:
84
diff
changeset
|
1350 |
return {"name" : name, "type" : attr_type, "value" : value, "children" : children} |
fd17b0e0fd7e
Adding members to classes for automatically generate infos and set the value of an element with its path
lbessard
parents:
84
diff
changeset
|
1351 |
return getElementInfos |
fd17b0e0fd7e
Adding members to classes for automatically generate infos and set the value of an element with its path
lbessard
parents:
84
diff
changeset
|
1352 |
|
151 | 1353 |
def generateSetElementValue(factory, classinfos): |
1354 |
attributes = dict([(attr["name"], attr) for attr in classinfos["attributes"] if attr["use"] != "prohibited"]) |
|
1355 |
elements = dict([(element["name"], element) for element in classinfos["elements"]]) |
|
1356 |
||
85
fd17b0e0fd7e
Adding members to classes for automatically generate infos and set the value of an element with its path
lbessard
parents:
84
diff
changeset
|
1357 |
def setElementValue(self, path, value): |
151 | 1358 |
if "content" in elements: |
85
fd17b0e0fd7e
Adding members to classes for automatically generate infos and set the value of an element with its path
lbessard
parents:
84
diff
changeset
|
1359 |
if path: |
fd17b0e0fd7e
Adding members to classes for automatically generate infos and set the value of an element with its path
lbessard
parents:
84
diff
changeset
|
1360 |
self.content["value"].setElementValue(path, value) |
fd17b0e0fd7e
Adding members to classes for automatically generate infos and set the value of an element with its path
lbessard
parents:
84
diff
changeset
|
1361 |
else: |
151 | 1362 |
self.addcontentbytype(value) |
85
fd17b0e0fd7e
Adding members to classes for automatically generate infos and set the value of an element with its path
lbessard
parents:
84
diff
changeset
|
1363 |
else: |
fd17b0e0fd7e
Adding members to classes for automatically generate infos and set the value of an element with its path
lbessard
parents:
84
diff
changeset
|
1364 |
parts = path.split(".", 1) |
151 | 1365 |
if parts[0] in attributes: |
1366 |
if len(parts) != 1: |
|
1367 |
raise ValueError, "Wrong path!" |
|
1368 |
if attributes[parts[0]]["attr_type"]["basename"] == "boolean": |
|
1369 |
setattr(self, parts[0], value) |
|
1370 |
else: |
|
1371 |
setattr(self, parts[0], attributes[parts[0]]["attr_type"]["extract"](value, False)) |
|
1372 |
elif parts[0] in elements: |
|
1373 |
if elements[parts[0]]["elmt_type"]["type"] == SIMPLETYPE: |
|
1374 |
if len(parts) != 1: |
|
1375 |
raise ValueError, "Wrong path!" |
|
1376 |
if elements[parts[0]]["elmt_type"]["basename"] == "boolean": |
|
1377 |
setattr(self, parts[0], value) |
|
1378 |
else: |
|
1379 |
setattr(self, parts[0], elements[parts[0]]["elmt_type"]["extract"](value, False)) |
|
1380 |
else: |
|
1381 |
instance = getattr(self, parts[0], None) |
|
1382 |
if instance != None: |
|
1383 |
if len(parts) == 1: |
|
1384 |
instance.setElementValue(None, value) |
|
85
fd17b0e0fd7e
Adding members to classes for automatically generate infos and set the value of an element with its path
lbessard
parents:
84
diff
changeset
|
1385 |
else: |
151 | 1386 |
instance.setElementValue(parts[1], value) |
85
fd17b0e0fd7e
Adding members to classes for automatically generate infos and set the value of an element with its path
lbessard
parents:
84
diff
changeset
|
1387 |
return setElementValue |
fd17b0e0fd7e
Adding members to classes for automatically generate infos and set the value of an element with its path
lbessard
parents:
84
diff
changeset
|
1388 |
|
75
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1389 |
""" |
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1390 |
Methods that generates the different methods for setting and getting the attributes |
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1391 |
""" |
151 | 1392 |
def generateInitMethod(factory, classinfos): |
75
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1393 |
def initMethod(self): |
151 | 1394 |
if "base" in classinfos: |
1395 |
classinfos["base"].__init__(self) |
|
1396 |
for attribute in classinfos["attributes"]: |
|
1397 |
if isinstance(attribute["attr_type"], (UnicodeType, StringType)): |
|
1398 |
namespace, name = DecomposeQualifiedName(attribute["attr_type"]) |
|
1399 |
attribute["attr_type"] = factory.GetQualifiedNameInfos(name, namespace) |
|
1400 |
if attribute["use"] == "required": |
|
1401 |
setattr(self, attribute["name"], attribute["attr_type"]["initial"]()) |
|
1402 |
elif attribute["use"] == "optional": |
|
1403 |
if "default" in attribute: |
|
1404 |
setattr(self, attribute["name"], attribute["attr_type"]["extract"](attribute["default"], False)) |
|
1405 |
else: |
|
1406 |
setattr(self, attribute["name"], None) |
|
1407 |
for element in classinfos["elements"]: |
|
1408 |
if isinstance(element["elmt_type"], (UnicodeType, StringType)): |
|
1409 |
namespace, name = DecomposeQualifiedName(element["elmt_type"]) |
|
1410 |
element["elmt_type"] = factory.GetQualifiedNameInfos(name, namespace) |
|
1411 |
if element["minOccurs"] == 0 and element["maxOccurs"] == 1: |
|
1412 |
if "default" in element: |
|
1413 |
setattr(self, element["name"], element["elmt_type"]["extract"](element["default"], False)) |
|
1414 |
else: |
|
1415 |
setattr(self, element["name"], None) |
|
1416 |
elif element["minOccurs"] == 1 and element["maxOccurs"] == 1: |
|
1417 |
setattr(self, element["name"], element["elmt_type"]["initial"]()) |
|
1418 |
else: |
|
1419 |
value = [] |
|
1420 |
for i in xrange(element["minOccurs"]): |
|
1421 |
value.append(element["elmt_type"]["initial"]()) |
|
1422 |
setattr(self, element["name"], value) |
|
75
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1423 |
return initMethod |
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1424 |
|
151 | 1425 |
def generateSetMethod(attr): |
75
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1426 |
def setMethod(self, value): |
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1427 |
setattr(self, attr, value) |
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1428 |
return setMethod |
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1429 |
|
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1430 |
def generateGetMethod(attr): |
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1431 |
def getMethod(self): |
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1432 |
return getattr(self, attr, None) |
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1433 |
return getMethod |
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1434 |
|
151 | 1435 |
def generateAddMethod(attr, factory, infos): |
75
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1436 |
def addMethod(self): |
151 | 1437 |
if infos["type"] == ATTRIBUTE: |
1438 |
if isinstance(infos["attr_type"], (UnicodeType, StringType)): |
|
1439 |
namespace, name = DecomposeQualifiedName(infos) |
|
1440 |
infos["attr_type"] = factory.GetQualifiedNameInfos(name, namespace) |
|
1441 |
initial = infos["attr_type"]["initial"] |
|
1442 |
extract = infos["attr_type"]["extract"] |
|
1443 |
elif infos["type"] == ELEMENT: |
|
1444 |
if isinstance(infos["elmt_type"], (UnicodeType, StringType)): |
|
1445 |
namespace, name = DecomposeQualifiedName(infos) |
|
1446 |
infos["elmt_type"] = factory.GetQualifiedNameInfos(name, namespace) |
|
1447 |
initial = infos["elmt_type"]["initial"] |
|
1448 |
extract = infos["elmt_type"]["extract"] |
|
1449 |
else: |
|
1450 |
raise ValueError, "Invalid class attribute!" |
|
1451 |
if "default" in infos: |
|
1452 |
setattr(self, attr, extract(infos["default"], False)) |
|
1453 |
else: |
|
1454 |
setattr(self, attr, initial()) |
|
75
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1455 |
return addMethod |
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1456 |
|
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1457 |
def generateDeleteMethod(attr): |
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1458 |
def deleteMethod(self): |
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1459 |
setattr(self, attr, None) |
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1460 |
return deleteMethod |
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1461 |
|
151 | 1462 |
def generateAppendMethod(attr, maxOccurs, factory, infos): |
75
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1463 |
def appendMethod(self, value): |
151 | 1464 |
if isinstance(infos["elmt_type"], (UnicodeType, StringType)): |
1465 |
namespace, name = DecomposeQualifiedName(infos) |
|
1466 |
infos["elmt_type"] = factory.GetQualifiedNameInfos(name, namespace) |
|
1467 |
attr_list = getattr(self, attr) |
|
1468 |
if maxOccurs == "unbounded" or len(attr_list) < maxOccurs: |
|
1469 |
if infos["elmt_type"]["check"](value): |
|
1470 |
attr_list.append(value) |
|
1471 |
else: |
|
1472 |
raise ValueError, "\"%s\" value isn't valid!"%attr |
|
1473 |
else: |
|
1474 |
raise ValueError, "There can't be more than %d values in \"%s\"!"%(maxOccurs, attr) |
|
75
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1475 |
return appendMethod |
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1476 |
|
151 | 1477 |
def generateInsertMethod(attr, maxOccurs, factory, infos): |
75
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1478 |
def insertMethod(self, index, value): |
151 | 1479 |
if isinstance(infos["elmt_type"], (UnicodeType, StringType)): |
1480 |
namespace, name = DecomposeQualifiedName(infos) |
|
1481 |
infos["elmt_type"] = factory.GetQualifiedNameInfos(name, namespace) |
|
1482 |
attr_list = getattr(self, attr) |
|
1483 |
if maxOccurs == "unbounded" or len(attr_list) < maxOccurs: |
|
1484 |
if infos["elmt_type"]["check"](value): |
|
1485 |
attr_list.insert(index, value) |
|
1486 |
else: |
|
1487 |
raise ValueError, "\"%s\" value isn't valid!"%attr |
|
1488 |
else: |
|
1489 |
raise ValueError, "There can't be more than %d values in \"%s\"!"%(maxOccurs, attr) |
|
75
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1490 |
return insertMethod |
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1491 |
|
151 | 1492 |
def generateGetChoicesMethod(choice_types): |
1493 |
def getChoicesMethod(self): |
|
1494 |
return [choice["name"] for choice in choice_types] |
|
1495 |
return getChoicesMethod |
|
1496 |
||
1497 |
def generateAddChoiceByTypeMethod(choice_types): |
|
1498 |
choices = dict([(choice["name"], choice) for choice in choice_types]) |
|
83 | 1499 |
def addChoiceMethod(self, name): |
151 | 1500 |
if name in choices: |
1501 |
if isinstance(choices["name"]["elmt_type"], (UnicodeType, StringType)): |
|
1502 |
namespace, name = DecomposeQualifiedName(infos) |
|
1503 |
choices["name"]["elmt_type"] = factory.GetQualifiedNameInfos(name, namespace) |
|
1504 |
self.content = {"name" : name, "value" : choices["name"]["elmt_type"]["initial"]()} |
|
83 | 1505 |
return addChoiceMethod |
1506 |
||
151 | 1507 |
def generateRemoveMethod(attr, minOccurs): |
75
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1508 |
def removeMethod(self, index): |
151 | 1509 |
attr_list = getattr(self, attr) |
1510 |
if len(attr_list) > minOccurs: |
|
1511 |
getattr(self, attr).pop(index) |
|
1512 |
else: |
|
1513 |
raise ValueError, "There can't be less than %d values in \"%s\"!"%(minOccurs, attr) |
|
75
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1514 |
return removeMethod |
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1515 |
|
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1516 |
def generateCountMethod(attr): |
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1517 |
def countMethod(self): |
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1518 |
return len(getattr(self, attr)) |
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1519 |
return countMethod |
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1520 |
|
82d371634f15
Changed the way class are generated, using classobj from "new" module, instead of type inheritence.
etisserant
parents:
67
diff
changeset
|
1521 |
""" |
76
5bac3213fea1
xmlclass modified for allowing class definitions for multiple XSD files and indicating which classes are the base classes
lbessard
parents:
75
diff
changeset
|
1522 |
This function generate the classes from a class factory |
5bac3213fea1
xmlclass modified for allowing class definitions for multiple XSD files and indicating which classes are the base classes
lbessard
parents:
75
diff
changeset
|
1523 |
""" |
5bac3213fea1
xmlclass modified for allowing class definitions for multiple XSD files and indicating which classes are the base classes
lbessard
parents:
75
diff
changeset
|
1524 |
def GenerateClasses(factory, declare = False): |
151 | 1525 |
ComputedClasses = factory.CreateClasses() |
1526 |
#factory.PrintClasses() |
|
76
5bac3213fea1
xmlclass modified for allowing class definitions for multiple XSD files and indicating which classes are the base classes
lbessard
parents:
75
diff
changeset
|
1527 |
if declare: |
5bac3213fea1
xmlclass modified for allowing class definitions for multiple XSD files and indicating which classes are the base classes
lbessard
parents:
75
diff
changeset
|
1528 |
for ClassName, Class in pluginClasses.items(): |
5bac3213fea1
xmlclass modified for allowing class definitions for multiple XSD files and indicating which classes are the base classes
lbessard
parents:
75
diff
changeset
|
1529 |
sys._getframe(1).f_locals[ClassName] = Class |
5bac3213fea1
xmlclass modified for allowing class definitions for multiple XSD files and indicating which classes are the base classes
lbessard
parents:
75
diff
changeset
|
1530 |
for TypeName, Type in pluginTypes.items(): |
5bac3213fea1
xmlclass modified for allowing class definitions for multiple XSD files and indicating which classes are the base classes
lbessard
parents:
75
diff
changeset
|
1531 |
sys._getframe(1).f_locals[TypeName] = Type |
83 | 1532 |
globals().update(ComputedClasses) |
151 | 1533 |
return ComputedClasses |
1534 |