karrio-tnt 2025.5rc1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- karrio/mappers/tnt/__init__.py +3 -0
- karrio/mappers/tnt/mapper.py +40 -0
- karrio/mappers/tnt/proxy.py +97 -0
- karrio/mappers/tnt/settings.py +22 -0
- karrio/plugins/tnt/__init__.py +24 -0
- karrio/providers/tnt/__init__.py +10 -0
- karrio/providers/tnt/error.py +129 -0
- karrio/providers/tnt/rate.py +184 -0
- karrio/providers/tnt/shipment/__init__.py +4 -0
- karrio/providers/tnt/shipment/create.py +226 -0
- karrio/providers/tnt/tracking.py +71 -0
- karrio/providers/tnt/units.py +166 -0
- karrio/providers/tnt/utils.py +162 -0
- karrio/schemas/tnt/__init__.py +0 -0
- karrio/schemas/tnt/label_common_definitions.py +3499 -0
- karrio/schemas/tnt/label_request.py +4409 -0
- karrio/schemas/tnt/label_response.py +5744 -0
- karrio/schemas/tnt/rating_common_definitions.py +1610 -0
- karrio/schemas/tnt/rating_request.py +2886 -0
- karrio/schemas/tnt/rating_response.py +3077 -0
- karrio/schemas/tnt/shipping_common_definitions.py +1216 -0
- karrio/schemas/tnt/shipping_request.py +6114 -0
- karrio/schemas/tnt/shipping_response.py +3404 -0
- karrio/schemas/tnt/tracking_request.py +2742 -0
- karrio/schemas/tnt/tracking_response.py +3729 -0
- karrio_tnt-2025.5rc1.dist-info/METADATA +44 -0
- karrio_tnt-2025.5rc1.dist-info/RECORD +30 -0
- karrio_tnt-2025.5rc1.dist-info/WHEEL +5 -0
- karrio_tnt-2025.5rc1.dist-info/entry_points.txt +2 -0
- karrio_tnt-2025.5rc1.dist-info/top_level.txt +3 -0
@@ -0,0 +1,1216 @@
|
|
1
|
+
#!/usr/bin/env python
|
2
|
+
# -*- coding: utf-8 -*-
|
3
|
+
|
4
|
+
#
|
5
|
+
# Generated Sun Oct 22 20:42:04 2023 by generateDS.py version 2.43.2.
|
6
|
+
# Python 3.10.12 (main, Jun 11 2023, 05:26:28) [GCC 11.4.0]
|
7
|
+
#
|
8
|
+
# Command line options:
|
9
|
+
# ('--no-namespace-defs', '')
|
10
|
+
# ('-o', './karrio/schemas/tnt/shipping_common_definitions.py')
|
11
|
+
#
|
12
|
+
# Command line arguments:
|
13
|
+
# ./schemas/shipping_common_definitions.xsd
|
14
|
+
#
|
15
|
+
# Command line:
|
16
|
+
# /home/kserver/Workspace/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./karrio/schemas/tnt/shipping_common_definitions.py" ./schemas/shipping_common_definitions.xsd
|
17
|
+
#
|
18
|
+
# Current working directory (os.getcwd()):
|
19
|
+
# tnt
|
20
|
+
#
|
21
|
+
|
22
|
+
import sys
|
23
|
+
try:
|
24
|
+
ModulenotfoundExp_ = ModuleNotFoundError
|
25
|
+
except NameError:
|
26
|
+
ModulenotfoundExp_ = ImportError
|
27
|
+
from six.moves import zip_longest
|
28
|
+
import os
|
29
|
+
import re as re_
|
30
|
+
import base64
|
31
|
+
import datetime as datetime_
|
32
|
+
import decimal as decimal_
|
33
|
+
from lxml import etree as etree_
|
34
|
+
|
35
|
+
|
36
|
+
Validate_simpletypes_ = True
|
37
|
+
SaveElementTreeNode = True
|
38
|
+
TagNamePrefix = ""
|
39
|
+
if sys.version_info.major == 2:
|
40
|
+
BaseStrType_ = basestring
|
41
|
+
else:
|
42
|
+
BaseStrType_ = str
|
43
|
+
|
44
|
+
|
45
|
+
def parsexml_(infile, parser=None, **kwargs):
|
46
|
+
if parser is None:
|
47
|
+
# Use the lxml ElementTree compatible parser so that, e.g.,
|
48
|
+
# we ignore comments.
|
49
|
+
try:
|
50
|
+
parser = etree_.ETCompatXMLParser()
|
51
|
+
except AttributeError:
|
52
|
+
# fallback to xml.etree
|
53
|
+
parser = etree_.XMLParser()
|
54
|
+
try:
|
55
|
+
if isinstance(infile, os.PathLike):
|
56
|
+
infile = os.path.join(infile)
|
57
|
+
except AttributeError:
|
58
|
+
pass
|
59
|
+
doc = etree_.parse(infile, parser=parser, **kwargs)
|
60
|
+
return doc
|
61
|
+
|
62
|
+
def parsexmlstring_(instring, parser=None, **kwargs):
|
63
|
+
if parser is None:
|
64
|
+
# Use the lxml ElementTree compatible parser so that, e.g.,
|
65
|
+
# we ignore comments.
|
66
|
+
try:
|
67
|
+
parser = etree_.ETCompatXMLParser()
|
68
|
+
except AttributeError:
|
69
|
+
# fallback to xml.etree
|
70
|
+
parser = etree_.XMLParser()
|
71
|
+
element = etree_.fromstring(instring, parser=parser, **kwargs)
|
72
|
+
return element
|
73
|
+
|
74
|
+
#
|
75
|
+
# Namespace prefix definition table (and other attributes, too)
|
76
|
+
#
|
77
|
+
# The module generatedsnamespaces, if it is importable, must contain
|
78
|
+
# a dictionary named GeneratedsNamespaceDefs. This Python dictionary
|
79
|
+
# should map element type names (strings) to XML schema namespace prefix
|
80
|
+
# definitions. The export method for any class for which there is
|
81
|
+
# a namespace prefix definition, will export that definition in the
|
82
|
+
# XML representation of that element. See the export method of
|
83
|
+
# any generated element type class for an example of the use of this
|
84
|
+
# table.
|
85
|
+
# A sample table is:
|
86
|
+
#
|
87
|
+
# # File: generatedsnamespaces.py
|
88
|
+
#
|
89
|
+
# GenerateDSNamespaceDefs = {
|
90
|
+
# "ElementtypeA": "http://www.xxx.com/namespaceA",
|
91
|
+
# "ElementtypeB": "http://www.xxx.com/namespaceB",
|
92
|
+
# }
|
93
|
+
#
|
94
|
+
# Additionally, the generatedsnamespaces module can contain a python
|
95
|
+
# dictionary named GenerateDSNamespaceTypePrefixes that associates element
|
96
|
+
# types with the namespace prefixes that are to be added to the
|
97
|
+
# "xsi:type" attribute value. See the _exportAttributes method of
|
98
|
+
# any generated element type and the generation of "xsi:type" for an
|
99
|
+
# example of the use of this table.
|
100
|
+
# An example table:
|
101
|
+
#
|
102
|
+
# # File: generatedsnamespaces.py
|
103
|
+
#
|
104
|
+
# GenerateDSNamespaceTypePrefixes = {
|
105
|
+
# "ElementtypeC": "aaa:",
|
106
|
+
# "ElementtypeD": "bbb:",
|
107
|
+
# }
|
108
|
+
#
|
109
|
+
|
110
|
+
try:
|
111
|
+
from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_
|
112
|
+
except ModulenotfoundExp_ :
|
113
|
+
GenerateDSNamespaceDefs_ = {}
|
114
|
+
try:
|
115
|
+
from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_
|
116
|
+
except ModulenotfoundExp_ :
|
117
|
+
GenerateDSNamespaceTypePrefixes_ = {}
|
118
|
+
|
119
|
+
#
|
120
|
+
# You can replace the following class definition by defining an
|
121
|
+
# importable module named "generatedscollector" containing a class
|
122
|
+
# named "GdsCollector". See the default class definition below for
|
123
|
+
# clues about the possible content of that class.
|
124
|
+
#
|
125
|
+
try:
|
126
|
+
from generatedscollector import GdsCollector as GdsCollector_
|
127
|
+
except ModulenotfoundExp_ :
|
128
|
+
|
129
|
+
class GdsCollector_(object):
|
130
|
+
|
131
|
+
def __init__(self, messages=None):
|
132
|
+
if messages is None:
|
133
|
+
self.messages = []
|
134
|
+
else:
|
135
|
+
self.messages = messages
|
136
|
+
|
137
|
+
def add_message(self, msg):
|
138
|
+
self.messages.append(msg)
|
139
|
+
|
140
|
+
def get_messages(self):
|
141
|
+
return self.messages
|
142
|
+
|
143
|
+
def clear_messages(self):
|
144
|
+
self.messages = []
|
145
|
+
|
146
|
+
def print_messages(self):
|
147
|
+
for msg in self.messages:
|
148
|
+
print("Warning: {}".format(msg))
|
149
|
+
|
150
|
+
def write_messages(self, outstream):
|
151
|
+
for msg in self.messages:
|
152
|
+
outstream.write("Warning: {}\n".format(msg))
|
153
|
+
|
154
|
+
|
155
|
+
#
|
156
|
+
# The super-class for enum types
|
157
|
+
#
|
158
|
+
|
159
|
+
try:
|
160
|
+
from enum import Enum
|
161
|
+
except ModulenotfoundExp_ :
|
162
|
+
Enum = object
|
163
|
+
|
164
|
+
#
|
165
|
+
# The root super-class for element type classes
|
166
|
+
#
|
167
|
+
# Calls to the methods in these classes are generated by generateDS.py.
|
168
|
+
# You can replace these methods by re-implementing the following class
|
169
|
+
# in a module named generatedssuper.py.
|
170
|
+
|
171
|
+
try:
|
172
|
+
from generatedssuper import GeneratedsSuper
|
173
|
+
except ModulenotfoundExp_ as exp:
|
174
|
+
try:
|
175
|
+
from generatedssupersuper import GeneratedsSuperSuper
|
176
|
+
except ModulenotfoundExp_ as exp:
|
177
|
+
class GeneratedsSuperSuper(object):
|
178
|
+
pass
|
179
|
+
|
180
|
+
class GeneratedsSuper(GeneratedsSuperSuper):
|
181
|
+
__hash__ = object.__hash__
|
182
|
+
tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$')
|
183
|
+
class _FixedOffsetTZ(datetime_.tzinfo):
|
184
|
+
def __init__(self, offset, name):
|
185
|
+
self.__offset = datetime_.timedelta(minutes=offset)
|
186
|
+
self.__name = name
|
187
|
+
def utcoffset(self, dt):
|
188
|
+
return self.__offset
|
189
|
+
def tzname(self, dt):
|
190
|
+
return self.__name
|
191
|
+
def dst(self, dt):
|
192
|
+
return None
|
193
|
+
def __str__(self):
|
194
|
+
settings = {
|
195
|
+
'str_pretty_print': True,
|
196
|
+
'str_indent_level': 0,
|
197
|
+
'str_namespaceprefix': '',
|
198
|
+
'str_name': self.__class__.__name__,
|
199
|
+
'str_namespacedefs': '',
|
200
|
+
}
|
201
|
+
for n in settings:
|
202
|
+
if hasattr(self, n):
|
203
|
+
settings[n] = getattr(self, n)
|
204
|
+
if sys.version_info.major == 2:
|
205
|
+
from StringIO import StringIO
|
206
|
+
else:
|
207
|
+
from io import StringIO
|
208
|
+
output = StringIO()
|
209
|
+
self.export(
|
210
|
+
output,
|
211
|
+
settings['str_indent_level'],
|
212
|
+
pretty_print=settings['str_pretty_print'],
|
213
|
+
namespaceprefix_=settings['str_namespaceprefix'],
|
214
|
+
name_=settings['str_name'],
|
215
|
+
namespacedef_=settings['str_namespacedefs']
|
216
|
+
)
|
217
|
+
strval = output.getvalue()
|
218
|
+
output.close()
|
219
|
+
return strval
|
220
|
+
def gds_format_string(self, input_data, input_name=''):
|
221
|
+
return input_data
|
222
|
+
def gds_parse_string(self, input_data, node=None, input_name=''):
|
223
|
+
return input_data
|
224
|
+
def gds_validate_string(self, input_data, node=None, input_name=''):
|
225
|
+
if not input_data:
|
226
|
+
return ''
|
227
|
+
else:
|
228
|
+
return input_data
|
229
|
+
def gds_format_base64(self, input_data, input_name=''):
|
230
|
+
return base64.b64encode(input_data).decode('ascii')
|
231
|
+
def gds_validate_base64(self, input_data, node=None, input_name=''):
|
232
|
+
return input_data
|
233
|
+
def gds_format_integer(self, input_data, input_name=''):
|
234
|
+
return '%d' % int(input_data)
|
235
|
+
def gds_parse_integer(self, input_data, node=None, input_name=''):
|
236
|
+
try:
|
237
|
+
ival = int(input_data)
|
238
|
+
except (TypeError, ValueError) as exp:
|
239
|
+
raise_parse_error(node, 'Requires integer value: %s' % exp)
|
240
|
+
return ival
|
241
|
+
def gds_validate_integer(self, input_data, node=None, input_name=''):
|
242
|
+
try:
|
243
|
+
value = int(input_data)
|
244
|
+
except (TypeError, ValueError):
|
245
|
+
raise_parse_error(node, 'Requires integer value')
|
246
|
+
return value
|
247
|
+
def gds_format_integer_list(self, input_data, input_name=''):
|
248
|
+
if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_):
|
249
|
+
input_data = [str(s) for s in input_data]
|
250
|
+
return '%s' % ' '.join(input_data)
|
251
|
+
def gds_validate_integer_list(
|
252
|
+
self, input_data, node=None, input_name=''):
|
253
|
+
values = input_data.split()
|
254
|
+
for value in values:
|
255
|
+
try:
|
256
|
+
int(value)
|
257
|
+
except (TypeError, ValueError):
|
258
|
+
raise_parse_error(node, 'Requires sequence of integer values')
|
259
|
+
return values
|
260
|
+
def gds_format_float(self, input_data, input_name=''):
|
261
|
+
value = ('%.15f' % float(input_data)).rstrip('0')
|
262
|
+
if value.endswith('.'):
|
263
|
+
value += '0'
|
264
|
+
return value
|
265
|
+
|
266
|
+
def gds_parse_float(self, input_data, node=None, input_name=''):
|
267
|
+
try:
|
268
|
+
fval_ = float(input_data)
|
269
|
+
except (TypeError, ValueError) as exp:
|
270
|
+
raise_parse_error(node, 'Requires float or double value: %s' % exp)
|
271
|
+
return fval_
|
272
|
+
def gds_validate_float(self, input_data, node=None, input_name=''):
|
273
|
+
try:
|
274
|
+
value = float(input_data)
|
275
|
+
except (TypeError, ValueError):
|
276
|
+
raise_parse_error(node, 'Requires float value')
|
277
|
+
return value
|
278
|
+
def gds_format_float_list(self, input_data, input_name=''):
|
279
|
+
if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_):
|
280
|
+
input_data = [str(s) for s in input_data]
|
281
|
+
return '%s' % ' '.join(input_data)
|
282
|
+
def gds_validate_float_list(
|
283
|
+
self, input_data, node=None, input_name=''):
|
284
|
+
values = input_data.split()
|
285
|
+
for value in values:
|
286
|
+
try:
|
287
|
+
float(value)
|
288
|
+
except (TypeError, ValueError):
|
289
|
+
raise_parse_error(node, 'Requires sequence of float values')
|
290
|
+
return values
|
291
|
+
def gds_format_decimal(self, input_data, input_name=''):
|
292
|
+
return_value = '%s' % input_data
|
293
|
+
if '.' in return_value:
|
294
|
+
return_value = return_value.rstrip('0')
|
295
|
+
if return_value.endswith('.'):
|
296
|
+
return_value = return_value.rstrip('.')
|
297
|
+
return return_value
|
298
|
+
def gds_parse_decimal(self, input_data, node=None, input_name=''):
|
299
|
+
try:
|
300
|
+
decimal_value = decimal_.Decimal(input_data)
|
301
|
+
except (TypeError, ValueError):
|
302
|
+
raise_parse_error(node, 'Requires decimal value')
|
303
|
+
return decimal_value
|
304
|
+
def gds_validate_decimal(self, input_data, node=None, input_name=''):
|
305
|
+
try:
|
306
|
+
value = decimal_.Decimal(input_data)
|
307
|
+
except (TypeError, ValueError):
|
308
|
+
raise_parse_error(node, 'Requires decimal value')
|
309
|
+
return value
|
310
|
+
def gds_format_decimal_list(self, input_data, input_name=''):
|
311
|
+
if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_):
|
312
|
+
input_data = [str(s) for s in input_data]
|
313
|
+
return ' '.join([self.gds_format_decimal(item) for item in input_data])
|
314
|
+
def gds_validate_decimal_list(
|
315
|
+
self, input_data, node=None, input_name=''):
|
316
|
+
values = input_data.split()
|
317
|
+
for value in values:
|
318
|
+
try:
|
319
|
+
decimal_.Decimal(value)
|
320
|
+
except (TypeError, ValueError):
|
321
|
+
raise_parse_error(node, 'Requires sequence of decimal values')
|
322
|
+
return values
|
323
|
+
def gds_format_double(self, input_data, input_name=''):
|
324
|
+
return '%s' % input_data
|
325
|
+
def gds_parse_double(self, input_data, node=None, input_name=''):
|
326
|
+
try:
|
327
|
+
fval_ = float(input_data)
|
328
|
+
except (TypeError, ValueError) as exp:
|
329
|
+
raise_parse_error(node, 'Requires double or float value: %s' % exp)
|
330
|
+
return fval_
|
331
|
+
def gds_validate_double(self, input_data, node=None, input_name=''):
|
332
|
+
try:
|
333
|
+
value = float(input_data)
|
334
|
+
except (TypeError, ValueError):
|
335
|
+
raise_parse_error(node, 'Requires double or float value')
|
336
|
+
return value
|
337
|
+
def gds_format_double_list(self, input_data, input_name=''):
|
338
|
+
if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_):
|
339
|
+
input_data = [str(s) for s in input_data]
|
340
|
+
return '%s' % ' '.join(input_data)
|
341
|
+
def gds_validate_double_list(
|
342
|
+
self, input_data, node=None, input_name=''):
|
343
|
+
values = input_data.split()
|
344
|
+
for value in values:
|
345
|
+
try:
|
346
|
+
float(value)
|
347
|
+
except (TypeError, ValueError):
|
348
|
+
raise_parse_error(
|
349
|
+
node, 'Requires sequence of double or float values')
|
350
|
+
return values
|
351
|
+
def gds_format_boolean(self, input_data, input_name=''):
|
352
|
+
return ('%s' % input_data).lower()
|
353
|
+
def gds_parse_boolean(self, input_data, node=None, input_name=''):
|
354
|
+
input_data = input_data.strip()
|
355
|
+
if input_data in ('true', '1'):
|
356
|
+
bval = True
|
357
|
+
elif input_data in ('false', '0'):
|
358
|
+
bval = False
|
359
|
+
else:
|
360
|
+
raise_parse_error(node, 'Requires boolean value')
|
361
|
+
return bval
|
362
|
+
def gds_validate_boolean(self, input_data, node=None, input_name=''):
|
363
|
+
if input_data not in (True, 1, False, 0, ):
|
364
|
+
raise_parse_error(
|
365
|
+
node,
|
366
|
+
'Requires boolean value '
|
367
|
+
'(one of True, 1, False, 0)')
|
368
|
+
return input_data
|
369
|
+
def gds_format_boolean_list(self, input_data, input_name=''):
|
370
|
+
if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_):
|
371
|
+
input_data = [str(s) for s in input_data]
|
372
|
+
return '%s' % ' '.join(input_data)
|
373
|
+
def gds_validate_boolean_list(
|
374
|
+
self, input_data, node=None, input_name=''):
|
375
|
+
values = input_data.split()
|
376
|
+
for value in values:
|
377
|
+
value = self.gds_parse_boolean(value, node, input_name)
|
378
|
+
if value not in (True, 1, False, 0, ):
|
379
|
+
raise_parse_error(
|
380
|
+
node,
|
381
|
+
'Requires sequence of boolean values '
|
382
|
+
'(one of True, 1, False, 0)')
|
383
|
+
return values
|
384
|
+
def gds_validate_datetime(self, input_data, node=None, input_name=''):
|
385
|
+
return input_data
|
386
|
+
def gds_format_datetime(self, input_data, input_name=''):
|
387
|
+
if input_data.microsecond == 0:
|
388
|
+
_svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % (
|
389
|
+
input_data.year,
|
390
|
+
input_data.month,
|
391
|
+
input_data.day,
|
392
|
+
input_data.hour,
|
393
|
+
input_data.minute,
|
394
|
+
input_data.second,
|
395
|
+
)
|
396
|
+
else:
|
397
|
+
_svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % (
|
398
|
+
input_data.year,
|
399
|
+
input_data.month,
|
400
|
+
input_data.day,
|
401
|
+
input_data.hour,
|
402
|
+
input_data.minute,
|
403
|
+
input_data.second,
|
404
|
+
('%f' % (float(input_data.microsecond) / 1000000))[2:],
|
405
|
+
)
|
406
|
+
if input_data.tzinfo is not None:
|
407
|
+
tzoff = input_data.tzinfo.utcoffset(input_data)
|
408
|
+
if tzoff is not None:
|
409
|
+
total_seconds = tzoff.seconds + (86400 * tzoff.days)
|
410
|
+
if total_seconds == 0:
|
411
|
+
_svalue += 'Z'
|
412
|
+
else:
|
413
|
+
if total_seconds < 0:
|
414
|
+
_svalue += '-'
|
415
|
+
total_seconds *= -1
|
416
|
+
else:
|
417
|
+
_svalue += '+'
|
418
|
+
hours = total_seconds // 3600
|
419
|
+
minutes = (total_seconds - (hours * 3600)) // 60
|
420
|
+
_svalue += '{0:02d}:{1:02d}'.format(hours, minutes)
|
421
|
+
return _svalue
|
422
|
+
@classmethod
|
423
|
+
def gds_parse_datetime(cls, input_data):
|
424
|
+
tz = None
|
425
|
+
if input_data[-1] == 'Z':
|
426
|
+
tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC')
|
427
|
+
input_data = input_data[:-1]
|
428
|
+
else:
|
429
|
+
results = GeneratedsSuper.tzoff_pattern.search(input_data)
|
430
|
+
if results is not None:
|
431
|
+
tzoff_parts = results.group(2).split(':')
|
432
|
+
tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1])
|
433
|
+
if results.group(1) == '-':
|
434
|
+
tzoff *= -1
|
435
|
+
tz = GeneratedsSuper._FixedOffsetTZ(
|
436
|
+
tzoff, results.group(0))
|
437
|
+
input_data = input_data[:-6]
|
438
|
+
time_parts = input_data.split('.')
|
439
|
+
if len(time_parts) > 1:
|
440
|
+
micro_seconds = int(float('0.' + time_parts[1]) * 1000000)
|
441
|
+
input_data = '%s.%s' % (
|
442
|
+
time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), )
|
443
|
+
dt = datetime_.datetime.strptime(
|
444
|
+
input_data, '%Y-%m-%dT%H:%M:%S.%f')
|
445
|
+
else:
|
446
|
+
dt = datetime_.datetime.strptime(
|
447
|
+
input_data, '%Y-%m-%dT%H:%M:%S')
|
448
|
+
dt = dt.replace(tzinfo=tz)
|
449
|
+
return dt
|
450
|
+
def gds_validate_date(self, input_data, node=None, input_name=''):
|
451
|
+
return input_data
|
452
|
+
def gds_format_date(self, input_data, input_name=''):
|
453
|
+
_svalue = '%04d-%02d-%02d' % (
|
454
|
+
input_data.year,
|
455
|
+
input_data.month,
|
456
|
+
input_data.day,
|
457
|
+
)
|
458
|
+
try:
|
459
|
+
if input_data.tzinfo is not None:
|
460
|
+
tzoff = input_data.tzinfo.utcoffset(input_data)
|
461
|
+
if tzoff is not None:
|
462
|
+
total_seconds = tzoff.seconds + (86400 * tzoff.days)
|
463
|
+
if total_seconds == 0:
|
464
|
+
_svalue += 'Z'
|
465
|
+
else:
|
466
|
+
if total_seconds < 0:
|
467
|
+
_svalue += '-'
|
468
|
+
total_seconds *= -1
|
469
|
+
else:
|
470
|
+
_svalue += '+'
|
471
|
+
hours = total_seconds // 3600
|
472
|
+
minutes = (total_seconds - (hours * 3600)) // 60
|
473
|
+
_svalue += '{0:02d}:{1:02d}'.format(
|
474
|
+
hours, minutes)
|
475
|
+
except AttributeError:
|
476
|
+
pass
|
477
|
+
return _svalue
|
478
|
+
@classmethod
|
479
|
+
def gds_parse_date(cls, input_data):
|
480
|
+
tz = None
|
481
|
+
if input_data[-1] == 'Z':
|
482
|
+
tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC')
|
483
|
+
input_data = input_data[:-1]
|
484
|
+
else:
|
485
|
+
results = GeneratedsSuper.tzoff_pattern.search(input_data)
|
486
|
+
if results is not None:
|
487
|
+
tzoff_parts = results.group(2).split(':')
|
488
|
+
tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1])
|
489
|
+
if results.group(1) == '-':
|
490
|
+
tzoff *= -1
|
491
|
+
tz = GeneratedsSuper._FixedOffsetTZ(
|
492
|
+
tzoff, results.group(0))
|
493
|
+
input_data = input_data[:-6]
|
494
|
+
dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d')
|
495
|
+
dt = dt.replace(tzinfo=tz)
|
496
|
+
return dt.date()
|
497
|
+
def gds_validate_time(self, input_data, node=None, input_name=''):
|
498
|
+
return input_data
|
499
|
+
def gds_format_time(self, input_data, input_name=''):
|
500
|
+
if input_data.microsecond == 0:
|
501
|
+
_svalue = '%02d:%02d:%02d' % (
|
502
|
+
input_data.hour,
|
503
|
+
input_data.minute,
|
504
|
+
input_data.second,
|
505
|
+
)
|
506
|
+
else:
|
507
|
+
_svalue = '%02d:%02d:%02d.%s' % (
|
508
|
+
input_data.hour,
|
509
|
+
input_data.minute,
|
510
|
+
input_data.second,
|
511
|
+
('%f' % (float(input_data.microsecond) / 1000000))[2:],
|
512
|
+
)
|
513
|
+
if input_data.tzinfo is not None:
|
514
|
+
tzoff = input_data.tzinfo.utcoffset(input_data)
|
515
|
+
if tzoff is not None:
|
516
|
+
total_seconds = tzoff.seconds + (86400 * tzoff.days)
|
517
|
+
if total_seconds == 0:
|
518
|
+
_svalue += 'Z'
|
519
|
+
else:
|
520
|
+
if total_seconds < 0:
|
521
|
+
_svalue += '-'
|
522
|
+
total_seconds *= -1
|
523
|
+
else:
|
524
|
+
_svalue += '+'
|
525
|
+
hours = total_seconds // 3600
|
526
|
+
minutes = (total_seconds - (hours * 3600)) // 60
|
527
|
+
_svalue += '{0:02d}:{1:02d}'.format(hours, minutes)
|
528
|
+
return _svalue
|
529
|
+
def gds_validate_simple_patterns(self, patterns, target):
|
530
|
+
# pat is a list of lists of strings/patterns.
|
531
|
+
# The target value must match at least one of the patterns
|
532
|
+
# in order for the test to succeed.
|
533
|
+
found1 = True
|
534
|
+
target = str(target)
|
535
|
+
for patterns1 in patterns:
|
536
|
+
found2 = False
|
537
|
+
for patterns2 in patterns1:
|
538
|
+
mo = re_.search(patterns2, target)
|
539
|
+
if mo is not None and len(mo.group(0)) == len(target):
|
540
|
+
found2 = True
|
541
|
+
break
|
542
|
+
if not found2:
|
543
|
+
found1 = False
|
544
|
+
break
|
545
|
+
return found1
|
546
|
+
@classmethod
|
547
|
+
def gds_parse_time(cls, input_data):
|
548
|
+
tz = None
|
549
|
+
if input_data[-1] == 'Z':
|
550
|
+
tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC')
|
551
|
+
input_data = input_data[:-1]
|
552
|
+
else:
|
553
|
+
results = GeneratedsSuper.tzoff_pattern.search(input_data)
|
554
|
+
if results is not None:
|
555
|
+
tzoff_parts = results.group(2).split(':')
|
556
|
+
tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1])
|
557
|
+
if results.group(1) == '-':
|
558
|
+
tzoff *= -1
|
559
|
+
tz = GeneratedsSuper._FixedOffsetTZ(
|
560
|
+
tzoff, results.group(0))
|
561
|
+
input_data = input_data[:-6]
|
562
|
+
if len(input_data.split('.')) > 1:
|
563
|
+
dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f')
|
564
|
+
else:
|
565
|
+
dt = datetime_.datetime.strptime(input_data, '%H:%M:%S')
|
566
|
+
dt = dt.replace(tzinfo=tz)
|
567
|
+
return dt.time()
|
568
|
+
def gds_check_cardinality_(
|
569
|
+
self, value, input_name,
|
570
|
+
min_occurs=0, max_occurs=1, required=None):
|
571
|
+
if value is None:
|
572
|
+
length = 0
|
573
|
+
elif isinstance(value, list):
|
574
|
+
length = len(value)
|
575
|
+
else:
|
576
|
+
length = 1
|
577
|
+
if required is not None :
|
578
|
+
if required and length < 1:
|
579
|
+
self.gds_collector_.add_message(
|
580
|
+
"Required value {}{} is missing".format(
|
581
|
+
input_name, self.gds_get_node_lineno_()))
|
582
|
+
if length < min_occurs:
|
583
|
+
self.gds_collector_.add_message(
|
584
|
+
"Number of values for {}{} is below "
|
585
|
+
"the minimum allowed, "
|
586
|
+
"expected at least {}, found {}".format(
|
587
|
+
input_name, self.gds_get_node_lineno_(),
|
588
|
+
min_occurs, length))
|
589
|
+
elif length > max_occurs:
|
590
|
+
self.gds_collector_.add_message(
|
591
|
+
"Number of values for {}{} is above "
|
592
|
+
"the maximum allowed, "
|
593
|
+
"expected at most {}, found {}".format(
|
594
|
+
input_name, self.gds_get_node_lineno_(),
|
595
|
+
max_occurs, length))
|
596
|
+
def gds_validate_builtin_ST_(
|
597
|
+
self, validator, value, input_name,
|
598
|
+
min_occurs=None, max_occurs=None, required=None):
|
599
|
+
if value is not None:
|
600
|
+
try:
|
601
|
+
validator(value, input_name=input_name)
|
602
|
+
except GDSParseError as parse_error:
|
603
|
+
self.gds_collector_.add_message(str(parse_error))
|
604
|
+
def gds_validate_defined_ST_(
|
605
|
+
self, validator, value, input_name,
|
606
|
+
min_occurs=None, max_occurs=None, required=None):
|
607
|
+
if value is not None:
|
608
|
+
try:
|
609
|
+
validator(value)
|
610
|
+
except GDSParseError as parse_error:
|
611
|
+
self.gds_collector_.add_message(str(parse_error))
|
612
|
+
def gds_str_lower(self, instring):
|
613
|
+
return instring.lower()
|
614
|
+
def get_path_(self, node):
|
615
|
+
path_list = []
|
616
|
+
self.get_path_list_(node, path_list)
|
617
|
+
path_list.reverse()
|
618
|
+
path = '/'.join(path_list)
|
619
|
+
return path
|
620
|
+
Tag_strip_pattern_ = re_.compile(r'\{.*\}')
|
621
|
+
def get_path_list_(self, node, path_list):
|
622
|
+
if node is None:
|
623
|
+
return
|
624
|
+
tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag)
|
625
|
+
if tag:
|
626
|
+
path_list.append(tag)
|
627
|
+
self.get_path_list_(node.getparent(), path_list)
|
628
|
+
def get_class_obj_(self, node, default_class=None):
|
629
|
+
class_obj1 = default_class
|
630
|
+
if 'xsi' in node.nsmap:
|
631
|
+
classname = node.get('{%s}type' % node.nsmap['xsi'])
|
632
|
+
if classname is not None:
|
633
|
+
names = classname.split(':')
|
634
|
+
if len(names) == 2:
|
635
|
+
classname = names[1]
|
636
|
+
class_obj2 = globals().get(classname)
|
637
|
+
if class_obj2 is not None:
|
638
|
+
class_obj1 = class_obj2
|
639
|
+
return class_obj1
|
640
|
+
def gds_build_any(self, node, type_name=None):
|
641
|
+
# provide default value in case option --disable-xml is used.
|
642
|
+
content = ""
|
643
|
+
content = etree_.tostring(node, encoding="unicode")
|
644
|
+
return content
|
645
|
+
@classmethod
|
646
|
+
def gds_reverse_node_mapping(cls, mapping):
|
647
|
+
return dict(((v, k) for k, v in mapping.items()))
|
648
|
+
@staticmethod
|
649
|
+
def gds_encode(instring):
|
650
|
+
if sys.version_info.major == 2:
|
651
|
+
if ExternalEncoding:
|
652
|
+
encoding = ExternalEncoding
|
653
|
+
else:
|
654
|
+
encoding = 'utf-8'
|
655
|
+
return instring.encode(encoding)
|
656
|
+
else:
|
657
|
+
return instring
|
658
|
+
@staticmethod
|
659
|
+
def convert_unicode(instring):
|
660
|
+
if isinstance(instring, str):
|
661
|
+
result = quote_xml(instring)
|
662
|
+
elif sys.version_info.major == 2 and isinstance(instring, unicode):
|
663
|
+
result = quote_xml(instring).encode('utf8')
|
664
|
+
else:
|
665
|
+
result = GeneratedsSuper.gds_encode(str(instring))
|
666
|
+
return result
|
667
|
+
def __eq__(self, other):
|
668
|
+
def excl_select_objs_(obj):
|
669
|
+
return (obj[0] != 'parent_object_' and
|
670
|
+
obj[0] != 'gds_collector_')
|
671
|
+
if type(self) != type(other):
|
672
|
+
return False
|
673
|
+
return all(x == y for x, y in zip_longest(
|
674
|
+
filter(excl_select_objs_, self.__dict__.items()),
|
675
|
+
filter(excl_select_objs_, other.__dict__.items())))
|
676
|
+
def __ne__(self, other):
|
677
|
+
return not self.__eq__(other)
|
678
|
+
# Django ETL transform hooks.
|
679
|
+
def gds_djo_etl_transform(self):
|
680
|
+
pass
|
681
|
+
def gds_djo_etl_transform_db_obj(self, dbobj):
|
682
|
+
pass
|
683
|
+
# SQLAlchemy ETL transform hooks.
|
684
|
+
def gds_sqa_etl_transform(self):
|
685
|
+
return 0, None
|
686
|
+
def gds_sqa_etl_transform_db_obj(self, dbobj):
|
687
|
+
pass
|
688
|
+
def gds_get_node_lineno_(self):
|
689
|
+
if (hasattr(self, "gds_elementtree_node_") and
|
690
|
+
self.gds_elementtree_node_ is not None):
|
691
|
+
return ' near line {}'.format(
|
692
|
+
self.gds_elementtree_node_.sourceline)
|
693
|
+
else:
|
694
|
+
return ""
|
695
|
+
|
696
|
+
|
697
|
+
def getSubclassFromModule_(module, class_):
|
698
|
+
'''Get the subclass of a class from a specific module.'''
|
699
|
+
name = class_.__name__ + 'Sub'
|
700
|
+
if hasattr(module, name):
|
701
|
+
return getattr(module, name)
|
702
|
+
else:
|
703
|
+
return None
|
704
|
+
|
705
|
+
|
706
|
+
#
|
707
|
+
# If you have installed IPython you can uncomment and use the following.
|
708
|
+
# IPython is available from http://ipython.scipy.org/.
|
709
|
+
#
|
710
|
+
|
711
|
+
## from IPython.Shell import IPShellEmbed
|
712
|
+
## args = ''
|
713
|
+
## ipshell = IPShellEmbed(args,
|
714
|
+
## banner = 'Dropping into IPython',
|
715
|
+
## exit_msg = 'Leaving Interpreter, back to program.')
|
716
|
+
|
717
|
+
# Then use the following line where and when you want to drop into the
|
718
|
+
# IPython shell:
|
719
|
+
# ipshell('<some message> -- Entering ipshell.\nHit Ctrl-D to exit')
|
720
|
+
|
721
|
+
#
|
722
|
+
# Globals
|
723
|
+
#
|
724
|
+
|
725
|
+
ExternalEncoding = ''
|
726
|
+
# Set this to false in order to deactivate during export, the use of
|
727
|
+
# name space prefixes captured from the input document.
|
728
|
+
UseCapturedNS_ = True
|
729
|
+
CapturedNsmap_ = {}
|
730
|
+
Tag_pattern_ = re_.compile(r'({.*})?(.*)')
|
731
|
+
String_cleanup_pat_ = re_.compile(r"[\n\r\s]+")
|
732
|
+
Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)')
|
733
|
+
CDATA_pattern_ = re_.compile(r"<!\[CDATA\[.*?\]\]>", re_.DOTALL)
|
734
|
+
|
735
|
+
# Change this to redirect the generated superclass module to use a
|
736
|
+
# specific subclass module.
|
737
|
+
CurrentSubclassModule_ = None
|
738
|
+
|
739
|
+
#
|
740
|
+
# Support/utility functions.
|
741
|
+
#
|
742
|
+
|
743
|
+
|
744
|
+
def showIndent(outfile, level, pretty_print=True):
|
745
|
+
if pretty_print:
|
746
|
+
for idx in range(level):
|
747
|
+
outfile.write(' ')
|
748
|
+
|
749
|
+
|
750
|
+
def quote_xml(inStr):
|
751
|
+
"Escape markup chars, but do not modify CDATA sections."
|
752
|
+
if not inStr:
|
753
|
+
return ''
|
754
|
+
s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr)
|
755
|
+
s2 = ''
|
756
|
+
pos = 0
|
757
|
+
matchobjects = CDATA_pattern_.finditer(s1)
|
758
|
+
for mo in matchobjects:
|
759
|
+
s3 = s1[pos:mo.start()]
|
760
|
+
s2 += quote_xml_aux(s3)
|
761
|
+
s2 += s1[mo.start():mo.end()]
|
762
|
+
pos = mo.end()
|
763
|
+
s3 = s1[pos:]
|
764
|
+
s2 += quote_xml_aux(s3)
|
765
|
+
return s2
|
766
|
+
|
767
|
+
|
768
|
+
def quote_xml_aux(inStr):
|
769
|
+
s1 = inStr.replace('&', '&')
|
770
|
+
s1 = s1.replace('<', '<')
|
771
|
+
s1 = s1.replace('>', '>')
|
772
|
+
return s1
|
773
|
+
|
774
|
+
|
775
|
+
def quote_attrib(inStr):
|
776
|
+
s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr)
|
777
|
+
s1 = s1.replace('&', '&')
|
778
|
+
s1 = s1.replace('<', '<')
|
779
|
+
s1 = s1.replace('>', '>')
|
780
|
+
s1 = s1.replace('\n', ' ')
|
781
|
+
if '"' in s1:
|
782
|
+
if "'" in s1:
|
783
|
+
s1 = '"%s"' % s1.replace('"', """)
|
784
|
+
else:
|
785
|
+
s1 = "'%s'" % s1
|
786
|
+
else:
|
787
|
+
s1 = '"%s"' % s1
|
788
|
+
return s1
|
789
|
+
|
790
|
+
|
791
|
+
def quote_python(inStr):
|
792
|
+
s1 = inStr
|
793
|
+
if s1.find("'") == -1:
|
794
|
+
if s1.find('\n') == -1:
|
795
|
+
return "'%s'" % s1
|
796
|
+
else:
|
797
|
+
return "'''%s'''" % s1
|
798
|
+
else:
|
799
|
+
if s1.find('"') != -1:
|
800
|
+
s1 = s1.replace('"', '\\"')
|
801
|
+
if s1.find('\n') == -1:
|
802
|
+
return '"%s"' % s1
|
803
|
+
else:
|
804
|
+
return '"""%s"""' % s1
|
805
|
+
|
806
|
+
|
807
|
+
def get_all_text_(node):
|
808
|
+
if node.text is not None:
|
809
|
+
text = node.text
|
810
|
+
else:
|
811
|
+
text = ''
|
812
|
+
for child in node:
|
813
|
+
if child.tail is not None:
|
814
|
+
text += child.tail
|
815
|
+
return text
|
816
|
+
|
817
|
+
|
818
|
+
def find_attr_value_(attr_name, node):
|
819
|
+
attrs = node.attrib
|
820
|
+
attr_parts = attr_name.split(':')
|
821
|
+
value = None
|
822
|
+
if len(attr_parts) == 1:
|
823
|
+
value = attrs.get(attr_name)
|
824
|
+
elif len(attr_parts) == 2:
|
825
|
+
prefix, name = attr_parts
|
826
|
+
if prefix == 'xml':
|
827
|
+
namespace = 'http://www.w3.org/XML/1998/namespace'
|
828
|
+
else:
|
829
|
+
namespace = node.nsmap.get(prefix)
|
830
|
+
if namespace is not None:
|
831
|
+
value = attrs.get('{%s}%s' % (namespace, name, ))
|
832
|
+
return value
|
833
|
+
|
834
|
+
|
835
|
+
def encode_str_2_3(instr):
|
836
|
+
return instr
|
837
|
+
|
838
|
+
|
839
|
+
class GDSParseError(Exception):
|
840
|
+
pass
|
841
|
+
|
842
|
+
|
843
|
+
def raise_parse_error(node, msg):
|
844
|
+
if node is not None:
|
845
|
+
msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, )
|
846
|
+
raise GDSParseError(msg)
|
847
|
+
|
848
|
+
|
849
|
+
class MixedContainer:
|
850
|
+
# Constants for category:
|
851
|
+
CategoryNone = 0
|
852
|
+
CategoryText = 1
|
853
|
+
CategorySimple = 2
|
854
|
+
CategoryComplex = 3
|
855
|
+
# Constants for content_type:
|
856
|
+
TypeNone = 0
|
857
|
+
TypeText = 1
|
858
|
+
TypeString = 2
|
859
|
+
TypeInteger = 3
|
860
|
+
TypeFloat = 4
|
861
|
+
TypeDecimal = 5
|
862
|
+
TypeDouble = 6
|
863
|
+
TypeBoolean = 7
|
864
|
+
TypeBase64 = 8
|
865
|
+
def __init__(self, category, content_type, name, value):
|
866
|
+
self.category = category
|
867
|
+
self.content_type = content_type
|
868
|
+
self.name = name
|
869
|
+
self.value = value
|
870
|
+
def getCategory(self):
|
871
|
+
return self.category
|
872
|
+
def getContenttype(self, content_type):
|
873
|
+
return self.content_type
|
874
|
+
def getValue(self):
|
875
|
+
return self.value
|
876
|
+
def getName(self):
|
877
|
+
return self.name
|
878
|
+
def export(self, outfile, level, name, namespace,
|
879
|
+
pretty_print=True):
|
880
|
+
if self.category == MixedContainer.CategoryText:
|
881
|
+
# Prevent exporting empty content as empty lines.
|
882
|
+
if self.value.strip():
|
883
|
+
outfile.write(self.value)
|
884
|
+
elif self.category == MixedContainer.CategorySimple:
|
885
|
+
self.exportSimple(outfile, level, name)
|
886
|
+
else: # category == MixedContainer.CategoryComplex
|
887
|
+
self.value.export(
|
888
|
+
outfile, level, namespace, name_=name,
|
889
|
+
pretty_print=pretty_print)
|
890
|
+
def exportSimple(self, outfile, level, name):
|
891
|
+
if self.content_type == MixedContainer.TypeString:
|
892
|
+
outfile.write('<%s>%s</%s>' % (
|
893
|
+
self.name, self.value, self.name))
|
894
|
+
elif self.content_type == MixedContainer.TypeInteger or \
|
895
|
+
self.content_type == MixedContainer.TypeBoolean:
|
896
|
+
outfile.write('<%s>%d</%s>' % (
|
897
|
+
self.name, self.value, self.name))
|
898
|
+
elif self.content_type == MixedContainer.TypeFloat or \
|
899
|
+
self.content_type == MixedContainer.TypeDecimal:
|
900
|
+
outfile.write('<%s>%f</%s>' % (
|
901
|
+
self.name, self.value, self.name))
|
902
|
+
elif self.content_type == MixedContainer.TypeDouble:
|
903
|
+
outfile.write('<%s>%g</%s>' % (
|
904
|
+
self.name, self.value, self.name))
|
905
|
+
elif self.content_type == MixedContainer.TypeBase64:
|
906
|
+
outfile.write('<%s>%s</%s>' % (
|
907
|
+
self.name,
|
908
|
+
base64.b64encode(self.value),
|
909
|
+
self.name))
|
910
|
+
def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None):
|
911
|
+
if self.category == MixedContainer.CategoryText:
|
912
|
+
# Prevent exporting empty content as empty lines.
|
913
|
+
if self.value.strip():
|
914
|
+
if len(element) > 0:
|
915
|
+
if element[-1].tail is None:
|
916
|
+
element[-1].tail = self.value
|
917
|
+
else:
|
918
|
+
element[-1].tail += self.value
|
919
|
+
else:
|
920
|
+
if element.text is None:
|
921
|
+
element.text = self.value
|
922
|
+
else:
|
923
|
+
element.text += self.value
|
924
|
+
elif self.category == MixedContainer.CategorySimple:
|
925
|
+
subelement = etree_.SubElement(
|
926
|
+
element, '%s' % self.name)
|
927
|
+
subelement.text = self.to_etree_simple()
|
928
|
+
else: # category == MixedContainer.CategoryComplex
|
929
|
+
self.value.to_etree(element)
|
930
|
+
def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None):
|
931
|
+
if self.content_type == MixedContainer.TypeString:
|
932
|
+
text = self.value
|
933
|
+
elif (self.content_type == MixedContainer.TypeInteger or
|
934
|
+
self.content_type == MixedContainer.TypeBoolean):
|
935
|
+
text = '%d' % self.value
|
936
|
+
elif (self.content_type == MixedContainer.TypeFloat or
|
937
|
+
self.content_type == MixedContainer.TypeDecimal):
|
938
|
+
text = '%f' % self.value
|
939
|
+
elif self.content_type == MixedContainer.TypeDouble:
|
940
|
+
text = '%g' % self.value
|
941
|
+
elif self.content_type == MixedContainer.TypeBase64:
|
942
|
+
text = '%s' % base64.b64encode(self.value)
|
943
|
+
return text
|
944
|
+
def exportLiteral(self, outfile, level, name):
|
945
|
+
if self.category == MixedContainer.CategoryText:
|
946
|
+
showIndent(outfile, level)
|
947
|
+
outfile.write(
|
948
|
+
'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % (
|
949
|
+
self.category, self.content_type,
|
950
|
+
self.name, self.value))
|
951
|
+
elif self.category == MixedContainer.CategorySimple:
|
952
|
+
showIndent(outfile, level)
|
953
|
+
outfile.write(
|
954
|
+
'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % (
|
955
|
+
self.category, self.content_type,
|
956
|
+
self.name, self.value))
|
957
|
+
else: # category == MixedContainer.CategoryComplex
|
958
|
+
showIndent(outfile, level)
|
959
|
+
outfile.write(
|
960
|
+
'model_.MixedContainer(%d, %d, "%s",\n' % (
|
961
|
+
self.category, self.content_type, self.name,))
|
962
|
+
self.value.exportLiteral(outfile, level + 1)
|
963
|
+
showIndent(outfile, level)
|
964
|
+
outfile.write(')\n')
|
965
|
+
|
966
|
+
|
967
|
+
class MemberSpec_(object):
|
968
|
+
def __init__(self, name='', data_type='', container=0,
|
969
|
+
optional=0, child_attrs=None, choice=None):
|
970
|
+
self.name = name
|
971
|
+
self.data_type = data_type
|
972
|
+
self.container = container
|
973
|
+
self.child_attrs = child_attrs
|
974
|
+
self.choice = choice
|
975
|
+
self.optional = optional
|
976
|
+
def set_name(self, name): self.name = name
|
977
|
+
def get_name(self): return self.name
|
978
|
+
def set_data_type(self, data_type): self.data_type = data_type
|
979
|
+
def get_data_type_chain(self): return self.data_type
|
980
|
+
def get_data_type(self):
|
981
|
+
if isinstance(self.data_type, list):
|
982
|
+
if len(self.data_type) > 0:
|
983
|
+
return self.data_type[-1]
|
984
|
+
else:
|
985
|
+
return 'xs:string'
|
986
|
+
else:
|
987
|
+
return self.data_type
|
988
|
+
def set_container(self, container): self.container = container
|
989
|
+
def get_container(self): return self.container
|
990
|
+
def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs
|
991
|
+
def get_child_attrs(self): return self.child_attrs
|
992
|
+
def set_choice(self, choice): self.choice = choice
|
993
|
+
def get_choice(self): return self.choice
|
994
|
+
def set_optional(self, optional): self.optional = optional
|
995
|
+
def get_optional(self): return self.optional
|
996
|
+
|
997
|
+
|
998
|
+
def _cast(typ, value):
|
999
|
+
if typ is None or value is None:
|
1000
|
+
return value
|
1001
|
+
return typ(value)
|
1002
|
+
|
1003
|
+
|
1004
|
+
#
|
1005
|
+
# Start enum classes
|
1006
|
+
#
|
1007
|
+
#
|
1008
|
+
# Start data representation classes
|
1009
|
+
#
|
1010
|
+
#
|
1011
|
+
# End data representation classes.
|
1012
|
+
#
|
1013
|
+
|
1014
|
+
|
1015
|
+
GDSClassesMapping = {
|
1016
|
+
}
|
1017
|
+
|
1018
|
+
|
1019
|
+
USAGE_TEXT = """
|
1020
|
+
Usage: python <Parser>.py [ -s ] <in_xml_file>
|
1021
|
+
"""
|
1022
|
+
|
1023
|
+
|
1024
|
+
def usage():
|
1025
|
+
print(USAGE_TEXT)
|
1026
|
+
sys.exit(1)
|
1027
|
+
|
1028
|
+
|
1029
|
+
def get_root_tag(node):
|
1030
|
+
tag = Tag_pattern_.match(node.tag).groups()[-1]
|
1031
|
+
prefix_tag = TagNamePrefix + tag
|
1032
|
+
rootClass = GDSClassesMapping.get(prefix_tag)
|
1033
|
+
if rootClass is None:
|
1034
|
+
rootClass = globals().get(prefix_tag)
|
1035
|
+
return tag, rootClass
|
1036
|
+
|
1037
|
+
|
1038
|
+
def get_required_ns_prefix_defs(rootNode):
|
1039
|
+
'''Get all name space prefix definitions required in this XML doc.
|
1040
|
+
Return a dictionary of definitions and a char string of definitions.
|
1041
|
+
'''
|
1042
|
+
nsmap = {
|
1043
|
+
prefix: uri
|
1044
|
+
for node in rootNode.iter()
|
1045
|
+
for (prefix, uri) in node.nsmap.items()
|
1046
|
+
if prefix is not None
|
1047
|
+
}
|
1048
|
+
namespacedefs = ' '.join([
|
1049
|
+
'xmlns:{}="{}"'.format(prefix, uri)
|
1050
|
+
for prefix, uri in nsmap.items()
|
1051
|
+
])
|
1052
|
+
return nsmap, namespacedefs
|
1053
|
+
|
1054
|
+
|
1055
|
+
def parse(inFileName, silence=False, print_warnings=True):
|
1056
|
+
global CapturedNsmap_
|
1057
|
+
gds_collector = GdsCollector_()
|
1058
|
+
parser = None
|
1059
|
+
doc = parsexml_(inFileName, parser)
|
1060
|
+
rootNode = doc.getroot()
|
1061
|
+
rootTag, rootClass = get_root_tag(rootNode)
|
1062
|
+
if rootClass is None:
|
1063
|
+
rootTag = 'xsd_string'
|
1064
|
+
rootClass = xsd_string
|
1065
|
+
rootObj = rootClass.factory()
|
1066
|
+
rootObj.build(rootNode, gds_collector_=gds_collector)
|
1067
|
+
CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode)
|
1068
|
+
if not SaveElementTreeNode:
|
1069
|
+
doc = None
|
1070
|
+
rootNode = None
|
1071
|
+
if not silence:
|
1072
|
+
sys.stdout.write('<?xml version="1.0" ?>\n')
|
1073
|
+
rootObj.export(
|
1074
|
+
sys.stdout, 0, name_=rootTag,
|
1075
|
+
namespacedef_=namespacedefs,
|
1076
|
+
pretty_print=True)
|
1077
|
+
if print_warnings and len(gds_collector.get_messages()) > 0:
|
1078
|
+
separator = ('-' * 50) + '\n'
|
1079
|
+
sys.stderr.write(separator)
|
1080
|
+
sys.stderr.write('----- Warnings -- count: {} -----\n'.format(
|
1081
|
+
len(gds_collector.get_messages()), ))
|
1082
|
+
gds_collector.write_messages(sys.stderr)
|
1083
|
+
sys.stderr.write(separator)
|
1084
|
+
return rootObj
|
1085
|
+
|
1086
|
+
|
1087
|
+
def parseEtree(inFileName, silence=False, print_warnings=True,
|
1088
|
+
mapping=None, reverse_mapping=None, nsmap=None):
|
1089
|
+
parser = None
|
1090
|
+
doc = parsexml_(inFileName, parser)
|
1091
|
+
gds_collector = GdsCollector_()
|
1092
|
+
rootNode = doc.getroot()
|
1093
|
+
rootTag, rootClass = get_root_tag(rootNode)
|
1094
|
+
if rootClass is None:
|
1095
|
+
rootTag = 'xsd_string'
|
1096
|
+
rootClass = xsd_string
|
1097
|
+
rootObj = rootClass.factory()
|
1098
|
+
rootObj.build(rootNode, gds_collector_=gds_collector)
|
1099
|
+
if mapping is None:
|
1100
|
+
mapping = {}
|
1101
|
+
if reverse_mapping is None:
|
1102
|
+
reverse_mapping = {}
|
1103
|
+
rootElement = rootObj.to_etree(
|
1104
|
+
None, name_=rootTag, mapping_=mapping,
|
1105
|
+
reverse_mapping_=reverse_mapping, nsmap_=nsmap)
|
1106
|
+
reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping)
|
1107
|
+
# Enable Python to collect the space used by the DOM.
|
1108
|
+
if not SaveElementTreeNode:
|
1109
|
+
doc = None
|
1110
|
+
rootNode = None
|
1111
|
+
if not silence:
|
1112
|
+
content = etree_.tostring(
|
1113
|
+
rootElement, pretty_print=True,
|
1114
|
+
xml_declaration=True, encoding="utf-8")
|
1115
|
+
sys.stdout.write(str(content))
|
1116
|
+
sys.stdout.write('\n')
|
1117
|
+
if print_warnings and len(gds_collector.get_messages()) > 0:
|
1118
|
+
separator = ('-' * 50) + '\n'
|
1119
|
+
sys.stderr.write(separator)
|
1120
|
+
sys.stderr.write('----- Warnings -- count: {} -----\n'.format(
|
1121
|
+
len(gds_collector.get_messages()), ))
|
1122
|
+
gds_collector.write_messages(sys.stderr)
|
1123
|
+
sys.stderr.write(separator)
|
1124
|
+
return rootObj, rootElement, mapping, reverse_node_mapping
|
1125
|
+
|
1126
|
+
|
1127
|
+
def parseString(inString, silence=False, print_warnings=True):
|
1128
|
+
'''Parse a string, create the object tree, and export it.
|
1129
|
+
|
1130
|
+
Arguments:
|
1131
|
+
- inString -- A string. This XML fragment should not start
|
1132
|
+
with an XML declaration containing an encoding.
|
1133
|
+
- silence -- A boolean. If False, export the object.
|
1134
|
+
Returns -- The root object in the tree.
|
1135
|
+
'''
|
1136
|
+
parser = None
|
1137
|
+
rootNode= parsexmlstring_(inString, parser)
|
1138
|
+
gds_collector = GdsCollector_()
|
1139
|
+
rootTag, rootClass = get_root_tag(rootNode)
|
1140
|
+
if rootClass is None:
|
1141
|
+
rootTag = 'xsd_string'
|
1142
|
+
rootClass = xsd_string
|
1143
|
+
rootObj = rootClass.factory()
|
1144
|
+
rootObj.build(rootNode, gds_collector_=gds_collector)
|
1145
|
+
if not SaveElementTreeNode:
|
1146
|
+
rootNode = None
|
1147
|
+
if not silence:
|
1148
|
+
sys.stdout.write('<?xml version="1.0" ?>\n')
|
1149
|
+
rootObj.export(
|
1150
|
+
sys.stdout, 0, name_=rootTag,
|
1151
|
+
namespacedef_='')
|
1152
|
+
if print_warnings and len(gds_collector.get_messages()) > 0:
|
1153
|
+
separator = ('-' * 50) + '\n'
|
1154
|
+
sys.stderr.write(separator)
|
1155
|
+
sys.stderr.write('----- Warnings -- count: {} -----\n'.format(
|
1156
|
+
len(gds_collector.get_messages()), ))
|
1157
|
+
gds_collector.write_messages(sys.stderr)
|
1158
|
+
sys.stderr.write(separator)
|
1159
|
+
return rootObj
|
1160
|
+
|
1161
|
+
|
1162
|
+
def parseLiteral(inFileName, silence=False, print_warnings=True):
|
1163
|
+
parser = None
|
1164
|
+
doc = parsexml_(inFileName, parser)
|
1165
|
+
gds_collector = GdsCollector_()
|
1166
|
+
rootNode = doc.getroot()
|
1167
|
+
rootTag, rootClass = get_root_tag(rootNode)
|
1168
|
+
if rootClass is None:
|
1169
|
+
rootTag = 'xsd_string'
|
1170
|
+
rootClass = xsd_string
|
1171
|
+
rootObj = rootClass.factory()
|
1172
|
+
rootObj.build(rootNode, gds_collector_=gds_collector)
|
1173
|
+
# Enable Python to collect the space used by the DOM.
|
1174
|
+
if not SaveElementTreeNode:
|
1175
|
+
doc = None
|
1176
|
+
rootNode = None
|
1177
|
+
if not silence:
|
1178
|
+
sys.stdout.write('#from shipping_common_definitions import *\n\n')
|
1179
|
+
sys.stdout.write('import shipping_common_definitions as model_\n\n')
|
1180
|
+
sys.stdout.write('rootObj = model_.rootClass(\n')
|
1181
|
+
rootObj.exportLiteral(sys.stdout, 0, name_=rootTag)
|
1182
|
+
sys.stdout.write(')\n')
|
1183
|
+
if print_warnings and len(gds_collector.get_messages()) > 0:
|
1184
|
+
separator = ('-' * 50) + '\n'
|
1185
|
+
sys.stderr.write(separator)
|
1186
|
+
sys.stderr.write('----- Warnings -- count: {} -----\n'.format(
|
1187
|
+
len(gds_collector.get_messages()), ))
|
1188
|
+
gds_collector.write_messages(sys.stderr)
|
1189
|
+
sys.stderr.write(separator)
|
1190
|
+
return rootObj
|
1191
|
+
|
1192
|
+
|
1193
|
+
def main():
|
1194
|
+
args = sys.argv[1:]
|
1195
|
+
if len(args) == 1:
|
1196
|
+
parse(args[0])
|
1197
|
+
else:
|
1198
|
+
usage()
|
1199
|
+
|
1200
|
+
|
1201
|
+
if __name__ == '__main__':
|
1202
|
+
#import pdb; pdb.set_trace()
|
1203
|
+
main()
|
1204
|
+
|
1205
|
+
RenameMappings_ = {
|
1206
|
+
}
|
1207
|
+
|
1208
|
+
#
|
1209
|
+
# Mapping of namespaces to types defined in them
|
1210
|
+
# and the file in which each is defined.
|
1211
|
+
# simpleTypes are marked "ST" and complexTypes "CT".
|
1212
|
+
NamespaceToDefMappings_ = {}
|
1213
|
+
|
1214
|
+
__all__ = [
|
1215
|
+
|
1216
|
+
]
|