karrio-canadapost 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.
Files changed (41) hide show
  1. karrio/mappers/canadapost/__init__.py +3 -0
  2. karrio/mappers/canadapost/mapper.py +88 -0
  3. karrio/mappers/canadapost/proxy.py +373 -0
  4. karrio/mappers/canadapost/settings.py +23 -0
  5. karrio/plugins/canadapost/__init__.py +23 -0
  6. karrio/providers/canadapost/__init__.py +25 -0
  7. karrio/providers/canadapost/error.py +42 -0
  8. karrio/providers/canadapost/manifest.py +127 -0
  9. karrio/providers/canadapost/pickup/__init__.py +3 -0
  10. karrio/providers/canadapost/pickup/cancel.py +33 -0
  11. karrio/providers/canadapost/pickup/create.py +217 -0
  12. karrio/providers/canadapost/pickup/update.py +55 -0
  13. karrio/providers/canadapost/rate.py +192 -0
  14. karrio/providers/canadapost/shipment/__init__.py +8 -0
  15. karrio/providers/canadapost/shipment/cancel.py +53 -0
  16. karrio/providers/canadapost/shipment/create.py +308 -0
  17. karrio/providers/canadapost/tracking.py +75 -0
  18. karrio/providers/canadapost/units.py +285 -0
  19. karrio/providers/canadapost/utils.py +92 -0
  20. karrio/schemas/canadapost/__init__.py +0 -0
  21. karrio/schemas/canadapost/authreturn.py +3389 -0
  22. karrio/schemas/canadapost/common.py +2037 -0
  23. karrio/schemas/canadapost/customerinfo.py +2307 -0
  24. karrio/schemas/canadapost/discovery.py +3016 -0
  25. karrio/schemas/canadapost/manifest.py +3704 -0
  26. karrio/schemas/canadapost/merchantregistration.py +1498 -0
  27. karrio/schemas/canadapost/messages.py +1431 -0
  28. karrio/schemas/canadapost/ncshipment.py +7231 -0
  29. karrio/schemas/canadapost/openreturn.py +2438 -0
  30. karrio/schemas/canadapost/pickup.py +1407 -0
  31. karrio/schemas/canadapost/pickuprequest.py +6794 -0
  32. karrio/schemas/canadapost/postoffice.py +2240 -0
  33. karrio/schemas/canadapost/rating.py +5308 -0
  34. karrio/schemas/canadapost/serviceinfo.py +1505 -0
  35. karrio/schemas/canadapost/shipment.py +9982 -0
  36. karrio/schemas/canadapost/track.py +3100 -0
  37. karrio_canadapost-2025.5rc1.dist-info/METADATA +44 -0
  38. karrio_canadapost-2025.5rc1.dist-info/RECORD +41 -0
  39. karrio_canadapost-2025.5rc1.dist-info/WHEEL +5 -0
  40. karrio_canadapost-2025.5rc1.dist-info/entry_points.txt +2 -0
  41. karrio_canadapost-2025.5rc1.dist-info/top_level.txt +3 -0
