karrio-freightcom 2025.5.6__py3-none-any.whl

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