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