karrio-aramex 2025.5rc34__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1469 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ #
5
+ # Generated Thu Feb 11 08:51:10 2021 by generateDS.py version 2.37.15.
6
+ # Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)]
7
+ #
8
+ # Command line options:
9
+ # ('--no-namespace-defs', '')
10
+ # ('-o', './aramex_lib/datatypes.py')
11
+ #
12
+ # Command line arguments:
13
+ # ./schemas/datatypes.xsd
14
+ #
15
+ # Command line:
16
+ # /Users/danielkobina/Workspace/project/karrio-carriers/.venv/karrio-carriers/bin/generateDS --no-namespace-defs -o "./aramex_lib/datatypes.py" ./schemas/datatypes.xsd
17
+ #
18
+ # Current working directory (os.getcwd()):
19
+ # aramex
20
+ #
21
+
22
+ import sys
23
+ try:
24
+ ModulenotfoundExp_ = ModuleNotFoundError
25
+ except NameError:
26
+ ModulenotfoundExp_ = ImportError
27
+ from six.moves import zip_longest
28
+ import os
29
+ import re as re_
30
+ import base64
31
+ import datetime as datetime_
32
+ import decimal as decimal_
33
+ try:
34
+ from lxml import etree as etree_
35
+ except ModulenotfoundExp_ :
36
+ from xml.etree import ElementTree as etree_
37
+
38
+
39
+ Validate_simpletypes_ = True
40
+ SaveElementTreeNode = True
41
+ if sys.version_info.major == 2:
42
+ BaseStrType_ = basestring
43
+ else:
44
+ BaseStrType_ = str
45
+
46
+
47
+ def parsexml_(infile, parser=None, **kwargs):
48
+ if parser is None:
49
+ # Use the lxml ElementTree compatible parser so that, e.g.,
50
+ # we ignore comments.
51
+ try:
52
+ parser = etree_.ETCompatXMLParser()
53
+ except AttributeError:
54
+ # fallback to xml.etree
55
+ parser = etree_.XMLParser()
56
+ try:
57
+ if isinstance(infile, os.PathLike):
58
+ infile = os.path.join(infile)
59
+ except AttributeError:
60
+ pass
61
+ doc = etree_.parse(infile, parser=parser, **kwargs)
62
+ return doc
63
+
64
+ def parsexmlstring_(instring, parser=None, **kwargs):
65
+ if parser is None:
66
+ # Use the lxml ElementTree compatible parser so that, e.g.,
67
+ # we ignore comments.
68
+ try:
69
+ parser = etree_.ETCompatXMLParser()
70
+ except AttributeError:
71
+ # fallback to xml.etree
72
+ parser = etree_.XMLParser()
73
+ element = etree_.fromstring(instring, parser=parser, **kwargs)
74
+ return element
75
+
76
+ #
77
+ # Namespace prefix definition table (and other attributes, too)
78
+ #
79
+ # The module generatedsnamespaces, if it is importable, must contain
80
+ # a dictionary named GeneratedsNamespaceDefs. This Python dictionary
81
+ # should map element type names (strings) to XML schema namespace prefix
82
+ # definitions. The export method for any class for which there is
83
+ # a namespace prefix definition, will export that definition in the
84
+ # XML representation of that element. See the export method of
85
+ # any generated element type class for an example of the use of this
86
+ # table.
87
+ # A sample table is:
88
+ #
89
+ # # File: generatedsnamespaces.py
90
+ #
91
+ # GenerateDSNamespaceDefs = {
92
+ # "ElementtypeA": "http://www.xxx.com/namespaceA",
93
+ # "ElementtypeB": "http://www.xxx.com/namespaceB",
94
+ # }
95
+ #
96
+ # Additionally, the generatedsnamespaces module can contain a python
97
+ # dictionary named GenerateDSNamespaceTypePrefixes that associates element
98
+ # types with the namespace prefixes that are to be added to the
99
+ # "xsi:type" attribute value. See the exportAttributes method of
100
+ # any generated element type and the generation of "xsi:type" for an
101
+ # example of the use of this table.
102
+ # An example table:
103
+ #
104
+ # # File: generatedsnamespaces.py
105
+ #
106
+ # GenerateDSNamespaceTypePrefixes = {
107
+ # "ElementtypeC": "aaa:",
108
+ # "ElementtypeD": "bbb:",
109
+ # }
110
+ #
111
+
112
+ try:
113
+ from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_
114
+ except ModulenotfoundExp_ :
115
+ GenerateDSNamespaceDefs_ = {}
116
+ try:
117
+ from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_
118
+ except ModulenotfoundExp_ :
119
+ GenerateDSNamespaceTypePrefixes_ = {}
120
+
121
+ #
122
+ # You can replace the following class definition by defining an
123
+ # importable module named "generatedscollector" containing a class
124
+ # named "GdsCollector". See the default class definition below for
125
+ # clues about the possible content of that class.
126
+ #
127
+ try:
128
+ from generatedscollector import GdsCollector as GdsCollector_
129
+ except ModulenotfoundExp_ :
130
+
131
+ class GdsCollector_(object):
132
+
133
+ def __init__(self, messages=None):
134
+ if messages is None:
135
+ self.messages = []
136
+ else:
137
+ self.messages = messages
138
+
139
+ def add_message(self, msg):
140
+ self.messages.append(msg)
141
+
142
+ def get_messages(self):
143
+ return self.messages
144
+
145
+ def clear_messages(self):
146
+ self.messages = []
147
+
148
+ def print_messages(self):
149
+ for msg in self.messages:
150
+ print("Warning: {}".format(msg))
151
+
152
+ def write_messages(self, outstream):
153
+ for msg in self.messages:
154
+ outstream.write("Warning: {}\n".format(msg))
155
+
156
+
157
+ #
158
+ # The super-class for enum types
159
+ #
160
+
161
+ try:
162
+ from enum import Enum
163
+ except ModulenotfoundExp_ :
164
+ Enum = object
165
+
166
+ #
167
+ # The root super-class for element type classes
168
+ #
169
+ # Calls to the methods in these classes are generated by generateDS.py.
170
+ # You can replace these methods by re-implementing the following class
171
+ # in a module named generatedssuper.py.
172
+
173
+ try:
174
+ from generatedssuper import GeneratedsSuper
175
+ except ModulenotfoundExp_ as exp:
176
+
177
+ class GeneratedsSuper(object):
178
+ __hash__ = object.__hash__
179
+ tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$')
180
+ class _FixedOffsetTZ(datetime_.tzinfo):
181
+ def __init__(self, offset, name):
182
+ self.__offset = datetime_.timedelta(minutes=offset)
183
+ self.__name = name
184
+ def utcoffset(self, dt):
185
+ return self.__offset
186
+ def tzname(self, dt):
187
+ return self.__name
188
+ def dst(self, dt):
189
+ return None
190
+ def gds_format_string(self, input_data, input_name=''):
191
+ return input_data
192
+ def gds_parse_string(self, input_data, node=None, input_name=''):
193
+ return input_data
194
+ def gds_validate_string(self, input_data, node=None, input_name=''):
195
+ if not input_data:
196
+ return ''
197
+ else:
198
+ return input_data
199
+ def gds_format_base64(self, input_data, input_name=''):
200
+ return base64.b64encode(input_data)
201
+ def gds_validate_base64(self, input_data, node=None, input_name=''):
202
+ return input_data
203
+ def gds_format_integer(self, input_data, input_name=''):
204
+ return '%d' % input_data
205
+ def gds_parse_integer(self, input_data, node=None, input_name=''):
206
+ try:
207
+ ival = int(input_data)
208
+ except (TypeError, ValueError) as exp:
209
+ raise_parse_error(node, 'Requires integer value: %s' % exp)
210
+ return ival
211
+ def gds_validate_integer(self, input_data, node=None, input_name=''):
212
+ try:
213
+ value = int(input_data)
214
+ except (TypeError, ValueError):
215
+ raise_parse_error(node, 'Requires integer value')
216
+ return value
217
+ def gds_format_integer_list(self, input_data, input_name=''):
218
+ if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_):
219
+ input_data = [str(s) for s in input_data]
220
+ return '%s' % ' '.join(input_data)
221
+ def gds_validate_integer_list(
222
+ self, input_data, node=None, input_name=''):
223
+ values = input_data.split()
224
+ for value in values:
225
+ try:
226
+ int(value)
227
+ except (TypeError, ValueError):
228
+ raise_parse_error(node, 'Requires sequence of integer values')
229
+ return values
230
+ def gds_format_float(self, input_data, input_name=''):
231
+ return ('%.15f' % input_data).rstrip('0')
232
+ def gds_parse_float(self, input_data, node=None, input_name=''):
233
+ try:
234
+ fval_ = float(input_data)
235
+ except (TypeError, ValueError) as exp:
236
+ raise_parse_error(node, 'Requires float or double value: %s' % exp)
237
+ return fval_
238
+ def gds_validate_float(self, input_data, node=None, input_name=''):
239
+ try:
240
+ value = float(input_data)
241
+ except (TypeError, ValueError):
242
+ raise_parse_error(node, 'Requires float value')
243
+ return value
244
+ def gds_format_float_list(self, input_data, input_name=''):
245
+ if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_):
246
+ input_data = [str(s) for s in input_data]
247
+ return '%s' % ' '.join(input_data)
248
+ def gds_validate_float_list(
249
+ self, input_data, node=None, input_name=''):
250
+ values = input_data.split()
251
+ for value in values:
252
+ try:
253
+ float(value)
254
+ except (TypeError, ValueError):
255
+ raise_parse_error(node, 'Requires sequence of float values')
256
+ return values
257
+ def gds_format_decimal(self, input_data, input_name=''):
258
+ return_value = '%s' % input_data
259
+ if '.' in return_value:
260
+ return_value = return_value.rstrip('0')
261
+ if return_value.endswith('.'):
262
+ return_value = return_value.rstrip('.')
263
+ return return_value
264
+ def gds_parse_decimal(self, input_data, node=None, input_name=''):
265
+ try:
266
+ decimal_value = decimal_.Decimal(input_data)
267
+ except (TypeError, ValueError):
268
+ raise_parse_error(node, 'Requires decimal value')
269
+ return decimal_value
270
+ def gds_validate_decimal(self, input_data, node=None, input_name=''):
271
+ try:
272
+ value = decimal_.Decimal(input_data)
273
+ except (TypeError, ValueError):
274
+ raise_parse_error(node, 'Requires decimal value')
275
+ return value
276
+ def gds_format_decimal_list(self, input_data, input_name=''):
277
+ if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_):
278
+ input_data = [str(s) for s in input_data]
279
+ return ' '.join([self.gds_format_decimal(item) for item in input_data])
280
+ def gds_validate_decimal_list(
281
+ self, input_data, node=None, input_name=''):
282
+ values = input_data.split()
283
+ for value in values:
284
+ try:
285
+ decimal_.Decimal(value)
286
+ except (TypeError, ValueError):
287
+ raise_parse_error(node, 'Requires sequence of decimal values')
288
+ return values
289
+ def gds_format_double(self, input_data, input_name=''):
290
+ return '%s' % input_data
291
+ def gds_parse_double(self, input_data, node=None, input_name=''):
292
+ try:
293
+ fval_ = float(input_data)
294
+ except (TypeError, ValueError) as exp:
295
+ raise_parse_error(node, 'Requires double or float value: %s' % exp)
296
+ return fval_
297
+ def gds_validate_double(self, input_data, node=None, input_name=''):
298
+ try:
299
+ value = float(input_data)
300
+ except (TypeError, ValueError):
301
+ raise_parse_error(node, 'Requires double or float value')
302
+ return value
303
+ def gds_format_double_list(self, input_data, input_name=''):
304
+ if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_):
305
+ input_data = [str(s) for s in input_data]
306
+ return '%s' % ' '.join(input_data)
307
+ def gds_validate_double_list(
308
+ self, input_data, node=None, input_name=''):
309
+ values = input_data.split()
310
+ for value in values:
311
+ try:
312
+ float(value)
313
+ except (TypeError, ValueError):
314
+ raise_parse_error(
315
+ node, 'Requires sequence of double or float values')
316
+ return values
317
+ def gds_format_boolean(self, input_data, input_name=''):
318
+ return ('%s' % input_data).lower()
319
+ def gds_parse_boolean(self, input_data, node=None, input_name=''):
320
+ if input_data in ('true', '1'):
321
+ bval = True
322
+ elif input_data in ('false', '0'):
323
+ bval = False
324
+ else:
325
+ raise_parse_error(node, 'Requires boolean value')
326
+ return bval
327
+ def gds_validate_boolean(self, input_data, node=None, input_name=''):
328
+ if input_data not in (True, 1, False, 0, ):
329
+ raise_parse_error(
330
+ node,
331
+ 'Requires boolean value '
332
+ '(one of True, 1, False, 0)')
333
+ return input_data
334
+ def gds_format_boolean_list(self, input_data, input_name=''):
335
+ if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_):
336
+ input_data = [str(s) for s in input_data]
337
+ return '%s' % ' '.join(input_data)
338
+ def gds_validate_boolean_list(
339
+ self, input_data, node=None, input_name=''):
340
+ values = input_data.split()
341
+ for value in values:
342
+ if value not in (True, 1, False, 0, ):
343
+ raise_parse_error(
344
+ node,
345
+ 'Requires sequence of boolean values '
346
+ '(one of True, 1, False, 0)')
347
+ return values
348
+ def gds_validate_datetime(self, input_data, node=None, input_name=''):
349
+ return input_data
350
+ def gds_format_datetime(self, input_data, input_name=''):
351
+ if input_data.microsecond == 0:
352
+ _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % (
353
+ input_data.year,
354
+ input_data.month,
355
+ input_data.day,
356
+ input_data.hour,
357
+ input_data.minute,
358
+ input_data.second,
359
+ )
360
+ else:
361
+ _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % (
362
+ input_data.year,
363
+ input_data.month,
364
+ input_data.day,
365
+ input_data.hour,
366
+ input_data.minute,
367
+ input_data.second,
368
+ ('%f' % (float(input_data.microsecond) / 1000000))[2:],
369
+ )
370
+ if input_data.tzinfo is not None:
371
+ tzoff = input_data.tzinfo.utcoffset(input_data)
372
+ if tzoff is not None:
373
+ total_seconds = tzoff.seconds + (86400 * tzoff.days)
374
+ if total_seconds == 0:
375
+ _svalue += 'Z'
376
+ else:
377
+ if total_seconds < 0:
378
+ _svalue += '-'
379
+ total_seconds *= -1
380
+ else:
381
+ _svalue += '+'
382
+ hours = total_seconds // 3600
383
+ minutes = (total_seconds - (hours * 3600)) // 60
384
+ _svalue += '{0:02d}:{1:02d}'.format(hours, minutes)
385
+ return _svalue
386
+ @classmethod
387
+ def gds_parse_datetime(cls, input_data):
388
+ tz = None
389
+ if input_data[-1] == 'Z':
390
+ tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC')
391
+ input_data = input_data[:-1]
392
+ else:
393
+ results = GeneratedsSuper.tzoff_pattern.search(input_data)
394
+ if results is not None:
395
+ tzoff_parts = results.group(2).split(':')
396
+ tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1])
397
+ if results.group(1) == '-':
398
+ tzoff *= -1
399
+ tz = GeneratedsSuper._FixedOffsetTZ(
400
+ tzoff, results.group(0))
401
+ input_data = input_data[:-6]
402
+ time_parts = input_data.split('.')
403
+ if len(time_parts) > 1:
404
+ micro_seconds = int(float('0.' + time_parts[1]) * 1000000)
405
+ input_data = '%s.%s' % (
406
+ time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), )
407
+ dt = datetime_.datetime.strptime(
408
+ input_data, '%Y-%m-%dT%H:%M:%S.%f')
409
+ else:
410
+ dt = datetime_.datetime.strptime(
411
+ input_data, '%Y-%m-%dT%H:%M:%S')
412
+ dt = dt.replace(tzinfo=tz)
413
+ return dt
414
+ def gds_validate_date(self, input_data, node=None, input_name=''):
415
+ return input_data
416
+ def gds_format_date(self, input_data, input_name=''):
417
+ _svalue = '%04d-%02d-%02d' % (
418
+ input_data.year,
419
+ input_data.month,
420
+ input_data.day,
421
+ )
422
+ try:
423
+ if input_data.tzinfo is not None:
424
+ tzoff = input_data.tzinfo.utcoffset(input_data)
425
+ if tzoff is not None:
426
+ total_seconds = tzoff.seconds + (86400 * tzoff.days)
427
+ if total_seconds == 0:
428
+ _svalue += 'Z'
429
+ else:
430
+ if total_seconds < 0:
431
+ _svalue += '-'
432
+ total_seconds *= -1
433
+ else:
434
+ _svalue += '+'
435
+ hours = total_seconds // 3600
436
+ minutes = (total_seconds - (hours * 3600)) // 60
437
+ _svalue += '{0:02d}:{1:02d}'.format(
438
+ hours, minutes)
439
+ except AttributeError:
440
+ pass
441
+ return _svalue
442
+ @classmethod
443
+ def gds_parse_date(cls, input_data):
444
+ tz = None
445
+ if input_data[-1] == 'Z':
446
+ tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC')
447
+ input_data = input_data[:-1]
448
+ else:
449
+ results = GeneratedsSuper.tzoff_pattern.search(input_data)
450
+ if results is not None:
451
+ tzoff_parts = results.group(2).split(':')
452
+ tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1])
453
+ if results.group(1) == '-':
454
+ tzoff *= -1
455
+ tz = GeneratedsSuper._FixedOffsetTZ(
456
+ tzoff, results.group(0))
457
+ input_data = input_data[:-6]
458
+ dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d')
459
+ dt = dt.replace(tzinfo=tz)
460
+ return dt.date()
461
+ def gds_validate_time(self, input_data, node=None, input_name=''):
462
+ return input_data
463
+ def gds_format_time(self, input_data, input_name=''):
464
+ if input_data.microsecond == 0:
465
+ _svalue = '%02d:%02d:%02d' % (
466
+ input_data.hour,
467
+ input_data.minute,
468
+ input_data.second,
469
+ )
470
+ else:
471
+ _svalue = '%02d:%02d:%02d.%s' % (
472
+ input_data.hour,
473
+ input_data.minute,
474
+ input_data.second,
475
+ ('%f' % (float(input_data.microsecond) / 1000000))[2:],
476
+ )
477
+ if input_data.tzinfo is not None:
478
+ tzoff = input_data.tzinfo.utcoffset(input_data)
479
+ if tzoff is not None:
480
+ total_seconds = tzoff.seconds + (86400 * tzoff.days)
481
+ if total_seconds == 0:
482
+ _svalue += 'Z'
483
+ else:
484
+ if total_seconds < 0:
485
+ _svalue += '-'
486
+ total_seconds *= -1
487
+ else:
488
+ _svalue += '+'
489
+ hours = total_seconds // 3600
490
+ minutes = (total_seconds - (hours * 3600)) // 60
491
+ _svalue += '{0:02d}:{1:02d}'.format(hours, minutes)
492
+ return _svalue
493
+ def gds_validate_simple_patterns(self, patterns, target):
494
+ # pat is a list of lists of strings/patterns.
495
+ # The target value must match at least one of the patterns
496
+ # in order for the test to succeed.
497
+ found1 = True
498
+ for patterns1 in patterns:
499
+ found2 = False
500
+ for patterns2 in patterns1:
501
+ mo = re_.search(patterns2, target)
502
+ if mo is not None and len(mo.group(0)) == len(target):
503
+ found2 = True
504
+ break
505
+ if not found2:
506
+ found1 = False
507
+ break
508
+ return found1
509
+ @classmethod
510
+ def gds_parse_time(cls, input_data):
511
+ tz = None
512
+ if input_data[-1] == 'Z':
513
+ tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC')
514
+ input_data = input_data[:-1]
515
+ else:
516
+ results = GeneratedsSuper.tzoff_pattern.search(input_data)
517
+ if results is not None:
518
+ tzoff_parts = results.group(2).split(':')
519
+ tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1])
520
+ if results.group(1) == '-':
521
+ tzoff *= -1
522
+ tz = GeneratedsSuper._FixedOffsetTZ(
523
+ tzoff, results.group(0))
524
+ input_data = input_data[:-6]
525
+ if len(input_data.split('.')) > 1:
526
+ dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f')
527
+ else:
528
+ dt = datetime_.datetime.strptime(input_data, '%H:%M:%S')
529
+ dt = dt.replace(tzinfo=tz)
530
+ return dt.time()
531
+ def gds_check_cardinality_(
532
+ self, value, input_name,
533
+ min_occurs=0, max_occurs=1, required=None):
534
+ if value is None:
535
+ length = 0
536
+ elif isinstance(value, list):
537
+ length = len(value)
538
+ else:
539
+ length = 1
540
+ if required is not None :
541
+ if required and length < 1:
542
+ self.gds_collector_.add_message(
543
+ "Required value {}{} is missing".format(
544
+ input_name, self.gds_get_node_lineno_()))
545
+ if length < min_occurs:
546
+ self.gds_collector_.add_message(
547
+ "Number of values for {}{} is below "
548
+ "the minimum allowed, "
549
+ "expected at least {}, found {}".format(
550
+ input_name, self.gds_get_node_lineno_(),
551
+ min_occurs, length))
552
+ elif length > max_occurs:
553
+ self.gds_collector_.add_message(
554
+ "Number of values for {}{} is above "
555
+ "the maximum allowed, "
556
+ "expected at most {}, found {}".format(
557
+ input_name, self.gds_get_node_lineno_(),
558
+ max_occurs, length))
559
+ def gds_validate_builtin_ST_(
560
+ self, validator, value, input_name,
561
+ min_occurs=None, max_occurs=None, required=None):
562
+ if value is not None:
563
+ try:
564
+ validator(value, input_name=input_name)
565
+ except GDSParseError as parse_error:
566
+ self.gds_collector_.add_message(str(parse_error))
567
+ def gds_validate_defined_ST_(
568
+ self, validator, value, input_name,
569
+ min_occurs=None, max_occurs=None, required=None):
570
+ if value is not None:
571
+ try:
572
+ validator(value)
573
+ except GDSParseError as parse_error:
574
+ self.gds_collector_.add_message(str(parse_error))
575
+ def gds_str_lower(self, instring):
576
+ return instring.lower()
577
+ def get_path_(self, node):
578
+ path_list = []
579
+ self.get_path_list_(node, path_list)
580
+ path_list.reverse()
581
+ path = '/'.join(path_list)
582
+ return path
583
+ Tag_strip_pattern_ = re_.compile(r'\{.*\}')
584
+ def get_path_list_(self, node, path_list):
585
+ if node is None:
586
+ return
587
+ tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag)
588
+ if tag:
589
+ path_list.append(tag)
590
+ self.get_path_list_(node.getparent(), path_list)
591
+ def get_class_obj_(self, node, default_class=None):
592
+ class_obj1 = default_class
593
+ if 'xsi' in node.nsmap:
594
+ classname = node.get('{%s}type' % node.nsmap['xsi'])
595
+ if classname is not None:
596
+ names = classname.split(':')
597
+ if len(names) == 2:
598
+ classname = names[1]
599
+ class_obj2 = globals().get(classname)
600
+ if class_obj2 is not None:
601
+ class_obj1 = class_obj2
602
+ return class_obj1
603
+ def gds_build_any(self, node, type_name=None):
604
+ # provide default value in case option --disable-xml is used.
605
+ content = ""
606
+ content = etree_.tostring(node, encoding="unicode")
607
+ return content
608
+ @classmethod
609
+ def gds_reverse_node_mapping(cls, mapping):
610
+ return dict(((v, k) for k, v in mapping.items()))
611
+ @staticmethod
612
+ def gds_encode(instring):
613
+ if sys.version_info.major == 2:
614
+ if ExternalEncoding:
615
+ encoding = ExternalEncoding
616
+ else:
617
+ encoding = 'utf-8'
618
+ return instring.encode(encoding)
619
+ else:
620
+ return instring
621
+ @staticmethod
622
+ def convert_unicode(instring):
623
+ if isinstance(instring, str):
624
+ result = quote_xml(instring)
625
+ elif sys.version_info.major == 2 and isinstance(instring, unicode):
626
+ result = quote_xml(instring).encode('utf8')
627
+ else:
628
+ result = GeneratedsSuper.gds_encode(str(instring))
629
+ return result
630
+ def __eq__(self, other):
631
+ def excl_select_objs_(obj):
632
+ return (obj[0] != 'parent_object_' and
633
+ obj[0] != 'gds_collector_')
634
+ if type(self) != type(other):
635
+ return False
636
+ return all(x == y for x, y in zip_longest(
637
+ filter(excl_select_objs_, self.__dict__.items()),
638
+ filter(excl_select_objs_, other.__dict__.items())))
639
+ def __ne__(self, other):
640
+ return not self.__eq__(other)
641
+ # Django ETL transform hooks.
642
+ def gds_djo_etl_transform(self):
643
+ pass
644
+ def gds_djo_etl_transform_db_obj(self, dbobj):
645
+ pass
646
+ # SQLAlchemy ETL transform hooks.
647
+ def gds_sqa_etl_transform(self):
648
+ return 0, None
649
+ def gds_sqa_etl_transform_db_obj(self, dbobj):
650
+ pass
651
+ def gds_get_node_lineno_(self):
652
+ if (hasattr(self, "gds_elementtree_node_") and
653
+ self.gds_elementtree_node_ is not None):
654
+ return ' near line {}'.format(
655
+ self.gds_elementtree_node_.sourceline)
656
+ else:
657
+ return ""
658
+
659
+
660
+ def getSubclassFromModule_(module, class_):
661
+ '''Get the subclass of a class from a specific module.'''
662
+ name = class_.__name__ + 'Sub'
663
+ if hasattr(module, name):
664
+ return getattr(module, name)
665
+ else:
666
+ return None
667
+
668
+
669
+ #
670
+ # If you have installed IPython you can uncomment and use the following.
671
+ # IPython is available from http://ipython.scipy.org/.
672
+ #
673
+
674
+ ## from IPython.Shell import IPShellEmbed
675
+ ## args = ''
676
+ ## ipshell = IPShellEmbed(args,
677
+ ## banner = 'Dropping into IPython',
678
+ ## exit_msg = 'Leaving Interpreter, back to program.')
679
+
680
+ # Then use the following line where and when you want to drop into the
681
+ # IPython shell:
682
+ # ipshell('<some message> -- Entering ipshell.\nHit Ctrl-D to exit')
683
+
684
+ #
685
+ # Globals
686
+ #
687
+
688
+ ExternalEncoding = ''
689
+ # Set this to false in order to deactivate during export, the use of
690
+ # name space prefixes captured from the input document.
691
+ UseCapturedNS_ = True
692
+ CapturedNsmap_ = {}
693
+ Tag_pattern_ = re_.compile(r'({.*})?(.*)')
694
+ String_cleanup_pat_ = re_.compile(r"[\n\r\s]+")
695
+ Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)')
696
+ CDATA_pattern_ = re_.compile(r"<!\[CDATA\[.*?\]\]>", re_.DOTALL)
697
+
698
+ # Change this to redirect the generated superclass module to use a
699
+ # specific subclass module.
700
+ CurrentSubclassModule_ = None
701
+
702
+ #
703
+ # Support/utility functions.
704
+ #
705
+
706
+
707
+ def showIndent(outfile, level, pretty_print=True):
708
+ if pretty_print:
709
+ for idx in range(level):
710
+ outfile.write(' ')
711
+
712
+
713
+ def quote_xml(inStr):
714
+ "Escape markup chars, but do not modify CDATA sections."
715
+ if not inStr:
716
+ return ''
717
+ s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr)
718
+ s2 = ''
719
+ pos = 0
720
+ matchobjects = CDATA_pattern_.finditer(s1)
721
+ for mo in matchobjects:
722
+ s3 = s1[pos:mo.start()]
723
+ s2 += quote_xml_aux(s3)
724
+ s2 += s1[mo.start():mo.end()]
725
+ pos = mo.end()
726
+ s3 = s1[pos:]
727
+ s2 += quote_xml_aux(s3)
728
+ return s2
729
+
730
+
731
+ def quote_xml_aux(inStr):
732
+ s1 = inStr.replace('&', '&amp;')
733
+ s1 = s1.replace('<', '&lt;')
734
+ s1 = s1.replace('>', '&gt;')
735
+ return s1
736
+
737
+
738
+ def quote_attrib(inStr):
739
+ s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr)
740
+ s1 = s1.replace('&', '&amp;')
741
+ s1 = s1.replace('<', '&lt;')
742
+ s1 = s1.replace('>', '&gt;')
743
+ if '"' in s1:
744
+ if "'" in s1:
745
+ s1 = '"%s"' % s1.replace('"', "&quot;")
746
+ else:
747
+ s1 = "'%s'" % s1
748
+ else:
749
+ s1 = '"%s"' % s1
750
+ return s1
751
+
752
+
753
+ def quote_python(inStr):
754
+ s1 = inStr
755
+ if s1.find("'") == -1:
756
+ if s1.find('\n') == -1:
757
+ return "'%s'" % s1
758
+ else:
759
+ return "'''%s'''" % s1
760
+ else:
761
+ if s1.find('"') != -1:
762
+ s1 = s1.replace('"', '\\"')
763
+ if s1.find('\n') == -1:
764
+ return '"%s"' % s1
765
+ else:
766
+ return '"""%s"""' % s1
767
+
768
+
769
+ def get_all_text_(node):
770
+ if node.text is not None:
771
+ text = node.text
772
+ else:
773
+ text = ''
774
+ for child in node:
775
+ if child.tail is not None:
776
+ text += child.tail
777
+ return text
778
+
779
+
780
+ def find_attr_value_(attr_name, node):
781
+ attrs = node.attrib
782
+ attr_parts = attr_name.split(':')
783
+ value = None
784
+ if len(attr_parts) == 1:
785
+ value = attrs.get(attr_name)
786
+ elif len(attr_parts) == 2:
787
+ prefix, name = attr_parts
788
+ if prefix == 'xml':
789
+ namespace = 'http://www.w3.org/XML/1998/namespace'
790
+ else:
791
+ namespace = node.nsmap.get(prefix)
792
+ if namespace is not None:
793
+ value = attrs.get('{%s}%s' % (namespace, name, ))
794
+ return value
795
+
796
+
797
+ def encode_str_2_3(instr):
798
+ return instr
799
+
800
+
801
+ class GDSParseError(Exception):
802
+ pass
803
+
804
+
805
+ def raise_parse_error(node, msg):
806
+ if node is not None:
807
+ msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, )
808
+ raise GDSParseError(msg)
809
+
810
+
811
+ class MixedContainer:
812
+ # Constants for category:
813
+ CategoryNone = 0
814
+ CategoryText = 1
815
+ CategorySimple = 2
816
+ CategoryComplex = 3
817
+ # Constants for content_type:
818
+ TypeNone = 0
819
+ TypeText = 1
820
+ TypeString = 2
821
+ TypeInteger = 3
822
+ TypeFloat = 4
823
+ TypeDecimal = 5
824
+ TypeDouble = 6
825
+ TypeBoolean = 7
826
+ TypeBase64 = 8
827
+ def __init__(self, category, content_type, name, value):
828
+ self.category = category
829
+ self.content_type = content_type
830
+ self.name = name
831
+ self.value = value
832
+ def getCategory(self):
833
+ return self.category
834
+ def getContenttype(self, content_type):
835
+ return self.content_type
836
+ def getValue(self):
837
+ return self.value
838
+ def getName(self):
839
+ return self.name
840
+ def export(self, outfile, level, name, namespace,
841
+ pretty_print=True):
842
+ if self.category == MixedContainer.CategoryText:
843
+ # Prevent exporting empty content as empty lines.
844
+ if self.value.strip():
845
+ outfile.write(self.value)
846
+ elif self.category == MixedContainer.CategorySimple:
847
+ self.exportSimple(outfile, level, name)
848
+ else: # category == MixedContainer.CategoryComplex
849
+ self.value.export(
850
+ outfile, level, namespace, name_=name,
851
+ pretty_print=pretty_print)
852
+ def exportSimple(self, outfile, level, name):
853
+ if self.content_type == MixedContainer.TypeString:
854
+ outfile.write('<%s>%s</%s>' % (
855
+ self.name, self.value, self.name))
856
+ elif self.content_type == MixedContainer.TypeInteger or \
857
+ self.content_type == MixedContainer.TypeBoolean:
858
+ outfile.write('<%s>%d</%s>' % (
859
+ self.name, self.value, self.name))
860
+ elif self.content_type == MixedContainer.TypeFloat or \
861
+ self.content_type == MixedContainer.TypeDecimal:
862
+ outfile.write('<%s>%f</%s>' % (
863
+ self.name, self.value, self.name))
864
+ elif self.content_type == MixedContainer.TypeDouble:
865
+ outfile.write('<%s>%g</%s>' % (
866
+ self.name, self.value, self.name))
867
+ elif self.content_type == MixedContainer.TypeBase64:
868
+ outfile.write('<%s>%s</%s>' % (
869
+ self.name,
870
+ base64.b64encode(self.value),
871
+ self.name))
872
+ def to_etree(self, element, mapping_=None, nsmap_=None):
873
+ if self.category == MixedContainer.CategoryText:
874
+ # Prevent exporting empty content as empty lines.
875
+ if self.value.strip():
876
+ if len(element) > 0:
877
+ if element[-1].tail is None:
878
+ element[-1].tail = self.value
879
+ else:
880
+ element[-1].tail += self.value
881
+ else:
882
+ if element.text is None:
883
+ element.text = self.value
884
+ else:
885
+ element.text += self.value
886
+ elif self.category == MixedContainer.CategorySimple:
887
+ subelement = etree_.SubElement(
888
+ element, '%s' % self.name)
889
+ subelement.text = self.to_etree_simple()
890
+ else: # category == MixedContainer.CategoryComplex
891
+ self.value.to_etree(element)
892
+ def to_etree_simple(self, mapping_=None, nsmap_=None):
893
+ if self.content_type == MixedContainer.TypeString:
894
+ text = self.value
895
+ elif (self.content_type == MixedContainer.TypeInteger or
896
+ self.content_type == MixedContainer.TypeBoolean):
897
+ text = '%d' % self.value
898
+ elif (self.content_type == MixedContainer.TypeFloat or
899
+ self.content_type == MixedContainer.TypeDecimal):
900
+ text = '%f' % self.value
901
+ elif self.content_type == MixedContainer.TypeDouble:
902
+ text = '%g' % self.value
903
+ elif self.content_type == MixedContainer.TypeBase64:
904
+ text = '%s' % base64.b64encode(self.value)
905
+ return text
906
+ def exportLiteral(self, outfile, level, name):
907
+ if self.category == MixedContainer.CategoryText:
908
+ showIndent(outfile, level)
909
+ outfile.write(
910
+ 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % (
911
+ self.category, self.content_type,
912
+ self.name, self.value))
913
+ elif self.category == MixedContainer.CategorySimple:
914
+ showIndent(outfile, level)
915
+ outfile.write(
916
+ 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % (
917
+ self.category, self.content_type,
918
+ self.name, self.value))
919
+ else: # category == MixedContainer.CategoryComplex
920
+ showIndent(outfile, level)
921
+ outfile.write(
922
+ 'model_.MixedContainer(%d, %d, "%s",\n' % (
923
+ self.category, self.content_type, self.name,))
924
+ self.value.exportLiteral(outfile, level + 1)
925
+ showIndent(outfile, level)
926
+ outfile.write(')\n')
927
+
928
+
929
+ class MemberSpec_(object):
930
+ def __init__(self, name='', data_type='', container=0,
931
+ optional=0, child_attrs=None, choice=None):
932
+ self.name = name
933
+ self.data_type = data_type
934
+ self.container = container
935
+ self.child_attrs = child_attrs
936
+ self.choice = choice
937
+ self.optional = optional
938
+ def set_name(self, name): self.name = name
939
+ def get_name(self): return self.name
940
+ def set_data_type(self, data_type): self.data_type = data_type
941
+ def get_data_type_chain(self): return self.data_type
942
+ def get_data_type(self):
943
+ if isinstance(self.data_type, list):
944
+ if len(self.data_type) > 0:
945
+ return self.data_type[-1]
946
+ else:
947
+ return 'xs:string'
948
+ else:
949
+ return self.data_type
950
+ def set_container(self, container): self.container = container
951
+ def get_container(self): return self.container
952
+ def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs
953
+ def get_child_attrs(self): return self.child_attrs
954
+ def set_choice(self, choice): self.choice = choice
955
+ def get_choice(self): return self.choice
956
+ def set_optional(self, optional): self.optional = optional
957
+ def get_optional(self): return self.optional
958
+
959
+
960
+ def _cast(typ, value):
961
+ if typ is None or value is None:
962
+ return value
963
+ return typ(value)
964
+
965
+ #
966
+ # Data representation classes.
967
+ #
968
+
969
+
970
+ class char(GeneratedsSuper):
971
+ __hash__ = GeneratedsSuper.__hash__
972
+ subclass = None
973
+ superclass = None
974
+ def __init__(self, valueOf_=None, gds_collector_=None, **kwargs_):
975
+ self.gds_collector_ = gds_collector_
976
+ self.gds_elementtree_node_ = None
977
+ self.original_tagname_ = None
978
+ self.parent_object_ = kwargs_.get('parent_object_')
979
+ self.ns_prefix_ = None
980
+ self.valueOf_ = valueOf_
981
+ def factory(*args_, **kwargs_):
982
+ if CurrentSubclassModule_ is not None:
983
+ subclass = getSubclassFromModule_(
984
+ CurrentSubclassModule_, char)
985
+ if subclass is not None:
986
+ return subclass(*args_, **kwargs_)
987
+ if char.subclass:
988
+ return char.subclass(*args_, **kwargs_)
989
+ else:
990
+ return char(*args_, **kwargs_)
991
+ factory = staticmethod(factory)
992
+ def get_ns_prefix_(self):
993
+ return self.ns_prefix_
994
+ def set_ns_prefix_(self, ns_prefix):
995
+ self.ns_prefix_ = ns_prefix
996
+ def get_valueOf_(self): return self.valueOf_
997
+ def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_
998
+ def validate_char_impl(self, value):
999
+ result = True
1000
+ # Validate type char_impl, a restriction on xs:int.
1001
+ if value is not None and Validate_simpletypes_ and self.gds_collector_ is not None:
1002
+ if not isinstance(value, int):
1003
+ lineno = self.gds_get_node_lineno_()
1004
+ self.gds_collector_.add_message('Value "%(value)s"%(lineno)s is not of the correct base simple type (int)' % {"value": value, "lineno": lineno, })
1005
+ return False
1006
+ pass
1007
+ return result
1008
+ def hasContent_(self):
1009
+ if (
1010
+ (1 if type(self.valueOf_) in [int,float] else self.valueOf_)
1011
+ ):
1012
+ return True
1013
+ else:
1014
+ return False
1015
+ def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='char', pretty_print=True):
1016
+ imported_ns_def_ = GenerateDSNamespaceDefs_.get('char')
1017
+ if imported_ns_def_ is not None:
1018
+ namespacedef_ = imported_ns_def_
1019
+ if pretty_print:
1020
+ eol_ = '\n'
1021
+ else:
1022
+ eol_ = ''
1023
+ if self.original_tagname_ is not None and name_ == 'char':
1024
+ name_ = self.original_tagname_
1025
+ if UseCapturedNS_ and self.ns_prefix_:
1026
+ namespaceprefix_ = self.ns_prefix_ + ':'
1027
+ showIndent(outfile, level, pretty_print)
1028
+ outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
1029
+ already_processed = set()
1030
+ self.exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='char')
1031
+ if self.hasContent_():
1032
+ outfile.write('>')
1033
+ outfile.write(self.convert_unicode(self.valueOf_))
1034
+ self.exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='char', pretty_print=pretty_print)
1035
+ outfile.write('</%s%s>%s' % (namespaceprefix_, name_, eol_))
1036
+ else:
1037
+ outfile.write('/>%s' % (eol_, ))
1038
+ def exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='char'):
1039
+ pass
1040
+ def exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='char', fromsubclass_=False, pretty_print=True):
1041
+ pass
1042
+ def build(self, node, gds_collector_=None):
1043
+ self.gds_collector_ = gds_collector_
1044
+ if SaveElementTreeNode:
1045
+ self.gds_elementtree_node_ = node
1046
+ already_processed = set()
1047
+ self.ns_prefix_ = node.prefix
1048
+ self.buildAttributes(node, node.attrib, already_processed)
1049
+ self.valueOf_ = get_all_text_(node)
1050
+ for child in node:
1051
+ nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
1052
+ self.buildChildren(child, node, nodeName_, gds_collector_=gds_collector_)
1053
+ return self
1054
+ def buildAttributes(self, node, attrs, already_processed):
1055
+ pass
1056
+ def buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None):
1057
+ pass
1058
+ # end class char
1059
+
1060
+
1061
+ class duration(GeneratedsSuper):
1062
+ __hash__ = GeneratedsSuper.__hash__
1063
+ subclass = None
1064
+ superclass = None
1065
+ def __init__(self, valueOf_=None, gds_collector_=None, **kwargs_):
1066
+ self.gds_collector_ = gds_collector_
1067
+ self.gds_elementtree_node_ = None
1068
+ self.original_tagname_ = None
1069
+ self.parent_object_ = kwargs_.get('parent_object_')
1070
+ self.ns_prefix_ = None
1071
+ self.valueOf_ = valueOf_
1072
+ def factory(*args_, **kwargs_):
1073
+ if CurrentSubclassModule_ is not None:
1074
+ subclass = getSubclassFromModule_(
1075
+ CurrentSubclassModule_, duration)
1076
+ if subclass is not None:
1077
+ return subclass(*args_, **kwargs_)
1078
+ if duration.subclass:
1079
+ return duration.subclass(*args_, **kwargs_)
1080
+ else:
1081
+ return duration(*args_, **kwargs_)
1082
+ factory = staticmethod(factory)
1083
+ def get_ns_prefix_(self):
1084
+ return self.ns_prefix_
1085
+ def set_ns_prefix_(self, ns_prefix):
1086
+ self.ns_prefix_ = ns_prefix
1087
+ def get_valueOf_(self): return self.valueOf_
1088
+ def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_
1089
+ def validate_duration_impl(self, value):
1090
+ result = True
1091
+ # Validate type duration_impl, a restriction on xs:duration.
1092
+ if value is not None and Validate_simpletypes_ and self.gds_collector_ is not None:
1093
+ if not isinstance(value, str):
1094
+ lineno = self.gds_get_node_lineno_()
1095
+ self.gds_collector_.add_message('Value "%(value)s"%(lineno)s is not of the correct base simple type (str)' % {"value": value, "lineno": lineno, })
1096
+ return False
1097
+ if value < -P10675199DT2H48M5.4775808S:
1098
+ lineno = self.gds_get_node_lineno_()
1099
+ self.gds_collector_.add_message('Value "%(value)s"%(lineno)s does not match xsd minInclusive restriction on duration_impl' % {"value": value, "lineno": lineno} )
1100
+ result = False
1101
+ if value > P10675199DT2H48M5.4775807S:
1102
+ lineno = self.gds_get_node_lineno_()
1103
+ self.gds_collector_.add_message('Value "%(value)s"%(lineno)s does not match xsd maxInclusive restriction on duration_impl' % {"value": value, "lineno": lineno} )
1104
+ result = False
1105
+ if not self.gds_validate_simple_patterns(
1106
+ self.validate_duration_impl_patterns_, value):
1107
+ self.gds_collector_.add_message('Value "%s" does not match xsd pattern restrictions: %s' % (encode_str_2_3(value), self.validate_duration_impl_patterns_, ))
1108
+ result = False
1109
+ return result
1110
+ validate_duration_impl_patterns_ = [['^(\\-?P(\\d*D)?(T(\\d*H)?(\\d*M)?(\\d*(\\.\\d*)?S)?)?)$']]
1111
+ def hasContent_(self):
1112
+ if (
1113
+ (1 if type(self.valueOf_) in [int,float] else self.valueOf_)
1114
+ ):
1115
+ return True
1116
+ else:
1117
+ return False
1118
+ def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='duration', pretty_print=True):
1119
+ imported_ns_def_ = GenerateDSNamespaceDefs_.get('duration')
1120
+ if imported_ns_def_ is not None:
1121
+ namespacedef_ = imported_ns_def_
1122
+ if pretty_print:
1123
+ eol_ = '\n'
1124
+ else:
1125
+ eol_ = ''
1126
+ if self.original_tagname_ is not None and name_ == 'duration':
1127
+ name_ = self.original_tagname_
1128
+ if UseCapturedNS_ and self.ns_prefix_:
1129
+ namespaceprefix_ = self.ns_prefix_ + ':'
1130
+ showIndent(outfile, level, pretty_print)
1131
+ outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
1132
+ already_processed = set()
1133
+ self.exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='duration')
1134
+ if self.hasContent_():
1135
+ outfile.write('>')
1136
+ outfile.write(self.convert_unicode(self.valueOf_))
1137
+ self.exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='duration', pretty_print=pretty_print)
1138
+ outfile.write('</%s%s>%s' % (namespaceprefix_, name_, eol_))
1139
+ else:
1140
+ outfile.write('/>%s' % (eol_, ))
1141
+ def exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='duration'):
1142
+ pass
1143
+ def exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='duration', fromsubclass_=False, pretty_print=True):
1144
+ pass
1145
+ def build(self, node, gds_collector_=None):
1146
+ self.gds_collector_ = gds_collector_
1147
+ if SaveElementTreeNode:
1148
+ self.gds_elementtree_node_ = node
1149
+ already_processed = set()
1150
+ self.ns_prefix_ = node.prefix
1151
+ self.buildAttributes(node, node.attrib, already_processed)
1152
+ self.valueOf_ = get_all_text_(node)
1153
+ for child in node:
1154
+ nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
1155
+ self.buildChildren(child, node, nodeName_, gds_collector_=gds_collector_)
1156
+ return self
1157
+ def buildAttributes(self, node, attrs, already_processed):
1158
+ pass
1159
+ def buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None):
1160
+ pass
1161
+ # end class duration
1162
+
1163
+
1164
+ class guid(GeneratedsSuper):
1165
+ __hash__ = GeneratedsSuper.__hash__
1166
+ subclass = None
1167
+ superclass = None
1168
+ def __init__(self, valueOf_=None, gds_collector_=None, **kwargs_):
1169
+ self.gds_collector_ = gds_collector_
1170
+ self.gds_elementtree_node_ = None
1171
+ self.original_tagname_ = None
1172
+ self.parent_object_ = kwargs_.get('parent_object_')
1173
+ self.ns_prefix_ = None
1174
+ self.valueOf_ = valueOf_
1175
+ def factory(*args_, **kwargs_):
1176
+ if CurrentSubclassModule_ is not None:
1177
+ subclass = getSubclassFromModule_(
1178
+ CurrentSubclassModule_, guid)
1179
+ if subclass is not None:
1180
+ return subclass(*args_, **kwargs_)
1181
+ if guid.subclass:
1182
+ return guid.subclass(*args_, **kwargs_)
1183
+ else:
1184
+ return guid(*args_, **kwargs_)
1185
+ factory = staticmethod(factory)
1186
+ def get_ns_prefix_(self):
1187
+ return self.ns_prefix_
1188
+ def set_ns_prefix_(self, ns_prefix):
1189
+ self.ns_prefix_ = ns_prefix
1190
+ def get_valueOf_(self): return self.valueOf_
1191
+ def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_
1192
+ def validate_guid_impl(self, value):
1193
+ result = True
1194
+ # Validate type guid_impl, a restriction on xs:string.
1195
+ if value is not None and Validate_simpletypes_ and self.gds_collector_ is not None:
1196
+ if not isinstance(value, str):
1197
+ lineno = self.gds_get_node_lineno_()
1198
+ self.gds_collector_.add_message('Value "%(value)s"%(lineno)s is not of the correct base simple type (str)' % {"value": value, "lineno": lineno, })
1199
+ return False
1200
+ if not self.gds_validate_simple_patterns(
1201
+ self.validate_guid_impl_patterns_, value):
1202
+ self.gds_collector_.add_message('Value "%s" does not match xsd pattern restrictions: %s' % (encode_str_2_3(value), self.validate_guid_impl_patterns_, ))
1203
+ result = False
1204
+ return result
1205
+ validate_guid_impl_patterns_ = [['^([\\da-fA-F]{8}-[\\da-fA-F]{4}-[\\da-fA-F]{4}-[\\da-fA-F]{4}-[\\da-fA-F]{12})$']]
1206
+ def hasContent_(self):
1207
+ if (
1208
+ (1 if type(self.valueOf_) in [int,float] else self.valueOf_)
1209
+ ):
1210
+ return True
1211
+ else:
1212
+ return False
1213
+ def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='guid', pretty_print=True):
1214
+ imported_ns_def_ = GenerateDSNamespaceDefs_.get('guid')
1215
+ if imported_ns_def_ is not None:
1216
+ namespacedef_ = imported_ns_def_
1217
+ if pretty_print:
1218
+ eol_ = '\n'
1219
+ else:
1220
+ eol_ = ''
1221
+ if self.original_tagname_ is not None and name_ == 'guid':
1222
+ name_ = self.original_tagname_
1223
+ if UseCapturedNS_ and self.ns_prefix_:
1224
+ namespaceprefix_ = self.ns_prefix_ + ':'
1225
+ showIndent(outfile, level, pretty_print)
1226
+ outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
1227
+ already_processed = set()
1228
+ self.exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='guid')
1229
+ if self.hasContent_():
1230
+ outfile.write('>')
1231
+ outfile.write(self.convert_unicode(self.valueOf_))
1232
+ self.exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='guid', pretty_print=pretty_print)
1233
+ outfile.write('</%s%s>%s' % (namespaceprefix_, name_, eol_))
1234
+ else:
1235
+ outfile.write('/>%s' % (eol_, ))
1236
+ def exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='guid'):
1237
+ pass
1238
+ def exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='guid', fromsubclass_=False, pretty_print=True):
1239
+ pass
1240
+ def build(self, node, gds_collector_=None):
1241
+ self.gds_collector_ = gds_collector_
1242
+ if SaveElementTreeNode:
1243
+ self.gds_elementtree_node_ = node
1244
+ already_processed = set()
1245
+ self.ns_prefix_ = node.prefix
1246
+ self.buildAttributes(node, node.attrib, already_processed)
1247
+ self.valueOf_ = get_all_text_(node)
1248
+ for child in node:
1249
+ nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
1250
+ self.buildChildren(child, node, nodeName_, gds_collector_=gds_collector_)
1251
+ return self
1252
+ def buildAttributes(self, node, attrs, already_processed):
1253
+ pass
1254
+ def buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None):
1255
+ pass
1256
+ # end class guid
1257
+
1258
+
1259
+ GDSClassesMapping = {
1260
+ 'char': char,
1261
+ 'duration': duration,
1262
+ 'guid': guid,
1263
+ }
1264
+
1265
+
1266
+ USAGE_TEXT = """
1267
+ Usage: python <Parser>.py [ -s ] <in_xml_file>
1268
+ """
1269
+
1270
+
1271
+ def usage():
1272
+ print(USAGE_TEXT)
1273
+ sys.exit(1)
1274
+
1275
+
1276
+ def get_root_tag(node):
1277
+ tag = Tag_pattern_.match(node.tag).groups()[-1]
1278
+ rootClass = GDSClassesMapping.get(tag)
1279
+ if rootClass is None:
1280
+ rootClass = globals().get(tag)
1281
+ return tag, rootClass
1282
+
1283
+
1284
+ def get_required_ns_prefix_defs(rootNode):
1285
+ '''Get all name space prefix definitions required in this XML doc.
1286
+ Return a dictionary of definitions and a char string of definitions.
1287
+ '''
1288
+ nsmap = {
1289
+ prefix: uri
1290
+ for node in rootNode.iter()
1291
+ for (prefix, uri) in node.nsmap.items()
1292
+ if prefix is not None
1293
+ }
1294
+ namespacedefs = ' '.join([
1295
+ 'xmlns:{}="{}"'.format(prefix, uri)
1296
+ for prefix, uri in nsmap.items()
1297
+ ])
1298
+ return nsmap, namespacedefs
1299
+
1300
+
1301
+ def parse(inFileName, silence=False, print_warnings=True):
1302
+ global CapturedNsmap_
1303
+ gds_collector = GdsCollector_()
1304
+ parser = None
1305
+ doc = parsexml_(inFileName, parser)
1306
+ rootNode = doc.getroot()
1307
+ rootTag, rootClass = get_root_tag(rootNode)
1308
+ if rootClass is None:
1309
+ rootTag = 'xs_string'
1310
+ rootClass = xs_string
1311
+ rootObj = rootClass.factory()
1312
+ rootObj.build(rootNode, gds_collector_=gds_collector)
1313
+ CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode)
1314
+ if not SaveElementTreeNode:
1315
+ doc = None
1316
+ rootNode = None
1317
+ if not silence:
1318
+ sys.stdout.write('<?xml version="1.0" ?>\n')
1319
+ rootObj.export(
1320
+ sys.stdout, 0, name_=rootTag,
1321
+ namespacedef_=namespacedefs,
1322
+ pretty_print=True)
1323
+ if print_warnings and len(gds_collector.get_messages()) > 0:
1324
+ separator = ('-' * 50) + '\n'
1325
+ sys.stderr.write(separator)
1326
+ sys.stderr.write('----- Warnings -- count: {} -----\n'.format(
1327
+ len(gds_collector.get_messages()), ))
1328
+ gds_collector.write_messages(sys.stderr)
1329
+ sys.stderr.write(separator)
1330
+ return rootObj
1331
+
1332
+
1333
+ def parseEtree(inFileName, silence=False, print_warnings=True,
1334
+ mapping=None, nsmap=None):
1335
+ parser = None
1336
+ doc = parsexml_(inFileName, parser)
1337
+ gds_collector = GdsCollector_()
1338
+ rootNode = doc.getroot()
1339
+ rootTag, rootClass = get_root_tag(rootNode)
1340
+ if rootClass is None:
1341
+ rootTag = 'xs_string'
1342
+ rootClass = xs_string
1343
+ rootObj = rootClass.factory()
1344
+ rootObj.build(rootNode, gds_collector_=gds_collector)
1345
+ # Enable Python to collect the space used by the DOM.
1346
+ if mapping is None:
1347
+ mapping = {}
1348
+ rootElement = rootObj.to_etree(
1349
+ None, name_=rootTag, mapping_=mapping, nsmap_=nsmap)
1350
+ reverse_mapping = rootObj.gds_reverse_node_mapping(mapping)
1351
+ if not SaveElementTreeNode:
1352
+ doc = None
1353
+ rootNode = None
1354
+ if not silence:
1355
+ content = etree_.tostring(
1356
+ rootElement, pretty_print=True,
1357
+ xml_declaration=True, encoding="utf-8")
1358
+ sys.stdout.write(str(content))
1359
+ sys.stdout.write('\n')
1360
+ if print_warnings and len(gds_collector.get_messages()) > 0:
1361
+ separator = ('-' * 50) + '\n'
1362
+ sys.stderr.write(separator)
1363
+ sys.stderr.write('----- Warnings -- count: {} -----\n'.format(
1364
+ len(gds_collector.get_messages()), ))
1365
+ gds_collector.write_messages(sys.stderr)
1366
+ sys.stderr.write(separator)
1367
+ return rootObj, rootElement, mapping, reverse_mapping
1368
+
1369
+
1370
+ def parseString(inString, silence=False, print_warnings=True):
1371
+ '''Parse a string, create the object tree, and export it.
1372
+
1373
+ Arguments:
1374
+ - inString -- A string. This XML fragment should not start
1375
+ with an XML declaration containing an encoding.
1376
+ - silence -- A boolean. If False, export the object.
1377
+ Returns -- The root object in the tree.
1378
+ '''
1379
+ parser = None
1380
+ rootNode= parsexmlstring_(inString, parser)
1381
+ gds_collector = GdsCollector_()
1382
+ rootTag, rootClass = get_root_tag(rootNode)
1383
+ if rootClass is None:
1384
+ rootTag = 'xs_string'
1385
+ rootClass = xs_string
1386
+ rootObj = rootClass.factory()
1387
+ rootObj.build(rootNode, gds_collector_=gds_collector)
1388
+ if not SaveElementTreeNode:
1389
+ rootNode = None
1390
+ if not silence:
1391
+ sys.stdout.write('<?xml version="1.0" ?>\n')
1392
+ rootObj.export(
1393
+ sys.stdout, 0, name_=rootTag,
1394
+ namespacedef_='xmlns:tns="http://schemas.microsoft.com/2003/10/Serialization/"')
1395
+ if print_warnings and len(gds_collector.get_messages()) > 0:
1396
+ separator = ('-' * 50) + '\n'
1397
+ sys.stderr.write(separator)
1398
+ sys.stderr.write('----- Warnings -- count: {} -----\n'.format(
1399
+ len(gds_collector.get_messages()), ))
1400
+ gds_collector.write_messages(sys.stderr)
1401
+ sys.stderr.write(separator)
1402
+ return rootObj
1403
+
1404
+
1405
+ def parseLiteral(inFileName, silence=False, print_warnings=True):
1406
+ parser = None
1407
+ doc = parsexml_(inFileName, parser)
1408
+ gds_collector = GdsCollector_()
1409
+ rootNode = doc.getroot()
1410
+ rootTag, rootClass = get_root_tag(rootNode)
1411
+ if rootClass is None:
1412
+ rootTag = 'xs_string'
1413
+ rootClass = xs_string
1414
+ rootObj = rootClass.factory()
1415
+ rootObj.build(rootNode, gds_collector_=gds_collector)
1416
+ # Enable Python to collect the space used by the DOM.
1417
+ if not SaveElementTreeNode:
1418
+ doc = None
1419
+ rootNode = None
1420
+ if not silence:
1421
+ sys.stdout.write('#from datatypes import *\n\n')
1422
+ sys.stdout.write('import datatypes as model_\n\n')
1423
+ sys.stdout.write('rootObj = model_.rootClass(\n')
1424
+ rootObj.exportLiteral(sys.stdout, 0, name_=rootTag)
1425
+ sys.stdout.write(')\n')
1426
+ if print_warnings and len(gds_collector.get_messages()) > 0:
1427
+ separator = ('-' * 50) + '\n'
1428
+ sys.stderr.write(separator)
1429
+ sys.stderr.write('----- Warnings -- count: {} -----\n'.format(
1430
+ len(gds_collector.get_messages()), ))
1431
+ gds_collector.write_messages(sys.stderr)
1432
+ sys.stderr.write(separator)
1433
+ return rootObj
1434
+
1435
+
1436
+ def main():
1437
+ args = sys.argv[1:]
1438
+ if len(args) == 1:
1439
+ parse(args[0])
1440
+ else:
1441
+ usage()
1442
+
1443
+
1444
+ if __name__ == '__main__':
1445
+ #import pdb; pdb.set_trace()
1446
+ main()
1447
+
1448
+ RenameMappings_ = {
1449
+ }
1450
+
1451
+ #
1452
+ # Mapping of namespaces to types defined in them
1453
+ # and the file in which each is defined.
1454
+ # simpleTypes are marked "ST" and complexTypes "CT".
1455
+ NamespaceToDefMappings_ = {'http://schemas.microsoft.com/2003/10/Serialization/': [('char',
1456
+ './schemas/datatypes.xsd',
1457
+ 'ST'),
1458
+ ('duration',
1459
+ './schemas/datatypes.xsd',
1460
+ 'ST'),
1461
+ ('guid',
1462
+ './schemas/datatypes.xsd',
1463
+ 'ST')]}
1464
+
1465
+ __all__ = [
1466
+ "char",
1467
+ "duration",
1468
+ "guid"
1469
+ ]