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,1498 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ #
5
+ # Generated Sat Mar 16 02:19:30 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/merchantregistration.py')
11
+ #
12
+ # Command line arguments:
13
+ # ./schemas/merchantregistration.xsd
14
+ #
15
+ # Command line:
16
+ # /home/kserver/Workspace/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./karrio/schemas/canadapost/merchantregistration.py" ./schemas/merchantregistration.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
+ #
1008
+ # Start data representation classes
1009
+ #
1010
+ class merchant_info(GeneratedsSuper):
1011
+ __hash__ = GeneratedsSuper.__hash__
1012
+ subclass = None
1013
+ superclass = None
1014
+ def __init__(self, customer_number=None, contract_number=None, merchant_username=None, merchant_password=None, has_default_credit_card=None, gds_collector_=None, **kwargs_):
1015
+ self.gds_collector_ = gds_collector_
1016
+ self.gds_elementtree_node_ = None
1017
+ self.original_tagname_ = None
1018
+ self.parent_object_ = kwargs_.get('parent_object_')
1019
+ self.ns_prefix_ = None
1020
+ self.customer_number = customer_number
1021
+ self.customer_number_nsprefix_ = None
1022
+ self.contract_number = contract_number
1023
+ self.contract_number_nsprefix_ = None
1024
+ self.merchant_username = merchant_username
1025
+ self.merchant_username_nsprefix_ = None
1026
+ self.merchant_password = merchant_password
1027
+ self.merchant_password_nsprefix_ = None
1028
+ self.has_default_credit_card = has_default_credit_card
1029
+ self.has_default_credit_card_nsprefix_ = None
1030
+ def factory(*args_, **kwargs_):
1031
+ if CurrentSubclassModule_ is not None:
1032
+ subclass = getSubclassFromModule_(
1033
+ CurrentSubclassModule_, merchant_info)
1034
+ if subclass is not None:
1035
+ return subclass(*args_, **kwargs_)
1036
+ if merchant_info.subclass:
1037
+ return merchant_info.subclass(*args_, **kwargs_)
1038
+ else:
1039
+ return merchant_info(*args_, **kwargs_)
1040
+ factory = staticmethod(factory)
1041
+ def get_ns_prefix_(self):
1042
+ return self.ns_prefix_
1043
+ def set_ns_prefix_(self, ns_prefix):
1044
+ self.ns_prefix_ = ns_prefix
1045
+ def get_customer_number(self):
1046
+ return self.customer_number
1047
+ def set_customer_number(self, customer_number):
1048
+ self.customer_number = customer_number
1049
+ def get_contract_number(self):
1050
+ return self.contract_number
1051
+ def set_contract_number(self, contract_number):
1052
+ self.contract_number = contract_number
1053
+ def get_merchant_username(self):
1054
+ return self.merchant_username
1055
+ def set_merchant_username(self, merchant_username):
1056
+ self.merchant_username = merchant_username
1057
+ def get_merchant_password(self):
1058
+ return self.merchant_password
1059
+ def set_merchant_password(self, merchant_password):
1060
+ self.merchant_password = merchant_password
1061
+ def get_has_default_credit_card(self):
1062
+ return self.has_default_credit_card
1063
+ def set_has_default_credit_card(self, has_default_credit_card):
1064
+ self.has_default_credit_card = has_default_credit_card
1065
+ def has__content(self):
1066
+ if (
1067
+ self.customer_number is not None or
1068
+ self.contract_number is not None or
1069
+ self.merchant_username is not None or
1070
+ self.merchant_password is not None or
1071
+ self.has_default_credit_card is not None
1072
+ ):
1073
+ return True
1074
+ else:
1075
+ return False
1076
+ def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='merchant-info', pretty_print=True):
1077
+ imported_ns_def_ = GenerateDSNamespaceDefs_.get('merchant-info')
1078
+ if imported_ns_def_ is not None:
1079
+ namespacedef_ = imported_ns_def_
1080
+ if pretty_print:
1081
+ eol_ = '\n'
1082
+ else:
1083
+ eol_ = ''
1084
+ if self.original_tagname_ is not None and name_ == 'merchant-info':
1085
+ name_ = self.original_tagname_
1086
+ if UseCapturedNS_ and self.ns_prefix_:
1087
+ namespaceprefix_ = self.ns_prefix_ + ':'
1088
+ showIndent(outfile, level, pretty_print)
1089
+ outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
1090
+ already_processed = set()
1091
+ self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='merchant-info')
1092
+ if self.has__content():
1093
+ outfile.write('>%s' % (eol_, ))
1094
+ self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='merchant-info', pretty_print=pretty_print)
1095
+ showIndent(outfile, level, pretty_print)
1096
+ outfile.write('</%s%s>%s' % (namespaceprefix_, name_, eol_))
1097
+ else:
1098
+ outfile.write('/>%s' % (eol_, ))
1099
+ def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='merchant-info'):
1100
+ pass
1101
+ def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='merchant-info', fromsubclass_=False, pretty_print=True):
1102
+ if pretty_print:
1103
+ eol_ = '\n'
1104
+ else:
1105
+ eol_ = ''
1106
+ if self.customer_number is not None:
1107
+ namespaceprefix_ = self.customer_number_nsprefix_ + ':' if (UseCapturedNS_ and self.customer_number_nsprefix_) else ''
1108
+ showIndent(outfile, level, pretty_print)
1109
+ outfile.write('<%scustomer-number>%s</%scustomer-number>%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.customer_number), input_name='customer-number')), namespaceprefix_ , eol_))
1110
+ if self.contract_number is not None:
1111
+ namespaceprefix_ = self.contract_number_nsprefix_ + ':' if (UseCapturedNS_ and self.contract_number_nsprefix_) else ''
1112
+ showIndent(outfile, level, pretty_print)
1113
+ outfile.write('<%scontract-number>%s</%scontract-number>%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.contract_number), input_name='contract-number')), namespaceprefix_ , eol_))
1114
+ if self.merchant_username is not None:
1115
+ namespaceprefix_ = self.merchant_username_nsprefix_ + ':' if (UseCapturedNS_ and self.merchant_username_nsprefix_) else ''
1116
+ showIndent(outfile, level, pretty_print)
1117
+ outfile.write('<%smerchant-username>%s</%smerchant-username>%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.merchant_username), input_name='merchant-username')), namespaceprefix_ , eol_))
1118
+ if self.merchant_password is not None:
1119
+ namespaceprefix_ = self.merchant_password_nsprefix_ + ':' if (UseCapturedNS_ and self.merchant_password_nsprefix_) else ''
1120
+ showIndent(outfile, level, pretty_print)
1121
+ outfile.write('<%smerchant-password>%s</%smerchant-password>%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.merchant_password), input_name='merchant-password')), namespaceprefix_ , eol_))
1122
+ if self.has_default_credit_card is not None:
1123
+ namespaceprefix_ = self.has_default_credit_card_nsprefix_ + ':' if (UseCapturedNS_ and self.has_default_credit_card_nsprefix_) else ''
1124
+ showIndent(outfile, level, pretty_print)
1125
+ outfile.write('<%shas-default-credit-card>%s</%shas-default-credit-card>%s' % (namespaceprefix_ , self.gds_format_boolean(self.has_default_credit_card, input_name='has-default-credit-card'), namespaceprefix_ , eol_))
1126
+ def build(self, node, gds_collector_=None):
1127
+ self.gds_collector_ = gds_collector_
1128
+ if SaveElementTreeNode:
1129
+ self.gds_elementtree_node_ = node
1130
+ already_processed = set()
1131
+ self.ns_prefix_ = node.prefix
1132
+ self._buildAttributes(node, node.attrib, already_processed)
1133
+ for child in node:
1134
+ nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
1135
+ self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_)
1136
+ return self
1137
+ def _buildAttributes(self, node, attrs, already_processed):
1138
+ pass
1139
+ def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None):
1140
+ if nodeName_ == 'customer-number':
1141
+ value_ = child_.text
1142
+ value_ = self.gds_parse_string(value_, node, 'customer_number')
1143
+ value_ = self.gds_validate_string(value_, node, 'customer_number')
1144
+ self.customer_number = value_
1145
+ self.customer_number_nsprefix_ = child_.prefix
1146
+ elif nodeName_ == 'contract-number':
1147
+ value_ = child_.text
1148
+ value_ = self.gds_parse_string(value_, node, 'contract_number')
1149
+ value_ = self.gds_validate_string(value_, node, 'contract_number')
1150
+ self.contract_number = value_
1151
+ self.contract_number_nsprefix_ = child_.prefix
1152
+ elif nodeName_ == 'merchant-username':
1153
+ value_ = child_.text
1154
+ value_ = self.gds_parse_string(value_, node, 'merchant_username')
1155
+ value_ = self.gds_validate_string(value_, node, 'merchant_username')
1156
+ self.merchant_username = value_
1157
+ self.merchant_username_nsprefix_ = child_.prefix
1158
+ elif nodeName_ == 'merchant-password':
1159
+ value_ = child_.text
1160
+ value_ = self.gds_parse_string(value_, node, 'merchant_password')
1161
+ value_ = self.gds_validate_string(value_, node, 'merchant_password')
1162
+ self.merchant_password = value_
1163
+ self.merchant_password_nsprefix_ = child_.prefix
1164
+ elif nodeName_ == 'has-default-credit-card':
1165
+ sval_ = child_.text
1166
+ ival_ = self.gds_parse_boolean(sval_, node, 'has_default_credit_card')
1167
+ ival_ = self.gds_validate_boolean(ival_, node, 'has_default_credit_card')
1168
+ self.has_default_credit_card = ival_
1169
+ self.has_default_credit_card_nsprefix_ = child_.prefix
1170
+ # end class merchant_info
1171
+
1172
+
1173
+ class token(GeneratedsSuper):
1174
+ __hash__ = GeneratedsSuper.__hash__
1175
+ subclass = None
1176
+ superclass = None
1177
+ def __init__(self, token_id=None, valueOf_=None, gds_collector_=None, **kwargs_):
1178
+ self.gds_collector_ = gds_collector_
1179
+ self.gds_elementtree_node_ = None
1180
+ self.original_tagname_ = None
1181
+ self.parent_object_ = kwargs_.get('parent_object_')
1182
+ self.ns_prefix_ = None
1183
+ self.token_id = token_id
1184
+ self.validate_TokenIDType(self.token_id)
1185
+ self.token_id_nsprefix_ = None
1186
+ self.valueOf_ = valueOf_
1187
+ def factory(*args_, **kwargs_):
1188
+ if CurrentSubclassModule_ is not None:
1189
+ subclass = getSubclassFromModule_(
1190
+ CurrentSubclassModule_, token)
1191
+ if subclass is not None:
1192
+ return subclass(*args_, **kwargs_)
1193
+ if token.subclass:
1194
+ return token.subclass(*args_, **kwargs_)
1195
+ else:
1196
+ return token(*args_, **kwargs_)
1197
+ factory = staticmethod(factory)
1198
+ def get_ns_prefix_(self):
1199
+ return self.ns_prefix_
1200
+ def set_ns_prefix_(self, ns_prefix):
1201
+ self.ns_prefix_ = ns_prefix
1202
+ def get_token_id(self):
1203
+ return self.token_id
1204
+ def set_token_id(self, token_id):
1205
+ self.token_id = token_id
1206
+ def validate_TokenIDType(self, value):
1207
+ result = True
1208
+ # Validate type TokenIDType, a restriction on xsd:string.
1209
+ if value is not None and Validate_simpletypes_ and self.gds_collector_ is not None:
1210
+ if not isinstance(value, str):
1211
+ lineno = self.gds_get_node_lineno_()
1212
+ self.gds_collector_.add_message('Value "%(value)s"%(lineno)s is not of the correct base simple type (str)' % {"value": value, "lineno": lineno, })
1213
+ return False
1214
+ if len(value) > 40:
1215
+ lineno = self.gds_get_node_lineno_()
1216
+ self.gds_collector_.add_message('Value "%(value)s"%(lineno)s does not match xsd maxLength restriction on TokenIDType' % {"value" : encode_str_2_3(value), "lineno": lineno} )
1217
+ result = False
1218
+ if len(value) < 1:
1219
+ lineno = self.gds_get_node_lineno_()
1220
+ self.gds_collector_.add_message('Value "%(value)s"%(lineno)s does not match xsd minLength restriction on TokenIDType' % {"value" : encode_str_2_3(value), "lineno": lineno} )
1221
+ result = False
1222
+ return result
1223
+ def has__content(self):
1224
+ if (
1225
+ self.token_id is not None
1226
+ ):
1227
+ return True
1228
+ else:
1229
+ return False
1230
+ def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='token', pretty_print=True):
1231
+ imported_ns_def_ = GenerateDSNamespaceDefs_.get('token')
1232
+ if imported_ns_def_ is not None:
1233
+ namespacedef_ = imported_ns_def_
1234
+ if pretty_print:
1235
+ eol_ = '\n'
1236
+ else:
1237
+ eol_ = ''
1238
+ if self.original_tagname_ is not None and name_ == 'token':
1239
+ name_ = self.original_tagname_
1240
+ if UseCapturedNS_ and self.ns_prefix_:
1241
+ namespaceprefix_ = self.ns_prefix_ + ':'
1242
+ showIndent(outfile, level, pretty_print)
1243
+ outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
1244
+ already_processed = set()
1245
+ self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='token')
1246
+ if self.has__content():
1247
+ outfile.write('>%s' % (eol_, ))
1248
+ self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='token', pretty_print=pretty_print)
1249
+ showIndent(outfile, level, pretty_print)
1250
+ outfile.write('</%s%s>%s' % (namespaceprefix_, name_, eol_))
1251
+ else:
1252
+ outfile.write('/>%s' % (eol_, ))
1253
+ def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='token'):
1254
+ pass
1255
+ def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='token', fromsubclass_=False, pretty_print=True):
1256
+ if pretty_print:
1257
+ eol_ = '\n'
1258
+ else:
1259
+ eol_ = ''
1260
+ if self.token_id is not None:
1261
+ namespaceprefix_ = self.token_id_nsprefix_ + ':' if (UseCapturedNS_ and self.token_id_nsprefix_) else ''
1262
+ showIndent(outfile, level, pretty_print)
1263
+ outfile.write('<%stoken-id>%s</%stoken-id>%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.token_id), input_name='token-id')), namespaceprefix_ , eol_))
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_ == 'token-id':
1279
+ value_ = child_.text
1280
+ value_ = self.gds_parse_string(value_, node, 'token_id')
1281
+ value_ = self.gds_validate_string(value_, node, 'token_id')
1282
+ self.token_id = value_
1283
+ self.token_id_nsprefix_ = child_.prefix
1284
+ # validate type TokenIDType
1285
+ self.validate_TokenIDType(self.token_id)
1286
+ # end class token
1287
+
1288
+
1289
+ #
1290
+ # End data representation classes.
1291
+ #
1292
+
1293
+
1294
+ GDSClassesMapping = {
1295
+ }
1296
+
1297
+
1298
+ USAGE_TEXT = """
1299
+ Usage: python <Parser>.py [ -s ] <in_xml_file>
1300
+ """
1301
+
1302
+
1303
+ def usage():
1304
+ print(USAGE_TEXT)
1305
+ sys.exit(1)
1306
+
1307
+
1308
+ def get_root_tag(node):
1309
+ tag = Tag_pattern_.match(node.tag).groups()[-1]
1310
+ prefix_tag = TagNamePrefix + tag
1311
+ rootClass = GDSClassesMapping.get(prefix_tag)
1312
+ if rootClass is None:
1313
+ rootClass = globals().get(prefix_tag)
1314
+ return tag, rootClass
1315
+
1316
+
1317
+ def get_required_ns_prefix_defs(rootNode):
1318
+ '''Get all name space prefix definitions required in this XML doc.
1319
+ Return a dictionary of definitions and a char string of definitions.
1320
+ '''
1321
+ nsmap = {
1322
+ prefix: uri
1323
+ for node in rootNode.iter()
1324
+ for (prefix, uri) in node.nsmap.items()
1325
+ if prefix is not None
1326
+ }
1327
+ namespacedefs = ' '.join([
1328
+ 'xmlns:{}="{}"'.format(prefix, uri)
1329
+ for prefix, uri in nsmap.items()
1330
+ ])
1331
+ return nsmap, namespacedefs
1332
+
1333
+
1334
+ def parse(inFileName, silence=False, print_warnings=True):
1335
+ global CapturedNsmap_
1336
+ gds_collector = GdsCollector_()
1337
+ parser = None
1338
+ doc = parsexml_(inFileName, parser)
1339
+ rootNode = doc.getroot()
1340
+ rootTag, rootClass = get_root_tag(rootNode)
1341
+ if rootClass is None:
1342
+ rootTag = 'merchant_info'
1343
+ rootClass = merchant_info
1344
+ rootObj = rootClass.factory()
1345
+ rootObj.build(rootNode, gds_collector_=gds_collector)
1346
+ CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode)
1347
+ if not SaveElementTreeNode:
1348
+ doc = None
1349
+ rootNode = None
1350
+ if not silence:
1351
+ sys.stdout.write('<?xml version="1.0" ?>\n')
1352
+ rootObj.export(
1353
+ sys.stdout, 0, name_=rootTag,
1354
+ namespacedef_=namespacedefs,
1355
+ pretty_print=True)
1356
+ if print_warnings and len(gds_collector.get_messages()) > 0:
1357
+ separator = ('-' * 50) + '\n'
1358
+ sys.stderr.write(separator)
1359
+ sys.stderr.write('----- Warnings -- count: {} -----\n'.format(
1360
+ len(gds_collector.get_messages()), ))
1361
+ gds_collector.write_messages(sys.stderr)
1362
+ sys.stderr.write(separator)
1363
+ return rootObj
1364
+
1365
+
1366
+ def parseEtree(inFileName, silence=False, print_warnings=True,
1367
+ mapping=None, reverse_mapping=None, nsmap=None):
1368
+ parser = None
1369
+ doc = parsexml_(inFileName, parser)
1370
+ gds_collector = GdsCollector_()
1371
+ rootNode = doc.getroot()
1372
+ rootTag, rootClass = get_root_tag(rootNode)
1373
+ if rootClass is None:
1374
+ rootTag = 'merchant_info'
1375
+ rootClass = merchant_info
1376
+ rootObj = rootClass.factory()
1377
+ rootObj.build(rootNode, gds_collector_=gds_collector)
1378
+ if mapping is None:
1379
+ mapping = {}
1380
+ if reverse_mapping is None:
1381
+ reverse_mapping = {}
1382
+ rootElement = rootObj.to_etree(
1383
+ None, name_=rootTag, mapping_=mapping,
1384
+ reverse_mapping_=reverse_mapping, nsmap_=nsmap)
1385
+ reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping)
1386
+ # Enable Python to collect the space used by the DOM.
1387
+ if not SaveElementTreeNode:
1388
+ doc = None
1389
+ rootNode = None
1390
+ if not silence:
1391
+ content = etree_.tostring(
1392
+ rootElement, pretty_print=True,
1393
+ xml_declaration=True, encoding="utf-8")
1394
+ sys.stdout.write(str(content))
1395
+ sys.stdout.write('\n')
1396
+ if print_warnings and len(gds_collector.get_messages()) > 0:
1397
+ separator = ('-' * 50) + '\n'
1398
+ sys.stderr.write(separator)
1399
+ sys.stderr.write('----- Warnings -- count: {} -----\n'.format(
1400
+ len(gds_collector.get_messages()), ))
1401
+ gds_collector.write_messages(sys.stderr)
1402
+ sys.stderr.write(separator)
1403
+ return rootObj, rootElement, mapping, reverse_node_mapping
1404
+
1405
+
1406
+ def parseString(inString, silence=False, print_warnings=True):
1407
+ '''Parse a string, create the object tree, and export it.
1408
+
1409
+ Arguments:
1410
+ - inString -- A string. This XML fragment should not start
1411
+ with an XML declaration containing an encoding.
1412
+ - silence -- A boolean. If False, export the object.
1413
+ Returns -- The root object in the tree.
1414
+ '''
1415
+ parser = None
1416
+ rootNode= parsexmlstring_(inString, parser)
1417
+ gds_collector = GdsCollector_()
1418
+ rootTag, rootClass = get_root_tag(rootNode)
1419
+ if rootClass is None:
1420
+ rootTag = 'merchant_info'
1421
+ rootClass = merchant_info
1422
+ rootObj = rootClass.factory()
1423
+ rootObj.build(rootNode, gds_collector_=gds_collector)
1424
+ if not SaveElementTreeNode:
1425
+ rootNode = None
1426
+ if not silence:
1427
+ sys.stdout.write('<?xml version="1.0" ?>\n')
1428
+ rootObj.export(
1429
+ sys.stdout, 0, name_=rootTag,
1430
+ namespacedef_='')
1431
+ if print_warnings and len(gds_collector.get_messages()) > 0:
1432
+ separator = ('-' * 50) + '\n'
1433
+ sys.stderr.write(separator)
1434
+ sys.stderr.write('----- Warnings -- count: {} -----\n'.format(
1435
+ len(gds_collector.get_messages()), ))
1436
+ gds_collector.write_messages(sys.stderr)
1437
+ sys.stderr.write(separator)
1438
+ return rootObj
1439
+
1440
+
1441
+ def parseLiteral(inFileName, silence=False, print_warnings=True):
1442
+ parser = None
1443
+ doc = parsexml_(inFileName, parser)
1444
+ gds_collector = GdsCollector_()
1445
+ rootNode = doc.getroot()
1446
+ rootTag, rootClass = get_root_tag(rootNode)
1447
+ if rootClass is None:
1448
+ rootTag = 'merchant_info'
1449
+ rootClass = merchant_info
1450
+ rootObj = rootClass.factory()
1451
+ rootObj.build(rootNode, gds_collector_=gds_collector)
1452
+ # Enable Python to collect the space used by the DOM.
1453
+ if not SaveElementTreeNode:
1454
+ doc = None
1455
+ rootNode = None
1456
+ if not silence:
1457
+ sys.stdout.write('#from merchantregistration import *\n\n')
1458
+ sys.stdout.write('import merchantregistration as model_\n\n')
1459
+ sys.stdout.write('rootObj = model_.rootClass(\n')
1460
+ rootObj.exportLiteral(sys.stdout, 0, name_=rootTag)
1461
+ sys.stdout.write(')\n')
1462
+ if print_warnings and len(gds_collector.get_messages()) > 0:
1463
+ separator = ('-' * 50) + '\n'
1464
+ sys.stderr.write(separator)
1465
+ sys.stderr.write('----- Warnings -- count: {} -----\n'.format(
1466
+ len(gds_collector.get_messages()), ))
1467
+ gds_collector.write_messages(sys.stderr)
1468
+ sys.stderr.write(separator)
1469
+ return rootObj
1470
+
1471
+
1472
+ def main():
1473
+ args = sys.argv[1:]
1474
+ if len(args) == 1:
1475
+ parse(args[0])
1476
+ else:
1477
+ usage()
1478
+
1479
+
1480
+ if __name__ == '__main__':
1481
+ #import pdb; pdb.set_trace()
1482
+ main()
1483
+
1484
+ RenameMappings_ = {
1485
+ }
1486
+
1487
+ #
1488
+ # Mapping of namespaces to types defined in them
1489
+ # and the file in which each is defined.
1490
+ # simpleTypes are marked "ST" and complexTypes "CT".
1491
+ NamespaceToDefMappings_ = {'http://www.canadapost.ca/ws/merchant/registration': [('TokenIDType',
1492
+ './schemas/merchantregistration.xsd',
1493
+ 'ST')]}
1494
+
1495
+ __all__ = [
1496
+ "merchant_info",
1497
+ "token"
1498
+ ]