@@ -0,0 +1,1505 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ #
5
+ # Generated Sat Mar 16 02:19:33 2024 by generateDS.py version 2.43.3.
6
+ # Python 3.12.2 (main, Feb 28 2024, 21:12:07) [GCC 11.4.0]
7
+ #
8
+ # Command line options:
9
+ # ('--no-namespace-defs', '')
10
+ # ('-o', './karrio/schemas/canadapost/serviceinfo.py')
11
+ #
12
+ # Command line arguments:
13
+ # ./schemas/serviceinfo.xsd
14
+ #
15
+ # Command line:
16
+ # /home/kserver/Workspace/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./karrio/schemas/canadapost/serviceinfo.py" ./schemas/serviceinfo.xsd
17
+ #
18
+ # Current working directory (os.getcwd()):
19
+ # canadapost
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
+ class MessageType(str, Enum):
1008
+ SO='SO'
1009
+
1010
+
1011
+ #
1012
+ # Start data representation classes
1013
+ #
1014
+ class InfoMessagesType(GeneratedsSuper):
1015
+ __hash__ = GeneratedsSuper.__hash__
1016
+ subclass = None
1017
+ superclass = None
1018
+ def __init__(self, info_message=None, gds_collector_=None, **kwargs_):
1019
+ self.gds_collector_ = gds_collector_
1020
+ self.gds_elementtree_node_ = None
1021
+ self.original_tagname_ = None
1022
+ self.parent_object_ = kwargs_.get('parent_object_')
1023
+ self.ns_prefix_ = None
1024
+ if info_message is None:
1025
+ self.info_message = []
1026
+ else:
1027
+ self.info_message = info_message
1028
+ self.info_message_nsprefix_ = None
1029
+ def factory(*args_, **kwargs_):
1030
+ if CurrentSubclassModule_ is not None:
1031
+ subclass = getSubclassFromModule_(
1032
+ CurrentSubclassModule_, InfoMessagesType)
1033
+ if subclass is not None:
1034
+ return subclass(*args_, **kwargs_)
1035
+ if InfoMessagesType.subclass:
1036
+ return InfoMessagesType.subclass(*args_, **kwargs_)
1037
+ else:
1038
+ return InfoMessagesType(*args_, **kwargs_)
1039
+ factory = staticmethod(factory)
1040
+ def get_ns_prefix_(self):
1041
+ return self.ns_prefix_
1042
+ def set_ns_prefix_(self, ns_prefix):
1043
+ self.ns_prefix_ = ns_prefix
1044
+ def get_info_message(self):
1045
+ return self.info_message
1046
+ def set_info_message(self, info_message):
1047
+ self.info_message = info_message
1048
+ def add_info_message(self, value):
1049
+ self.info_message.append(value)
1050
+ def insert_info_message_at(self, index, value):
1051
+ self.info_message.insert(index, value)
1052
+ def replace_info_message_at(self, index, value):
1053
+ self.info_message[index] = value
1054
+ def has__content(self):
1055
+ if (
1056
+ self.info_message
1057
+ ):
1058
+ return True
1059
+ else:
1060
+ return False
1061
+ def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='InfoMessagesType', pretty_print=True):
1062
+ imported_ns_def_ = GenerateDSNamespaceDefs_.get('InfoMessagesType')
1063
+ if imported_ns_def_ is not None:
1064
+ namespacedef_ = imported_ns_def_
1065
+ if pretty_print:
1066
+ eol_ = '\n'
1067
+ else:
1068
+ eol_ = ''
1069
+ if self.original_tagname_ is not None and name_ == 'InfoMessagesType':
1070
+ name_ = self.original_tagname_
1071
+ if UseCapturedNS_ and self.ns_prefix_:
1072
+ namespaceprefix_ = self.ns_prefix_ + ':'
1073
+ showIndent(outfile, level, pretty_print)
1074
+ outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
1075
+ already_processed = set()
1076
+ self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='InfoMessagesType')
1077
+ if self.has__content():
1078
+ outfile.write('>%s' % (eol_, ))
1079
+ self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='InfoMessagesType', pretty_print=pretty_print)
1080
+ showIndent(outfile, level, pretty_print)
1081
+ outfile.write('</%s%s>%s' % (namespaceprefix_, name_, eol_))
1082
+ else:
1083
+ outfile.write('/>%s' % (eol_, ))
1084
+ def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='InfoMessagesType'):
1085
+ pass
1086
+ def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='InfoMessagesType', fromsubclass_=False, pretty_print=True):
1087
+ if pretty_print:
1088
+ eol_ = '\n'
1089
+ else:
1090
+ eol_ = ''
1091
+ for info_message_ in self.info_message:
1092
+ namespaceprefix_ = self.info_message_nsprefix_ + ':' if (UseCapturedNS_ and self.info_message_nsprefix_) else ''
1093
+ info_message_.export(outfile, level, namespaceprefix_, namespacedef_='', name_='info-message', pretty_print=pretty_print)
1094
+ def build(self, node, gds_collector_=None):
1095
+ self.gds_collector_ = gds_collector_
1096
+ if SaveElementTreeNode:
1097
+ self.gds_elementtree_node_ = node
1098
+ already_processed = set()
1099
+ self.ns_prefix_ = node.prefix
1100
+ self._buildAttributes(node, node.attrib, already_processed)
1101
+ for child in node:
1102
+ nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
1103
+ self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_)
1104
+ return self
1105
+ def _buildAttributes(self, node, attrs, already_processed):
1106
+ pass
1107
+ def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None):
1108
+ if nodeName_ == 'info-message':
1109
+ obj_ = InfoMessageType.factory(parent_object_=self)
1110
+ obj_.build(child_, gds_collector_=gds_collector_)
1111
+ self.info_message.append(obj_)
1112
+ obj_.original_tagname_ = 'info-message'
1113
+ # end class InfoMessagesType
1114
+
1115
+
1116
+ class InfoMessageType(GeneratedsSuper):
1117
+ __hash__ = GeneratedsSuper.__hash__
1118
+ subclass = None
1119
+ superclass = None
1120
+ def __init__(self, message_type=None, message_text=None, from_datetime=None, to_datetime=None, gds_collector_=None, **kwargs_):
1121
+ self.gds_collector_ = gds_collector_
1122
+ self.gds_elementtree_node_ = None
1123
+ self.original_tagname_ = None
1124
+ self.parent_object_ = kwargs_.get('parent_object_')
1125
+ self.ns_prefix_ = None
1126
+ self.message_type = message_type
1127
+ self.validate_MessageType(self.message_type)
1128
+ self.message_type_nsprefix_ = None
1129
+ self.message_text = message_text
1130
+ self.message_text_nsprefix_ = None
1131
+ if isinstance(from_datetime, BaseStrType_):
1132
+ initvalue_ = datetime_.datetime.strptime(from_datetime, '%Y-%m-%dT%H:%M:%S')
1133
+ else:
1134
+ initvalue_ = from_datetime
1135
+ self.from_datetime = initvalue_
1136
+ self.from_datetime_nsprefix_ = None
1137
+ if isinstance(to_datetime, BaseStrType_):
1138
+ initvalue_ = datetime_.datetime.strptime(to_datetime, '%Y-%m-%dT%H:%M:%S')
1139
+ else:
1140
+ initvalue_ = to_datetime
1141
+ self.to_datetime = initvalue_
1142
+ self.to_datetime_nsprefix_ = None
1143
+ def factory(*args_, **kwargs_):
1144
+ if CurrentSubclassModule_ is not None:
1145
+ subclass = getSubclassFromModule_(
1146
+ CurrentSubclassModule_, InfoMessageType)
1147
+ if subclass is not None:
1148
+ return subclass(*args_, **kwargs_)
1149
+ if InfoMessageType.subclass:
1150
+ return InfoMessageType.subclass(*args_, **kwargs_)
1151
+ else:
1152
+ return InfoMessageType(*args_, **kwargs_)
1153
+ factory = staticmethod(factory)
1154
+ def get_ns_prefix_(self):
1155
+ return self.ns_prefix_
1156
+ def set_ns_prefix_(self, ns_prefix):
1157
+ self.ns_prefix_ = ns_prefix
1158
+ def get_message_type(self):
1159
+ return self.message_type
1160
+ def set_message_type(self, message_type):
1161
+ self.message_type = message_type
1162
+ def get_message_text(self):
1163
+ return self.message_text
1164
+ def set_message_text(self, message_text):
1165
+ self.message_text = message_text
1166
+ def get_from_datetime(self):
1167
+ return self.from_datetime
1168
+ def set_from_datetime(self, from_datetime):
1169
+ self.from_datetime = from_datetime
1170
+ def get_to_datetime(self):
1171
+ return self.to_datetime
1172
+ def set_to_datetime(self, to_datetime):
1173
+ self.to_datetime = to_datetime
1174
+ def validate_MessageType(self, value):
1175
+ result = True
1176
+ # Validate type MessageType, a restriction on xsd:normalizedString.
1177
+ if value is not None and Validate_simpletypes_ and self.gds_collector_ is not None:
1178
+ if not isinstance(value, str):
1179
+ lineno = self.gds_get_node_lineno_()
1180
+ self.gds_collector_.add_message('Value "%(value)s"%(lineno)s is not of the correct base simple type (str)' % {"value": value, "lineno": lineno, })
1181
+ return False
1182
+ value = value
1183
+ enumerations = ['SO']
1184
+ if value not in enumerations:
1185
+ lineno = self.gds_get_node_lineno_()
1186
+ self.gds_collector_.add_message('Value "%(value)s"%(lineno)s does not match xsd enumeration restriction on MessageType' % {"value" : encode_str_2_3(value), "lineno": lineno} )
1187
+ result = False
1188
+ return result
1189
+ def has__content(self):
1190
+ if (
1191
+ self.message_type is not None or
1192
+ self.message_text is not None or
1193
+ self.from_datetime is not None or
1194
+ self.to_datetime is not None
1195
+ ):
1196
+ return True
1197
+ else:
1198
+ return False
1199
+ def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='InfoMessageType', pretty_print=True):
1200
+ imported_ns_def_ = GenerateDSNamespaceDefs_.get('InfoMessageType')
1201
+ if imported_ns_def_ is not None:
1202
+ namespacedef_ = imported_ns_def_
1203
+ if pretty_print:
1204
+ eol_ = '\n'
1205
+ else:
1206
+ eol_ = ''
1207
+ if self.original_tagname_ is not None and name_ == 'InfoMessageType':
1208
+ name_ = self.original_tagname_
1209
+ if UseCapturedNS_ and self.ns_prefix_:
1210
+ namespaceprefix_ = self.ns_prefix_ + ':'
1211
+ showIndent(outfile, level, pretty_print)
1212
+ outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
1213
+ already_processed = set()
1214
+ self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='InfoMessageType')
1215
+ if self.has__content():
1216
+ outfile.write('>%s' % (eol_, ))
1217
+ self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='InfoMessageType', pretty_print=pretty_print)
1218
+ showIndent(outfile, level, pretty_print)
1219
+ outfile.write('</%s%s>%s' % (namespaceprefix_, name_, eol_))
1220
+ else:
1221
+ outfile.write('/>%s' % (eol_, ))
1222
+ def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='InfoMessageType'):
1223
+ pass
1224
+ def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='InfoMessageType', fromsubclass_=False, pretty_print=True):
1225
+ if pretty_print:
1226
+ eol_ = '\n'
1227
+ else:
1228
+ eol_ = ''
1229
+ if self.message_type is not None:
1230
+ namespaceprefix_ = self.message_type_nsprefix_ + ':' if (UseCapturedNS_ and self.message_type_nsprefix_) else ''
1231
+ showIndent(outfile, level, pretty_print)
1232
+ outfile.write('<%smessage-type>%s</%smessage-type>%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.message_type), input_name='message-type')), namespaceprefix_ , eol_))
1233
+ if self.message_text is not None:
1234
+ namespaceprefix_ = self.message_text_nsprefix_ + ':' if (UseCapturedNS_ and self.message_text_nsprefix_) else ''
1235
+ showIndent(outfile, level, pretty_print)
1236
+ outfile.write('<%smessage-text>%s</%smessage-text>%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.message_text), input_name='message-text')), namespaceprefix_ , eol_))
1237
+ if self.from_datetime is not None:
1238
+ namespaceprefix_ = self.from_datetime_nsprefix_ + ':' if (UseCapturedNS_ and self.from_datetime_nsprefix_) else ''
1239
+ showIndent(outfile, level, pretty_print)
1240
+ outfile.write('<%sfrom-datetime>%s</%sfrom-datetime>%s' % (namespaceprefix_ , self.gds_format_datetime(self.from_datetime, input_name='from-datetime'), namespaceprefix_ , eol_))
1241
+ if self.to_datetime is not None:
1242
+ namespaceprefix_ = self.to_datetime_nsprefix_ + ':' if (UseCapturedNS_ and self.to_datetime_nsprefix_) else ''
1243
+ showIndent(outfile, level, pretty_print)
1244
+ outfile.write('<%sto-datetime>%s</%sto-datetime>%s' % (namespaceprefix_ , self.gds_format_datetime(self.to_datetime, input_name='to-datetime'), namespaceprefix_ , eol_))
1245
+ def build(self, node, gds_collector_=None):
1246
+ self.gds_collector_ = gds_collector_
1247
+ if SaveElementTreeNode:
1248
+ self.gds_elementtree_node_ = node
1249
+ already_processed = set()
1250
+ self.ns_prefix_ = node.prefix
1251
+ self._buildAttributes(node, node.attrib, already_processed)
1252
+ for child in node:
1253
+ nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
1254
+ self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_)
1255
+ return self
1256
+ def _buildAttributes(self, node, attrs, already_processed):
1257
+ pass
1258
+ def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None):
1259
+ if nodeName_ == 'message-type':
1260
+ value_ = child_.text
1261
+ value_ = self.gds_parse_string(value_, node, 'message_type')
1262
+ value_ = self.gds_validate_string(value_, node, 'message_type')
1263
+ self.message_type = value_
1264
+ self.message_type_nsprefix_ = child_.prefix
1265
+ # validate type MessageType
1266
+ self.validate_MessageType(self.message_type)
1267
+ elif nodeName_ == 'message-text':
1268
+ value_ = child_.text
1269
+ if value_:
1270
+ value_ = re_.sub(String_cleanup_pat_, " ", value_).strip()
1271
+ else:
1272
+ value_ = ""
1273
+ value_ = self.gds_parse_string(value_, node, 'message_text')
1274
+ value_ = self.gds_validate_string(value_, node, 'message_text')
1275
+ self.message_text = value_
1276
+ self.message_text_nsprefix_ = child_.prefix
1277
+ elif nodeName_ == 'from-datetime':
1278
+ sval_ = child_.text
1279
+ dval_ = self.gds_parse_datetime(sval_)
1280
+ self.from_datetime = dval_
1281
+ self.from_datetime_nsprefix_ = child_.prefix
1282
+ elif nodeName_ == 'to-datetime':
1283
+ sval_ = child_.text
1284
+ dval_ = self.gds_parse_datetime(sval_)
1285
+ self.to_datetime = dval_
1286
+ self.to_datetime_nsprefix_ = child_.prefix
1287
+ # end class InfoMessageType
1288
+
1289
+
1290
+ #
1291
+ # End data representation classes.
1292
+ #
1293
+
1294
+
1295
+ GDSClassesMapping = {
1296
+ }
1297
+
1298
+
1299
+ USAGE_TEXT = """
1300
+ Usage: python <Parser>.py [ -s ] <in_xml_file>
1301
+ """
1302
+
1303
+
1304
+ def usage():
1305
+ print(USAGE_TEXT)
1306
+ sys.exit(1)
1307
+
1308
+
1309
+ def get_root_tag(node):
1310
+ tag = Tag_pattern_.match(node.tag).groups()[-1]
1311
+ prefix_tag = TagNamePrefix + tag
1312
+ rootClass = GDSClassesMapping.get(prefix_tag)
1313
+ if rootClass is None:
1314
+ rootClass = globals().get(prefix_tag)
1315
+ return tag, rootClass
1316
+
1317
+
1318
+ def get_required_ns_prefix_defs(rootNode):
1319
+ '''Get all name space prefix definitions required in this XML doc.
1320
+ Return a dictionary of definitions and a char string of definitions.
1321
+ '''
1322
+ nsmap = {
1323
+ prefix: uri
1324
+ for node in rootNode.iter()
1325
+ for (prefix, uri) in node.nsmap.items()
1326
+ if prefix is not None
1327
+ }
1328
+ namespacedefs = ' '.join([
1329
+ 'xmlns:{}="{}"'.format(prefix, uri)
1330
+ for prefix, uri in nsmap.items()
1331
+ ])
1332
+ return nsmap, namespacedefs
1333
+
1334
+
1335
+ def parse(inFileName, silence=False, print_warnings=True):
1336
+ global CapturedNsmap_
1337
+ gds_collector = GdsCollector_()
1338
+ parser = None
1339
+ doc = parsexml_(inFileName, parser)
1340
+ rootNode = doc.getroot()
1341
+ rootTag, rootClass = get_root_tag(rootNode)
1342
+ if rootClass is None:
1343
+ rootTag = 'InfoMessagesType'
1344
+ rootClass = InfoMessagesType
1345
+ rootObj = rootClass.factory()
1346
+ rootObj.build(rootNode, gds_collector_=gds_collector)
1347
+ CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode)
1348
+ if not SaveElementTreeNode:
1349
+ doc = None
1350
+ rootNode = None
1351
+ if not silence:
1352
+ sys.stdout.write('<?xml version="1.0" ?>\n')
1353
+ rootObj.export(
1354
+ sys.stdout, 0, name_=rootTag,
1355
+ namespacedef_=namespacedefs,
1356
+ pretty_print=True)
1357
+ if print_warnings and len(gds_collector.get_messages()) > 0:
1358
+ separator = ('-' * 50) + '\n'
1359
+ sys.stderr.write(separator)
1360
+ sys.stderr.write('----- Warnings -- count: {} -----\n'.format(
1361
+ len(gds_collector.get_messages()), ))
1362
+ gds_collector.write_messages(sys.stderr)
1363
+ sys.stderr.write(separator)
1364
+ return rootObj
1365
+
1366
+
1367
+ def parseEtree(inFileName, silence=False, print_warnings=True,
1368
+ mapping=None, reverse_mapping=None, nsmap=None):
1369
+ parser = None
1370
+ doc = parsexml_(inFileName, parser)
1371
+ gds_collector = GdsCollector_()
1372
+ rootNode = doc.getroot()
1373
+ rootTag, rootClass = get_root_tag(rootNode)
1374
+ if rootClass is None:
1375
+ rootTag = 'InfoMessagesType'
1376
+ rootClass = InfoMessagesType
1377
+ rootObj = rootClass.factory()
1378
+ rootObj.build(rootNode, gds_collector_=gds_collector)
1379
+ if mapping is None:
1380
+ mapping = {}
1381
+ if reverse_mapping is None:
1382
+ reverse_mapping = {}
1383
+ rootElement = rootObj.to_etree(
1384
+ None, name_=rootTag, mapping_=mapping,
1385
+ reverse_mapping_=reverse_mapping, nsmap_=nsmap)
1386
+ reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping)
1387
+ # Enable Python to collect the space used by the DOM.
1388
+ if not SaveElementTreeNode:
1389
+ doc = None
1390
+ rootNode = None
1391
+ if not silence:
1392
+ content = etree_.tostring(
1393
+ rootElement, pretty_print=True,
1394
+ xml_declaration=True, encoding="utf-8")
1395
+ sys.stdout.write(str(content))
1396
+ sys.stdout.write('\n')
1397
+ if print_warnings and len(gds_collector.get_messages()) > 0:
1398
+ separator = ('-' * 50) + '\n'
1399
+ sys.stderr.write(separator)
1400
+ sys.stderr.write('----- Warnings -- count: {} -----\n'.format(
1401
+ len(gds_collector.get_messages()), ))
1402
+ gds_collector.write_messages(sys.stderr)
1403
+ sys.stderr.write(separator)
1404
+ return rootObj, rootElement, mapping, reverse_node_mapping
1405
+
1406
+
1407
+ def parseString(inString, silence=False, print_warnings=True):
1408
+ '''Parse a string, create the object tree, and export it.
1409
+
1410
+ Arguments:
1411
+ - inString -- A string. This XML fragment should not start
1412
+ with an XML declaration containing an encoding.
1413
+ - silence -- A boolean. If False, export the object.
1414
+ Returns -- The root object in the tree.
1415
+ '''
1416
+ parser = None
1417
+ rootNode= parsexmlstring_(inString, parser)
1418
+ gds_collector = GdsCollector_()
1419
+ rootTag, rootClass = get_root_tag(rootNode)
1420
+ if rootClass is None:
1421
+ rootTag = 'InfoMessagesType'
1422
+ rootClass = InfoMessagesType
1423
+ rootObj = rootClass.factory()
1424
+ rootObj.build(rootNode, gds_collector_=gds_collector)
1425
+ if not SaveElementTreeNode:
1426
+ rootNode = None
1427
+ if not silence:
1428
+ sys.stdout.write('<?xml version="1.0" ?>\n')
1429
+ rootObj.export(
1430
+ sys.stdout, 0, name_=rootTag,
1431
+ namespacedef_='')
1432
+ if print_warnings and len(gds_collector.get_messages()) > 0:
1433
+ separator = ('-' * 50) + '\n'
1434
+ sys.stderr.write(separator)
1435
+ sys.stderr.write('----- Warnings -- count: {} -----\n'.format(
1436
+ len(gds_collector.get_messages()), ))
1437
+ gds_collector.write_messages(sys.stderr)
1438
+ sys.stderr.write(separator)
1439
+ return rootObj
1440
+
1441
+
1442
+ def parseLiteral(inFileName, silence=False, print_warnings=True):
1443
+ parser = None
1444
+ doc = parsexml_(inFileName, parser)
1445
+ gds_collector = GdsCollector_()
1446
+ rootNode = doc.getroot()
1447
+ rootTag, rootClass = get_root_tag(rootNode)
1448
+ if rootClass is None:
1449
+ rootTag = 'InfoMessagesType'
1450
+ rootClass = InfoMessagesType
1451
+ rootObj = rootClass.factory()
1452
+ rootObj.build(rootNode, gds_collector_=gds_collector)
1453
+ # Enable Python to collect the space used by the DOM.
1454
+ if not SaveElementTreeNode:
1455
+ doc = None
1456
+ rootNode = None
1457
+ if not silence:
1458
+ sys.stdout.write('#from serviceinfo import *\n\n')
1459
+ sys.stdout.write('import serviceinfo as model_\n\n')
1460
+ sys.stdout.write('rootObj = model_.rootClass(\n')
1461
+ rootObj.exportLiteral(sys.stdout, 0, name_=rootTag)
1462
+ sys.stdout.write(')\n')
1463
+ if print_warnings and len(gds_collector.get_messages()) > 0:
1464
+ separator = ('-' * 50) + '\n'
1465
+ sys.stderr.write(separator)
1466
+ sys.stderr.write('----- Warnings -- count: {} -----\n'.format(
1467
+ len(gds_collector.get_messages()), ))
1468
+ gds_collector.write_messages(sys.stderr)
1469
+ sys.stderr.write(separator)
1470
+ return rootObj
1471
+
1472
+
1473
+ def main():
1474
+ args = sys.argv[1:]
1475
+ if len(args) == 1:
1476
+ parse(args[0])
1477
+ else:
1478
+ usage()
1479
+
1480
+
1481
+ if __name__ == '__main__':
1482
+ #import pdb; pdb.set_trace()
1483
+ main()
1484
+
1485
+ RenameMappings_ = {
1486
+ }
1487
+
1488
+ #
1489
+ # Mapping of namespaces to types defined in them
1490
+ # and the file in which each is defined.
1491
+ # simpleTypes are marked "ST" and complexTypes "CT".
1492
+ NamespaceToDefMappings_ = {'http://www.canadapost.ca/ws/serviceinfo-v2': [('MessageType',
1493
+ './schemas/serviceinfo.xsd',
1494
+ 'ST'),
1495
+ ('InfoMessagesType',
1496
+ './schemas/serviceinfo.xsd',
1497
+ 'CT'),
1498
+ ('InfoMessageType',
1499
+ './schemas/serviceinfo.xsd',
1500
+ 'CT')]}
1501
+
1502
+ __all__ = [
1503
+ "InfoMessageType",
1504
+ "InfoMessagesType"
1505
+ ]