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,1859 @@
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/error.py')
11
+ #
12
+ # Command line arguments:
13
+ # ./vendor/schemas/error.xsd
14
+ #
15
+ # Command line:
16
+ # /Users/danielk/Documents/karrio/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./karrio.schemas.freightcom/error.py" ./vendor/schemas/error.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__(self, version=None, ErrorReply=None, gds_collector_=None, **kwargs_):
1160
+ self.gds_collector_ = gds_collector_
1161
+ self.gds_elementtree_node_ = None
1162
+ self.original_tagname_ = None
1163
+ self.parent_object_ = kwargs_.get("parent_object_")
1164
+ self.ns_prefix_ = None
1165
+ self.version = _cast(None, version)
1166
+ self.version_nsprefix_ = None
1167
+ self.ErrorReply = ErrorReply
1168
+ self.ErrorReply_nsprefix_ = None
1169
+
1170
+ def factory(*args_, **kwargs_):
1171
+ if CurrentSubclassModule_ is not None:
1172
+ subclass = getSubclassFromModule_(CurrentSubclassModule_, Freightcom)
1173
+ if subclass is not None:
1174
+ return subclass(*args_, **kwargs_)
1175
+ if Freightcom.subclass:
1176
+ return Freightcom.subclass(*args_, **kwargs_)
1177
+ else:
1178
+ return Freightcom(*args_, **kwargs_)
1179
+
1180
+ factory = staticmethod(factory)
1181
+
1182
+ def get_ns_prefix_(self):
1183
+ return self.ns_prefix_
1184
+
1185
+ def set_ns_prefix_(self, ns_prefix):
1186
+ self.ns_prefix_ = ns_prefix
1187
+
1188
+ def get_ErrorReply(self):
1189
+ return self.ErrorReply
1190
+
1191
+ def set_ErrorReply(self, ErrorReply):
1192
+ self.ErrorReply = ErrorReply
1193
+
1194
+ def get_version(self):
1195
+ return self.version
1196
+
1197
+ def set_version(self, version):
1198
+ self.version = version
1199
+
1200
+ def _hasContent(self):
1201
+ if self.ErrorReply is not None:
1202
+ return True
1203
+ else:
1204
+ return False
1205
+
1206
+ def export(
1207
+ self,
1208
+ outfile,
1209
+ level,
1210
+ namespaceprefix_="",
1211
+ namespacedef_="",
1212
+ name_="Freightcom",
1213
+ pretty_print=True,
1214
+ ):
1215
+ imported_ns_def_ = GenerateDSNamespaceDefs_.get("Freightcom")
1216
+ if imported_ns_def_ is not None:
1217
+ namespacedef_ = imported_ns_def_
1218
+ if pretty_print:
1219
+ eol_ = "\n"
1220
+ else:
1221
+ eol_ = ""
1222
+ if self.original_tagname_ is not None and name_ == "Freightcom":
1223
+ name_ = self.original_tagname_
1224
+ if UseCapturedNS_ and self.ns_prefix_:
1225
+ namespaceprefix_ = self.ns_prefix_ + ":"
1226
+ showIndent(outfile, level, pretty_print)
1227
+ outfile.write(
1228
+ "<%s%s%s"
1229
+ % (
1230
+ namespaceprefix_,
1231
+ name_,
1232
+ namespacedef_ and " " + namespacedef_ or "",
1233
+ )
1234
+ )
1235
+ already_processed = set()
1236
+ self._exportAttributes(
1237
+ outfile, level, already_processed, namespaceprefix_, name_="Freightcom"
1238
+ )
1239
+ if self._hasContent():
1240
+ outfile.write(">%s" % (eol_,))
1241
+ self._exportChildren(
1242
+ outfile,
1243
+ level + 1,
1244
+ namespaceprefix_,
1245
+ namespacedef_,
1246
+ name_="Freightcom",
1247
+ pretty_print=pretty_print,
1248
+ )
1249
+ showIndent(outfile, level, pretty_print)
1250
+ outfile.write("</%s%s>%s" % (namespaceprefix_, name_, eol_))
1251
+ else:
1252
+ outfile.write("/>%s" % (eol_,))
1253
+
1254
+ def _exportAttributes(
1255
+ self, outfile, level, already_processed, namespaceprefix_="", name_="Freightcom"
1256
+ ):
1257
+ if self.version is not None and "version" not in already_processed:
1258
+ already_processed.add("version")
1259
+ outfile.write(
1260
+ " version=%s"
1261
+ % (
1262
+ self.gds_encode(
1263
+ self.gds_format_string(
1264
+ quote_attrib(self.version), input_name="version"
1265
+ )
1266
+ ),
1267
+ )
1268
+ )
1269
+
1270
+ def _exportChildren(
1271
+ self,
1272
+ outfile,
1273
+ level,
1274
+ namespaceprefix_="",
1275
+ namespacedef_="",
1276
+ name_="Freightcom",
1277
+ fromsubclass_=False,
1278
+ pretty_print=True,
1279
+ ):
1280
+ if pretty_print:
1281
+ eol_ = "\n"
1282
+ else:
1283
+ eol_ = ""
1284
+ if self.ErrorReply is not None:
1285
+ namespaceprefix_ = (
1286
+ self.ErrorReply_nsprefix_ + ":"
1287
+ if (UseCapturedNS_ and self.ErrorReply_nsprefix_)
1288
+ else ""
1289
+ )
1290
+ self.ErrorReply.export(
1291
+ outfile,
1292
+ level,
1293
+ namespaceprefix_,
1294
+ namespacedef_="",
1295
+ name_="ErrorReply",
1296
+ pretty_print=pretty_print,
1297
+ )
1298
+
1299
+ def build(self, node, gds_collector_=None):
1300
+ self.gds_collector_ = gds_collector_
1301
+ if SaveElementTreeNode:
1302
+ self.gds_elementtree_node_ = node
1303
+ already_processed = set()
1304
+ self.ns_prefix_ = node.prefix
1305
+ self._buildAttributes(node, node.attrib, already_processed)
1306
+ for child in node:
1307
+ nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
1308
+ self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_)
1309
+ return self
1310
+
1311
+ def _buildAttributes(self, node, attrs, already_processed):
1312
+ value = find_attr_value_("version", node)
1313
+ if value is not None and "version" not in already_processed:
1314
+ already_processed.add("version")
1315
+ self.version = value
1316
+
1317
+ def _buildChildren(
1318
+ self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None
1319
+ ):
1320
+ if nodeName_ == "ErrorReply":
1321
+ obj_ = ErrorReplyType.factory(parent_object_=self)
1322
+ obj_.build(child_, gds_collector_=gds_collector_)
1323
+ self.ErrorReply = obj_
1324
+ obj_.original_tagname_ = "ErrorReply"
1325
+
1326
+
1327
+ # end class Freightcom
1328
+
1329
+
1330
+ class ErrorReplyType(GeneratedsSuper):
1331
+ __hash__ = GeneratedsSuper.__hash__
1332
+ subclass = None
1333
+ superclass = None
1334
+
1335
+ def __init__(self, Error=None, gds_collector_=None, **kwargs_):
1336
+ self.gds_collector_ = gds_collector_
1337
+ self.gds_elementtree_node_ = None
1338
+ self.original_tagname_ = None
1339
+ self.parent_object_ = kwargs_.get("parent_object_")
1340
+ self.ns_prefix_ = None
1341
+ self.Error = Error
1342
+ self.Error_nsprefix_ = None
1343
+
1344
+ def factory(*args_, **kwargs_):
1345
+ if CurrentSubclassModule_ is not None:
1346
+ subclass = getSubclassFromModule_(CurrentSubclassModule_, ErrorReplyType)
1347
+ if subclass is not None:
1348
+ return subclass(*args_, **kwargs_)
1349
+ if ErrorReplyType.subclass:
1350
+ return ErrorReplyType.subclass(*args_, **kwargs_)
1351
+ else:
1352
+ return ErrorReplyType(*args_, **kwargs_)
1353
+
1354
+ factory = staticmethod(factory)
1355
+
1356
+ def get_ns_prefix_(self):
1357
+ return self.ns_prefix_
1358
+
1359
+ def set_ns_prefix_(self, ns_prefix):
1360
+ self.ns_prefix_ = ns_prefix
1361
+
1362
+ def get_Error(self):
1363
+ return self.Error
1364
+
1365
+ def set_Error(self, Error):
1366
+ self.Error = Error
1367
+
1368
+ def _hasContent(self):
1369
+ if self.Error is not None:
1370
+ return True
1371
+ else:
1372
+ return False
1373
+
1374
+ def export(
1375
+ self,
1376
+ outfile,
1377
+ level,
1378
+ namespaceprefix_="",
1379
+ namespacedef_="",
1380
+ name_="ErrorReplyType",
1381
+ pretty_print=True,
1382
+ ):
1383
+ imported_ns_def_ = GenerateDSNamespaceDefs_.get("ErrorReplyType")
1384
+ if imported_ns_def_ is not None:
1385
+ namespacedef_ = imported_ns_def_
1386
+ if pretty_print:
1387
+ eol_ = "\n"
1388
+ else:
1389
+ eol_ = ""
1390
+ if self.original_tagname_ is not None and name_ == "ErrorReplyType":
1391
+ name_ = self.original_tagname_
1392
+ if UseCapturedNS_ and self.ns_prefix_:
1393
+ namespaceprefix_ = self.ns_prefix_ + ":"
1394
+ showIndent(outfile, level, pretty_print)
1395
+ outfile.write(
1396
+ "<%s%s%s"
1397
+ % (
1398
+ namespaceprefix_,
1399
+ name_,
1400
+ namespacedef_ and " " + namespacedef_ or "",
1401
+ )
1402
+ )
1403
+ already_processed = set()
1404
+ self._exportAttributes(
1405
+ outfile, level, already_processed, namespaceprefix_, name_="ErrorReplyType"
1406
+ )
1407
+ if self._hasContent():
1408
+ outfile.write(">%s" % (eol_,))
1409
+ self._exportChildren(
1410
+ outfile,
1411
+ level + 1,
1412
+ namespaceprefix_,
1413
+ namespacedef_,
1414
+ name_="ErrorReplyType",
1415
+ pretty_print=pretty_print,
1416
+ )
1417
+ showIndent(outfile, level, pretty_print)
1418
+ outfile.write("</%s%s>%s" % (namespaceprefix_, name_, eol_))
1419
+ else:
1420
+ outfile.write("/>%s" % (eol_,))
1421
+
1422
+ def _exportAttributes(
1423
+ self,
1424
+ outfile,
1425
+ level,
1426
+ already_processed,
1427
+ namespaceprefix_="",
1428
+ name_="ErrorReplyType",
1429
+ ):
1430
+ pass
1431
+
1432
+ def _exportChildren(
1433
+ self,
1434
+ outfile,
1435
+ level,
1436
+ namespaceprefix_="",
1437
+ namespacedef_="",
1438
+ name_="ErrorReplyType",
1439
+ fromsubclass_=False,
1440
+ pretty_print=True,
1441
+ ):
1442
+ if pretty_print:
1443
+ eol_ = "\n"
1444
+ else:
1445
+ eol_ = ""
1446
+ if self.Error is not None:
1447
+ namespaceprefix_ = (
1448
+ self.Error_nsprefix_ + ":"
1449
+ if (UseCapturedNS_ and self.Error_nsprefix_)
1450
+ else ""
1451
+ )
1452
+ self.Error.export(
1453
+ outfile,
1454
+ level,
1455
+ namespaceprefix_,
1456
+ namespacedef_="",
1457
+ name_="Error",
1458
+ pretty_print=pretty_print,
1459
+ )
1460
+
1461
+ def build(self, node, gds_collector_=None):
1462
+ self.gds_collector_ = gds_collector_
1463
+ if SaveElementTreeNode:
1464
+ self.gds_elementtree_node_ = node
1465
+ already_processed = set()
1466
+ self.ns_prefix_ = node.prefix
1467
+ self._buildAttributes(node, node.attrib, already_processed)
1468
+ for child in node:
1469
+ nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
1470
+ self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_)
1471
+ return self
1472
+
1473
+ def _buildAttributes(self, node, attrs, already_processed):
1474
+ pass
1475
+
1476
+ def _buildChildren(
1477
+ self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None
1478
+ ):
1479
+ if nodeName_ == "Error":
1480
+ obj_ = ErrorType.factory(parent_object_=self)
1481
+ obj_.build(child_, gds_collector_=gds_collector_)
1482
+ self.Error = obj_
1483
+ obj_.original_tagname_ = "Error"
1484
+
1485
+
1486
+ # end class ErrorReplyType
1487
+
1488
+
1489
+ class ErrorType(GeneratedsSuper):
1490
+ __hash__ = GeneratedsSuper.__hash__
1491
+ subclass = None
1492
+ superclass = None
1493
+
1494
+ def __init__(self, Message=None, valueOf_=None, gds_collector_=None, **kwargs_):
1495
+ self.gds_collector_ = gds_collector_
1496
+ self.gds_elementtree_node_ = None
1497
+ self.original_tagname_ = None
1498
+ self.parent_object_ = kwargs_.get("parent_object_")
1499
+ self.ns_prefix_ = None
1500
+ self.Message = _cast(None, Message)
1501
+ self.Message_nsprefix_ = None
1502
+ self.valueOf_ = valueOf_
1503
+
1504
+ def factory(*args_, **kwargs_):
1505
+ if CurrentSubclassModule_ is not None:
1506
+ subclass = getSubclassFromModule_(CurrentSubclassModule_, ErrorType)
1507
+ if subclass is not None:
1508
+ return subclass(*args_, **kwargs_)
1509
+ if ErrorType.subclass:
1510
+ return ErrorType.subclass(*args_, **kwargs_)
1511
+ else:
1512
+ return ErrorType(*args_, **kwargs_)
1513
+
1514
+ factory = staticmethod(factory)
1515
+
1516
+ def get_ns_prefix_(self):
1517
+ return self.ns_prefix_
1518
+
1519
+ def set_ns_prefix_(self, ns_prefix):
1520
+ self.ns_prefix_ = ns_prefix
1521
+
1522
+ def get_Message(self):
1523
+ return self.Message
1524
+
1525
+ def set_Message(self, Message):
1526
+ self.Message = Message
1527
+
1528
+ def get_valueOf_(self):
1529
+ return self.valueOf_
1530
+
1531
+ def set_valueOf_(self, valueOf_):
1532
+ self.valueOf_ = valueOf_
1533
+
1534
+ def _hasContent(self):
1535
+ if 1 if type(self.valueOf_) in [int, float] else self.valueOf_:
1536
+ return True
1537
+ else:
1538
+ return False
1539
+
1540
+ def export(
1541
+ self,
1542
+ outfile,
1543
+ level,
1544
+ namespaceprefix_="",
1545
+ namespacedef_="",
1546
+ name_="ErrorType",
1547
+ pretty_print=True,
1548
+ ):
1549
+ imported_ns_def_ = GenerateDSNamespaceDefs_.get("ErrorType")
1550
+ if imported_ns_def_ is not None:
1551
+ namespacedef_ = imported_ns_def_
1552
+ if pretty_print:
1553
+ eol_ = "\n"
1554
+ else:
1555
+ eol_ = ""
1556
+ if self.original_tagname_ is not None and name_ == "ErrorType":
1557
+ name_ = self.original_tagname_
1558
+ if UseCapturedNS_ and self.ns_prefix_:
1559
+ namespaceprefix_ = self.ns_prefix_ + ":"
1560
+ showIndent(outfile, level, pretty_print)
1561
+ outfile.write(
1562
+ "<%s%s%s"
1563
+ % (
1564
+ namespaceprefix_,
1565
+ name_,
1566
+ namespacedef_ and " " + namespacedef_ or "",
1567
+ )
1568
+ )
1569
+ already_processed = set()
1570
+ self._exportAttributes(
1571
+ outfile, level, already_processed, namespaceprefix_, name_="ErrorType"
1572
+ )
1573
+ if self._hasContent():
1574
+ outfile.write(">")
1575
+ outfile.write(self.convert_unicode(self.valueOf_))
1576
+ self._exportChildren(
1577
+ outfile,
1578
+ level + 1,
1579
+ namespaceprefix_,
1580
+ namespacedef_,
1581
+ name_="ErrorType",
1582
+ pretty_print=pretty_print,
1583
+ )
1584
+ outfile.write("</%s%s>%s" % (namespaceprefix_, name_, eol_))
1585
+ else:
1586
+ outfile.write("/>%s" % (eol_,))
1587
+
1588
+ def _exportAttributes(
1589
+ self, outfile, level, already_processed, namespaceprefix_="", name_="ErrorType"
1590
+ ):
1591
+ if self.Message is not None and "Message" not in already_processed:
1592
+ already_processed.add("Message")
1593
+ outfile.write(
1594
+ " Message=%s"
1595
+ % (
1596
+ self.gds_encode(
1597
+ self.gds_format_string(
1598
+ quote_attrib(self.Message), input_name="Message"
1599
+ )
1600
+ ),
1601
+ )
1602
+ )
1603
+
1604
+ def _exportChildren(
1605
+ self,
1606
+ outfile,
1607
+ level,
1608
+ namespaceprefix_="",
1609
+ namespacedef_="",
1610
+ name_="ErrorType",
1611
+ fromsubclass_=False,
1612
+ pretty_print=True,
1613
+ ):
1614
+ pass
1615
+
1616
+ def build(self, node, gds_collector_=None):
1617
+ self.gds_collector_ = gds_collector_
1618
+ if SaveElementTreeNode:
1619
+ self.gds_elementtree_node_ = node
1620
+ already_processed = set()
1621
+ self.ns_prefix_ = node.prefix
1622
+ self._buildAttributes(node, node.attrib, already_processed)
1623
+ self.valueOf_ = get_all_text_(node)
1624
+ for child in node:
1625
+ nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
1626
+ self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_)
1627
+ return self
1628
+
1629
+ def _buildAttributes(self, node, attrs, already_processed):
1630
+ value = find_attr_value_("Message", node)
1631
+ if value is not None and "Message" not in already_processed:
1632
+ already_processed.add("Message")
1633
+ self.Message = value
1634
+
1635
+ def _buildChildren(
1636
+ self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None
1637
+ ):
1638
+ pass
1639
+
1640
+
1641
+ # end class ErrorType
1642
+
1643
+
1644
+ GDSClassesMapping = {}
1645
+
1646
+
1647
+ USAGE_TEXT = """
1648
+ Usage: python <Parser>.py [ -s ] <in_xml_file>
1649
+ """
1650
+
1651
+
1652
+ def usage():
1653
+ print(USAGE_TEXT)
1654
+ sys.exit(1)
1655
+
1656
+
1657
+ def get_root_tag(node):
1658
+ tag = Tag_pattern_.match(node.tag).groups()[-1]
1659
+ prefix_tag = TagNamePrefix + tag
1660
+ rootClass = GDSClassesMapping.get(prefix_tag)
1661
+ if rootClass is None:
1662
+ rootClass = globals().get(prefix_tag)
1663
+ return tag, rootClass
1664
+
1665
+
1666
+ def get_required_ns_prefix_defs(rootNode):
1667
+ """Get all name space prefix definitions required in this XML doc.
1668
+ Return a dictionary of definitions and a char string of definitions.
1669
+ """
1670
+ nsmap = {
1671
+ prefix: uri
1672
+ for node in rootNode.iter()
1673
+ for (prefix, uri) in node.nsmap.items()
1674
+ if prefix is not None
1675
+ }
1676
+ namespacedefs = " ".join(
1677
+ ['xmlns:{}="{}"'.format(prefix, uri) for prefix, uri in nsmap.items()]
1678
+ )
1679
+ return nsmap, namespacedefs
1680
+
1681
+
1682
+ def parse(inFileName, silence=False, print_warnings=True):
1683
+ global CapturedNsmap_
1684
+ gds_collector = GdsCollector_()
1685
+ parser = None
1686
+ doc = parsexml_(inFileName, parser)
1687
+ rootNode = doc.getroot()
1688
+ rootTag, rootClass = get_root_tag(rootNode)
1689
+ if rootClass is None:
1690
+ rootTag = "Freightcom"
1691
+ rootClass = Freightcom
1692
+ rootObj = rootClass.factory()
1693
+ rootObj.build(rootNode, gds_collector_=gds_collector)
1694
+ CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode)
1695
+ if not SaveElementTreeNode:
1696
+ doc = None
1697
+ rootNode = None
1698
+ if not silence:
1699
+ sys.stdout.write('<?xml version="1.0" ?>\n')
1700
+ rootObj.export(
1701
+ sys.stdout, 0, name_=rootTag, namespacedef_=namespacedefs, pretty_print=True
1702
+ )
1703
+ if print_warnings and len(gds_collector.get_messages()) > 0:
1704
+ separator = ("-" * 50) + "\n"
1705
+ sys.stderr.write(separator)
1706
+ sys.stderr.write(
1707
+ "----- Warnings -- count: {} -----\n".format(
1708
+ len(gds_collector.get_messages()),
1709
+ )
1710
+ )
1711
+ gds_collector.write_messages(sys.stderr)
1712
+ sys.stderr.write(separator)
1713
+ return rootObj
1714
+
1715
+
1716
+ def parseEtree(
1717
+ inFileName,
1718
+ silence=False,
1719
+ print_warnings=True,
1720
+ mapping=None,
1721
+ reverse_mapping=None,
1722
+ nsmap=None,
1723
+ ):
1724
+ parser = None
1725
+ doc = parsexml_(inFileName, parser)
1726
+ gds_collector = GdsCollector_()
1727
+ rootNode = doc.getroot()
1728
+ rootTag, rootClass = get_root_tag(rootNode)
1729
+ if rootClass is None:
1730
+ rootTag = "Freightcom"
1731
+ rootClass = Freightcom
1732
+ rootObj = rootClass.factory()
1733
+ rootObj.build(rootNode, gds_collector_=gds_collector)
1734
+ if mapping is None:
1735
+ mapping = {}
1736
+ if reverse_mapping is None:
1737
+ reverse_mapping = {}
1738
+ rootElement = rootObj.to_etree(
1739
+ None,
1740
+ name_=rootTag,
1741
+ mapping_=mapping,
1742
+ reverse_mapping_=reverse_mapping,
1743
+ nsmap_=nsmap,
1744
+ )
1745
+ reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping)
1746
+ # Enable Python to collect the space used by the DOM.
1747
+ if not SaveElementTreeNode:
1748
+ doc = None
1749
+ rootNode = None
1750
+ if not silence:
1751
+ content = etree_.tostring(
1752
+ rootElement, pretty_print=True, xml_declaration=True, encoding="utf-8"
1753
+ )
1754
+ sys.stdout.write(str(content))
1755
+ sys.stdout.write("\n")
1756
+ if print_warnings and len(gds_collector.get_messages()) > 0:
1757
+ separator = ("-" * 50) + "\n"
1758
+ sys.stderr.write(separator)
1759
+ sys.stderr.write(
1760
+ "----- Warnings -- count: {} -----\n".format(
1761
+ len(gds_collector.get_messages()),
1762
+ )
1763
+ )
1764
+ gds_collector.write_messages(sys.stderr)
1765
+ sys.stderr.write(separator)
1766
+ return rootObj, rootElement, mapping, reverse_node_mapping
1767
+
1768
+
1769
+ def parseString(inString, silence=False, print_warnings=True):
1770
+ """Parse a string, create the object tree, and export it.
1771
+
1772
+ Arguments:
1773
+ - inString -- A string. This XML fragment should not start
1774
+ with an XML declaration containing an encoding.
1775
+ - silence -- A boolean. If False, export the object.
1776
+ Returns -- The root object in the tree.
1777
+ """
1778
+ parser = None
1779
+ rootNode = parsexmlstring_(inString, parser)
1780
+ gds_collector = GdsCollector_()
1781
+ rootTag, rootClass = get_root_tag(rootNode)
1782
+ if rootClass is None:
1783
+ rootTag = "Freightcom"
1784
+ rootClass = Freightcom
1785
+ rootObj = rootClass.factory()
1786
+ rootObj.build(rootNode, gds_collector_=gds_collector)
1787
+ if not SaveElementTreeNode:
1788
+ rootNode = None
1789
+ if not silence:
1790
+ sys.stdout.write('<?xml version="1.0" ?>\n')
1791
+ rootObj.export(sys.stdout, 0, name_=rootTag, namespacedef_="")
1792
+ if print_warnings and len(gds_collector.get_messages()) > 0:
1793
+ separator = ("-" * 50) + "\n"
1794
+ sys.stderr.write(separator)
1795
+ sys.stderr.write(
1796
+ "----- Warnings -- count: {} -----\n".format(
1797
+ len(gds_collector.get_messages()),
1798
+ )
1799
+ )
1800
+ gds_collector.write_messages(sys.stderr)
1801
+ sys.stderr.write(separator)
1802
+ return rootObj
1803
+
1804
+
1805
+ def parseLiteral(inFileName, silence=False, print_warnings=True):
1806
+ parser = None
1807
+ doc = parsexml_(inFileName, parser)
1808
+ gds_collector = GdsCollector_()
1809
+ rootNode = doc.getroot()
1810
+ rootTag, rootClass = get_root_tag(rootNode)
1811
+ if rootClass is None:
1812
+ rootTag = "Freightcom"
1813
+ rootClass = Freightcom
1814
+ rootObj = rootClass.factory()
1815
+ rootObj.build(rootNode, gds_collector_=gds_collector)
1816
+ # Enable Python to collect the space used by the DOM.
1817
+ if not SaveElementTreeNode:
1818
+ doc = None
1819
+ rootNode = None
1820
+ if not silence:
1821
+ sys.stdout.write("#from error import *\n\n")
1822
+ sys.stdout.write("import error as model_\n\n")
1823
+ sys.stdout.write("rootObj = model_.rootClass(\n")
1824
+ rootObj.exportLiteral(sys.stdout, 0, name_=rootTag)
1825
+ sys.stdout.write(")\n")
1826
+ if print_warnings and len(gds_collector.get_messages()) > 0:
1827
+ separator = ("-" * 50) + "\n"
1828
+ sys.stderr.write(separator)
1829
+ sys.stderr.write(
1830
+ "----- Warnings -- count: {} -----\n".format(
1831
+ len(gds_collector.get_messages()),
1832
+ )
1833
+ )
1834
+ gds_collector.write_messages(sys.stderr)
1835
+ sys.stderr.write(separator)
1836
+ return rootObj
1837
+
1838
+
1839
+ def main():
1840
+ args = sys.argv[1:]
1841
+ if len(args) == 1:
1842
+ parse(args[0])
1843
+ else:
1844
+ usage()
1845
+
1846
+
1847
+ if __name__ == "__main__":
1848
+ # import pdb; pdb.set_trace()
1849
+ main()
1850
+
1851
+ RenameMappings_ = {}
1852
+
1853
+ #
1854
+ # Mapping of namespaces to types defined in them
1855
+ # and the file in which each is defined.
1856
+ # simpleTypes are marked "ST" and complexTypes "CT".
1857
+ NamespaceToDefMappings_ = {"http://www.freightcom.net/xml/XMLSchema": []}
1858
+
1859
+ __all__ = ["ErrorReplyType", "ErrorType", "Freightcom"]