From ae01ed0f83f4b17dfaf49556085dad981f1de8ac Mon Sep 17 00:00:00 2001 From: Daniel K Date: Sat, 4 Nov 2023 00:24:54 -0700 Subject: [PATCH] (clean) up old files --- schemas/README.md | 27 - schemas/usps/README.md | 19 - schemas/usps/generate | 68 - schemas/usps/karrio/schemas/usps/__init__.py | 0 .../schemas/usps/address_validate_request.py | 1552 ------- .../schemas/usps/address_validate_response.py | 1711 ------- .../carrier_pickup_availability_request.py | 1447 ------ .../carrier_pickup_availability_response.py | 1470 ------ .../usps/carrier_pickup_cancel_request.py | 1447 ------ .../usps/carrier_pickup_cancel_response.py | 1743 ------- .../usps/carrier_pickup_change_request.py | 1720 ------- .../usps/carrier_pickup_change_response.py | 1743 ------- .../usps/carrier_pickup_inquiry_request.py | 1447 ------ .../usps/carrier_pickup_inquiry_response.py | 1743 ------- .../usps/carrier_pickup_schedule_request.py | 1703 ------- .../usps/carrier_pickup_schedule_response.py | 1743 ------- .../schemas/usps/city_state_lookup_request.py | 1416 ------ .../usps/city_state_lookup_response.py | 1448 ------ .../schemas/usps/emrsv4_0_bulk_request.py | 1822 -------- schemas/usps/karrio/schemas/usps/error.py | 1368 ------ .../karrio/schemas/usps/evs_cancel_request.py | 1311 ------ .../schemas/usps/evs_cancel_response.py | 1334 ------ .../usps/evs_express_mail_intl_request.py | 3332 -------------- .../usps/evs_express_mail_intl_response.py | 1589 ------- .../usps/evs_first_class_mail_intl_request.py | 3150 ------------- .../evs_first_class_mail_intl_response.py | 1735 ------- .../schemas/usps/evs_gxg_get_label_request.py | 3341 -------------- .../usps/evs_gxg_get_label_response.py | 1683 ------- .../usps/evs_priority_mail_intl_request.py | 3422 -------------- .../usps/evs_priority_mail_intl_response.py | 1820 -------- .../usps/karrio/schemas/usps/evs_request.py | 4010 ----------------- .../usps/karrio/schemas/usps/evs_response.py | 1968 -------- .../schemas/usps/evsi_cancel_request.py | 1311 ------ .../schemas/usps/evsi_cancel_response.py | 1334 ------ .../usps/express_mail_commitment_request.py | 1413 ------ .../usps/express_mail_commitment_response.py | 1835 -------- .../schemas/usps/first_class_mail_request.py | 1379 ------ .../schemas/usps/first_class_mail_response.py | 1385 ------ .../schemas/usps/hfp_facility_info_request.py | 1379 ------ .../usps/hfp_facility_info_response.py | 1590 ------- .../schemas/usps/intl_rate_v2_request.py | 2126 --------- .../schemas/usps/intl_rate_v2_response.py | 2866 ------------ .../karrio/schemas/usps/mrsv4_0_request.py | 1804 -------- .../schemas/usps/priority_mail_request.py | 1379 ------ .../schemas/usps/priority_mail_response.py | 1385 ------ .../karrio/schemas/usps/pts_email_request.py | 1473 ------ .../karrio/schemas/usps/pts_emailresult.py | 1317 ------ .../karrio/schemas/usps/ptspod_request.py | 1617 ------- .../usps/karrio/schemas/usps/ptspod_result.py | 1317 ------ .../karrio/schemas/usps/ptsrre_request.py | 1481 ------ .../usps/karrio/schemas/usps/ptsrre_result.py | 1317 ------ .../karrio/schemas/usps/ptstpod_request.py | 1498 ------ .../karrio/schemas/usps/ptstpod_result.py | 1317 ------ .../karrio/schemas/usps/rate_v4_request.py | 2195 --------- .../karrio/schemas/usps/rate_v4_response.py | 2720 ----------- .../usps/karrio/schemas/usps/scan_request.py | 1831 -------- .../usps/karrio/schemas/usps/scan_response.py | 1531 ------- .../schemas/usps/sdc_get_locations_request.py | 1413 ------ .../usps/sdc_get_locations_response.py | 3206 ------------- .../karrio/schemas/usps/standard_b_request.py | 1362 ------ .../schemas/usps/standard_b_response.py | 1385 ------ .../schemas/usps/track_field_request.py | 1496 ------ .../usps/karrio/schemas/usps/track_request.py | 1411 ------ .../karrio/schemas/usps/track_response.py | 3338 -------------- .../schemas/usps/zip_code_lookup_request.py | 1518 ------- .../schemas/usps/zip_code_lookup_response.py | 1533 ------- .../usps/schemas/AddressValidateRequest.xsd | 25 - .../usps/schemas/AddressValidateResponse.xsd | 34 - .../CarrierPickupAvailabilityRequest.xsd | 18 - .../CarrierPickupAvailabilityResponse.xsd | 19 - .../schemas/CarrierPickupCancelRequest.xsd | 18 - .../schemas/CarrierPickupCancelResponse.xsd | 35 - .../schemas/CarrierPickupChangeRequest.xsd | 34 - .../schemas/CarrierPickupChangeResponse.xsd | 35 - .../schemas/CarrierPickupInquiryRequest.xsd | 18 - .../schemas/CarrierPickupInquiryResponse.xsd | 35 - .../schemas/CarrierPickupScheduleRequest.xsd | 33 - .../schemas/CarrierPickupScheduleResponse.xsd | 35 - .../usps/schemas/CityStateLookupRequest.xsd | 17 - .../usps/schemas/CityStateLookupResponse.xsd | 18 - schemas/usps/schemas/EMRSV4.0BulkRequest.xsd | 40 - schemas/usps/schemas/Error.xsd | 13 - .../schemas/ExpressMailCommitmentRequest.xsd | 17 - .../schemas/ExpressMailCommitmentResponse.xsd | 41 - .../usps/schemas/FirstClassMailRequest.xsd | 15 - .../usps/schemas/FirstClassMailResponse.xsd | 15 - .../usps/schemas/HFPFacilityInfoRequest.xsd | 15 - .../usps/schemas/HFPFacilityInfoResponse.xsd | 27 - schemas/usps/schemas/IntlRateV2Request.xsd | 72 - schemas/usps/schemas/IntlRateV2Response.xsd | 104 - schemas/usps/schemas/MRSV4.0Request.xsd | 40 - schemas/usps/schemas/PTSEmailRequest.xsd | 20 - schemas/usps/schemas/PTSEmailResult.xsd | 11 - schemas/usps/schemas/PTSPODRequest.xsd | 29 - schemas/usps/schemas/PTSPODResult.xsd | 11 - schemas/usps/schemas/PTSRRERequest.xsd | 21 - schemas/usps/schemas/PTSRREResult.xsd | 11 - schemas/usps/schemas/PTSTPODResult.xsd | 11 - schemas/usps/schemas/PTSTPodRequest.xsd | 22 - schemas/usps/schemas/PriorityMailRequest.xsd | 15 - schemas/usps/schemas/PriorityMailResponse.xsd | 15 - schemas/usps/schemas/RateV4Request.xsd | 80 - schemas/usps/schemas/RateV4Response.xsd | 85 - schemas/usps/schemas/SCANRequest.xsd | 43 - schemas/usps/schemas/SCANResponse.xsd | 32 - .../usps/schemas/SDCGetLocationsRequest.xsd | 17 - .../usps/schemas/SDCGetLocationsResponse.xsd | 124 - schemas/usps/schemas/StandardBRequest.xsd | 14 - schemas/usps/schemas/StandardBResponse.xsd | 15 - schemas/usps/schemas/TrackFieldRequest.xsd | 27 - schemas/usps/schemas/TrackRequest.xsd | 19 - schemas/usps/schemas/TrackResponse.xsd | 132 - schemas/usps/schemas/ZipCodeLookupRequest.xsd | 24 - .../usps/schemas/ZipCodeLookupResponse.xsd | 24 - schemas/usps/schemas/eVSCancelRequest.xsd | 10 - schemas/usps/schemas/eVSCancelResponse.xsd | 11 - .../schemas/eVSExpressMailIntlRequest.xsd | 131 - .../schemas/eVSExpressMailIntlResponse.xsd | 27 - .../schemas/eVSFirstClassMailIntlRequest.xsd | 120 - .../schemas/eVSFirstClassMailIntlResponse.xsd | 36 - .../usps/schemas/eVSGXGGetLabelRequest.xsd | 132 - .../usps/schemas/eVSGXGGetLabelResponse.xsd | 33 - schemas/usps/schemas/eVSICancelRequest.xsd | 11 - schemas/usps/schemas/eVSICancelResponse.xsd | 12 - .../schemas/eVSPriorityMailIntlRequest.xsd | 136 - .../schemas/eVSPriorityMailIntlResponse.xsd | 41 - schemas/usps/schemas/eVSRequest.xsd | 176 - schemas/usps/schemas/eVSResponse.xsd | 53 - schemas/usps/setup.py | 26 - .../colissimo/{setup.py => _setup.py} | 0 130 files changed, 114324 deletions(-) delete mode 100644 schemas/README.md delete mode 100644 schemas/usps/README.md delete mode 100755 schemas/usps/generate delete mode 100644 schemas/usps/karrio/schemas/usps/__init__.py delete mode 100644 schemas/usps/karrio/schemas/usps/address_validate_request.py delete mode 100644 schemas/usps/karrio/schemas/usps/address_validate_response.py delete mode 100644 schemas/usps/karrio/schemas/usps/carrier_pickup_availability_request.py delete mode 100644 schemas/usps/karrio/schemas/usps/carrier_pickup_availability_response.py delete mode 100644 schemas/usps/karrio/schemas/usps/carrier_pickup_cancel_request.py delete mode 100644 schemas/usps/karrio/schemas/usps/carrier_pickup_cancel_response.py delete mode 100644 schemas/usps/karrio/schemas/usps/carrier_pickup_change_request.py delete mode 100644 schemas/usps/karrio/schemas/usps/carrier_pickup_change_response.py delete mode 100644 schemas/usps/karrio/schemas/usps/carrier_pickup_inquiry_request.py delete mode 100644 schemas/usps/karrio/schemas/usps/carrier_pickup_inquiry_response.py delete mode 100644 schemas/usps/karrio/schemas/usps/carrier_pickup_schedule_request.py delete mode 100644 schemas/usps/karrio/schemas/usps/carrier_pickup_schedule_response.py delete mode 100644 schemas/usps/karrio/schemas/usps/city_state_lookup_request.py delete mode 100644 schemas/usps/karrio/schemas/usps/city_state_lookup_response.py delete mode 100644 schemas/usps/karrio/schemas/usps/emrsv4_0_bulk_request.py delete mode 100644 schemas/usps/karrio/schemas/usps/error.py delete mode 100644 schemas/usps/karrio/schemas/usps/evs_cancel_request.py delete mode 100644 schemas/usps/karrio/schemas/usps/evs_cancel_response.py delete mode 100644 schemas/usps/karrio/schemas/usps/evs_express_mail_intl_request.py delete mode 100644 schemas/usps/karrio/schemas/usps/evs_express_mail_intl_response.py delete mode 100644 schemas/usps/karrio/schemas/usps/evs_first_class_mail_intl_request.py delete mode 100644 schemas/usps/karrio/schemas/usps/evs_first_class_mail_intl_response.py delete mode 100644 schemas/usps/karrio/schemas/usps/evs_gxg_get_label_request.py delete mode 100644 schemas/usps/karrio/schemas/usps/evs_gxg_get_label_response.py delete mode 100644 schemas/usps/karrio/schemas/usps/evs_priority_mail_intl_request.py delete mode 100644 schemas/usps/karrio/schemas/usps/evs_priority_mail_intl_response.py delete mode 100644 schemas/usps/karrio/schemas/usps/evs_request.py delete mode 100644 schemas/usps/karrio/schemas/usps/evs_response.py delete mode 100644 schemas/usps/karrio/schemas/usps/evsi_cancel_request.py delete mode 100644 schemas/usps/karrio/schemas/usps/evsi_cancel_response.py delete mode 100644 schemas/usps/karrio/schemas/usps/express_mail_commitment_request.py delete mode 100644 schemas/usps/karrio/schemas/usps/express_mail_commitment_response.py delete mode 100644 schemas/usps/karrio/schemas/usps/first_class_mail_request.py delete mode 100644 schemas/usps/karrio/schemas/usps/first_class_mail_response.py delete mode 100644 schemas/usps/karrio/schemas/usps/hfp_facility_info_request.py delete mode 100644 schemas/usps/karrio/schemas/usps/hfp_facility_info_response.py delete mode 100644 schemas/usps/karrio/schemas/usps/intl_rate_v2_request.py delete mode 100644 schemas/usps/karrio/schemas/usps/intl_rate_v2_response.py delete mode 100644 schemas/usps/karrio/schemas/usps/mrsv4_0_request.py delete mode 100644 schemas/usps/karrio/schemas/usps/priority_mail_request.py delete mode 100644 schemas/usps/karrio/schemas/usps/priority_mail_response.py delete mode 100644 schemas/usps/karrio/schemas/usps/pts_email_request.py delete mode 100644 schemas/usps/karrio/schemas/usps/pts_emailresult.py delete mode 100644 schemas/usps/karrio/schemas/usps/ptspod_request.py delete mode 100644 schemas/usps/karrio/schemas/usps/ptspod_result.py delete mode 100644 schemas/usps/karrio/schemas/usps/ptsrre_request.py delete mode 100644 schemas/usps/karrio/schemas/usps/ptsrre_result.py delete mode 100644 schemas/usps/karrio/schemas/usps/ptstpod_request.py delete mode 100644 schemas/usps/karrio/schemas/usps/ptstpod_result.py delete mode 100644 schemas/usps/karrio/schemas/usps/rate_v4_request.py delete mode 100644 schemas/usps/karrio/schemas/usps/rate_v4_response.py delete mode 100644 schemas/usps/karrio/schemas/usps/scan_request.py delete mode 100644 schemas/usps/karrio/schemas/usps/scan_response.py delete mode 100644 schemas/usps/karrio/schemas/usps/sdc_get_locations_request.py delete mode 100644 schemas/usps/karrio/schemas/usps/sdc_get_locations_response.py delete mode 100644 schemas/usps/karrio/schemas/usps/standard_b_request.py delete mode 100644 schemas/usps/karrio/schemas/usps/standard_b_response.py delete mode 100644 schemas/usps/karrio/schemas/usps/track_field_request.py delete mode 100644 schemas/usps/karrio/schemas/usps/track_request.py delete mode 100644 schemas/usps/karrio/schemas/usps/track_response.py delete mode 100644 schemas/usps/karrio/schemas/usps/zip_code_lookup_request.py delete mode 100644 schemas/usps/karrio/schemas/usps/zip_code_lookup_response.py delete mode 100644 schemas/usps/schemas/AddressValidateRequest.xsd delete mode 100644 schemas/usps/schemas/AddressValidateResponse.xsd delete mode 100644 schemas/usps/schemas/CarrierPickupAvailabilityRequest.xsd delete mode 100644 schemas/usps/schemas/CarrierPickupAvailabilityResponse.xsd delete mode 100644 schemas/usps/schemas/CarrierPickupCancelRequest.xsd delete mode 100644 schemas/usps/schemas/CarrierPickupCancelResponse.xsd delete mode 100644 schemas/usps/schemas/CarrierPickupChangeRequest.xsd delete mode 100644 schemas/usps/schemas/CarrierPickupChangeResponse.xsd delete mode 100644 schemas/usps/schemas/CarrierPickupInquiryRequest.xsd delete mode 100644 schemas/usps/schemas/CarrierPickupInquiryResponse.xsd delete mode 100644 schemas/usps/schemas/CarrierPickupScheduleRequest.xsd delete mode 100644 schemas/usps/schemas/CarrierPickupScheduleResponse.xsd delete mode 100644 schemas/usps/schemas/CityStateLookupRequest.xsd delete mode 100644 schemas/usps/schemas/CityStateLookupResponse.xsd delete mode 100644 schemas/usps/schemas/EMRSV4.0BulkRequest.xsd delete mode 100644 schemas/usps/schemas/Error.xsd delete mode 100644 schemas/usps/schemas/ExpressMailCommitmentRequest.xsd delete mode 100644 schemas/usps/schemas/ExpressMailCommitmentResponse.xsd delete mode 100644 schemas/usps/schemas/FirstClassMailRequest.xsd delete mode 100644 schemas/usps/schemas/FirstClassMailResponse.xsd delete mode 100644 schemas/usps/schemas/HFPFacilityInfoRequest.xsd delete mode 100644 schemas/usps/schemas/HFPFacilityInfoResponse.xsd delete mode 100644 schemas/usps/schemas/IntlRateV2Request.xsd delete mode 100644 schemas/usps/schemas/IntlRateV2Response.xsd delete mode 100644 schemas/usps/schemas/MRSV4.0Request.xsd delete mode 100644 schemas/usps/schemas/PTSEmailRequest.xsd delete mode 100644 schemas/usps/schemas/PTSEmailResult.xsd delete mode 100644 schemas/usps/schemas/PTSPODRequest.xsd delete mode 100644 schemas/usps/schemas/PTSPODResult.xsd delete mode 100644 schemas/usps/schemas/PTSRRERequest.xsd delete mode 100644 schemas/usps/schemas/PTSRREResult.xsd delete mode 100644 schemas/usps/schemas/PTSTPODResult.xsd delete mode 100644 schemas/usps/schemas/PTSTPodRequest.xsd delete mode 100644 schemas/usps/schemas/PriorityMailRequest.xsd delete mode 100644 schemas/usps/schemas/PriorityMailResponse.xsd delete mode 100644 schemas/usps/schemas/RateV4Request.xsd delete mode 100644 schemas/usps/schemas/RateV4Response.xsd delete mode 100644 schemas/usps/schemas/SCANRequest.xsd delete mode 100644 schemas/usps/schemas/SCANResponse.xsd delete mode 100644 schemas/usps/schemas/SDCGetLocationsRequest.xsd delete mode 100644 schemas/usps/schemas/SDCGetLocationsResponse.xsd delete mode 100644 schemas/usps/schemas/StandardBRequest.xsd delete mode 100644 schemas/usps/schemas/StandardBResponse.xsd delete mode 100644 schemas/usps/schemas/TrackFieldRequest.xsd delete mode 100644 schemas/usps/schemas/TrackRequest.xsd delete mode 100644 schemas/usps/schemas/TrackResponse.xsd delete mode 100644 schemas/usps/schemas/ZipCodeLookupRequest.xsd delete mode 100644 schemas/usps/schemas/ZipCodeLookupResponse.xsd delete mode 100644 schemas/usps/schemas/eVSCancelRequest.xsd delete mode 100644 schemas/usps/schemas/eVSCancelResponse.xsd delete mode 100644 schemas/usps/schemas/eVSExpressMailIntlRequest.xsd delete mode 100644 schemas/usps/schemas/eVSExpressMailIntlResponse.xsd delete mode 100644 schemas/usps/schemas/eVSFirstClassMailIntlRequest.xsd delete mode 100644 schemas/usps/schemas/eVSFirstClassMailIntlResponse.xsd delete mode 100644 schemas/usps/schemas/eVSGXGGetLabelRequest.xsd delete mode 100644 schemas/usps/schemas/eVSGXGGetLabelResponse.xsd delete mode 100644 schemas/usps/schemas/eVSICancelRequest.xsd delete mode 100644 schemas/usps/schemas/eVSICancelResponse.xsd delete mode 100644 schemas/usps/schemas/eVSPriorityMailIntlRequest.xsd delete mode 100644 schemas/usps/schemas/eVSPriorityMailIntlResponse.xsd delete mode 100644 schemas/usps/schemas/eVSRequest.xsd delete mode 100644 schemas/usps/schemas/eVSResponse.xsd delete mode 100644 schemas/usps/setup.py rename sdk/extensions/colissimo/{setup.py => _setup.py} (100%) diff --git a/schemas/README.md b/schemas/README.md deleted file mode 100644 index 00fd5888a1..0000000000 --- a/schemas/README.md +++ /dev/null @@ -1,27 +0,0 @@ -# carriers and tools generated liraries - -- [Australia Post - carrier.australiapost](/australiapost) -- [Andreani - carrier.andreani](/andreani) -- [Asendia US - carrier.asendia_us](/asendia_us) -- [BoxKnight - carrier.boxknight](/boxknight) -- [Canada Post - carrier.canadapost](/canadapost) -- [Canpar - carrier.canpar](/canpar) -- [DHL Express - carrier.dhl_express](/dhl_express) -- [DHL eCommerce - carrier.dhl_ecommerce](/dhl_ecommerce) -- [DHL Universal Tracking - carrier.dhl_universal](/dhl_universal) -- [Dicom - carrier.dicom](/dicom) -- [FedEx - carrier.fedex](/fedex) -- [ICS Courier - carrier.ics_courier](/ics_courier) -- [Nationex - carrier.nationex](/nationex) -- [OCA - carrier.oca](/oca) -- [Purolator - carrier.purolator](/purolator) -- [Sendle - carrier.sendle](/sendle) -- [SF-Express - carrier.sf_express](/sf_express) -- [UPS - carrier.ups](/ups) -- [USPS - carrier.usps](/usps) -- [Yanwen - carrier.yanwen](/yanwen) -- [Yunexpress - carrier.yunexpress](/yunexpress) - -## Tools - -- [SOAP - pysoap](/soap) diff --git a/schemas/usps/README.md b/schemas/usps/README.md deleted file mode 100644 index a89ce0a9fd..0000000000 --- a/schemas/usps/README.md +++ /dev/null @@ -1,19 +0,0 @@ -# usps - -USPS Web API schemas Python Data Types generated with [generateDS](http://www.davekuhlman.org/generateDS.html) - -## Installation - -```bash -pip install carrier.usps -``` - -## Usage - -```python -import usps_lib - -help(usps_lib) -``` - -*This package is used by the [Karrio Multi-carrier Shipping Interface](https://github.com/PurplShip/karrio)* diff --git a/schemas/usps/generate b/schemas/usps/generate deleted file mode 100755 index f8519c5fd1..0000000000 --- a/schemas/usps/generate +++ /dev/null @@ -1,68 +0,0 @@ -SCHEMAS=./schemas -LIB_MODULES=./karrio/schemas/usps -mkdir -p $LIB_MODULES -find $LIB_MODULES -name "*.py" -exec rm -r {} \; -touch $LIB_MODULES/__init__.py - -generateDS --no-namespace-defs -o "$LIB_MODULES/address_validate_request.py" $SCHEMAS/AddressValidateRequest.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/address_validate_response.py" $SCHEMAS/AddressValidateResponse.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/carrier_pickup_availability_request.py" $SCHEMAS/CarrierPickupAvailabilityRequest.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/carrier_pickup_availability_response.py" $SCHEMAS/CarrierPickupAvailabilityResponse.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/carrier_pickup_cancel_request.py" $SCHEMAS/CarrierPickupCancelRequest.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/carrier_pickup_cancel_response.py" $SCHEMAS/CarrierPickupCancelResponse.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/carrier_pickup_change_request.py" $SCHEMAS/CarrierPickupChangeRequest.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/carrier_pickup_change_response.py" $SCHEMAS/CarrierPickupChangeResponse.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/carrier_pickup_inquiry_request.py" $SCHEMAS/CarrierPickupInquiryRequest.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/carrier_pickup_inquiry_response.py" $SCHEMAS/CarrierPickupInquiryResponse.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/carrier_pickup_schedule_request.py" $SCHEMAS/CarrierPickupScheduleRequest.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/carrier_pickup_schedule_response.py" $SCHEMAS/CarrierPickupScheduleResponse.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/city_state_lookup_request.py" $SCHEMAS/CityStateLookupRequest.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/city_state_lookup_response.py" $SCHEMAS/CityStateLookupResponse.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/emrsv4_0_bulk_request.py" $SCHEMAS/EMRSV4.0BulkRequest.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/error.py" $SCHEMAS/Error.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/express_mail_commitment_request.py" $SCHEMAS/ExpressMailCommitmentRequest.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/express_mail_commitment_response.py" $SCHEMAS/ExpressMailCommitmentResponse.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/first_class_mail_request.py" $SCHEMAS/FirstClassMailRequest.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/first_class_mail_response.py" $SCHEMAS/FirstClassMailResponse.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/hfp_facility_info_request.py" $SCHEMAS/HFPFacilityInfoRequest.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/hfp_facility_info_response.py" $SCHEMAS/HFPFacilityInfoResponse.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/intl_rate_v2_request.py" $SCHEMAS/IntlRateV2Request.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/intl_rate_v2_response.py" $SCHEMAS/IntlRateV2Response.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/mrsv4_0_request.py" $SCHEMAS/MRSV4.0Request.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/pts_emailresult.py" $SCHEMAS/PTSEmailResult.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/pts_email_request.py" $SCHEMAS/PTSEmailRequest.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/ptspod_result.py" $SCHEMAS/PTSPODResult.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/ptspod_request.py" $SCHEMAS/PTSPodRequest.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/ptsrre_result.py" $SCHEMAS/PTSRREResult.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/ptsrre_request.py" $SCHEMAS/PTSRreRequest.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/ptstpod_result.py" $SCHEMAS/PTSTPODResult.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/ptstpod_request.py" $SCHEMAS/PTSTPodRequest.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/priority_mail_request.py" $SCHEMAS/PriorityMailRequest.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/priority_mail_response.py" $SCHEMAS/PriorityMailResponse.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/rate_v4_request.py" $SCHEMAS/RateV4Request.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/rate_v4_response.py" $SCHEMAS/RateV4Response.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/scan_request.py" $SCHEMAS/SCANRequest.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/scan_response.py" $SCHEMAS/SCANResponse.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/sdc_get_locations_request.py" $SCHEMAS/SDCGetLocationsRequest.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/sdc_get_locations_response.py" $SCHEMAS/SDCGetLocationsResponse.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/standard_b_request.py" $SCHEMAS/StandardBRequest.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/standard_b_response.py" $SCHEMAS/StandardBResponse.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/track_field_request.py" $SCHEMAS/TrackFieldRequest.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/track_request.py" $SCHEMAS/TrackRequest.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/track_response.py" $SCHEMAS/TrackResponse.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/zip_code_lookup_request.py" $SCHEMAS/ZipCodeLookupRequest.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/zip_code_lookup_response.py" $SCHEMAS/ZipCodeLookupResponse.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/evs_cancel_request.py" $SCHEMAS/eVSCancelRequest.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/evs_cancel_response.py" $SCHEMAS/eVSCancelResponse.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/evs_request.py" $SCHEMAS/eVSRequest.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/evs_response.py" $SCHEMAS/eVSResponse.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/evs_express_mail_intl_request.py" $SCHEMAS/eVSExpressMailIntlRequest.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/evs_express_mail_intl_response.py" $SCHEMAS/eVSExpressMailIntlResponse.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/evs_first_class_mail_intl_request.py" $SCHEMAS/eVSFirstClassMailIntlRequest.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/evs_first_class_mail_intl_response.py" $SCHEMAS/eVSFirstClassMailIntlResponse.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/evs_gxg_get_label_request.py" $SCHEMAS/eVSGXGGetLabelRequest.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/evs_gxg_get_label_response.py" $SCHEMAS/eVSGXGGetLabelResponse.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/evsi_cancel_request.py" $SCHEMAS/eVSICancelRequest.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/evsi_cancel_response.py" $SCHEMAS/eVSICancelResponse.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/evs_priority_mail_intl_request.py" $SCHEMAS/eVSPriorityMailIntlRequest.xsd -generateDS --no-namespace-defs -o "$LIB_MODULES/evs_priority_mail_intl_response.py" $SCHEMAS/eVSPriorityMailIntlResponse.xsd diff --git a/schemas/usps/karrio/schemas/usps/__init__.py b/schemas/usps/karrio/schemas/usps/__init__.py deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/schemas/usps/karrio/schemas/usps/address_validate_request.py b/schemas/usps/karrio/schemas/usps/address_validate_request.py deleted file mode 100644 index cf08516429..0000000000 --- a/schemas/usps/karrio/schemas/usps/address_validate_request.py +++ /dev/null @@ -1,1552 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:03 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/address_validate_request.py') -# -# Command line arguments: -# ./schemas/AddressValidateRequest.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/address_validate_request.py" ./schemas/AddressValidateRequest.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class AddressValidateRequest(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, USERID=None, Revision=None, Address=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.USERID = _cast(None, USERID) - self.USERID_nsprefix_ = None - self.Revision = Revision - self.Revision_nsprefix_ = None - self.Address = Address - self.Address_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, AddressValidateRequest) - if subclass is not None: - return subclass(*args_, **kwargs_) - if AddressValidateRequest.subclass: - return AddressValidateRequest.subclass(*args_, **kwargs_) - else: - return AddressValidateRequest(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_Revision(self): - return self.Revision - def set_Revision(self, Revision): - self.Revision = Revision - def get_Address(self): - return self.Address - def set_Address(self, Address): - self.Address = Address - def get_USERID(self): - return self.USERID - def set_USERID(self, USERID): - self.USERID = USERID - def _hasContent(self): - if ( - self.Revision is not None or - self.Address is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='AddressValidateRequest', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('AddressValidateRequest') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'AddressValidateRequest': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='AddressValidateRequest') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='AddressValidateRequest', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='AddressValidateRequest'): - if self.USERID is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - outfile.write(' USERID=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.USERID), input_name='USERID')), )) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='AddressValidateRequest', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.Revision is not None: - namespaceprefix_ = self.Revision_nsprefix_ + ':' if (UseCapturedNS_ and self.Revision_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRevision>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Revision), input_name='Revision')), namespaceprefix_ , eol_)) - if self.Address is not None: - namespaceprefix_ = self.Address_nsprefix_ + ':' if (UseCapturedNS_ and self.Address_nsprefix_) else '' - self.Address.export(outfile, level, namespaceprefix_, namespacedef_='', name_='Address', pretty_print=pretty_print) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('USERID', node) - if value is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - self.USERID = value - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'Revision': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Revision') - value_ = self.gds_validate_string(value_, node, 'Revision') - self.Revision = value_ - self.Revision_nsprefix_ = child_.prefix - elif nodeName_ == 'Address': - obj_ = AddressType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.Address = obj_ - obj_.original_tagname_ = 'Address' -# end class AddressValidateRequest - - -class AddressType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ID=None, FirmName=None, Address1=None, Address2=None, City=None, State=None, Urbanization=None, Zip5=None, Zip4=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.ID = _cast(None, ID) - self.ID_nsprefix_ = None - self.FirmName = FirmName - self.FirmName_nsprefix_ = None - self.Address1 = Address1 - self.Address1_nsprefix_ = None - self.Address2 = Address2 - self.Address2_nsprefix_ = None - self.City = City - self.City_nsprefix_ = None - self.State = State - self.State_nsprefix_ = None - self.Urbanization = Urbanization - self.Urbanization_nsprefix_ = None - self.Zip5 = Zip5 - self.Zip5_nsprefix_ = None - self.Zip4 = Zip4 - self.Zip4_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, AddressType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if AddressType.subclass: - return AddressType.subclass(*args_, **kwargs_) - else: - return AddressType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_FirmName(self): - return self.FirmName - def set_FirmName(self, FirmName): - self.FirmName = FirmName - def get_Address1(self): - return self.Address1 - def set_Address1(self, Address1): - self.Address1 = Address1 - def get_Address2(self): - return self.Address2 - def set_Address2(self, Address2): - self.Address2 = Address2 - def get_City(self): - return self.City - def set_City(self, City): - self.City = City - def get_State(self): - return self.State - def set_State(self, State): - self.State = State - def get_Urbanization(self): - return self.Urbanization - def set_Urbanization(self, Urbanization): - self.Urbanization = Urbanization - def get_Zip5(self): - return self.Zip5 - def set_Zip5(self, Zip5): - self.Zip5 = Zip5 - def get_Zip4(self): - return self.Zip4 - def set_Zip4(self, Zip4): - self.Zip4 = Zip4 - def get_ID(self): - return self.ID - def set_ID(self, ID): - self.ID = ID - def _hasContent(self): - if ( - self.FirmName is not None or - self.Address1 is not None or - self.Address2 is not None or - self.City is not None or - self.State is not None or - self.Urbanization is not None or - self.Zip5 is not None or - self.Zip4 is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='AddressType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('AddressType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'AddressType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='AddressType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='AddressType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='AddressType'): - if self.ID is not None and 'ID' not in already_processed: - already_processed.add('ID') - outfile.write(' ID=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.ID), input_name='ID')), )) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='AddressType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.FirmName is not None: - namespaceprefix_ = self.FirmName_nsprefix_ + ':' if (UseCapturedNS_ and self.FirmName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFirmName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FirmName), input_name='FirmName')), namespaceprefix_ , eol_)) - if self.Address1 is not None: - namespaceprefix_ = self.Address1_nsprefix_ + ':' if (UseCapturedNS_ and self.Address1_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAddress1>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Address1), input_name='Address1')), namespaceprefix_ , eol_)) - if self.Address2 is not None: - namespaceprefix_ = self.Address2_nsprefix_ + ':' if (UseCapturedNS_ and self.Address2_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAddress2>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Address2), input_name='Address2')), namespaceprefix_ , eol_)) - if self.City is not None: - namespaceprefix_ = self.City_nsprefix_ + ':' if (UseCapturedNS_ and self.City_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.City), input_name='City')), namespaceprefix_ , eol_)) - if self.State is not None: - namespaceprefix_ = self.State_nsprefix_ + ':' if (UseCapturedNS_ and self.State_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.State), input_name='State')), namespaceprefix_ , eol_)) - if self.Urbanization is not None: - namespaceprefix_ = self.Urbanization_nsprefix_ + ':' if (UseCapturedNS_ and self.Urbanization_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sUrbanization>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Urbanization), input_name='Urbanization')), namespaceprefix_ , eol_)) - if self.Zip5 is not None: - namespaceprefix_ = self.Zip5_nsprefix_ + ':' if (UseCapturedNS_ and self.Zip5_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sZip5>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Zip5), input_name='Zip5')), namespaceprefix_ , eol_)) - if self.Zip4 is not None: - namespaceprefix_ = self.Zip4_nsprefix_ + ':' if (UseCapturedNS_ and self.Zip4_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sZip4>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Zip4), input_name='Zip4')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('ID', node) - if value is not None and 'ID' not in already_processed: - already_processed.add('ID') - self.ID = value - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'FirmName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FirmName') - value_ = self.gds_validate_string(value_, node, 'FirmName') - self.FirmName = value_ - self.FirmName_nsprefix_ = child_.prefix - elif nodeName_ == 'Address1': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Address1') - value_ = self.gds_validate_string(value_, node, 'Address1') - self.Address1 = value_ - self.Address1_nsprefix_ = child_.prefix - elif nodeName_ == 'Address2': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Address2') - value_ = self.gds_validate_string(value_, node, 'Address2') - self.Address2 = value_ - self.Address2_nsprefix_ = child_.prefix - elif nodeName_ == 'City': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'City') - value_ = self.gds_validate_string(value_, node, 'City') - self.City = value_ - self.City_nsprefix_ = child_.prefix - elif nodeName_ == 'State': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'State') - value_ = self.gds_validate_string(value_, node, 'State') - self.State = value_ - self.State_nsprefix_ = child_.prefix - elif nodeName_ == 'Urbanization': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Urbanization') - value_ = self.gds_validate_string(value_, node, 'Urbanization') - self.Urbanization = value_ - self.Urbanization_nsprefix_ = child_.prefix - elif nodeName_ == 'Zip5': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Zip5') - value_ = self.gds_validate_string(value_, node, 'Zip5') - self.Zip5 = value_ - self.Zip5_nsprefix_ = child_.prefix - elif nodeName_ == 'Zip4': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Zip4') - value_ = self.gds_validate_string(value_, node, 'Zip4') - self.Zip4 = value_ - self.Zip4_nsprefix_ = child_.prefix -# end class AddressType - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'AddressValidateRequest' - rootClass = AddressValidateRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'AddressValidateRequest' - rootClass = AddressValidateRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'AddressValidateRequest' - rootClass = AddressValidateRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'AddressValidateRequest' - rootClass = AddressValidateRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from address_validate_request import *\n\n') - sys.stdout.write('import address_validate_request as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "AddressType", - "AddressValidateRequest" -] diff --git a/schemas/usps/karrio/schemas/usps/address_validate_response.py b/schemas/usps/karrio/schemas/usps/address_validate_response.py deleted file mode 100644 index ef27e6c52e..0000000000 --- a/schemas/usps/karrio/schemas/usps/address_validate_response.py +++ /dev/null @@ -1,1711 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:04 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/address_validate_response.py') -# -# Command line arguments: -# ./schemas/AddressValidateResponse.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/address_validate_response.py" ./schemas/AddressValidateResponse.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class AddressValidateResponse(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, Address=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.Address = Address - self.Address_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, AddressValidateResponse) - if subclass is not None: - return subclass(*args_, **kwargs_) - if AddressValidateResponse.subclass: - return AddressValidateResponse.subclass(*args_, **kwargs_) - else: - return AddressValidateResponse(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_Address(self): - return self.Address - def set_Address(self, Address): - self.Address = Address - def _hasContent(self): - if ( - self.Address is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='AddressValidateResponse', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('AddressValidateResponse') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'AddressValidateResponse': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='AddressValidateResponse') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='AddressValidateResponse', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='AddressValidateResponse'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='AddressValidateResponse', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.Address is not None: - namespaceprefix_ = self.Address_nsprefix_ + ':' if (UseCapturedNS_ and self.Address_nsprefix_) else '' - self.Address.export(outfile, level, namespaceprefix_, namespacedef_='', name_='Address', pretty_print=pretty_print) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'Address': - obj_ = AddressType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.Address = obj_ - obj_.original_tagname_ = 'Address' -# end class AddressValidateResponse - - -class AddressType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ID=None, FirmName=None, Address1=None, Address2=None, Address2Abbreviation=None, City=None, CityAbbreviation=None, State=None, Urbanization=None, Zip5=None, Zip4=None, DeliveryPoint=None, CarrierRoute=None, Footnotes=None, DPVConfirmation=None, DPVCMRA=None, DPVFootnotes=None, Business=None, CentralDeliveryPoint=None, Vacant=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.ID = _cast(int, ID) - self.ID_nsprefix_ = None - self.FirmName = FirmName - self.FirmName_nsprefix_ = None - self.Address1 = Address1 - self.Address1_nsprefix_ = None - self.Address2 = Address2 - self.Address2_nsprefix_ = None - self.Address2Abbreviation = Address2Abbreviation - self.Address2Abbreviation_nsprefix_ = None - self.City = City - self.City_nsprefix_ = None - self.CityAbbreviation = CityAbbreviation - self.CityAbbreviation_nsprefix_ = None - self.State = State - self.State_nsprefix_ = None - self.Urbanization = Urbanization - self.Urbanization_nsprefix_ = None - self.Zip5 = Zip5 - self.Zip5_nsprefix_ = None - self.Zip4 = Zip4 - self.Zip4_nsprefix_ = None - self.DeliveryPoint = DeliveryPoint - self.DeliveryPoint_nsprefix_ = None - self.CarrierRoute = CarrierRoute - self.CarrierRoute_nsprefix_ = None - self.Footnotes = Footnotes - self.Footnotes_nsprefix_ = None - self.DPVConfirmation = DPVConfirmation - self.DPVConfirmation_nsprefix_ = None - self.DPVCMRA = DPVCMRA - self.DPVCMRA_nsprefix_ = None - self.DPVFootnotes = DPVFootnotes - self.DPVFootnotes_nsprefix_ = None - self.Business = Business - self.Business_nsprefix_ = None - self.CentralDeliveryPoint = CentralDeliveryPoint - self.CentralDeliveryPoint_nsprefix_ = None - self.Vacant = Vacant - self.Vacant_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, AddressType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if AddressType.subclass: - return AddressType.subclass(*args_, **kwargs_) - else: - return AddressType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_FirmName(self): - return self.FirmName - def set_FirmName(self, FirmName): - self.FirmName = FirmName - def get_Address1(self): - return self.Address1 - def set_Address1(self, Address1): - self.Address1 = Address1 - def get_Address2(self): - return self.Address2 - def set_Address2(self, Address2): - self.Address2 = Address2 - def get_Address2Abbreviation(self): - return self.Address2Abbreviation - def set_Address2Abbreviation(self, Address2Abbreviation): - self.Address2Abbreviation = Address2Abbreviation - def get_City(self): - return self.City - def set_City(self, City): - self.City = City - def get_CityAbbreviation(self): - return self.CityAbbreviation - def set_CityAbbreviation(self, CityAbbreviation): - self.CityAbbreviation = CityAbbreviation - def get_State(self): - return self.State - def set_State(self, State): - self.State = State - def get_Urbanization(self): - return self.Urbanization - def set_Urbanization(self, Urbanization): - self.Urbanization = Urbanization - def get_Zip5(self): - return self.Zip5 - def set_Zip5(self, Zip5): - self.Zip5 = Zip5 - def get_Zip4(self): - return self.Zip4 - def set_Zip4(self, Zip4): - self.Zip4 = Zip4 - def get_DeliveryPoint(self): - return self.DeliveryPoint - def set_DeliveryPoint(self, DeliveryPoint): - self.DeliveryPoint = DeliveryPoint - def get_CarrierRoute(self): - return self.CarrierRoute - def set_CarrierRoute(self, CarrierRoute): - self.CarrierRoute = CarrierRoute - def get_Footnotes(self): - return self.Footnotes - def set_Footnotes(self, Footnotes): - self.Footnotes = Footnotes - def get_DPVConfirmation(self): - return self.DPVConfirmation - def set_DPVConfirmation(self, DPVConfirmation): - self.DPVConfirmation = DPVConfirmation - def get_DPVCMRA(self): - return self.DPVCMRA - def set_DPVCMRA(self, DPVCMRA): - self.DPVCMRA = DPVCMRA - def get_DPVFootnotes(self): - return self.DPVFootnotes - def set_DPVFootnotes(self, DPVFootnotes): - self.DPVFootnotes = DPVFootnotes - def get_Business(self): - return self.Business - def set_Business(self, Business): - self.Business = Business - def get_CentralDeliveryPoint(self): - return self.CentralDeliveryPoint - def set_CentralDeliveryPoint(self, CentralDeliveryPoint): - self.CentralDeliveryPoint = CentralDeliveryPoint - def get_Vacant(self): - return self.Vacant - def set_Vacant(self, Vacant): - self.Vacant = Vacant - def get_ID(self): - return self.ID - def set_ID(self, ID): - self.ID = ID - def _hasContent(self): - if ( - self.FirmName is not None or - self.Address1 is not None or - self.Address2 is not None or - self.Address2Abbreviation is not None or - self.City is not None or - self.CityAbbreviation is not None or - self.State is not None or - self.Urbanization is not None or - self.Zip5 is not None or - self.Zip4 is not None or - self.DeliveryPoint is not None or - self.CarrierRoute is not None or - self.Footnotes is not None or - self.DPVConfirmation is not None or - self.DPVCMRA is not None or - self.DPVFootnotes is not None or - self.Business is not None or - self.CentralDeliveryPoint is not None or - self.Vacant is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='AddressType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('AddressType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'AddressType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='AddressType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='AddressType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='AddressType'): - if self.ID is not None and 'ID' not in already_processed: - already_processed.add('ID') - outfile.write(' ID="%s"' % self.gds_format_integer(self.ID, input_name='ID')) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='AddressType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.FirmName is not None: - namespaceprefix_ = self.FirmName_nsprefix_ + ':' if (UseCapturedNS_ and self.FirmName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFirmName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FirmName), input_name='FirmName')), namespaceprefix_ , eol_)) - if self.Address1 is not None: - namespaceprefix_ = self.Address1_nsprefix_ + ':' if (UseCapturedNS_ and self.Address1_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAddress1>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Address1), input_name='Address1')), namespaceprefix_ , eol_)) - if self.Address2 is not None: - namespaceprefix_ = self.Address2_nsprefix_ + ':' if (UseCapturedNS_ and self.Address2_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAddress2>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Address2), input_name='Address2')), namespaceprefix_ , eol_)) - if self.Address2Abbreviation is not None: - namespaceprefix_ = self.Address2Abbreviation_nsprefix_ + ':' if (UseCapturedNS_ and self.Address2Abbreviation_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAddress2Abbreviation>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Address2Abbreviation), input_name='Address2Abbreviation')), namespaceprefix_ , eol_)) - if self.City is not None: - namespaceprefix_ = self.City_nsprefix_ + ':' if (UseCapturedNS_ and self.City_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.City), input_name='City')), namespaceprefix_ , eol_)) - if self.CityAbbreviation is not None: - namespaceprefix_ = self.CityAbbreviation_nsprefix_ + ':' if (UseCapturedNS_ and self.CityAbbreviation_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCityAbbreviation>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CityAbbreviation), input_name='CityAbbreviation')), namespaceprefix_ , eol_)) - if self.State is not None: - namespaceprefix_ = self.State_nsprefix_ + ':' if (UseCapturedNS_ and self.State_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.State), input_name='State')), namespaceprefix_ , eol_)) - if self.Urbanization is not None: - namespaceprefix_ = self.Urbanization_nsprefix_ + ':' if (UseCapturedNS_ and self.Urbanization_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sUrbanization>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Urbanization), input_name='Urbanization')), namespaceprefix_ , eol_)) - if self.Zip5 is not None: - namespaceprefix_ = self.Zip5_nsprefix_ + ':' if (UseCapturedNS_ and self.Zip5_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sZip5>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Zip5), input_name='Zip5')), namespaceprefix_ , eol_)) - if self.Zip4 is not None: - namespaceprefix_ = self.Zip4_nsprefix_ + ':' if (UseCapturedNS_ and self.Zip4_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sZip4>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Zip4), input_name='Zip4')), namespaceprefix_ , eol_)) - if self.DeliveryPoint is not None: - namespaceprefix_ = self.DeliveryPoint_nsprefix_ + ':' if (UseCapturedNS_ and self.DeliveryPoint_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDeliveryPoint>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.DeliveryPoint), input_name='DeliveryPoint')), namespaceprefix_ , eol_)) - if self.CarrierRoute is not None: - namespaceprefix_ = self.CarrierRoute_nsprefix_ + ':' if (UseCapturedNS_ and self.CarrierRoute_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCarrierRoute>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CarrierRoute), input_name='CarrierRoute')), namespaceprefix_ , eol_)) - if self.Footnotes is not None: - namespaceprefix_ = self.Footnotes_nsprefix_ + ':' if (UseCapturedNS_ and self.Footnotes_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFootnotes>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Footnotes), input_name='Footnotes')), namespaceprefix_ , eol_)) - if self.DPVConfirmation is not None: - namespaceprefix_ = self.DPVConfirmation_nsprefix_ + ':' if (UseCapturedNS_ and self.DPVConfirmation_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDPVConfirmation>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.DPVConfirmation), input_name='DPVConfirmation')), namespaceprefix_ , eol_)) - if self.DPVCMRA is not None: - namespaceprefix_ = self.DPVCMRA_nsprefix_ + ':' if (UseCapturedNS_ and self.DPVCMRA_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDPVCMRA>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.DPVCMRA), input_name='DPVCMRA')), namespaceprefix_ , eol_)) - if self.DPVFootnotes is not None: - namespaceprefix_ = self.DPVFootnotes_nsprefix_ + ':' if (UseCapturedNS_ and self.DPVFootnotes_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDPVFootnotes>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.DPVFootnotes), input_name='DPVFootnotes')), namespaceprefix_ , eol_)) - if self.Business is not None: - namespaceprefix_ = self.Business_nsprefix_ + ':' if (UseCapturedNS_ and self.Business_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sBusiness>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Business), input_name='Business')), namespaceprefix_ , eol_)) - if self.CentralDeliveryPoint is not None: - namespaceprefix_ = self.CentralDeliveryPoint_nsprefix_ + ':' if (UseCapturedNS_ and self.CentralDeliveryPoint_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCentralDeliveryPoint>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CentralDeliveryPoint), input_name='CentralDeliveryPoint')), namespaceprefix_ , eol_)) - if self.Vacant is not None: - namespaceprefix_ = self.Vacant_nsprefix_ + ':' if (UseCapturedNS_ and self.Vacant_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sVacant>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Vacant), input_name='Vacant')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('ID', node) - if value is not None and 'ID' not in already_processed: - already_processed.add('ID') - self.ID = self.gds_parse_integer(value, node, 'ID') - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'FirmName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FirmName') - value_ = self.gds_validate_string(value_, node, 'FirmName') - self.FirmName = value_ - self.FirmName_nsprefix_ = child_.prefix - elif nodeName_ == 'Address1': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Address1') - value_ = self.gds_validate_string(value_, node, 'Address1') - self.Address1 = value_ - self.Address1_nsprefix_ = child_.prefix - elif nodeName_ == 'Address2': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Address2') - value_ = self.gds_validate_string(value_, node, 'Address2') - self.Address2 = value_ - self.Address2_nsprefix_ = child_.prefix - elif nodeName_ == 'Address2Abbreviation': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Address2Abbreviation') - value_ = self.gds_validate_string(value_, node, 'Address2Abbreviation') - self.Address2Abbreviation = value_ - self.Address2Abbreviation_nsprefix_ = child_.prefix - elif nodeName_ == 'City': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'City') - value_ = self.gds_validate_string(value_, node, 'City') - self.City = value_ - self.City_nsprefix_ = child_.prefix - elif nodeName_ == 'CityAbbreviation': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CityAbbreviation') - value_ = self.gds_validate_string(value_, node, 'CityAbbreviation') - self.CityAbbreviation = value_ - self.CityAbbreviation_nsprefix_ = child_.prefix - elif nodeName_ == 'State': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'State') - value_ = self.gds_validate_string(value_, node, 'State') - self.State = value_ - self.State_nsprefix_ = child_.prefix - elif nodeName_ == 'Urbanization': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Urbanization') - value_ = self.gds_validate_string(value_, node, 'Urbanization') - self.Urbanization = value_ - self.Urbanization_nsprefix_ = child_.prefix - elif nodeName_ == 'Zip5': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Zip5') - value_ = self.gds_validate_string(value_, node, 'Zip5') - self.Zip5 = value_ - self.Zip5_nsprefix_ = child_.prefix - elif nodeName_ == 'Zip4': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Zip4') - value_ = self.gds_validate_string(value_, node, 'Zip4') - self.Zip4 = value_ - self.Zip4_nsprefix_ = child_.prefix - elif nodeName_ == 'DeliveryPoint': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'DeliveryPoint') - value_ = self.gds_validate_string(value_, node, 'DeliveryPoint') - self.DeliveryPoint = value_ - self.DeliveryPoint_nsprefix_ = child_.prefix - elif nodeName_ == 'CarrierRoute': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CarrierRoute') - value_ = self.gds_validate_string(value_, node, 'CarrierRoute') - self.CarrierRoute = value_ - self.CarrierRoute_nsprefix_ = child_.prefix - elif nodeName_ == 'Footnotes': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Footnotes') - value_ = self.gds_validate_string(value_, node, 'Footnotes') - self.Footnotes = value_ - self.Footnotes_nsprefix_ = child_.prefix - elif nodeName_ == 'DPVConfirmation': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'DPVConfirmation') - value_ = self.gds_validate_string(value_, node, 'DPVConfirmation') - self.DPVConfirmation = value_ - self.DPVConfirmation_nsprefix_ = child_.prefix - elif nodeName_ == 'DPVCMRA': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'DPVCMRA') - value_ = self.gds_validate_string(value_, node, 'DPVCMRA') - self.DPVCMRA = value_ - self.DPVCMRA_nsprefix_ = child_.prefix - elif nodeName_ == 'DPVFootnotes': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'DPVFootnotes') - value_ = self.gds_validate_string(value_, node, 'DPVFootnotes') - self.DPVFootnotes = value_ - self.DPVFootnotes_nsprefix_ = child_.prefix - elif nodeName_ == 'Business': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Business') - value_ = self.gds_validate_string(value_, node, 'Business') - self.Business = value_ - self.Business_nsprefix_ = child_.prefix - elif nodeName_ == 'CentralDeliveryPoint': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CentralDeliveryPoint') - value_ = self.gds_validate_string(value_, node, 'CentralDeliveryPoint') - self.CentralDeliveryPoint = value_ - self.CentralDeliveryPoint_nsprefix_ = child_.prefix - elif nodeName_ == 'Vacant': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Vacant') - value_ = self.gds_validate_string(value_, node, 'Vacant') - self.Vacant = value_ - self.Vacant_nsprefix_ = child_.prefix -# end class AddressType - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'AddressValidateResponse' - rootClass = AddressValidateResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'AddressValidateResponse' - rootClass = AddressValidateResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'AddressValidateResponse' - rootClass = AddressValidateResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'AddressValidateResponse' - rootClass = AddressValidateResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from address_validate_response import *\n\n') - sys.stdout.write('import address_validate_response as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "AddressType", - "AddressValidateResponse" -] diff --git a/schemas/usps/karrio/schemas/usps/carrier_pickup_availability_request.py b/schemas/usps/karrio/schemas/usps/carrier_pickup_availability_request.py deleted file mode 100644 index e873ba12f4..0000000000 --- a/schemas/usps/karrio/schemas/usps/carrier_pickup_availability_request.py +++ /dev/null @@ -1,1447 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:04 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/carrier_pickup_availability_request.py') -# -# Command line arguments: -# ./schemas/CarrierPickupAvailabilityRequest.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/carrier_pickup_availability_request.py" ./schemas/CarrierPickupAvailabilityRequest.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class CarrierPickupAvailabilityRequest(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, USERID=None, FirmName=None, SuiteOrApt=None, Address2=None, Urbanization=None, City=None, State=None, ZIP5=None, ZIP4=None, Date=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.USERID = _cast(None, USERID) - self.USERID_nsprefix_ = None - self.FirmName = FirmName - self.FirmName_nsprefix_ = None - self.SuiteOrApt = SuiteOrApt - self.SuiteOrApt_nsprefix_ = None - self.Address2 = Address2 - self.Address2_nsprefix_ = None - self.Urbanization = Urbanization - self.Urbanization_nsprefix_ = None - self.City = City - self.City_nsprefix_ = None - self.State = State - self.State_nsprefix_ = None - self.ZIP5 = ZIP5 - self.ZIP5_nsprefix_ = None - self.ZIP4 = ZIP4 - self.ZIP4_nsprefix_ = None - self.Date = Date - self.Date_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, CarrierPickupAvailabilityRequest) - if subclass is not None: - return subclass(*args_, **kwargs_) - if CarrierPickupAvailabilityRequest.subclass: - return CarrierPickupAvailabilityRequest.subclass(*args_, **kwargs_) - else: - return CarrierPickupAvailabilityRequest(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_FirmName(self): - return self.FirmName - def set_FirmName(self, FirmName): - self.FirmName = FirmName - def get_SuiteOrApt(self): - return self.SuiteOrApt - def set_SuiteOrApt(self, SuiteOrApt): - self.SuiteOrApt = SuiteOrApt - def get_Address2(self): - return self.Address2 - def set_Address2(self, Address2): - self.Address2 = Address2 - def get_Urbanization(self): - return self.Urbanization - def set_Urbanization(self, Urbanization): - self.Urbanization = Urbanization - def get_City(self): - return self.City - def set_City(self, City): - self.City = City - def get_State(self): - return self.State - def set_State(self, State): - self.State = State - def get_ZIP5(self): - return self.ZIP5 - def set_ZIP5(self, ZIP5): - self.ZIP5 = ZIP5 - def get_ZIP4(self): - return self.ZIP4 - def set_ZIP4(self, ZIP4): - self.ZIP4 = ZIP4 - def get_Date(self): - return self.Date - def set_Date(self, Date): - self.Date = Date - def get_USERID(self): - return self.USERID - def set_USERID(self, USERID): - self.USERID = USERID - def _hasContent(self): - if ( - self.FirmName is not None or - self.SuiteOrApt is not None or - self.Address2 is not None or - self.Urbanization is not None or - self.City is not None or - self.State is not None or - self.ZIP5 is not None or - self.ZIP4 is not None or - self.Date is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='CarrierPickupAvailabilityRequest', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('CarrierPickupAvailabilityRequest') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'CarrierPickupAvailabilityRequest': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='CarrierPickupAvailabilityRequest') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='CarrierPickupAvailabilityRequest', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='CarrierPickupAvailabilityRequest'): - if self.USERID is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - outfile.write(' USERID=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.USERID), input_name='USERID')), )) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='CarrierPickupAvailabilityRequest', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.FirmName is not None: - namespaceprefix_ = self.FirmName_nsprefix_ + ':' if (UseCapturedNS_ and self.FirmName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFirmName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FirmName), input_name='FirmName')), namespaceprefix_ , eol_)) - if self.SuiteOrApt is not None: - namespaceprefix_ = self.SuiteOrApt_nsprefix_ + ':' if (UseCapturedNS_ and self.SuiteOrApt_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSuiteOrApt>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SuiteOrApt), input_name='SuiteOrApt')), namespaceprefix_ , eol_)) - if self.Address2 is not None: - namespaceprefix_ = self.Address2_nsprefix_ + ':' if (UseCapturedNS_ and self.Address2_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAddress2>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Address2), input_name='Address2')), namespaceprefix_ , eol_)) - if self.Urbanization is not None: - namespaceprefix_ = self.Urbanization_nsprefix_ + ':' if (UseCapturedNS_ and self.Urbanization_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sUrbanization>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Urbanization), input_name='Urbanization')), namespaceprefix_ , eol_)) - if self.City is not None: - namespaceprefix_ = self.City_nsprefix_ + ':' if (UseCapturedNS_ and self.City_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.City), input_name='City')), namespaceprefix_ , eol_)) - if self.State is not None: - namespaceprefix_ = self.State_nsprefix_ + ':' if (UseCapturedNS_ and self.State_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.State), input_name='State')), namespaceprefix_ , eol_)) - if self.ZIP5 is not None: - namespaceprefix_ = self.ZIP5_nsprefix_ + ':' if (UseCapturedNS_ and self.ZIP5_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sZIP5>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ZIP5), input_name='ZIP5')), namespaceprefix_ , eol_)) - if self.ZIP4 is not None: - namespaceprefix_ = self.ZIP4_nsprefix_ + ':' if (UseCapturedNS_ and self.ZIP4_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sZIP4>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ZIP4), input_name='ZIP4')), namespaceprefix_ , eol_)) - if self.Date is not None: - namespaceprefix_ = self.Date_nsprefix_ + ':' if (UseCapturedNS_ and self.Date_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDate>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Date), input_name='Date')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('USERID', node) - if value is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - self.USERID = value - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'FirmName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FirmName') - value_ = self.gds_validate_string(value_, node, 'FirmName') - self.FirmName = value_ - self.FirmName_nsprefix_ = child_.prefix - elif nodeName_ == 'SuiteOrApt': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SuiteOrApt') - value_ = self.gds_validate_string(value_, node, 'SuiteOrApt') - self.SuiteOrApt = value_ - self.SuiteOrApt_nsprefix_ = child_.prefix - elif nodeName_ == 'Address2': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Address2') - value_ = self.gds_validate_string(value_, node, 'Address2') - self.Address2 = value_ - self.Address2_nsprefix_ = child_.prefix - elif nodeName_ == 'Urbanization': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Urbanization') - value_ = self.gds_validate_string(value_, node, 'Urbanization') - self.Urbanization = value_ - self.Urbanization_nsprefix_ = child_.prefix - elif nodeName_ == 'City': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'City') - value_ = self.gds_validate_string(value_, node, 'City') - self.City = value_ - self.City_nsprefix_ = child_.prefix - elif nodeName_ == 'State': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'State') - value_ = self.gds_validate_string(value_, node, 'State') - self.State = value_ - self.State_nsprefix_ = child_.prefix - elif nodeName_ == 'ZIP5': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ZIP5') - value_ = self.gds_validate_string(value_, node, 'ZIP5') - self.ZIP5 = value_ - self.ZIP5_nsprefix_ = child_.prefix - elif nodeName_ == 'ZIP4': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ZIP4') - value_ = self.gds_validate_string(value_, node, 'ZIP4') - self.ZIP4 = value_ - self.ZIP4_nsprefix_ = child_.prefix - elif nodeName_ == 'Date': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Date') - value_ = self.gds_validate_string(value_, node, 'Date') - self.Date = value_ - self.Date_nsprefix_ = child_.prefix -# end class CarrierPickupAvailabilityRequest - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CarrierPickupAvailabilityRequest' - rootClass = CarrierPickupAvailabilityRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CarrierPickupAvailabilityRequest' - rootClass = CarrierPickupAvailabilityRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CarrierPickupAvailabilityRequest' - rootClass = CarrierPickupAvailabilityRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CarrierPickupAvailabilityRequest' - rootClass = CarrierPickupAvailabilityRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from carrier_pickup_availability_request import *\n\n') - sys.stdout.write('import carrier_pickup_availability_request as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "CarrierPickupAvailabilityRequest" -] diff --git a/schemas/usps/karrio/schemas/usps/carrier_pickup_availability_response.py b/schemas/usps/karrio/schemas/usps/carrier_pickup_availability_response.py deleted file mode 100644 index a758a1c413..0000000000 --- a/schemas/usps/karrio/schemas/usps/carrier_pickup_availability_response.py +++ /dev/null @@ -1,1470 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:04 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/carrier_pickup_availability_response.py') -# -# Command line arguments: -# ./schemas/CarrierPickupAvailabilityResponse.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/carrier_pickup_availability_response.py" ./schemas/CarrierPickupAvailabilityResponse.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class CarrierPickupAvailabilityResponse(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, FirmName=None, SuiteOrApt=None, Address2=None, Urbanization=None, City=None, State=None, ZIP5=None, ZIP4=None, DayOfWeek=None, Date=None, CarrierRoute=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.FirmName = FirmName - self.FirmName_nsprefix_ = None - self.SuiteOrApt = SuiteOrApt - self.SuiteOrApt_nsprefix_ = None - self.Address2 = Address2 - self.Address2_nsprefix_ = None - self.Urbanization = Urbanization - self.Urbanization_nsprefix_ = None - self.City = City - self.City_nsprefix_ = None - self.State = State - self.State_nsprefix_ = None - self.ZIP5 = ZIP5 - self.ZIP5_nsprefix_ = None - self.ZIP4 = ZIP4 - self.ZIP4_nsprefix_ = None - self.DayOfWeek = DayOfWeek - self.DayOfWeek_nsprefix_ = None - self.Date = Date - self.Date_nsprefix_ = None - self.CarrierRoute = CarrierRoute - self.CarrierRoute_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, CarrierPickupAvailabilityResponse) - if subclass is not None: - return subclass(*args_, **kwargs_) - if CarrierPickupAvailabilityResponse.subclass: - return CarrierPickupAvailabilityResponse.subclass(*args_, **kwargs_) - else: - return CarrierPickupAvailabilityResponse(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_FirmName(self): - return self.FirmName - def set_FirmName(self, FirmName): - self.FirmName = FirmName - def get_SuiteOrApt(self): - return self.SuiteOrApt - def set_SuiteOrApt(self, SuiteOrApt): - self.SuiteOrApt = SuiteOrApt - def get_Address2(self): - return self.Address2 - def set_Address2(self, Address2): - self.Address2 = Address2 - def get_Urbanization(self): - return self.Urbanization - def set_Urbanization(self, Urbanization): - self.Urbanization = Urbanization - def get_City(self): - return self.City - def set_City(self, City): - self.City = City - def get_State(self): - return self.State - def set_State(self, State): - self.State = State - def get_ZIP5(self): - return self.ZIP5 - def set_ZIP5(self, ZIP5): - self.ZIP5 = ZIP5 - def get_ZIP4(self): - return self.ZIP4 - def set_ZIP4(self, ZIP4): - self.ZIP4 = ZIP4 - def get_DayOfWeek(self): - return self.DayOfWeek - def set_DayOfWeek(self, DayOfWeek): - self.DayOfWeek = DayOfWeek - def get_Date(self): - return self.Date - def set_Date(self, Date): - self.Date = Date - def get_CarrierRoute(self): - return self.CarrierRoute - def set_CarrierRoute(self, CarrierRoute): - self.CarrierRoute = CarrierRoute - def _hasContent(self): - if ( - self.FirmName is not None or - self.SuiteOrApt is not None or - self.Address2 is not None or - self.Urbanization is not None or - self.City is not None or - self.State is not None or - self.ZIP5 is not None or - self.ZIP4 is not None or - self.DayOfWeek is not None or - self.Date is not None or - self.CarrierRoute is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='CarrierPickupAvailabilityResponse', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('CarrierPickupAvailabilityResponse') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'CarrierPickupAvailabilityResponse': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='CarrierPickupAvailabilityResponse') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='CarrierPickupAvailabilityResponse', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='CarrierPickupAvailabilityResponse'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='CarrierPickupAvailabilityResponse', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.FirmName is not None: - namespaceprefix_ = self.FirmName_nsprefix_ + ':' if (UseCapturedNS_ and self.FirmName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFirmName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FirmName), input_name='FirmName')), namespaceprefix_ , eol_)) - if self.SuiteOrApt is not None: - namespaceprefix_ = self.SuiteOrApt_nsprefix_ + ':' if (UseCapturedNS_ and self.SuiteOrApt_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSuiteOrApt>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SuiteOrApt), input_name='SuiteOrApt')), namespaceprefix_ , eol_)) - if self.Address2 is not None: - namespaceprefix_ = self.Address2_nsprefix_ + ':' if (UseCapturedNS_ and self.Address2_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAddress2>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Address2), input_name='Address2')), namespaceprefix_ , eol_)) - if self.Urbanization is not None: - namespaceprefix_ = self.Urbanization_nsprefix_ + ':' if (UseCapturedNS_ and self.Urbanization_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sUrbanization>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Urbanization), input_name='Urbanization')), namespaceprefix_ , eol_)) - if self.City is not None: - namespaceprefix_ = self.City_nsprefix_ + ':' if (UseCapturedNS_ and self.City_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.City), input_name='City')), namespaceprefix_ , eol_)) - if self.State is not None: - namespaceprefix_ = self.State_nsprefix_ + ':' if (UseCapturedNS_ and self.State_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.State), input_name='State')), namespaceprefix_ , eol_)) - if self.ZIP5 is not None: - namespaceprefix_ = self.ZIP5_nsprefix_ + ':' if (UseCapturedNS_ and self.ZIP5_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sZIP5>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ZIP5), input_name='ZIP5')), namespaceprefix_ , eol_)) - if self.ZIP4 is not None: - namespaceprefix_ = self.ZIP4_nsprefix_ + ':' if (UseCapturedNS_ and self.ZIP4_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sZIP4>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ZIP4), input_name='ZIP4')), namespaceprefix_ , eol_)) - if self.DayOfWeek is not None: - namespaceprefix_ = self.DayOfWeek_nsprefix_ + ':' if (UseCapturedNS_ and self.DayOfWeek_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDayOfWeek>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.DayOfWeek), input_name='DayOfWeek')), namespaceprefix_ , eol_)) - if self.Date is not None: - namespaceprefix_ = self.Date_nsprefix_ + ':' if (UseCapturedNS_ and self.Date_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDate>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Date), input_name='Date')), namespaceprefix_ , eol_)) - if self.CarrierRoute is not None: - namespaceprefix_ = self.CarrierRoute_nsprefix_ + ':' if (UseCapturedNS_ and self.CarrierRoute_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCarrierRoute>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CarrierRoute), input_name='CarrierRoute')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'FirmName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FirmName') - value_ = self.gds_validate_string(value_, node, 'FirmName') - self.FirmName = value_ - self.FirmName_nsprefix_ = child_.prefix - elif nodeName_ == 'SuiteOrApt': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SuiteOrApt') - value_ = self.gds_validate_string(value_, node, 'SuiteOrApt') - self.SuiteOrApt = value_ - self.SuiteOrApt_nsprefix_ = child_.prefix - elif nodeName_ == 'Address2': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Address2') - value_ = self.gds_validate_string(value_, node, 'Address2') - self.Address2 = value_ - self.Address2_nsprefix_ = child_.prefix - elif nodeName_ == 'Urbanization': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Urbanization') - value_ = self.gds_validate_string(value_, node, 'Urbanization') - self.Urbanization = value_ - self.Urbanization_nsprefix_ = child_.prefix - elif nodeName_ == 'City': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'City') - value_ = self.gds_validate_string(value_, node, 'City') - self.City = value_ - self.City_nsprefix_ = child_.prefix - elif nodeName_ == 'State': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'State') - value_ = self.gds_validate_string(value_, node, 'State') - self.State = value_ - self.State_nsprefix_ = child_.prefix - elif nodeName_ == 'ZIP5': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ZIP5') - value_ = self.gds_validate_string(value_, node, 'ZIP5') - self.ZIP5 = value_ - self.ZIP5_nsprefix_ = child_.prefix - elif nodeName_ == 'ZIP4': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ZIP4') - value_ = self.gds_validate_string(value_, node, 'ZIP4') - self.ZIP4 = value_ - self.ZIP4_nsprefix_ = child_.prefix - elif nodeName_ == 'DayOfWeek': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'DayOfWeek') - value_ = self.gds_validate_string(value_, node, 'DayOfWeek') - self.DayOfWeek = value_ - self.DayOfWeek_nsprefix_ = child_.prefix - elif nodeName_ == 'Date': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Date') - value_ = self.gds_validate_string(value_, node, 'Date') - self.Date = value_ - self.Date_nsprefix_ = child_.prefix - elif nodeName_ == 'CarrierRoute': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CarrierRoute') - value_ = self.gds_validate_string(value_, node, 'CarrierRoute') - self.CarrierRoute = value_ - self.CarrierRoute_nsprefix_ = child_.prefix -# end class CarrierPickupAvailabilityResponse - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CarrierPickupAvailabilityResponse' - rootClass = CarrierPickupAvailabilityResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CarrierPickupAvailabilityResponse' - rootClass = CarrierPickupAvailabilityResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CarrierPickupAvailabilityResponse' - rootClass = CarrierPickupAvailabilityResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CarrierPickupAvailabilityResponse' - rootClass = CarrierPickupAvailabilityResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from carrier_pickup_availability_response import *\n\n') - sys.stdout.write('import carrier_pickup_availability_response as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "CarrierPickupAvailabilityResponse" -] diff --git a/schemas/usps/karrio/schemas/usps/carrier_pickup_cancel_request.py b/schemas/usps/karrio/schemas/usps/carrier_pickup_cancel_request.py deleted file mode 100644 index 59045b292c..0000000000 --- a/schemas/usps/karrio/schemas/usps/carrier_pickup_cancel_request.py +++ /dev/null @@ -1,1447 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:04 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/carrier_pickup_cancel_request.py') -# -# Command line arguments: -# ./schemas/CarrierPickupCancelRequest.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/carrier_pickup_cancel_request.py" ./schemas/CarrierPickupCancelRequest.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class CarrierPickupCancelRequest(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, USERID=None, FirmName=None, SuiteOrApt=None, Address2=None, Urbanization=None, City=None, State=None, ZIP5=None, ZIP4=None, ConfirmationNumber=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.USERID = _cast(None, USERID) - self.USERID_nsprefix_ = None - self.FirmName = FirmName - self.FirmName_nsprefix_ = None - self.SuiteOrApt = SuiteOrApt - self.SuiteOrApt_nsprefix_ = None - self.Address2 = Address2 - self.Address2_nsprefix_ = None - self.Urbanization = Urbanization - self.Urbanization_nsprefix_ = None - self.City = City - self.City_nsprefix_ = None - self.State = State - self.State_nsprefix_ = None - self.ZIP5 = ZIP5 - self.ZIP5_nsprefix_ = None - self.ZIP4 = ZIP4 - self.ZIP4_nsprefix_ = None - self.ConfirmationNumber = ConfirmationNumber - self.ConfirmationNumber_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, CarrierPickupCancelRequest) - if subclass is not None: - return subclass(*args_, **kwargs_) - if CarrierPickupCancelRequest.subclass: - return CarrierPickupCancelRequest.subclass(*args_, **kwargs_) - else: - return CarrierPickupCancelRequest(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_FirmName(self): - return self.FirmName - def set_FirmName(self, FirmName): - self.FirmName = FirmName - def get_SuiteOrApt(self): - return self.SuiteOrApt - def set_SuiteOrApt(self, SuiteOrApt): - self.SuiteOrApt = SuiteOrApt - def get_Address2(self): - return self.Address2 - def set_Address2(self, Address2): - self.Address2 = Address2 - def get_Urbanization(self): - return self.Urbanization - def set_Urbanization(self, Urbanization): - self.Urbanization = Urbanization - def get_City(self): - return self.City - def set_City(self, City): - self.City = City - def get_State(self): - return self.State - def set_State(self, State): - self.State = State - def get_ZIP5(self): - return self.ZIP5 - def set_ZIP5(self, ZIP5): - self.ZIP5 = ZIP5 - def get_ZIP4(self): - return self.ZIP4 - def set_ZIP4(self, ZIP4): - self.ZIP4 = ZIP4 - def get_ConfirmationNumber(self): - return self.ConfirmationNumber - def set_ConfirmationNumber(self, ConfirmationNumber): - self.ConfirmationNumber = ConfirmationNumber - def get_USERID(self): - return self.USERID - def set_USERID(self, USERID): - self.USERID = USERID - def _hasContent(self): - if ( - self.FirmName is not None or - self.SuiteOrApt is not None or - self.Address2 is not None or - self.Urbanization is not None or - self.City is not None or - self.State is not None or - self.ZIP5 is not None or - self.ZIP4 is not None or - self.ConfirmationNumber is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='CarrierPickupCancelRequest', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('CarrierPickupCancelRequest') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'CarrierPickupCancelRequest': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='CarrierPickupCancelRequest') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='CarrierPickupCancelRequest', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='CarrierPickupCancelRequest'): - if self.USERID is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - outfile.write(' USERID=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.USERID), input_name='USERID')), )) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='CarrierPickupCancelRequest', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.FirmName is not None: - namespaceprefix_ = self.FirmName_nsprefix_ + ':' if (UseCapturedNS_ and self.FirmName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFirmName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FirmName), input_name='FirmName')), namespaceprefix_ , eol_)) - if self.SuiteOrApt is not None: - namespaceprefix_ = self.SuiteOrApt_nsprefix_ + ':' if (UseCapturedNS_ and self.SuiteOrApt_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSuiteOrApt>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SuiteOrApt), input_name='SuiteOrApt')), namespaceprefix_ , eol_)) - if self.Address2 is not None: - namespaceprefix_ = self.Address2_nsprefix_ + ':' if (UseCapturedNS_ and self.Address2_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAddress2>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Address2), input_name='Address2')), namespaceprefix_ , eol_)) - if self.Urbanization is not None: - namespaceprefix_ = self.Urbanization_nsprefix_ + ':' if (UseCapturedNS_ and self.Urbanization_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sUrbanization>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Urbanization), input_name='Urbanization')), namespaceprefix_ , eol_)) - if self.City is not None: - namespaceprefix_ = self.City_nsprefix_ + ':' if (UseCapturedNS_ and self.City_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.City), input_name='City')), namespaceprefix_ , eol_)) - if self.State is not None: - namespaceprefix_ = self.State_nsprefix_ + ':' if (UseCapturedNS_ and self.State_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.State), input_name='State')), namespaceprefix_ , eol_)) - if self.ZIP5 is not None: - namespaceprefix_ = self.ZIP5_nsprefix_ + ':' if (UseCapturedNS_ and self.ZIP5_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sZIP5>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ZIP5), input_name='ZIP5')), namespaceprefix_ , eol_)) - if self.ZIP4 is not None: - namespaceprefix_ = self.ZIP4_nsprefix_ + ':' if (UseCapturedNS_ and self.ZIP4_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sZIP4>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ZIP4), input_name='ZIP4')), namespaceprefix_ , eol_)) - if self.ConfirmationNumber is not None: - namespaceprefix_ = self.ConfirmationNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.ConfirmationNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sConfirmationNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ConfirmationNumber), input_name='ConfirmationNumber')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('USERID', node) - if value is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - self.USERID = value - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'FirmName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FirmName') - value_ = self.gds_validate_string(value_, node, 'FirmName') - self.FirmName = value_ - self.FirmName_nsprefix_ = child_.prefix - elif nodeName_ == 'SuiteOrApt': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SuiteOrApt') - value_ = self.gds_validate_string(value_, node, 'SuiteOrApt') - self.SuiteOrApt = value_ - self.SuiteOrApt_nsprefix_ = child_.prefix - elif nodeName_ == 'Address2': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Address2') - value_ = self.gds_validate_string(value_, node, 'Address2') - self.Address2 = value_ - self.Address2_nsprefix_ = child_.prefix - elif nodeName_ == 'Urbanization': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Urbanization') - value_ = self.gds_validate_string(value_, node, 'Urbanization') - self.Urbanization = value_ - self.Urbanization_nsprefix_ = child_.prefix - elif nodeName_ == 'City': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'City') - value_ = self.gds_validate_string(value_, node, 'City') - self.City = value_ - self.City_nsprefix_ = child_.prefix - elif nodeName_ == 'State': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'State') - value_ = self.gds_validate_string(value_, node, 'State') - self.State = value_ - self.State_nsprefix_ = child_.prefix - elif nodeName_ == 'ZIP5': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ZIP5') - value_ = self.gds_validate_string(value_, node, 'ZIP5') - self.ZIP5 = value_ - self.ZIP5_nsprefix_ = child_.prefix - elif nodeName_ == 'ZIP4': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ZIP4') - value_ = self.gds_validate_string(value_, node, 'ZIP4') - self.ZIP4 = value_ - self.ZIP4_nsprefix_ = child_.prefix - elif nodeName_ == 'ConfirmationNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ConfirmationNumber') - value_ = self.gds_validate_string(value_, node, 'ConfirmationNumber') - self.ConfirmationNumber = value_ - self.ConfirmationNumber_nsprefix_ = child_.prefix -# end class CarrierPickupCancelRequest - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CarrierPickupCancelRequest' - rootClass = CarrierPickupCancelRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CarrierPickupCancelRequest' - rootClass = CarrierPickupCancelRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CarrierPickupCancelRequest' - rootClass = CarrierPickupCancelRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CarrierPickupCancelRequest' - rootClass = CarrierPickupCancelRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from carrier_pickup_cancel_request import *\n\n') - sys.stdout.write('import carrier_pickup_cancel_request as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "CarrierPickupCancelRequest" -] diff --git a/schemas/usps/karrio/schemas/usps/carrier_pickup_cancel_response.py b/schemas/usps/karrio/schemas/usps/carrier_pickup_cancel_response.py deleted file mode 100644 index 520de561d1..0000000000 --- a/schemas/usps/karrio/schemas/usps/carrier_pickup_cancel_response.py +++ /dev/null @@ -1,1743 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:04 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/carrier_pickup_cancel_response.py') -# -# Command line arguments: -# ./schemas/CarrierPickupCancelResponse.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/carrier_pickup_cancel_response.py" ./schemas/CarrierPickupCancelResponse.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class CarrierPickupCancelResponse(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, FirstName=None, LastName=None, FirmName=None, SuiteOrApt=None, Address2=None, Urbanization=None, City=None, State=None, ZIP5=None, ZIP4=None, Phone=None, Extension=None, Package=None, EstimatedWeight=None, PackageLocation=None, SpecialInstructions=None, ConfirmationNumber=None, DayOfWeek=None, Date=None, CarrierRoute=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.FirstName = FirstName - self.FirstName_nsprefix_ = None - self.LastName = LastName - self.LastName_nsprefix_ = None - self.FirmName = FirmName - self.FirmName_nsprefix_ = None - self.SuiteOrApt = SuiteOrApt - self.SuiteOrApt_nsprefix_ = None - self.Address2 = Address2 - self.Address2_nsprefix_ = None - self.Urbanization = Urbanization - self.Urbanization_nsprefix_ = None - self.City = City - self.City_nsprefix_ = None - self.State = State - self.State_nsprefix_ = None - self.ZIP5 = ZIP5 - self.ZIP5_nsprefix_ = None - self.ZIP4 = ZIP4 - self.ZIP4_nsprefix_ = None - self.Phone = Phone - self.Phone_nsprefix_ = None - self.Extension = Extension - self.Extension_nsprefix_ = None - if Package is None: - self.Package = [] - else: - self.Package = Package - self.Package_nsprefix_ = None - self.EstimatedWeight = EstimatedWeight - self.EstimatedWeight_nsprefix_ = None - self.PackageLocation = PackageLocation - self.PackageLocation_nsprefix_ = None - self.SpecialInstructions = SpecialInstructions - self.SpecialInstructions_nsprefix_ = None - self.ConfirmationNumber = ConfirmationNumber - self.ConfirmationNumber_nsprefix_ = None - self.DayOfWeek = DayOfWeek - self.DayOfWeek_nsprefix_ = None - self.Date = Date - self.Date_nsprefix_ = None - self.CarrierRoute = CarrierRoute - self.CarrierRoute_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, CarrierPickupCancelResponse) - if subclass is not None: - return subclass(*args_, **kwargs_) - if CarrierPickupCancelResponse.subclass: - return CarrierPickupCancelResponse.subclass(*args_, **kwargs_) - else: - return CarrierPickupCancelResponse(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_FirstName(self): - return self.FirstName - def set_FirstName(self, FirstName): - self.FirstName = FirstName - def get_LastName(self): - return self.LastName - def set_LastName(self, LastName): - self.LastName = LastName - def get_FirmName(self): - return self.FirmName - def set_FirmName(self, FirmName): - self.FirmName = FirmName - def get_SuiteOrApt(self): - return self.SuiteOrApt - def set_SuiteOrApt(self, SuiteOrApt): - self.SuiteOrApt = SuiteOrApt - def get_Address2(self): - return self.Address2 - def set_Address2(self, Address2): - self.Address2 = Address2 - def get_Urbanization(self): - return self.Urbanization - def set_Urbanization(self, Urbanization): - self.Urbanization = Urbanization - def get_City(self): - return self.City - def set_City(self, City): - self.City = City - def get_State(self): - return self.State - def set_State(self, State): - self.State = State - def get_ZIP5(self): - return self.ZIP5 - def set_ZIP5(self, ZIP5): - self.ZIP5 = ZIP5 - def get_ZIP4(self): - return self.ZIP4 - def set_ZIP4(self, ZIP4): - self.ZIP4 = ZIP4 - def get_Phone(self): - return self.Phone - def set_Phone(self, Phone): - self.Phone = Phone - def get_Extension(self): - return self.Extension - def set_Extension(self, Extension): - self.Extension = Extension - def get_Package(self): - return self.Package - def set_Package(self, Package): - self.Package = Package - def add_Package(self, value): - self.Package.append(value) - def insert_Package_at(self, index, value): - self.Package.insert(index, value) - def replace_Package_at(self, index, value): - self.Package[index] = value - def get_EstimatedWeight(self): - return self.EstimatedWeight - def set_EstimatedWeight(self, EstimatedWeight): - self.EstimatedWeight = EstimatedWeight - def get_PackageLocation(self): - return self.PackageLocation - def set_PackageLocation(self, PackageLocation): - self.PackageLocation = PackageLocation - def get_SpecialInstructions(self): - return self.SpecialInstructions - def set_SpecialInstructions(self, SpecialInstructions): - self.SpecialInstructions = SpecialInstructions - def get_ConfirmationNumber(self): - return self.ConfirmationNumber - def set_ConfirmationNumber(self, ConfirmationNumber): - self.ConfirmationNumber = ConfirmationNumber - def get_DayOfWeek(self): - return self.DayOfWeek - def set_DayOfWeek(self, DayOfWeek): - self.DayOfWeek = DayOfWeek - def get_Date(self): - return self.Date - def set_Date(self, Date): - self.Date = Date - def get_CarrierRoute(self): - return self.CarrierRoute - def set_CarrierRoute(self, CarrierRoute): - self.CarrierRoute = CarrierRoute - def _hasContent(self): - if ( - self.FirstName is not None or - self.LastName is not None or - self.FirmName is not None or - self.SuiteOrApt is not None or - self.Address2 is not None or - self.Urbanization is not None or - self.City is not None or - self.State is not None or - self.ZIP5 is not None or - self.ZIP4 is not None or - self.Phone is not None or - self.Extension is not None or - self.Package or - self.EstimatedWeight is not None or - self.PackageLocation is not None or - self.SpecialInstructions is not None or - self.ConfirmationNumber is not None or - self.DayOfWeek is not None or - self.Date is not None or - self.CarrierRoute is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='CarrierPickupCancelResponse', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('CarrierPickupCancelResponse') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'CarrierPickupCancelResponse': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='CarrierPickupCancelResponse') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='CarrierPickupCancelResponse', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='CarrierPickupCancelResponse'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='CarrierPickupCancelResponse', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.FirstName is not None: - namespaceprefix_ = self.FirstName_nsprefix_ + ':' if (UseCapturedNS_ and self.FirstName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFirstName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FirstName), input_name='FirstName')), namespaceprefix_ , eol_)) - if self.LastName is not None: - namespaceprefix_ = self.LastName_nsprefix_ + ':' if (UseCapturedNS_ and self.LastName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sLastName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.LastName), input_name='LastName')), namespaceprefix_ , eol_)) - if self.FirmName is not None: - namespaceprefix_ = self.FirmName_nsprefix_ + ':' if (UseCapturedNS_ and self.FirmName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFirmName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FirmName), input_name='FirmName')), namespaceprefix_ , eol_)) - if self.SuiteOrApt is not None: - namespaceprefix_ = self.SuiteOrApt_nsprefix_ + ':' if (UseCapturedNS_ and self.SuiteOrApt_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSuiteOrApt>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SuiteOrApt), input_name='SuiteOrApt')), namespaceprefix_ , eol_)) - if self.Address2 is not None: - namespaceprefix_ = self.Address2_nsprefix_ + ':' if (UseCapturedNS_ and self.Address2_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAddress2>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Address2), input_name='Address2')), namespaceprefix_ , eol_)) - if self.Urbanization is not None: - namespaceprefix_ = self.Urbanization_nsprefix_ + ':' if (UseCapturedNS_ and self.Urbanization_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sUrbanization>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Urbanization), input_name='Urbanization')), namespaceprefix_ , eol_)) - if self.City is not None: - namespaceprefix_ = self.City_nsprefix_ + ':' if (UseCapturedNS_ and self.City_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.City), input_name='City')), namespaceprefix_ , eol_)) - if self.State is not None: - namespaceprefix_ = self.State_nsprefix_ + ':' if (UseCapturedNS_ and self.State_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.State), input_name='State')), namespaceprefix_ , eol_)) - if self.ZIP5 is not None: - namespaceprefix_ = self.ZIP5_nsprefix_ + ':' if (UseCapturedNS_ and self.ZIP5_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sZIP5>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ZIP5), input_name='ZIP5')), namespaceprefix_ , eol_)) - if self.ZIP4 is not None: - namespaceprefix_ = self.ZIP4_nsprefix_ + ':' if (UseCapturedNS_ and self.ZIP4_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sZIP4>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ZIP4), input_name='ZIP4')), namespaceprefix_ , eol_)) - if self.Phone is not None: - namespaceprefix_ = self.Phone_nsprefix_ + ':' if (UseCapturedNS_ and self.Phone_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPhone>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Phone), input_name='Phone')), namespaceprefix_ , eol_)) - if self.Extension is not None: - namespaceprefix_ = self.Extension_nsprefix_ + ':' if (UseCapturedNS_ and self.Extension_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sExtension>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Extension), input_name='Extension')), namespaceprefix_ , eol_)) - for Package_ in self.Package: - namespaceprefix_ = self.Package_nsprefix_ + ':' if (UseCapturedNS_ and self.Package_nsprefix_) else '' - Package_.export(outfile, level, namespaceprefix_, namespacedef_='', name_='Package', pretty_print=pretty_print) - if self.EstimatedWeight is not None: - namespaceprefix_ = self.EstimatedWeight_nsprefix_ + ':' if (UseCapturedNS_ and self.EstimatedWeight_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEstimatedWeight>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.EstimatedWeight), input_name='EstimatedWeight')), namespaceprefix_ , eol_)) - if self.PackageLocation is not None: - namespaceprefix_ = self.PackageLocation_nsprefix_ + ':' if (UseCapturedNS_ and self.PackageLocation_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPackageLocation>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PackageLocation), input_name='PackageLocation')), namespaceprefix_ , eol_)) - if self.SpecialInstructions is not None: - namespaceprefix_ = self.SpecialInstructions_nsprefix_ + ':' if (UseCapturedNS_ and self.SpecialInstructions_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSpecialInstructions>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SpecialInstructions), input_name='SpecialInstructions')), namespaceprefix_ , eol_)) - if self.ConfirmationNumber is not None: - namespaceprefix_ = self.ConfirmationNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.ConfirmationNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sConfirmationNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ConfirmationNumber), input_name='ConfirmationNumber')), namespaceprefix_ , eol_)) - if self.DayOfWeek is not None: - namespaceprefix_ = self.DayOfWeek_nsprefix_ + ':' if (UseCapturedNS_ and self.DayOfWeek_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDayOfWeek>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.DayOfWeek), input_name='DayOfWeek')), namespaceprefix_ , eol_)) - if self.Date is not None: - namespaceprefix_ = self.Date_nsprefix_ + ':' if (UseCapturedNS_ and self.Date_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDate>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Date), input_name='Date')), namespaceprefix_ , eol_)) - if self.CarrierRoute is not None: - namespaceprefix_ = self.CarrierRoute_nsprefix_ + ':' if (UseCapturedNS_ and self.CarrierRoute_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCarrierRoute>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CarrierRoute), input_name='CarrierRoute')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'FirstName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FirstName') - value_ = self.gds_validate_string(value_, node, 'FirstName') - self.FirstName = value_ - self.FirstName_nsprefix_ = child_.prefix - elif nodeName_ == 'LastName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'LastName') - value_ = self.gds_validate_string(value_, node, 'LastName') - self.LastName = value_ - self.LastName_nsprefix_ = child_.prefix - elif nodeName_ == 'FirmName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FirmName') - value_ = self.gds_validate_string(value_, node, 'FirmName') - self.FirmName = value_ - self.FirmName_nsprefix_ = child_.prefix - elif nodeName_ == 'SuiteOrApt': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SuiteOrApt') - value_ = self.gds_validate_string(value_, node, 'SuiteOrApt') - self.SuiteOrApt = value_ - self.SuiteOrApt_nsprefix_ = child_.prefix - elif nodeName_ == 'Address2': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Address2') - value_ = self.gds_validate_string(value_, node, 'Address2') - self.Address2 = value_ - self.Address2_nsprefix_ = child_.prefix - elif nodeName_ == 'Urbanization': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Urbanization') - value_ = self.gds_validate_string(value_, node, 'Urbanization') - self.Urbanization = value_ - self.Urbanization_nsprefix_ = child_.prefix - elif nodeName_ == 'City': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'City') - value_ = self.gds_validate_string(value_, node, 'City') - self.City = value_ - self.City_nsprefix_ = child_.prefix - elif nodeName_ == 'State': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'State') - value_ = self.gds_validate_string(value_, node, 'State') - self.State = value_ - self.State_nsprefix_ = child_.prefix - elif nodeName_ == 'ZIP5': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ZIP5') - value_ = self.gds_validate_string(value_, node, 'ZIP5') - self.ZIP5 = value_ - self.ZIP5_nsprefix_ = child_.prefix - elif nodeName_ == 'ZIP4': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ZIP4') - value_ = self.gds_validate_string(value_, node, 'ZIP4') - self.ZIP4 = value_ - self.ZIP4_nsprefix_ = child_.prefix - elif nodeName_ == 'Phone': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Phone') - value_ = self.gds_validate_string(value_, node, 'Phone') - self.Phone = value_ - self.Phone_nsprefix_ = child_.prefix - elif nodeName_ == 'Extension': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Extension') - value_ = self.gds_validate_string(value_, node, 'Extension') - self.Extension = value_ - self.Extension_nsprefix_ = child_.prefix - elif nodeName_ == 'Package': - obj_ = PackageType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.Package.append(obj_) - obj_.original_tagname_ = 'Package' - elif nodeName_ == 'EstimatedWeight': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'EstimatedWeight') - value_ = self.gds_validate_string(value_, node, 'EstimatedWeight') - self.EstimatedWeight = value_ - self.EstimatedWeight_nsprefix_ = child_.prefix - elif nodeName_ == 'PackageLocation': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PackageLocation') - value_ = self.gds_validate_string(value_, node, 'PackageLocation') - self.PackageLocation = value_ - self.PackageLocation_nsprefix_ = child_.prefix - elif nodeName_ == 'SpecialInstructions': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SpecialInstructions') - value_ = self.gds_validate_string(value_, node, 'SpecialInstructions') - self.SpecialInstructions = value_ - self.SpecialInstructions_nsprefix_ = child_.prefix - elif nodeName_ == 'ConfirmationNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ConfirmationNumber') - value_ = self.gds_validate_string(value_, node, 'ConfirmationNumber') - self.ConfirmationNumber = value_ - self.ConfirmationNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'DayOfWeek': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'DayOfWeek') - value_ = self.gds_validate_string(value_, node, 'DayOfWeek') - self.DayOfWeek = value_ - self.DayOfWeek_nsprefix_ = child_.prefix - elif nodeName_ == 'Date': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Date') - value_ = self.gds_validate_string(value_, node, 'Date') - self.Date = value_ - self.Date_nsprefix_ = child_.prefix - elif nodeName_ == 'CarrierRoute': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CarrierRoute') - value_ = self.gds_validate_string(value_, node, 'CarrierRoute') - self.CarrierRoute = value_ - self.CarrierRoute_nsprefix_ = child_.prefix -# end class CarrierPickupCancelResponse - - -class PackageType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ServiceType=None, Count=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.ServiceType = ServiceType - self.ServiceType_nsprefix_ = None - self.Count = Count - self.Count_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, PackageType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if PackageType.subclass: - return PackageType.subclass(*args_, **kwargs_) - else: - return PackageType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_ServiceType(self): - return self.ServiceType - def set_ServiceType(self, ServiceType): - self.ServiceType = ServiceType - def get_Count(self): - return self.Count - def set_Count(self, Count): - self.Count = Count - def _hasContent(self): - if ( - self.ServiceType is not None or - self.Count is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='PackageType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('PackageType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'PackageType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='PackageType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='PackageType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='PackageType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='PackageType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.ServiceType is not None: - namespaceprefix_ = self.ServiceType_nsprefix_ + ':' if (UseCapturedNS_ and self.ServiceType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sServiceType>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ServiceType), input_name='ServiceType')), namespaceprefix_ , eol_)) - if self.Count is not None: - namespaceprefix_ = self.Count_nsprefix_ + ':' if (UseCapturedNS_ and self.Count_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCount>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.Count, input_name='Count'), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'ServiceType': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ServiceType') - value_ = self.gds_validate_string(value_, node, 'ServiceType') - self.ServiceType = value_ - self.ServiceType_nsprefix_ = child_.prefix - elif nodeName_ == 'Count' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'Count') - ival_ = self.gds_validate_integer(ival_, node, 'Count') - self.Count = ival_ - self.Count_nsprefix_ = child_.prefix -# end class PackageType - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CarrierPickupCancelResponse' - rootClass = CarrierPickupCancelResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CarrierPickupCancelResponse' - rootClass = CarrierPickupCancelResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CarrierPickupCancelResponse' - rootClass = CarrierPickupCancelResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CarrierPickupCancelResponse' - rootClass = CarrierPickupCancelResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from carrier_pickup_cancel_response import *\n\n') - sys.stdout.write('import carrier_pickup_cancel_response as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "CarrierPickupCancelResponse", - "PackageType" -] diff --git a/schemas/usps/karrio/schemas/usps/carrier_pickup_change_request.py b/schemas/usps/karrio/schemas/usps/carrier_pickup_change_request.py deleted file mode 100644 index c2435f06cc..0000000000 --- a/schemas/usps/karrio/schemas/usps/carrier_pickup_change_request.py +++ /dev/null @@ -1,1720 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:05 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/carrier_pickup_change_request.py') -# -# Command line arguments: -# ./schemas/CarrierPickupChangeRequest.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/carrier_pickup_change_request.py" ./schemas/CarrierPickupChangeRequest.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class CarrierPickupChangeRequest(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, USERID=None, FirstName=None, LastName=None, FirmName=None, SuiteOrApt=None, Address2=None, Urbanization=None, City=None, State=None, ZIP5=None, ZIP4=None, Phone=None, Extension=None, Package=None, EstimatedWeight=None, PackageLocation=None, SpecialInstructions=None, ConfirmationNumber=None, EmailAddress=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.USERID = _cast(None, USERID) - self.USERID_nsprefix_ = None - self.FirstName = FirstName - self.FirstName_nsprefix_ = None - self.LastName = LastName - self.LastName_nsprefix_ = None - self.FirmName = FirmName - self.FirmName_nsprefix_ = None - self.SuiteOrApt = SuiteOrApt - self.SuiteOrApt_nsprefix_ = None - self.Address2 = Address2 - self.Address2_nsprefix_ = None - self.Urbanization = Urbanization - self.Urbanization_nsprefix_ = None - self.City = City - self.City_nsprefix_ = None - self.State = State - self.State_nsprefix_ = None - self.ZIP5 = ZIP5 - self.ZIP5_nsprefix_ = None - self.ZIP4 = ZIP4 - self.ZIP4_nsprefix_ = None - self.Phone = Phone - self.Phone_nsprefix_ = None - self.Extension = Extension - self.Extension_nsprefix_ = None - if Package is None: - self.Package = [] - else: - self.Package = Package - self.Package_nsprefix_ = None - self.EstimatedWeight = EstimatedWeight - self.EstimatedWeight_nsprefix_ = None - self.PackageLocation = PackageLocation - self.PackageLocation_nsprefix_ = None - self.SpecialInstructions = SpecialInstructions - self.SpecialInstructions_nsprefix_ = None - self.ConfirmationNumber = ConfirmationNumber - self.ConfirmationNumber_nsprefix_ = None - self.EmailAddress = EmailAddress - self.EmailAddress_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, CarrierPickupChangeRequest) - if subclass is not None: - return subclass(*args_, **kwargs_) - if CarrierPickupChangeRequest.subclass: - return CarrierPickupChangeRequest.subclass(*args_, **kwargs_) - else: - return CarrierPickupChangeRequest(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_FirstName(self): - return self.FirstName - def set_FirstName(self, FirstName): - self.FirstName = FirstName - def get_LastName(self): - return self.LastName - def set_LastName(self, LastName): - self.LastName = LastName - def get_FirmName(self): - return self.FirmName - def set_FirmName(self, FirmName): - self.FirmName = FirmName - def get_SuiteOrApt(self): - return self.SuiteOrApt - def set_SuiteOrApt(self, SuiteOrApt): - self.SuiteOrApt = SuiteOrApt - def get_Address2(self): - return self.Address2 - def set_Address2(self, Address2): - self.Address2 = Address2 - def get_Urbanization(self): - return self.Urbanization - def set_Urbanization(self, Urbanization): - self.Urbanization = Urbanization - def get_City(self): - return self.City - def set_City(self, City): - self.City = City - def get_State(self): - return self.State - def set_State(self, State): - self.State = State - def get_ZIP5(self): - return self.ZIP5 - def set_ZIP5(self, ZIP5): - self.ZIP5 = ZIP5 - def get_ZIP4(self): - return self.ZIP4 - def set_ZIP4(self, ZIP4): - self.ZIP4 = ZIP4 - def get_Phone(self): - return self.Phone - def set_Phone(self, Phone): - self.Phone = Phone - def get_Extension(self): - return self.Extension - def set_Extension(self, Extension): - self.Extension = Extension - def get_Package(self): - return self.Package - def set_Package(self, Package): - self.Package = Package - def add_Package(self, value): - self.Package.append(value) - def insert_Package_at(self, index, value): - self.Package.insert(index, value) - def replace_Package_at(self, index, value): - self.Package[index] = value - def get_EstimatedWeight(self): - return self.EstimatedWeight - def set_EstimatedWeight(self, EstimatedWeight): - self.EstimatedWeight = EstimatedWeight - def get_PackageLocation(self): - return self.PackageLocation - def set_PackageLocation(self, PackageLocation): - self.PackageLocation = PackageLocation - def get_SpecialInstructions(self): - return self.SpecialInstructions - def set_SpecialInstructions(self, SpecialInstructions): - self.SpecialInstructions = SpecialInstructions - def get_ConfirmationNumber(self): - return self.ConfirmationNumber - def set_ConfirmationNumber(self, ConfirmationNumber): - self.ConfirmationNumber = ConfirmationNumber - def get_EmailAddress(self): - return self.EmailAddress - def set_EmailAddress(self, EmailAddress): - self.EmailAddress = EmailAddress - def get_USERID(self): - return self.USERID - def set_USERID(self, USERID): - self.USERID = USERID - def _hasContent(self): - if ( - self.FirstName is not None or - self.LastName is not None or - self.FirmName is not None or - self.SuiteOrApt is not None or - self.Address2 is not None or - self.Urbanization is not None or - self.City is not None or - self.State is not None or - self.ZIP5 is not None or - self.ZIP4 is not None or - self.Phone is not None or - self.Extension is not None or - self.Package or - self.EstimatedWeight is not None or - self.PackageLocation is not None or - self.SpecialInstructions is not None or - self.ConfirmationNumber is not None or - self.EmailAddress is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='CarrierPickupChangeRequest', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('CarrierPickupChangeRequest') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'CarrierPickupChangeRequest': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='CarrierPickupChangeRequest') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='CarrierPickupChangeRequest', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='CarrierPickupChangeRequest'): - if self.USERID is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - outfile.write(' USERID=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.USERID), input_name='USERID')), )) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='CarrierPickupChangeRequest', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.FirstName is not None: - namespaceprefix_ = self.FirstName_nsprefix_ + ':' if (UseCapturedNS_ and self.FirstName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFirstName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FirstName), input_name='FirstName')), namespaceprefix_ , eol_)) - if self.LastName is not None: - namespaceprefix_ = self.LastName_nsprefix_ + ':' if (UseCapturedNS_ and self.LastName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sLastName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.LastName), input_name='LastName')), namespaceprefix_ , eol_)) - if self.FirmName is not None: - namespaceprefix_ = self.FirmName_nsprefix_ + ':' if (UseCapturedNS_ and self.FirmName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFirmName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FirmName), input_name='FirmName')), namespaceprefix_ , eol_)) - if self.SuiteOrApt is not None: - namespaceprefix_ = self.SuiteOrApt_nsprefix_ + ':' if (UseCapturedNS_ and self.SuiteOrApt_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSuiteOrApt>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SuiteOrApt), input_name='SuiteOrApt')), namespaceprefix_ , eol_)) - if self.Address2 is not None: - namespaceprefix_ = self.Address2_nsprefix_ + ':' if (UseCapturedNS_ and self.Address2_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAddress2>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Address2), input_name='Address2')), namespaceprefix_ , eol_)) - if self.Urbanization is not None: - namespaceprefix_ = self.Urbanization_nsprefix_ + ':' if (UseCapturedNS_ and self.Urbanization_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sUrbanization>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Urbanization), input_name='Urbanization')), namespaceprefix_ , eol_)) - if self.City is not None: - namespaceprefix_ = self.City_nsprefix_ + ':' if (UseCapturedNS_ and self.City_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.City), input_name='City')), namespaceprefix_ , eol_)) - if self.State is not None: - namespaceprefix_ = self.State_nsprefix_ + ':' if (UseCapturedNS_ and self.State_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.State), input_name='State')), namespaceprefix_ , eol_)) - if self.ZIP5 is not None: - namespaceprefix_ = self.ZIP5_nsprefix_ + ':' if (UseCapturedNS_ and self.ZIP5_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sZIP5>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ZIP5), input_name='ZIP5')), namespaceprefix_ , eol_)) - if self.ZIP4 is not None: - namespaceprefix_ = self.ZIP4_nsprefix_ + ':' if (UseCapturedNS_ and self.ZIP4_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sZIP4>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ZIP4), input_name='ZIP4')), namespaceprefix_ , eol_)) - if self.Phone is not None: - namespaceprefix_ = self.Phone_nsprefix_ + ':' if (UseCapturedNS_ and self.Phone_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPhone>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Phone), input_name='Phone')), namespaceprefix_ , eol_)) - if self.Extension is not None: - namespaceprefix_ = self.Extension_nsprefix_ + ':' if (UseCapturedNS_ and self.Extension_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sExtension>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Extension), input_name='Extension')), namespaceprefix_ , eol_)) - for Package_ in self.Package: - namespaceprefix_ = self.Package_nsprefix_ + ':' if (UseCapturedNS_ and self.Package_nsprefix_) else '' - Package_.export(outfile, level, namespaceprefix_, namespacedef_='', name_='Package', pretty_print=pretty_print) - if self.EstimatedWeight is not None: - namespaceprefix_ = self.EstimatedWeight_nsprefix_ + ':' if (UseCapturedNS_ and self.EstimatedWeight_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEstimatedWeight>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.EstimatedWeight), input_name='EstimatedWeight')), namespaceprefix_ , eol_)) - if self.PackageLocation is not None: - namespaceprefix_ = self.PackageLocation_nsprefix_ + ':' if (UseCapturedNS_ and self.PackageLocation_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPackageLocation>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PackageLocation), input_name='PackageLocation')), namespaceprefix_ , eol_)) - if self.SpecialInstructions is not None: - namespaceprefix_ = self.SpecialInstructions_nsprefix_ + ':' if (UseCapturedNS_ and self.SpecialInstructions_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSpecialInstructions>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SpecialInstructions), input_name='SpecialInstructions')), namespaceprefix_ , eol_)) - if self.ConfirmationNumber is not None: - namespaceprefix_ = self.ConfirmationNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.ConfirmationNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sConfirmationNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ConfirmationNumber), input_name='ConfirmationNumber')), namespaceprefix_ , eol_)) - if self.EmailAddress is not None: - namespaceprefix_ = self.EmailAddress_nsprefix_ + ':' if (UseCapturedNS_ and self.EmailAddress_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEmailAddress>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.EmailAddress), input_name='EmailAddress')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('USERID', node) - if value is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - self.USERID = value - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'FirstName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FirstName') - value_ = self.gds_validate_string(value_, node, 'FirstName') - self.FirstName = value_ - self.FirstName_nsprefix_ = child_.prefix - elif nodeName_ == 'LastName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'LastName') - value_ = self.gds_validate_string(value_, node, 'LastName') - self.LastName = value_ - self.LastName_nsprefix_ = child_.prefix - elif nodeName_ == 'FirmName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FirmName') - value_ = self.gds_validate_string(value_, node, 'FirmName') - self.FirmName = value_ - self.FirmName_nsprefix_ = child_.prefix - elif nodeName_ == 'SuiteOrApt': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SuiteOrApt') - value_ = self.gds_validate_string(value_, node, 'SuiteOrApt') - self.SuiteOrApt = value_ - self.SuiteOrApt_nsprefix_ = child_.prefix - elif nodeName_ == 'Address2': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Address2') - value_ = self.gds_validate_string(value_, node, 'Address2') - self.Address2 = value_ - self.Address2_nsprefix_ = child_.prefix - elif nodeName_ == 'Urbanization': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Urbanization') - value_ = self.gds_validate_string(value_, node, 'Urbanization') - self.Urbanization = value_ - self.Urbanization_nsprefix_ = child_.prefix - elif nodeName_ == 'City': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'City') - value_ = self.gds_validate_string(value_, node, 'City') - self.City = value_ - self.City_nsprefix_ = child_.prefix - elif nodeName_ == 'State': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'State') - value_ = self.gds_validate_string(value_, node, 'State') - self.State = value_ - self.State_nsprefix_ = child_.prefix - elif nodeName_ == 'ZIP5': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ZIP5') - value_ = self.gds_validate_string(value_, node, 'ZIP5') - self.ZIP5 = value_ - self.ZIP5_nsprefix_ = child_.prefix - elif nodeName_ == 'ZIP4': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ZIP4') - value_ = self.gds_validate_string(value_, node, 'ZIP4') - self.ZIP4 = value_ - self.ZIP4_nsprefix_ = child_.prefix - elif nodeName_ == 'Phone': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Phone') - value_ = self.gds_validate_string(value_, node, 'Phone') - self.Phone = value_ - self.Phone_nsprefix_ = child_.prefix - elif nodeName_ == 'Extension': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Extension') - value_ = self.gds_validate_string(value_, node, 'Extension') - self.Extension = value_ - self.Extension_nsprefix_ = child_.prefix - elif nodeName_ == 'Package': - obj_ = PackageType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.Package.append(obj_) - obj_.original_tagname_ = 'Package' - elif nodeName_ == 'EstimatedWeight': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'EstimatedWeight') - value_ = self.gds_validate_string(value_, node, 'EstimatedWeight') - self.EstimatedWeight = value_ - self.EstimatedWeight_nsprefix_ = child_.prefix - elif nodeName_ == 'PackageLocation': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PackageLocation') - value_ = self.gds_validate_string(value_, node, 'PackageLocation') - self.PackageLocation = value_ - self.PackageLocation_nsprefix_ = child_.prefix - elif nodeName_ == 'SpecialInstructions': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SpecialInstructions') - value_ = self.gds_validate_string(value_, node, 'SpecialInstructions') - self.SpecialInstructions = value_ - self.SpecialInstructions_nsprefix_ = child_.prefix - elif nodeName_ == 'ConfirmationNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ConfirmationNumber') - value_ = self.gds_validate_string(value_, node, 'ConfirmationNumber') - self.ConfirmationNumber = value_ - self.ConfirmationNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'EmailAddress': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'EmailAddress') - value_ = self.gds_validate_string(value_, node, 'EmailAddress') - self.EmailAddress = value_ - self.EmailAddress_nsprefix_ = child_.prefix -# end class CarrierPickupChangeRequest - - -class PackageType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ServiceType=None, Count=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.ServiceType = ServiceType - self.ServiceType_nsprefix_ = None - self.Count = Count - self.Count_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, PackageType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if PackageType.subclass: - return PackageType.subclass(*args_, **kwargs_) - else: - return PackageType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_ServiceType(self): - return self.ServiceType - def set_ServiceType(self, ServiceType): - self.ServiceType = ServiceType - def get_Count(self): - return self.Count - def set_Count(self, Count): - self.Count = Count - def _hasContent(self): - if ( - self.ServiceType is not None or - self.Count is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='PackageType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('PackageType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'PackageType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='PackageType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='PackageType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='PackageType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='PackageType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.ServiceType is not None: - namespaceprefix_ = self.ServiceType_nsprefix_ + ':' if (UseCapturedNS_ and self.ServiceType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sServiceType>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ServiceType), input_name='ServiceType')), namespaceprefix_ , eol_)) - if self.Count is not None: - namespaceprefix_ = self.Count_nsprefix_ + ':' if (UseCapturedNS_ and self.Count_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCount>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.Count, input_name='Count'), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'ServiceType': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ServiceType') - value_ = self.gds_validate_string(value_, node, 'ServiceType') - self.ServiceType = value_ - self.ServiceType_nsprefix_ = child_.prefix - elif nodeName_ == 'Count' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'Count') - ival_ = self.gds_validate_integer(ival_, node, 'Count') - self.Count = ival_ - self.Count_nsprefix_ = child_.prefix -# end class PackageType - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CarrierPickupChangeRequest' - rootClass = CarrierPickupChangeRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CarrierPickupChangeRequest' - rootClass = CarrierPickupChangeRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CarrierPickupChangeRequest' - rootClass = CarrierPickupChangeRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CarrierPickupChangeRequest' - rootClass = CarrierPickupChangeRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from carrier_pickup_change_request import *\n\n') - sys.stdout.write('import carrier_pickup_change_request as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "CarrierPickupChangeRequest", - "PackageType" -] diff --git a/schemas/usps/karrio/schemas/usps/carrier_pickup_change_response.py b/schemas/usps/karrio/schemas/usps/carrier_pickup_change_response.py deleted file mode 100644 index 26b93bea1e..0000000000 --- a/schemas/usps/karrio/schemas/usps/carrier_pickup_change_response.py +++ /dev/null @@ -1,1743 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:05 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/carrier_pickup_change_response.py') -# -# Command line arguments: -# ./schemas/CarrierPickupChangeResponse.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/carrier_pickup_change_response.py" ./schemas/CarrierPickupChangeResponse.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class CarrierPickupChangeResponse(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, FirstName=None, LastName=None, FirmName=None, SuiteOrApt=None, Address2=None, Urbanization=None, City=None, State=None, ZIP5=None, ZIP4=None, Phone=None, Extension=None, Package=None, EstimatedWeight=None, PackageLocation=None, SpecialInstructions=None, ConfirmationNumber=None, DayOfWeek=None, Date=None, Status=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.FirstName = FirstName - self.FirstName_nsprefix_ = None - self.LastName = LastName - self.LastName_nsprefix_ = None - self.FirmName = FirmName - self.FirmName_nsprefix_ = None - self.SuiteOrApt = SuiteOrApt - self.SuiteOrApt_nsprefix_ = None - self.Address2 = Address2 - self.Address2_nsprefix_ = None - self.Urbanization = Urbanization - self.Urbanization_nsprefix_ = None - self.City = City - self.City_nsprefix_ = None - self.State = State - self.State_nsprefix_ = None - self.ZIP5 = ZIP5 - self.ZIP5_nsprefix_ = None - self.ZIP4 = ZIP4 - self.ZIP4_nsprefix_ = None - self.Phone = Phone - self.Phone_nsprefix_ = None - self.Extension = Extension - self.Extension_nsprefix_ = None - if Package is None: - self.Package = [] - else: - self.Package = Package - self.Package_nsprefix_ = None - self.EstimatedWeight = EstimatedWeight - self.EstimatedWeight_nsprefix_ = None - self.PackageLocation = PackageLocation - self.PackageLocation_nsprefix_ = None - self.SpecialInstructions = SpecialInstructions - self.SpecialInstructions_nsprefix_ = None - self.ConfirmationNumber = ConfirmationNumber - self.ConfirmationNumber_nsprefix_ = None - self.DayOfWeek = DayOfWeek - self.DayOfWeek_nsprefix_ = None - self.Date = Date - self.Date_nsprefix_ = None - self.Status = Status - self.Status_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, CarrierPickupChangeResponse) - if subclass is not None: - return subclass(*args_, **kwargs_) - if CarrierPickupChangeResponse.subclass: - return CarrierPickupChangeResponse.subclass(*args_, **kwargs_) - else: - return CarrierPickupChangeResponse(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_FirstName(self): - return self.FirstName - def set_FirstName(self, FirstName): - self.FirstName = FirstName - def get_LastName(self): - return self.LastName - def set_LastName(self, LastName): - self.LastName = LastName - def get_FirmName(self): - return self.FirmName - def set_FirmName(self, FirmName): - self.FirmName = FirmName - def get_SuiteOrApt(self): - return self.SuiteOrApt - def set_SuiteOrApt(self, SuiteOrApt): - self.SuiteOrApt = SuiteOrApt - def get_Address2(self): - return self.Address2 - def set_Address2(self, Address2): - self.Address2 = Address2 - def get_Urbanization(self): - return self.Urbanization - def set_Urbanization(self, Urbanization): - self.Urbanization = Urbanization - def get_City(self): - return self.City - def set_City(self, City): - self.City = City - def get_State(self): - return self.State - def set_State(self, State): - self.State = State - def get_ZIP5(self): - return self.ZIP5 - def set_ZIP5(self, ZIP5): - self.ZIP5 = ZIP5 - def get_ZIP4(self): - return self.ZIP4 - def set_ZIP4(self, ZIP4): - self.ZIP4 = ZIP4 - def get_Phone(self): - return self.Phone - def set_Phone(self, Phone): - self.Phone = Phone - def get_Extension(self): - return self.Extension - def set_Extension(self, Extension): - self.Extension = Extension - def get_Package(self): - return self.Package - def set_Package(self, Package): - self.Package = Package - def add_Package(self, value): - self.Package.append(value) - def insert_Package_at(self, index, value): - self.Package.insert(index, value) - def replace_Package_at(self, index, value): - self.Package[index] = value - def get_EstimatedWeight(self): - return self.EstimatedWeight - def set_EstimatedWeight(self, EstimatedWeight): - self.EstimatedWeight = EstimatedWeight - def get_PackageLocation(self): - return self.PackageLocation - def set_PackageLocation(self, PackageLocation): - self.PackageLocation = PackageLocation - def get_SpecialInstructions(self): - return self.SpecialInstructions - def set_SpecialInstructions(self, SpecialInstructions): - self.SpecialInstructions = SpecialInstructions - def get_ConfirmationNumber(self): - return self.ConfirmationNumber - def set_ConfirmationNumber(self, ConfirmationNumber): - self.ConfirmationNumber = ConfirmationNumber - def get_DayOfWeek(self): - return self.DayOfWeek - def set_DayOfWeek(self, DayOfWeek): - self.DayOfWeek = DayOfWeek - def get_Date(self): - return self.Date - def set_Date(self, Date): - self.Date = Date - def get_Status(self): - return self.Status - def set_Status(self, Status): - self.Status = Status - def _hasContent(self): - if ( - self.FirstName is not None or - self.LastName is not None or - self.FirmName is not None or - self.SuiteOrApt is not None or - self.Address2 is not None or - self.Urbanization is not None or - self.City is not None or - self.State is not None or - self.ZIP5 is not None or - self.ZIP4 is not None or - self.Phone is not None or - self.Extension is not None or - self.Package or - self.EstimatedWeight is not None or - self.PackageLocation is not None or - self.SpecialInstructions is not None or - self.ConfirmationNumber is not None or - self.DayOfWeek is not None or - self.Date is not None or - self.Status is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='CarrierPickupChangeResponse', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('CarrierPickupChangeResponse') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'CarrierPickupChangeResponse': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='CarrierPickupChangeResponse') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='CarrierPickupChangeResponse', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='CarrierPickupChangeResponse'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='CarrierPickupChangeResponse', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.FirstName is not None: - namespaceprefix_ = self.FirstName_nsprefix_ + ':' if (UseCapturedNS_ and self.FirstName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFirstName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FirstName), input_name='FirstName')), namespaceprefix_ , eol_)) - if self.LastName is not None: - namespaceprefix_ = self.LastName_nsprefix_ + ':' if (UseCapturedNS_ and self.LastName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sLastName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.LastName), input_name='LastName')), namespaceprefix_ , eol_)) - if self.FirmName is not None: - namespaceprefix_ = self.FirmName_nsprefix_ + ':' if (UseCapturedNS_ and self.FirmName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFirmName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FirmName), input_name='FirmName')), namespaceprefix_ , eol_)) - if self.SuiteOrApt is not None: - namespaceprefix_ = self.SuiteOrApt_nsprefix_ + ':' if (UseCapturedNS_ and self.SuiteOrApt_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSuiteOrApt>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SuiteOrApt), input_name='SuiteOrApt')), namespaceprefix_ , eol_)) - if self.Address2 is not None: - namespaceprefix_ = self.Address2_nsprefix_ + ':' if (UseCapturedNS_ and self.Address2_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAddress2>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Address2), input_name='Address2')), namespaceprefix_ , eol_)) - if self.Urbanization is not None: - namespaceprefix_ = self.Urbanization_nsprefix_ + ':' if (UseCapturedNS_ and self.Urbanization_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sUrbanization>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Urbanization), input_name='Urbanization')), namespaceprefix_ , eol_)) - if self.City is not None: - namespaceprefix_ = self.City_nsprefix_ + ':' if (UseCapturedNS_ and self.City_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.City), input_name='City')), namespaceprefix_ , eol_)) - if self.State is not None: - namespaceprefix_ = self.State_nsprefix_ + ':' if (UseCapturedNS_ and self.State_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.State), input_name='State')), namespaceprefix_ , eol_)) - if self.ZIP5 is not None: - namespaceprefix_ = self.ZIP5_nsprefix_ + ':' if (UseCapturedNS_ and self.ZIP5_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sZIP5>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ZIP5), input_name='ZIP5')), namespaceprefix_ , eol_)) - if self.ZIP4 is not None: - namespaceprefix_ = self.ZIP4_nsprefix_ + ':' if (UseCapturedNS_ and self.ZIP4_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sZIP4>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ZIP4), input_name='ZIP4')), namespaceprefix_ , eol_)) - if self.Phone is not None: - namespaceprefix_ = self.Phone_nsprefix_ + ':' if (UseCapturedNS_ and self.Phone_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPhone>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Phone), input_name='Phone')), namespaceprefix_ , eol_)) - if self.Extension is not None: - namespaceprefix_ = self.Extension_nsprefix_ + ':' if (UseCapturedNS_ and self.Extension_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sExtension>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Extension), input_name='Extension')), namespaceprefix_ , eol_)) - for Package_ in self.Package: - namespaceprefix_ = self.Package_nsprefix_ + ':' if (UseCapturedNS_ and self.Package_nsprefix_) else '' - Package_.export(outfile, level, namespaceprefix_, namespacedef_='', name_='Package', pretty_print=pretty_print) - if self.EstimatedWeight is not None: - namespaceprefix_ = self.EstimatedWeight_nsprefix_ + ':' if (UseCapturedNS_ and self.EstimatedWeight_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEstimatedWeight>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.EstimatedWeight), input_name='EstimatedWeight')), namespaceprefix_ , eol_)) - if self.PackageLocation is not None: - namespaceprefix_ = self.PackageLocation_nsprefix_ + ':' if (UseCapturedNS_ and self.PackageLocation_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPackageLocation>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PackageLocation), input_name='PackageLocation')), namespaceprefix_ , eol_)) - if self.SpecialInstructions is not None: - namespaceprefix_ = self.SpecialInstructions_nsprefix_ + ':' if (UseCapturedNS_ and self.SpecialInstructions_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSpecialInstructions>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SpecialInstructions), input_name='SpecialInstructions')), namespaceprefix_ , eol_)) - if self.ConfirmationNumber is not None: - namespaceprefix_ = self.ConfirmationNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.ConfirmationNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sConfirmationNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ConfirmationNumber), input_name='ConfirmationNumber')), namespaceprefix_ , eol_)) - if self.DayOfWeek is not None: - namespaceprefix_ = self.DayOfWeek_nsprefix_ + ':' if (UseCapturedNS_ and self.DayOfWeek_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDayOfWeek>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.DayOfWeek), input_name='DayOfWeek')), namespaceprefix_ , eol_)) - if self.Date is not None: - namespaceprefix_ = self.Date_nsprefix_ + ':' if (UseCapturedNS_ and self.Date_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDate>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Date), input_name='Date')), namespaceprefix_ , eol_)) - if self.Status is not None: - namespaceprefix_ = self.Status_nsprefix_ + ':' if (UseCapturedNS_ and self.Status_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sStatus>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Status), input_name='Status')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'FirstName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FirstName') - value_ = self.gds_validate_string(value_, node, 'FirstName') - self.FirstName = value_ - self.FirstName_nsprefix_ = child_.prefix - elif nodeName_ == 'LastName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'LastName') - value_ = self.gds_validate_string(value_, node, 'LastName') - self.LastName = value_ - self.LastName_nsprefix_ = child_.prefix - elif nodeName_ == 'FirmName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FirmName') - value_ = self.gds_validate_string(value_, node, 'FirmName') - self.FirmName = value_ - self.FirmName_nsprefix_ = child_.prefix - elif nodeName_ == 'SuiteOrApt': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SuiteOrApt') - value_ = self.gds_validate_string(value_, node, 'SuiteOrApt') - self.SuiteOrApt = value_ - self.SuiteOrApt_nsprefix_ = child_.prefix - elif nodeName_ == 'Address2': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Address2') - value_ = self.gds_validate_string(value_, node, 'Address2') - self.Address2 = value_ - self.Address2_nsprefix_ = child_.prefix - elif nodeName_ == 'Urbanization': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Urbanization') - value_ = self.gds_validate_string(value_, node, 'Urbanization') - self.Urbanization = value_ - self.Urbanization_nsprefix_ = child_.prefix - elif nodeName_ == 'City': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'City') - value_ = self.gds_validate_string(value_, node, 'City') - self.City = value_ - self.City_nsprefix_ = child_.prefix - elif nodeName_ == 'State': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'State') - value_ = self.gds_validate_string(value_, node, 'State') - self.State = value_ - self.State_nsprefix_ = child_.prefix - elif nodeName_ == 'ZIP5': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ZIP5') - value_ = self.gds_validate_string(value_, node, 'ZIP5') - self.ZIP5 = value_ - self.ZIP5_nsprefix_ = child_.prefix - elif nodeName_ == 'ZIP4': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ZIP4') - value_ = self.gds_validate_string(value_, node, 'ZIP4') - self.ZIP4 = value_ - self.ZIP4_nsprefix_ = child_.prefix - elif nodeName_ == 'Phone': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Phone') - value_ = self.gds_validate_string(value_, node, 'Phone') - self.Phone = value_ - self.Phone_nsprefix_ = child_.prefix - elif nodeName_ == 'Extension': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Extension') - value_ = self.gds_validate_string(value_, node, 'Extension') - self.Extension = value_ - self.Extension_nsprefix_ = child_.prefix - elif nodeName_ == 'Package': - obj_ = PackageType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.Package.append(obj_) - obj_.original_tagname_ = 'Package' - elif nodeName_ == 'EstimatedWeight': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'EstimatedWeight') - value_ = self.gds_validate_string(value_, node, 'EstimatedWeight') - self.EstimatedWeight = value_ - self.EstimatedWeight_nsprefix_ = child_.prefix - elif nodeName_ == 'PackageLocation': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PackageLocation') - value_ = self.gds_validate_string(value_, node, 'PackageLocation') - self.PackageLocation = value_ - self.PackageLocation_nsprefix_ = child_.prefix - elif nodeName_ == 'SpecialInstructions': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SpecialInstructions') - value_ = self.gds_validate_string(value_, node, 'SpecialInstructions') - self.SpecialInstructions = value_ - self.SpecialInstructions_nsprefix_ = child_.prefix - elif nodeName_ == 'ConfirmationNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ConfirmationNumber') - value_ = self.gds_validate_string(value_, node, 'ConfirmationNumber') - self.ConfirmationNumber = value_ - self.ConfirmationNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'DayOfWeek': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'DayOfWeek') - value_ = self.gds_validate_string(value_, node, 'DayOfWeek') - self.DayOfWeek = value_ - self.DayOfWeek_nsprefix_ = child_.prefix - elif nodeName_ == 'Date': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Date') - value_ = self.gds_validate_string(value_, node, 'Date') - self.Date = value_ - self.Date_nsprefix_ = child_.prefix - elif nodeName_ == 'Status': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Status') - value_ = self.gds_validate_string(value_, node, 'Status') - self.Status = value_ - self.Status_nsprefix_ = child_.prefix -# end class CarrierPickupChangeResponse - - -class PackageType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ServiceType=None, Count=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.ServiceType = ServiceType - self.ServiceType_nsprefix_ = None - self.Count = Count - self.Count_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, PackageType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if PackageType.subclass: - return PackageType.subclass(*args_, **kwargs_) - else: - return PackageType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_ServiceType(self): - return self.ServiceType - def set_ServiceType(self, ServiceType): - self.ServiceType = ServiceType - def get_Count(self): - return self.Count - def set_Count(self, Count): - self.Count = Count - def _hasContent(self): - if ( - self.ServiceType is not None or - self.Count is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='PackageType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('PackageType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'PackageType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='PackageType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='PackageType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='PackageType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='PackageType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.ServiceType is not None: - namespaceprefix_ = self.ServiceType_nsprefix_ + ':' if (UseCapturedNS_ and self.ServiceType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sServiceType>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ServiceType), input_name='ServiceType')), namespaceprefix_ , eol_)) - if self.Count is not None: - namespaceprefix_ = self.Count_nsprefix_ + ':' if (UseCapturedNS_ and self.Count_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCount>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.Count, input_name='Count'), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'ServiceType': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ServiceType') - value_ = self.gds_validate_string(value_, node, 'ServiceType') - self.ServiceType = value_ - self.ServiceType_nsprefix_ = child_.prefix - elif nodeName_ == 'Count' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'Count') - ival_ = self.gds_validate_integer(ival_, node, 'Count') - self.Count = ival_ - self.Count_nsprefix_ = child_.prefix -# end class PackageType - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CarrierPickupChangeResponse' - rootClass = CarrierPickupChangeResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CarrierPickupChangeResponse' - rootClass = CarrierPickupChangeResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CarrierPickupChangeResponse' - rootClass = CarrierPickupChangeResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CarrierPickupChangeResponse' - rootClass = CarrierPickupChangeResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from carrier_pickup_change_response import *\n\n') - sys.stdout.write('import carrier_pickup_change_response as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "CarrierPickupChangeResponse", - "PackageType" -] diff --git a/schemas/usps/karrio/schemas/usps/carrier_pickup_inquiry_request.py b/schemas/usps/karrio/schemas/usps/carrier_pickup_inquiry_request.py deleted file mode 100644 index 818d44f981..0000000000 --- a/schemas/usps/karrio/schemas/usps/carrier_pickup_inquiry_request.py +++ /dev/null @@ -1,1447 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:05 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/carrier_pickup_inquiry_request.py') -# -# Command line arguments: -# ./schemas/CarrierPickupInquiryRequest.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/carrier_pickup_inquiry_request.py" ./schemas/CarrierPickupInquiryRequest.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class CarrierPickupInquiryRequest(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, USERID=None, FirmName=None, SuiteOrApt=None, Address2=None, Urbanization=None, City=None, State=None, ZIP5=None, ZIP4=None, ConfirmationNumber=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.USERID = _cast(None, USERID) - self.USERID_nsprefix_ = None - self.FirmName = FirmName - self.FirmName_nsprefix_ = None - self.SuiteOrApt = SuiteOrApt - self.SuiteOrApt_nsprefix_ = None - self.Address2 = Address2 - self.Address2_nsprefix_ = None - self.Urbanization = Urbanization - self.Urbanization_nsprefix_ = None - self.City = City - self.City_nsprefix_ = None - self.State = State - self.State_nsprefix_ = None - self.ZIP5 = ZIP5 - self.ZIP5_nsprefix_ = None - self.ZIP4 = ZIP4 - self.ZIP4_nsprefix_ = None - self.ConfirmationNumber = ConfirmationNumber - self.ConfirmationNumber_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, CarrierPickupInquiryRequest) - if subclass is not None: - return subclass(*args_, **kwargs_) - if CarrierPickupInquiryRequest.subclass: - return CarrierPickupInquiryRequest.subclass(*args_, **kwargs_) - else: - return CarrierPickupInquiryRequest(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_FirmName(self): - return self.FirmName - def set_FirmName(self, FirmName): - self.FirmName = FirmName - def get_SuiteOrApt(self): - return self.SuiteOrApt - def set_SuiteOrApt(self, SuiteOrApt): - self.SuiteOrApt = SuiteOrApt - def get_Address2(self): - return self.Address2 - def set_Address2(self, Address2): - self.Address2 = Address2 - def get_Urbanization(self): - return self.Urbanization - def set_Urbanization(self, Urbanization): - self.Urbanization = Urbanization - def get_City(self): - return self.City - def set_City(self, City): - self.City = City - def get_State(self): - return self.State - def set_State(self, State): - self.State = State - def get_ZIP5(self): - return self.ZIP5 - def set_ZIP5(self, ZIP5): - self.ZIP5 = ZIP5 - def get_ZIP4(self): - return self.ZIP4 - def set_ZIP4(self, ZIP4): - self.ZIP4 = ZIP4 - def get_ConfirmationNumber(self): - return self.ConfirmationNumber - def set_ConfirmationNumber(self, ConfirmationNumber): - self.ConfirmationNumber = ConfirmationNumber - def get_USERID(self): - return self.USERID - def set_USERID(self, USERID): - self.USERID = USERID - def _hasContent(self): - if ( - self.FirmName is not None or - self.SuiteOrApt is not None or - self.Address2 is not None or - self.Urbanization is not None or - self.City is not None or - self.State is not None or - self.ZIP5 is not None or - self.ZIP4 is not None or - self.ConfirmationNumber is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='CarrierPickupInquiryRequest', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('CarrierPickupInquiryRequest') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'CarrierPickupInquiryRequest': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='CarrierPickupInquiryRequest') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='CarrierPickupInquiryRequest', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='CarrierPickupInquiryRequest'): - if self.USERID is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - outfile.write(' USERID=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.USERID), input_name='USERID')), )) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='CarrierPickupInquiryRequest', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.FirmName is not None: - namespaceprefix_ = self.FirmName_nsprefix_ + ':' if (UseCapturedNS_ and self.FirmName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFirmName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FirmName), input_name='FirmName')), namespaceprefix_ , eol_)) - if self.SuiteOrApt is not None: - namespaceprefix_ = self.SuiteOrApt_nsprefix_ + ':' if (UseCapturedNS_ and self.SuiteOrApt_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSuiteOrApt>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SuiteOrApt), input_name='SuiteOrApt')), namespaceprefix_ , eol_)) - if self.Address2 is not None: - namespaceprefix_ = self.Address2_nsprefix_ + ':' if (UseCapturedNS_ and self.Address2_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAddress2>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Address2), input_name='Address2')), namespaceprefix_ , eol_)) - if self.Urbanization is not None: - namespaceprefix_ = self.Urbanization_nsprefix_ + ':' if (UseCapturedNS_ and self.Urbanization_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sUrbanization>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Urbanization), input_name='Urbanization')), namespaceprefix_ , eol_)) - if self.City is not None: - namespaceprefix_ = self.City_nsprefix_ + ':' if (UseCapturedNS_ and self.City_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.City), input_name='City')), namespaceprefix_ , eol_)) - if self.State is not None: - namespaceprefix_ = self.State_nsprefix_ + ':' if (UseCapturedNS_ and self.State_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.State), input_name='State')), namespaceprefix_ , eol_)) - if self.ZIP5 is not None: - namespaceprefix_ = self.ZIP5_nsprefix_ + ':' if (UseCapturedNS_ and self.ZIP5_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sZIP5>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ZIP5), input_name='ZIP5')), namespaceprefix_ , eol_)) - if self.ZIP4 is not None: - namespaceprefix_ = self.ZIP4_nsprefix_ + ':' if (UseCapturedNS_ and self.ZIP4_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sZIP4>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ZIP4), input_name='ZIP4')), namespaceprefix_ , eol_)) - if self.ConfirmationNumber is not None: - namespaceprefix_ = self.ConfirmationNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.ConfirmationNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sConfirmationNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ConfirmationNumber), input_name='ConfirmationNumber')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('USERID', node) - if value is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - self.USERID = value - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'FirmName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FirmName') - value_ = self.gds_validate_string(value_, node, 'FirmName') - self.FirmName = value_ - self.FirmName_nsprefix_ = child_.prefix - elif nodeName_ == 'SuiteOrApt': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SuiteOrApt') - value_ = self.gds_validate_string(value_, node, 'SuiteOrApt') - self.SuiteOrApt = value_ - self.SuiteOrApt_nsprefix_ = child_.prefix - elif nodeName_ == 'Address2': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Address2') - value_ = self.gds_validate_string(value_, node, 'Address2') - self.Address2 = value_ - self.Address2_nsprefix_ = child_.prefix - elif nodeName_ == 'Urbanization': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Urbanization') - value_ = self.gds_validate_string(value_, node, 'Urbanization') - self.Urbanization = value_ - self.Urbanization_nsprefix_ = child_.prefix - elif nodeName_ == 'City': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'City') - value_ = self.gds_validate_string(value_, node, 'City') - self.City = value_ - self.City_nsprefix_ = child_.prefix - elif nodeName_ == 'State': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'State') - value_ = self.gds_validate_string(value_, node, 'State') - self.State = value_ - self.State_nsprefix_ = child_.prefix - elif nodeName_ == 'ZIP5': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ZIP5') - value_ = self.gds_validate_string(value_, node, 'ZIP5') - self.ZIP5 = value_ - self.ZIP5_nsprefix_ = child_.prefix - elif nodeName_ == 'ZIP4': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ZIP4') - value_ = self.gds_validate_string(value_, node, 'ZIP4') - self.ZIP4 = value_ - self.ZIP4_nsprefix_ = child_.prefix - elif nodeName_ == 'ConfirmationNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ConfirmationNumber') - value_ = self.gds_validate_string(value_, node, 'ConfirmationNumber') - self.ConfirmationNumber = value_ - self.ConfirmationNumber_nsprefix_ = child_.prefix -# end class CarrierPickupInquiryRequest - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CarrierPickupInquiryRequest' - rootClass = CarrierPickupInquiryRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CarrierPickupInquiryRequest' - rootClass = CarrierPickupInquiryRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CarrierPickupInquiryRequest' - rootClass = CarrierPickupInquiryRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CarrierPickupInquiryRequest' - rootClass = CarrierPickupInquiryRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from carrier_pickup_inquiry_request import *\n\n') - sys.stdout.write('import carrier_pickup_inquiry_request as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "CarrierPickupInquiryRequest" -] diff --git a/schemas/usps/karrio/schemas/usps/carrier_pickup_inquiry_response.py b/schemas/usps/karrio/schemas/usps/carrier_pickup_inquiry_response.py deleted file mode 100644 index 9181f36dcd..0000000000 --- a/schemas/usps/karrio/schemas/usps/carrier_pickup_inquiry_response.py +++ /dev/null @@ -1,1743 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:05 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/carrier_pickup_inquiry_response.py') -# -# Command line arguments: -# ./schemas/CarrierPickupInquiryResponse.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/carrier_pickup_inquiry_response.py" ./schemas/CarrierPickupInquiryResponse.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class CarrierPickupInquiryResponse(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, FirstName=None, LastName=None, FirmName=None, SuiteOrApt=None, Address2=None, Urbanization=None, City=None, State=None, ZIP5=None, ZIP4=None, Phone=None, Extension=None, Package=None, EstimatedWeight=None, PackageLocation=None, SpecialInstructions=None, ConfirmationNumber=None, DayOfWeek=None, Date=None, EmailAddress=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.FirstName = FirstName - self.FirstName_nsprefix_ = None - self.LastName = LastName - self.LastName_nsprefix_ = None - self.FirmName = FirmName - self.FirmName_nsprefix_ = None - self.SuiteOrApt = SuiteOrApt - self.SuiteOrApt_nsprefix_ = None - self.Address2 = Address2 - self.Address2_nsprefix_ = None - self.Urbanization = Urbanization - self.Urbanization_nsprefix_ = None - self.City = City - self.City_nsprefix_ = None - self.State = State - self.State_nsprefix_ = None - self.ZIP5 = ZIP5 - self.ZIP5_nsprefix_ = None - self.ZIP4 = ZIP4 - self.ZIP4_nsprefix_ = None - self.Phone = Phone - self.Phone_nsprefix_ = None - self.Extension = Extension - self.Extension_nsprefix_ = None - if Package is None: - self.Package = [] - else: - self.Package = Package - self.Package_nsprefix_ = None - self.EstimatedWeight = EstimatedWeight - self.EstimatedWeight_nsprefix_ = None - self.PackageLocation = PackageLocation - self.PackageLocation_nsprefix_ = None - self.SpecialInstructions = SpecialInstructions - self.SpecialInstructions_nsprefix_ = None - self.ConfirmationNumber = ConfirmationNumber - self.ConfirmationNumber_nsprefix_ = None - self.DayOfWeek = DayOfWeek - self.DayOfWeek_nsprefix_ = None - self.Date = Date - self.Date_nsprefix_ = None - self.EmailAddress = EmailAddress - self.EmailAddress_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, CarrierPickupInquiryResponse) - if subclass is not None: - return subclass(*args_, **kwargs_) - if CarrierPickupInquiryResponse.subclass: - return CarrierPickupInquiryResponse.subclass(*args_, **kwargs_) - else: - return CarrierPickupInquiryResponse(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_FirstName(self): - return self.FirstName - def set_FirstName(self, FirstName): - self.FirstName = FirstName - def get_LastName(self): - return self.LastName - def set_LastName(self, LastName): - self.LastName = LastName - def get_FirmName(self): - return self.FirmName - def set_FirmName(self, FirmName): - self.FirmName = FirmName - def get_SuiteOrApt(self): - return self.SuiteOrApt - def set_SuiteOrApt(self, SuiteOrApt): - self.SuiteOrApt = SuiteOrApt - def get_Address2(self): - return self.Address2 - def set_Address2(self, Address2): - self.Address2 = Address2 - def get_Urbanization(self): - return self.Urbanization - def set_Urbanization(self, Urbanization): - self.Urbanization = Urbanization - def get_City(self): - return self.City - def set_City(self, City): - self.City = City - def get_State(self): - return self.State - def set_State(self, State): - self.State = State - def get_ZIP5(self): - return self.ZIP5 - def set_ZIP5(self, ZIP5): - self.ZIP5 = ZIP5 - def get_ZIP4(self): - return self.ZIP4 - def set_ZIP4(self, ZIP4): - self.ZIP4 = ZIP4 - def get_Phone(self): - return self.Phone - def set_Phone(self, Phone): - self.Phone = Phone - def get_Extension(self): - return self.Extension - def set_Extension(self, Extension): - self.Extension = Extension - def get_Package(self): - return self.Package - def set_Package(self, Package): - self.Package = Package - def add_Package(self, value): - self.Package.append(value) - def insert_Package_at(self, index, value): - self.Package.insert(index, value) - def replace_Package_at(self, index, value): - self.Package[index] = value - def get_EstimatedWeight(self): - return self.EstimatedWeight - def set_EstimatedWeight(self, EstimatedWeight): - self.EstimatedWeight = EstimatedWeight - def get_PackageLocation(self): - return self.PackageLocation - def set_PackageLocation(self, PackageLocation): - self.PackageLocation = PackageLocation - def get_SpecialInstructions(self): - return self.SpecialInstructions - def set_SpecialInstructions(self, SpecialInstructions): - self.SpecialInstructions = SpecialInstructions - def get_ConfirmationNumber(self): - return self.ConfirmationNumber - def set_ConfirmationNumber(self, ConfirmationNumber): - self.ConfirmationNumber = ConfirmationNumber - def get_DayOfWeek(self): - return self.DayOfWeek - def set_DayOfWeek(self, DayOfWeek): - self.DayOfWeek = DayOfWeek - def get_Date(self): - return self.Date - def set_Date(self, Date): - self.Date = Date - def get_EmailAddress(self): - return self.EmailAddress - def set_EmailAddress(self, EmailAddress): - self.EmailAddress = EmailAddress - def _hasContent(self): - if ( - self.FirstName is not None or - self.LastName is not None or - self.FirmName is not None or - self.SuiteOrApt is not None or - self.Address2 is not None or - self.Urbanization is not None or - self.City is not None or - self.State is not None or - self.ZIP5 is not None or - self.ZIP4 is not None or - self.Phone is not None or - self.Extension is not None or - self.Package or - self.EstimatedWeight is not None or - self.PackageLocation is not None or - self.SpecialInstructions is not None or - self.ConfirmationNumber is not None or - self.DayOfWeek is not None or - self.Date is not None or - self.EmailAddress is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='CarrierPickupInquiryResponse', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('CarrierPickupInquiryResponse') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'CarrierPickupInquiryResponse': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='CarrierPickupInquiryResponse') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='CarrierPickupInquiryResponse', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='CarrierPickupInquiryResponse'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='CarrierPickupInquiryResponse', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.FirstName is not None: - namespaceprefix_ = self.FirstName_nsprefix_ + ':' if (UseCapturedNS_ and self.FirstName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFirstName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FirstName), input_name='FirstName')), namespaceprefix_ , eol_)) - if self.LastName is not None: - namespaceprefix_ = self.LastName_nsprefix_ + ':' if (UseCapturedNS_ and self.LastName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sLastName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.LastName), input_name='LastName')), namespaceprefix_ , eol_)) - if self.FirmName is not None: - namespaceprefix_ = self.FirmName_nsprefix_ + ':' if (UseCapturedNS_ and self.FirmName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFirmName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FirmName), input_name='FirmName')), namespaceprefix_ , eol_)) - if self.SuiteOrApt is not None: - namespaceprefix_ = self.SuiteOrApt_nsprefix_ + ':' if (UseCapturedNS_ and self.SuiteOrApt_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSuiteOrApt>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SuiteOrApt), input_name='SuiteOrApt')), namespaceprefix_ , eol_)) - if self.Address2 is not None: - namespaceprefix_ = self.Address2_nsprefix_ + ':' if (UseCapturedNS_ and self.Address2_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAddress2>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Address2), input_name='Address2')), namespaceprefix_ , eol_)) - if self.Urbanization is not None: - namespaceprefix_ = self.Urbanization_nsprefix_ + ':' if (UseCapturedNS_ and self.Urbanization_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sUrbanization>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Urbanization), input_name='Urbanization')), namespaceprefix_ , eol_)) - if self.City is not None: - namespaceprefix_ = self.City_nsprefix_ + ':' if (UseCapturedNS_ and self.City_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.City), input_name='City')), namespaceprefix_ , eol_)) - if self.State is not None: - namespaceprefix_ = self.State_nsprefix_ + ':' if (UseCapturedNS_ and self.State_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.State), input_name='State')), namespaceprefix_ , eol_)) - if self.ZIP5 is not None: - namespaceprefix_ = self.ZIP5_nsprefix_ + ':' if (UseCapturedNS_ and self.ZIP5_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sZIP5>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ZIP5), input_name='ZIP5')), namespaceprefix_ , eol_)) - if self.ZIP4 is not None: - namespaceprefix_ = self.ZIP4_nsprefix_ + ':' if (UseCapturedNS_ and self.ZIP4_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sZIP4>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ZIP4), input_name='ZIP4')), namespaceprefix_ , eol_)) - if self.Phone is not None: - namespaceprefix_ = self.Phone_nsprefix_ + ':' if (UseCapturedNS_ and self.Phone_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPhone>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Phone), input_name='Phone')), namespaceprefix_ , eol_)) - if self.Extension is not None: - namespaceprefix_ = self.Extension_nsprefix_ + ':' if (UseCapturedNS_ and self.Extension_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sExtension>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Extension), input_name='Extension')), namespaceprefix_ , eol_)) - for Package_ in self.Package: - namespaceprefix_ = self.Package_nsprefix_ + ':' if (UseCapturedNS_ and self.Package_nsprefix_) else '' - Package_.export(outfile, level, namespaceprefix_, namespacedef_='', name_='Package', pretty_print=pretty_print) - if self.EstimatedWeight is not None: - namespaceprefix_ = self.EstimatedWeight_nsprefix_ + ':' if (UseCapturedNS_ and self.EstimatedWeight_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEstimatedWeight>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.EstimatedWeight), input_name='EstimatedWeight')), namespaceprefix_ , eol_)) - if self.PackageLocation is not None: - namespaceprefix_ = self.PackageLocation_nsprefix_ + ':' if (UseCapturedNS_ and self.PackageLocation_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPackageLocation>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PackageLocation), input_name='PackageLocation')), namespaceprefix_ , eol_)) - if self.SpecialInstructions is not None: - namespaceprefix_ = self.SpecialInstructions_nsprefix_ + ':' if (UseCapturedNS_ and self.SpecialInstructions_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSpecialInstructions>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SpecialInstructions), input_name='SpecialInstructions')), namespaceprefix_ , eol_)) - if self.ConfirmationNumber is not None: - namespaceprefix_ = self.ConfirmationNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.ConfirmationNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sConfirmationNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ConfirmationNumber), input_name='ConfirmationNumber')), namespaceprefix_ , eol_)) - if self.DayOfWeek is not None: - namespaceprefix_ = self.DayOfWeek_nsprefix_ + ':' if (UseCapturedNS_ and self.DayOfWeek_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDayOfWeek>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.DayOfWeek), input_name='DayOfWeek')), namespaceprefix_ , eol_)) - if self.Date is not None: - namespaceprefix_ = self.Date_nsprefix_ + ':' if (UseCapturedNS_ and self.Date_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDate>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Date), input_name='Date')), namespaceprefix_ , eol_)) - if self.EmailAddress is not None: - namespaceprefix_ = self.EmailAddress_nsprefix_ + ':' if (UseCapturedNS_ and self.EmailAddress_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEmailAddress>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.EmailAddress), input_name='EmailAddress')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'FirstName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FirstName') - value_ = self.gds_validate_string(value_, node, 'FirstName') - self.FirstName = value_ - self.FirstName_nsprefix_ = child_.prefix - elif nodeName_ == 'LastName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'LastName') - value_ = self.gds_validate_string(value_, node, 'LastName') - self.LastName = value_ - self.LastName_nsprefix_ = child_.prefix - elif nodeName_ == 'FirmName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FirmName') - value_ = self.gds_validate_string(value_, node, 'FirmName') - self.FirmName = value_ - self.FirmName_nsprefix_ = child_.prefix - elif nodeName_ == 'SuiteOrApt': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SuiteOrApt') - value_ = self.gds_validate_string(value_, node, 'SuiteOrApt') - self.SuiteOrApt = value_ - self.SuiteOrApt_nsprefix_ = child_.prefix - elif nodeName_ == 'Address2': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Address2') - value_ = self.gds_validate_string(value_, node, 'Address2') - self.Address2 = value_ - self.Address2_nsprefix_ = child_.prefix - elif nodeName_ == 'Urbanization': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Urbanization') - value_ = self.gds_validate_string(value_, node, 'Urbanization') - self.Urbanization = value_ - self.Urbanization_nsprefix_ = child_.prefix - elif nodeName_ == 'City': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'City') - value_ = self.gds_validate_string(value_, node, 'City') - self.City = value_ - self.City_nsprefix_ = child_.prefix - elif nodeName_ == 'State': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'State') - value_ = self.gds_validate_string(value_, node, 'State') - self.State = value_ - self.State_nsprefix_ = child_.prefix - elif nodeName_ == 'ZIP5': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ZIP5') - value_ = self.gds_validate_string(value_, node, 'ZIP5') - self.ZIP5 = value_ - self.ZIP5_nsprefix_ = child_.prefix - elif nodeName_ == 'ZIP4': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ZIP4') - value_ = self.gds_validate_string(value_, node, 'ZIP4') - self.ZIP4 = value_ - self.ZIP4_nsprefix_ = child_.prefix - elif nodeName_ == 'Phone': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Phone') - value_ = self.gds_validate_string(value_, node, 'Phone') - self.Phone = value_ - self.Phone_nsprefix_ = child_.prefix - elif nodeName_ == 'Extension': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Extension') - value_ = self.gds_validate_string(value_, node, 'Extension') - self.Extension = value_ - self.Extension_nsprefix_ = child_.prefix - elif nodeName_ == 'Package': - obj_ = PackageType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.Package.append(obj_) - obj_.original_tagname_ = 'Package' - elif nodeName_ == 'EstimatedWeight': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'EstimatedWeight') - value_ = self.gds_validate_string(value_, node, 'EstimatedWeight') - self.EstimatedWeight = value_ - self.EstimatedWeight_nsprefix_ = child_.prefix - elif nodeName_ == 'PackageLocation': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PackageLocation') - value_ = self.gds_validate_string(value_, node, 'PackageLocation') - self.PackageLocation = value_ - self.PackageLocation_nsprefix_ = child_.prefix - elif nodeName_ == 'SpecialInstructions': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SpecialInstructions') - value_ = self.gds_validate_string(value_, node, 'SpecialInstructions') - self.SpecialInstructions = value_ - self.SpecialInstructions_nsprefix_ = child_.prefix - elif nodeName_ == 'ConfirmationNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ConfirmationNumber') - value_ = self.gds_validate_string(value_, node, 'ConfirmationNumber') - self.ConfirmationNumber = value_ - self.ConfirmationNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'DayOfWeek': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'DayOfWeek') - value_ = self.gds_validate_string(value_, node, 'DayOfWeek') - self.DayOfWeek = value_ - self.DayOfWeek_nsprefix_ = child_.prefix - elif nodeName_ == 'Date': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Date') - value_ = self.gds_validate_string(value_, node, 'Date') - self.Date = value_ - self.Date_nsprefix_ = child_.prefix - elif nodeName_ == 'EmailAddress': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'EmailAddress') - value_ = self.gds_validate_string(value_, node, 'EmailAddress') - self.EmailAddress = value_ - self.EmailAddress_nsprefix_ = child_.prefix -# end class CarrierPickupInquiryResponse - - -class PackageType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ServiceType=None, Count=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.ServiceType = ServiceType - self.ServiceType_nsprefix_ = None - self.Count = Count - self.Count_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, PackageType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if PackageType.subclass: - return PackageType.subclass(*args_, **kwargs_) - else: - return PackageType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_ServiceType(self): - return self.ServiceType - def set_ServiceType(self, ServiceType): - self.ServiceType = ServiceType - def get_Count(self): - return self.Count - def set_Count(self, Count): - self.Count = Count - def _hasContent(self): - if ( - self.ServiceType is not None or - self.Count is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='PackageType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('PackageType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'PackageType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='PackageType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='PackageType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='PackageType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='PackageType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.ServiceType is not None: - namespaceprefix_ = self.ServiceType_nsprefix_ + ':' if (UseCapturedNS_ and self.ServiceType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sServiceType>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ServiceType), input_name='ServiceType')), namespaceprefix_ , eol_)) - if self.Count is not None: - namespaceprefix_ = self.Count_nsprefix_ + ':' if (UseCapturedNS_ and self.Count_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCount>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.Count, input_name='Count'), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'ServiceType': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ServiceType') - value_ = self.gds_validate_string(value_, node, 'ServiceType') - self.ServiceType = value_ - self.ServiceType_nsprefix_ = child_.prefix - elif nodeName_ == 'Count' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'Count') - ival_ = self.gds_validate_integer(ival_, node, 'Count') - self.Count = ival_ - self.Count_nsprefix_ = child_.prefix -# end class PackageType - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CarrierPickupInquiryResponse' - rootClass = CarrierPickupInquiryResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CarrierPickupInquiryResponse' - rootClass = CarrierPickupInquiryResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CarrierPickupInquiryResponse' - rootClass = CarrierPickupInquiryResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CarrierPickupInquiryResponse' - rootClass = CarrierPickupInquiryResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from carrier_pickup_inquiry_response import *\n\n') - sys.stdout.write('import carrier_pickup_inquiry_response as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "CarrierPickupInquiryResponse", - "PackageType" -] diff --git a/schemas/usps/karrio/schemas/usps/carrier_pickup_schedule_request.py b/schemas/usps/karrio/schemas/usps/carrier_pickup_schedule_request.py deleted file mode 100644 index 6995c453db..0000000000 --- a/schemas/usps/karrio/schemas/usps/carrier_pickup_schedule_request.py +++ /dev/null @@ -1,1703 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:05 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/carrier_pickup_schedule_request.py') -# -# Command line arguments: -# ./schemas/CarrierPickupScheduleRequest.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/carrier_pickup_schedule_request.py" ./schemas/CarrierPickupScheduleRequest.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class CarrierPickupScheduleRequest(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, USERID=None, FirstName=None, LastName=None, FirmName=None, SuiteOrApt=None, Address2=None, Urbanization=None, City=None, State=None, ZIP5=None, ZIP4=None, Phone=None, Extension=None, Package=None, EstimatedWeight=None, PackageLocation=None, SpecialInstructions=None, EmailAddress=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.USERID = _cast(None, USERID) - self.USERID_nsprefix_ = None - self.FirstName = FirstName - self.FirstName_nsprefix_ = None - self.LastName = LastName - self.LastName_nsprefix_ = None - self.FirmName = FirmName - self.FirmName_nsprefix_ = None - self.SuiteOrApt = SuiteOrApt - self.SuiteOrApt_nsprefix_ = None - self.Address2 = Address2 - self.Address2_nsprefix_ = None - self.Urbanization = Urbanization - self.Urbanization_nsprefix_ = None - self.City = City - self.City_nsprefix_ = None - self.State = State - self.State_nsprefix_ = None - self.ZIP5 = ZIP5 - self.ZIP5_nsprefix_ = None - self.ZIP4 = ZIP4 - self.ZIP4_nsprefix_ = None - self.Phone = Phone - self.Phone_nsprefix_ = None - self.Extension = Extension - self.Extension_nsprefix_ = None - if Package is None: - self.Package = [] - else: - self.Package = Package - self.Package_nsprefix_ = None - self.EstimatedWeight = EstimatedWeight - self.EstimatedWeight_nsprefix_ = None - self.PackageLocation = PackageLocation - self.PackageLocation_nsprefix_ = None - self.SpecialInstructions = SpecialInstructions - self.SpecialInstructions_nsprefix_ = None - self.EmailAddress = EmailAddress - self.EmailAddress_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, CarrierPickupScheduleRequest) - if subclass is not None: - return subclass(*args_, **kwargs_) - if CarrierPickupScheduleRequest.subclass: - return CarrierPickupScheduleRequest.subclass(*args_, **kwargs_) - else: - return CarrierPickupScheduleRequest(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_FirstName(self): - return self.FirstName - def set_FirstName(self, FirstName): - self.FirstName = FirstName - def get_LastName(self): - return self.LastName - def set_LastName(self, LastName): - self.LastName = LastName - def get_FirmName(self): - return self.FirmName - def set_FirmName(self, FirmName): - self.FirmName = FirmName - def get_SuiteOrApt(self): - return self.SuiteOrApt - def set_SuiteOrApt(self, SuiteOrApt): - self.SuiteOrApt = SuiteOrApt - def get_Address2(self): - return self.Address2 - def set_Address2(self, Address2): - self.Address2 = Address2 - def get_Urbanization(self): - return self.Urbanization - def set_Urbanization(self, Urbanization): - self.Urbanization = Urbanization - def get_City(self): - return self.City - def set_City(self, City): - self.City = City - def get_State(self): - return self.State - def set_State(self, State): - self.State = State - def get_ZIP5(self): - return self.ZIP5 - def set_ZIP5(self, ZIP5): - self.ZIP5 = ZIP5 - def get_ZIP4(self): - return self.ZIP4 - def set_ZIP4(self, ZIP4): - self.ZIP4 = ZIP4 - def get_Phone(self): - return self.Phone - def set_Phone(self, Phone): - self.Phone = Phone - def get_Extension(self): - return self.Extension - def set_Extension(self, Extension): - self.Extension = Extension - def get_Package(self): - return self.Package - def set_Package(self, Package): - self.Package = Package - def add_Package(self, value): - self.Package.append(value) - def insert_Package_at(self, index, value): - self.Package.insert(index, value) - def replace_Package_at(self, index, value): - self.Package[index] = value - def get_EstimatedWeight(self): - return self.EstimatedWeight - def set_EstimatedWeight(self, EstimatedWeight): - self.EstimatedWeight = EstimatedWeight - def get_PackageLocation(self): - return self.PackageLocation - def set_PackageLocation(self, PackageLocation): - self.PackageLocation = PackageLocation - def get_SpecialInstructions(self): - return self.SpecialInstructions - def set_SpecialInstructions(self, SpecialInstructions): - self.SpecialInstructions = SpecialInstructions - def get_EmailAddress(self): - return self.EmailAddress - def set_EmailAddress(self, EmailAddress): - self.EmailAddress = EmailAddress - def get_USERID(self): - return self.USERID - def set_USERID(self, USERID): - self.USERID = USERID - def _hasContent(self): - if ( - self.FirstName is not None or - self.LastName is not None or - self.FirmName is not None or - self.SuiteOrApt is not None or - self.Address2 is not None or - self.Urbanization is not None or - self.City is not None or - self.State is not None or - self.ZIP5 is not None or - self.ZIP4 is not None or - self.Phone is not None or - self.Extension is not None or - self.Package or - self.EstimatedWeight is not None or - self.PackageLocation is not None or - self.SpecialInstructions is not None or - self.EmailAddress is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='CarrierPickupScheduleRequest', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('CarrierPickupScheduleRequest') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'CarrierPickupScheduleRequest': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='CarrierPickupScheduleRequest') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='CarrierPickupScheduleRequest', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='CarrierPickupScheduleRequest'): - if self.USERID is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - outfile.write(' USERID=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.USERID), input_name='USERID')), )) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='CarrierPickupScheduleRequest', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.FirstName is not None: - namespaceprefix_ = self.FirstName_nsprefix_ + ':' if (UseCapturedNS_ and self.FirstName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFirstName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FirstName), input_name='FirstName')), namespaceprefix_ , eol_)) - if self.LastName is not None: - namespaceprefix_ = self.LastName_nsprefix_ + ':' if (UseCapturedNS_ and self.LastName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sLastName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.LastName), input_name='LastName')), namespaceprefix_ , eol_)) - if self.FirmName is not None: - namespaceprefix_ = self.FirmName_nsprefix_ + ':' if (UseCapturedNS_ and self.FirmName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFirmName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FirmName), input_name='FirmName')), namespaceprefix_ , eol_)) - if self.SuiteOrApt is not None: - namespaceprefix_ = self.SuiteOrApt_nsprefix_ + ':' if (UseCapturedNS_ and self.SuiteOrApt_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSuiteOrApt>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SuiteOrApt), input_name='SuiteOrApt')), namespaceprefix_ , eol_)) - if self.Address2 is not None: - namespaceprefix_ = self.Address2_nsprefix_ + ':' if (UseCapturedNS_ and self.Address2_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAddress2>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Address2), input_name='Address2')), namespaceprefix_ , eol_)) - if self.Urbanization is not None: - namespaceprefix_ = self.Urbanization_nsprefix_ + ':' if (UseCapturedNS_ and self.Urbanization_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sUrbanization>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Urbanization), input_name='Urbanization')), namespaceprefix_ , eol_)) - if self.City is not None: - namespaceprefix_ = self.City_nsprefix_ + ':' if (UseCapturedNS_ and self.City_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.City), input_name='City')), namespaceprefix_ , eol_)) - if self.State is not None: - namespaceprefix_ = self.State_nsprefix_ + ':' if (UseCapturedNS_ and self.State_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.State), input_name='State')), namespaceprefix_ , eol_)) - if self.ZIP5 is not None: - namespaceprefix_ = self.ZIP5_nsprefix_ + ':' if (UseCapturedNS_ and self.ZIP5_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sZIP5>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ZIP5), input_name='ZIP5')), namespaceprefix_ , eol_)) - if self.ZIP4 is not None: - namespaceprefix_ = self.ZIP4_nsprefix_ + ':' if (UseCapturedNS_ and self.ZIP4_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sZIP4>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ZIP4), input_name='ZIP4')), namespaceprefix_ , eol_)) - if self.Phone is not None: - namespaceprefix_ = self.Phone_nsprefix_ + ':' if (UseCapturedNS_ and self.Phone_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPhone>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Phone), input_name='Phone')), namespaceprefix_ , eol_)) - if self.Extension is not None: - namespaceprefix_ = self.Extension_nsprefix_ + ':' if (UseCapturedNS_ and self.Extension_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sExtension>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Extension), input_name='Extension')), namespaceprefix_ , eol_)) - for Package_ in self.Package: - namespaceprefix_ = self.Package_nsprefix_ + ':' if (UseCapturedNS_ and self.Package_nsprefix_) else '' - Package_.export(outfile, level, namespaceprefix_, namespacedef_='', name_='Package', pretty_print=pretty_print) - if self.EstimatedWeight is not None: - namespaceprefix_ = self.EstimatedWeight_nsprefix_ + ':' if (UseCapturedNS_ and self.EstimatedWeight_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEstimatedWeight>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.EstimatedWeight), input_name='EstimatedWeight')), namespaceprefix_ , eol_)) - if self.PackageLocation is not None: - namespaceprefix_ = self.PackageLocation_nsprefix_ + ':' if (UseCapturedNS_ and self.PackageLocation_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPackageLocation>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PackageLocation), input_name='PackageLocation')), namespaceprefix_ , eol_)) - if self.SpecialInstructions is not None: - namespaceprefix_ = self.SpecialInstructions_nsprefix_ + ':' if (UseCapturedNS_ and self.SpecialInstructions_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSpecialInstructions>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SpecialInstructions), input_name='SpecialInstructions')), namespaceprefix_ , eol_)) - if self.EmailAddress is not None: - namespaceprefix_ = self.EmailAddress_nsprefix_ + ':' if (UseCapturedNS_ and self.EmailAddress_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEmailAddress>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.EmailAddress), input_name='EmailAddress')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('USERID', node) - if value is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - self.USERID = value - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'FirstName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FirstName') - value_ = self.gds_validate_string(value_, node, 'FirstName') - self.FirstName = value_ - self.FirstName_nsprefix_ = child_.prefix - elif nodeName_ == 'LastName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'LastName') - value_ = self.gds_validate_string(value_, node, 'LastName') - self.LastName = value_ - self.LastName_nsprefix_ = child_.prefix - elif nodeName_ == 'FirmName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FirmName') - value_ = self.gds_validate_string(value_, node, 'FirmName') - self.FirmName = value_ - self.FirmName_nsprefix_ = child_.prefix - elif nodeName_ == 'SuiteOrApt': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SuiteOrApt') - value_ = self.gds_validate_string(value_, node, 'SuiteOrApt') - self.SuiteOrApt = value_ - self.SuiteOrApt_nsprefix_ = child_.prefix - elif nodeName_ == 'Address2': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Address2') - value_ = self.gds_validate_string(value_, node, 'Address2') - self.Address2 = value_ - self.Address2_nsprefix_ = child_.prefix - elif nodeName_ == 'Urbanization': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Urbanization') - value_ = self.gds_validate_string(value_, node, 'Urbanization') - self.Urbanization = value_ - self.Urbanization_nsprefix_ = child_.prefix - elif nodeName_ == 'City': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'City') - value_ = self.gds_validate_string(value_, node, 'City') - self.City = value_ - self.City_nsprefix_ = child_.prefix - elif nodeName_ == 'State': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'State') - value_ = self.gds_validate_string(value_, node, 'State') - self.State = value_ - self.State_nsprefix_ = child_.prefix - elif nodeName_ == 'ZIP5': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ZIP5') - value_ = self.gds_validate_string(value_, node, 'ZIP5') - self.ZIP5 = value_ - self.ZIP5_nsprefix_ = child_.prefix - elif nodeName_ == 'ZIP4': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ZIP4') - value_ = self.gds_validate_string(value_, node, 'ZIP4') - self.ZIP4 = value_ - self.ZIP4_nsprefix_ = child_.prefix - elif nodeName_ == 'Phone': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Phone') - value_ = self.gds_validate_string(value_, node, 'Phone') - self.Phone = value_ - self.Phone_nsprefix_ = child_.prefix - elif nodeName_ == 'Extension': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Extension') - value_ = self.gds_validate_string(value_, node, 'Extension') - self.Extension = value_ - self.Extension_nsprefix_ = child_.prefix - elif nodeName_ == 'Package': - obj_ = PackageType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.Package.append(obj_) - obj_.original_tagname_ = 'Package' - elif nodeName_ == 'EstimatedWeight': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'EstimatedWeight') - value_ = self.gds_validate_string(value_, node, 'EstimatedWeight') - self.EstimatedWeight = value_ - self.EstimatedWeight_nsprefix_ = child_.prefix - elif nodeName_ == 'PackageLocation': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PackageLocation') - value_ = self.gds_validate_string(value_, node, 'PackageLocation') - self.PackageLocation = value_ - self.PackageLocation_nsprefix_ = child_.prefix - elif nodeName_ == 'SpecialInstructions': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SpecialInstructions') - value_ = self.gds_validate_string(value_, node, 'SpecialInstructions') - self.SpecialInstructions = value_ - self.SpecialInstructions_nsprefix_ = child_.prefix - elif nodeName_ == 'EmailAddress': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'EmailAddress') - value_ = self.gds_validate_string(value_, node, 'EmailAddress') - self.EmailAddress = value_ - self.EmailAddress_nsprefix_ = child_.prefix -# end class CarrierPickupScheduleRequest - - -class PackageType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ServiceType=None, Count=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.ServiceType = ServiceType - self.ServiceType_nsprefix_ = None - self.Count = Count - self.Count_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, PackageType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if PackageType.subclass: - return PackageType.subclass(*args_, **kwargs_) - else: - return PackageType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_ServiceType(self): - return self.ServiceType - def set_ServiceType(self, ServiceType): - self.ServiceType = ServiceType - def get_Count(self): - return self.Count - def set_Count(self, Count): - self.Count = Count - def _hasContent(self): - if ( - self.ServiceType is not None or - self.Count is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='PackageType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('PackageType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'PackageType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='PackageType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='PackageType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='PackageType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='PackageType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.ServiceType is not None: - namespaceprefix_ = self.ServiceType_nsprefix_ + ':' if (UseCapturedNS_ and self.ServiceType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sServiceType>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ServiceType), input_name='ServiceType')), namespaceprefix_ , eol_)) - if self.Count is not None: - namespaceprefix_ = self.Count_nsprefix_ + ':' if (UseCapturedNS_ and self.Count_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCount>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.Count, input_name='Count'), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'ServiceType': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ServiceType') - value_ = self.gds_validate_string(value_, node, 'ServiceType') - self.ServiceType = value_ - self.ServiceType_nsprefix_ = child_.prefix - elif nodeName_ == 'Count' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'Count') - ival_ = self.gds_validate_integer(ival_, node, 'Count') - self.Count = ival_ - self.Count_nsprefix_ = child_.prefix -# end class PackageType - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CarrierPickupScheduleRequest' - rootClass = CarrierPickupScheduleRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CarrierPickupScheduleRequest' - rootClass = CarrierPickupScheduleRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CarrierPickupScheduleRequest' - rootClass = CarrierPickupScheduleRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CarrierPickupScheduleRequest' - rootClass = CarrierPickupScheduleRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from carrier_pickup_schedule_request import *\n\n') - sys.stdout.write('import carrier_pickup_schedule_request as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "CarrierPickupScheduleRequest", - "PackageType" -] diff --git a/schemas/usps/karrio/schemas/usps/carrier_pickup_schedule_response.py b/schemas/usps/karrio/schemas/usps/carrier_pickup_schedule_response.py deleted file mode 100644 index b5930e80d3..0000000000 --- a/schemas/usps/karrio/schemas/usps/carrier_pickup_schedule_response.py +++ /dev/null @@ -1,1743 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:06 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/carrier_pickup_schedule_response.py') -# -# Command line arguments: -# ./schemas/CarrierPickupScheduleResponse.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/carrier_pickup_schedule_response.py" ./schemas/CarrierPickupScheduleResponse.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class CarrierPickupScheduleResponse(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, FirstName=None, LastName=None, FirmName=None, SuiteOrApt=None, Address2=None, Urbanization=None, City=None, State=None, ZIP5=None, ZIP4=None, Phone=None, Extension=None, Package=None, EstimatedWeight=None, PackageLocation=None, SpecialInstructions=None, ConfirmationNumber=None, DayOfWeek=None, Date=None, CarrierRoute=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.FirstName = FirstName - self.FirstName_nsprefix_ = None - self.LastName = LastName - self.LastName_nsprefix_ = None - self.FirmName = FirmName - self.FirmName_nsprefix_ = None - self.SuiteOrApt = SuiteOrApt - self.SuiteOrApt_nsprefix_ = None - self.Address2 = Address2 - self.Address2_nsprefix_ = None - self.Urbanization = Urbanization - self.Urbanization_nsprefix_ = None - self.City = City - self.City_nsprefix_ = None - self.State = State - self.State_nsprefix_ = None - self.ZIP5 = ZIP5 - self.ZIP5_nsprefix_ = None - self.ZIP4 = ZIP4 - self.ZIP4_nsprefix_ = None - self.Phone = Phone - self.Phone_nsprefix_ = None - self.Extension = Extension - self.Extension_nsprefix_ = None - if Package is None: - self.Package = [] - else: - self.Package = Package - self.Package_nsprefix_ = None - self.EstimatedWeight = EstimatedWeight - self.EstimatedWeight_nsprefix_ = None - self.PackageLocation = PackageLocation - self.PackageLocation_nsprefix_ = None - self.SpecialInstructions = SpecialInstructions - self.SpecialInstructions_nsprefix_ = None - self.ConfirmationNumber = ConfirmationNumber - self.ConfirmationNumber_nsprefix_ = None - self.DayOfWeek = DayOfWeek - self.DayOfWeek_nsprefix_ = None - self.Date = Date - self.Date_nsprefix_ = None - self.CarrierRoute = CarrierRoute - self.CarrierRoute_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, CarrierPickupScheduleResponse) - if subclass is not None: - return subclass(*args_, **kwargs_) - if CarrierPickupScheduleResponse.subclass: - return CarrierPickupScheduleResponse.subclass(*args_, **kwargs_) - else: - return CarrierPickupScheduleResponse(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_FirstName(self): - return self.FirstName - def set_FirstName(self, FirstName): - self.FirstName = FirstName - def get_LastName(self): - return self.LastName - def set_LastName(self, LastName): - self.LastName = LastName - def get_FirmName(self): - return self.FirmName - def set_FirmName(self, FirmName): - self.FirmName = FirmName - def get_SuiteOrApt(self): - return self.SuiteOrApt - def set_SuiteOrApt(self, SuiteOrApt): - self.SuiteOrApt = SuiteOrApt - def get_Address2(self): - return self.Address2 - def set_Address2(self, Address2): - self.Address2 = Address2 - def get_Urbanization(self): - return self.Urbanization - def set_Urbanization(self, Urbanization): - self.Urbanization = Urbanization - def get_City(self): - return self.City - def set_City(self, City): - self.City = City - def get_State(self): - return self.State - def set_State(self, State): - self.State = State - def get_ZIP5(self): - return self.ZIP5 - def set_ZIP5(self, ZIP5): - self.ZIP5 = ZIP5 - def get_ZIP4(self): - return self.ZIP4 - def set_ZIP4(self, ZIP4): - self.ZIP4 = ZIP4 - def get_Phone(self): - return self.Phone - def set_Phone(self, Phone): - self.Phone = Phone - def get_Extension(self): - return self.Extension - def set_Extension(self, Extension): - self.Extension = Extension - def get_Package(self): - return self.Package - def set_Package(self, Package): - self.Package = Package - def add_Package(self, value): - self.Package.append(value) - def insert_Package_at(self, index, value): - self.Package.insert(index, value) - def replace_Package_at(self, index, value): - self.Package[index] = value - def get_EstimatedWeight(self): - return self.EstimatedWeight - def set_EstimatedWeight(self, EstimatedWeight): - self.EstimatedWeight = EstimatedWeight - def get_PackageLocation(self): - return self.PackageLocation - def set_PackageLocation(self, PackageLocation): - self.PackageLocation = PackageLocation - def get_SpecialInstructions(self): - return self.SpecialInstructions - def set_SpecialInstructions(self, SpecialInstructions): - self.SpecialInstructions = SpecialInstructions - def get_ConfirmationNumber(self): - return self.ConfirmationNumber - def set_ConfirmationNumber(self, ConfirmationNumber): - self.ConfirmationNumber = ConfirmationNumber - def get_DayOfWeek(self): - return self.DayOfWeek - def set_DayOfWeek(self, DayOfWeek): - self.DayOfWeek = DayOfWeek - def get_Date(self): - return self.Date - def set_Date(self, Date): - self.Date = Date - def get_CarrierRoute(self): - return self.CarrierRoute - def set_CarrierRoute(self, CarrierRoute): - self.CarrierRoute = CarrierRoute - def _hasContent(self): - if ( - self.FirstName is not None or - self.LastName is not None or - self.FirmName is not None or - self.SuiteOrApt is not None or - self.Address2 is not None or - self.Urbanization is not None or - self.City is not None or - self.State is not None or - self.ZIP5 is not None or - self.ZIP4 is not None or - self.Phone is not None or - self.Extension is not None or - self.Package or - self.EstimatedWeight is not None or - self.PackageLocation is not None or - self.SpecialInstructions is not None or - self.ConfirmationNumber is not None or - self.DayOfWeek is not None or - self.Date is not None or - self.CarrierRoute is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='CarrierPickupScheduleResponse', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('CarrierPickupScheduleResponse') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'CarrierPickupScheduleResponse': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='CarrierPickupScheduleResponse') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='CarrierPickupScheduleResponse', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='CarrierPickupScheduleResponse'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='CarrierPickupScheduleResponse', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.FirstName is not None: - namespaceprefix_ = self.FirstName_nsprefix_ + ':' if (UseCapturedNS_ and self.FirstName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFirstName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FirstName), input_name='FirstName')), namespaceprefix_ , eol_)) - if self.LastName is not None: - namespaceprefix_ = self.LastName_nsprefix_ + ':' if (UseCapturedNS_ and self.LastName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sLastName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.LastName), input_name='LastName')), namespaceprefix_ , eol_)) - if self.FirmName is not None: - namespaceprefix_ = self.FirmName_nsprefix_ + ':' if (UseCapturedNS_ and self.FirmName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFirmName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FirmName), input_name='FirmName')), namespaceprefix_ , eol_)) - if self.SuiteOrApt is not None: - namespaceprefix_ = self.SuiteOrApt_nsprefix_ + ':' if (UseCapturedNS_ and self.SuiteOrApt_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSuiteOrApt>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SuiteOrApt), input_name='SuiteOrApt')), namespaceprefix_ , eol_)) - if self.Address2 is not None: - namespaceprefix_ = self.Address2_nsprefix_ + ':' if (UseCapturedNS_ and self.Address2_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAddress2>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Address2), input_name='Address2')), namespaceprefix_ , eol_)) - if self.Urbanization is not None: - namespaceprefix_ = self.Urbanization_nsprefix_ + ':' if (UseCapturedNS_ and self.Urbanization_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sUrbanization>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Urbanization), input_name='Urbanization')), namespaceprefix_ , eol_)) - if self.City is not None: - namespaceprefix_ = self.City_nsprefix_ + ':' if (UseCapturedNS_ and self.City_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.City), input_name='City')), namespaceprefix_ , eol_)) - if self.State is not None: - namespaceprefix_ = self.State_nsprefix_ + ':' if (UseCapturedNS_ and self.State_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.State), input_name='State')), namespaceprefix_ , eol_)) - if self.ZIP5 is not None: - namespaceprefix_ = self.ZIP5_nsprefix_ + ':' if (UseCapturedNS_ and self.ZIP5_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sZIP5>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ZIP5), input_name='ZIP5')), namespaceprefix_ , eol_)) - if self.ZIP4 is not None: - namespaceprefix_ = self.ZIP4_nsprefix_ + ':' if (UseCapturedNS_ and self.ZIP4_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sZIP4>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ZIP4), input_name='ZIP4')), namespaceprefix_ , eol_)) - if self.Phone is not None: - namespaceprefix_ = self.Phone_nsprefix_ + ':' if (UseCapturedNS_ and self.Phone_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPhone>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Phone), input_name='Phone')), namespaceprefix_ , eol_)) - if self.Extension is not None: - namespaceprefix_ = self.Extension_nsprefix_ + ':' if (UseCapturedNS_ and self.Extension_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sExtension>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Extension), input_name='Extension')), namespaceprefix_ , eol_)) - for Package_ in self.Package: - namespaceprefix_ = self.Package_nsprefix_ + ':' if (UseCapturedNS_ and self.Package_nsprefix_) else '' - Package_.export(outfile, level, namespaceprefix_, namespacedef_='', name_='Package', pretty_print=pretty_print) - if self.EstimatedWeight is not None: - namespaceprefix_ = self.EstimatedWeight_nsprefix_ + ':' if (UseCapturedNS_ and self.EstimatedWeight_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEstimatedWeight>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.EstimatedWeight), input_name='EstimatedWeight')), namespaceprefix_ , eol_)) - if self.PackageLocation is not None: - namespaceprefix_ = self.PackageLocation_nsprefix_ + ':' if (UseCapturedNS_ and self.PackageLocation_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPackageLocation>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PackageLocation), input_name='PackageLocation')), namespaceprefix_ , eol_)) - if self.SpecialInstructions is not None: - namespaceprefix_ = self.SpecialInstructions_nsprefix_ + ':' if (UseCapturedNS_ and self.SpecialInstructions_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSpecialInstructions>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SpecialInstructions), input_name='SpecialInstructions')), namespaceprefix_ , eol_)) - if self.ConfirmationNumber is not None: - namespaceprefix_ = self.ConfirmationNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.ConfirmationNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sConfirmationNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ConfirmationNumber), input_name='ConfirmationNumber')), namespaceprefix_ , eol_)) - if self.DayOfWeek is not None: - namespaceprefix_ = self.DayOfWeek_nsprefix_ + ':' if (UseCapturedNS_ and self.DayOfWeek_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDayOfWeek>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.DayOfWeek), input_name='DayOfWeek')), namespaceprefix_ , eol_)) - if self.Date is not None: - namespaceprefix_ = self.Date_nsprefix_ + ':' if (UseCapturedNS_ and self.Date_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDate>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Date), input_name='Date')), namespaceprefix_ , eol_)) - if self.CarrierRoute is not None: - namespaceprefix_ = self.CarrierRoute_nsprefix_ + ':' if (UseCapturedNS_ and self.CarrierRoute_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCarrierRoute>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CarrierRoute), input_name='CarrierRoute')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'FirstName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FirstName') - value_ = self.gds_validate_string(value_, node, 'FirstName') - self.FirstName = value_ - self.FirstName_nsprefix_ = child_.prefix - elif nodeName_ == 'LastName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'LastName') - value_ = self.gds_validate_string(value_, node, 'LastName') - self.LastName = value_ - self.LastName_nsprefix_ = child_.prefix - elif nodeName_ == 'FirmName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FirmName') - value_ = self.gds_validate_string(value_, node, 'FirmName') - self.FirmName = value_ - self.FirmName_nsprefix_ = child_.prefix - elif nodeName_ == 'SuiteOrApt': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SuiteOrApt') - value_ = self.gds_validate_string(value_, node, 'SuiteOrApt') - self.SuiteOrApt = value_ - self.SuiteOrApt_nsprefix_ = child_.prefix - elif nodeName_ == 'Address2': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Address2') - value_ = self.gds_validate_string(value_, node, 'Address2') - self.Address2 = value_ - self.Address2_nsprefix_ = child_.prefix - elif nodeName_ == 'Urbanization': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Urbanization') - value_ = self.gds_validate_string(value_, node, 'Urbanization') - self.Urbanization = value_ - self.Urbanization_nsprefix_ = child_.prefix - elif nodeName_ == 'City': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'City') - value_ = self.gds_validate_string(value_, node, 'City') - self.City = value_ - self.City_nsprefix_ = child_.prefix - elif nodeName_ == 'State': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'State') - value_ = self.gds_validate_string(value_, node, 'State') - self.State = value_ - self.State_nsprefix_ = child_.prefix - elif nodeName_ == 'ZIP5': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ZIP5') - value_ = self.gds_validate_string(value_, node, 'ZIP5') - self.ZIP5 = value_ - self.ZIP5_nsprefix_ = child_.prefix - elif nodeName_ == 'ZIP4': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ZIP4') - value_ = self.gds_validate_string(value_, node, 'ZIP4') - self.ZIP4 = value_ - self.ZIP4_nsprefix_ = child_.prefix - elif nodeName_ == 'Phone': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Phone') - value_ = self.gds_validate_string(value_, node, 'Phone') - self.Phone = value_ - self.Phone_nsprefix_ = child_.prefix - elif nodeName_ == 'Extension': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Extension') - value_ = self.gds_validate_string(value_, node, 'Extension') - self.Extension = value_ - self.Extension_nsprefix_ = child_.prefix - elif nodeName_ == 'Package': - obj_ = PackageType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.Package.append(obj_) - obj_.original_tagname_ = 'Package' - elif nodeName_ == 'EstimatedWeight': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'EstimatedWeight') - value_ = self.gds_validate_string(value_, node, 'EstimatedWeight') - self.EstimatedWeight = value_ - self.EstimatedWeight_nsprefix_ = child_.prefix - elif nodeName_ == 'PackageLocation': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PackageLocation') - value_ = self.gds_validate_string(value_, node, 'PackageLocation') - self.PackageLocation = value_ - self.PackageLocation_nsprefix_ = child_.prefix - elif nodeName_ == 'SpecialInstructions': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SpecialInstructions') - value_ = self.gds_validate_string(value_, node, 'SpecialInstructions') - self.SpecialInstructions = value_ - self.SpecialInstructions_nsprefix_ = child_.prefix - elif nodeName_ == 'ConfirmationNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ConfirmationNumber') - value_ = self.gds_validate_string(value_, node, 'ConfirmationNumber') - self.ConfirmationNumber = value_ - self.ConfirmationNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'DayOfWeek': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'DayOfWeek') - value_ = self.gds_validate_string(value_, node, 'DayOfWeek') - self.DayOfWeek = value_ - self.DayOfWeek_nsprefix_ = child_.prefix - elif nodeName_ == 'Date': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Date') - value_ = self.gds_validate_string(value_, node, 'Date') - self.Date = value_ - self.Date_nsprefix_ = child_.prefix - elif nodeName_ == 'CarrierRoute': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CarrierRoute') - value_ = self.gds_validate_string(value_, node, 'CarrierRoute') - self.CarrierRoute = value_ - self.CarrierRoute_nsprefix_ = child_.prefix -# end class CarrierPickupScheduleResponse - - -class PackageType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ServiceType=None, Count=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.ServiceType = ServiceType - self.ServiceType_nsprefix_ = None - self.Count = Count - self.Count_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, PackageType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if PackageType.subclass: - return PackageType.subclass(*args_, **kwargs_) - else: - return PackageType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_ServiceType(self): - return self.ServiceType - def set_ServiceType(self, ServiceType): - self.ServiceType = ServiceType - def get_Count(self): - return self.Count - def set_Count(self, Count): - self.Count = Count - def _hasContent(self): - if ( - self.ServiceType is not None or - self.Count is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='PackageType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('PackageType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'PackageType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='PackageType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='PackageType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='PackageType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='PackageType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.ServiceType is not None: - namespaceprefix_ = self.ServiceType_nsprefix_ + ':' if (UseCapturedNS_ and self.ServiceType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sServiceType>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ServiceType), input_name='ServiceType')), namespaceprefix_ , eol_)) - if self.Count is not None: - namespaceprefix_ = self.Count_nsprefix_ + ':' if (UseCapturedNS_ and self.Count_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCount>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.Count, input_name='Count'), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'ServiceType': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ServiceType') - value_ = self.gds_validate_string(value_, node, 'ServiceType') - self.ServiceType = value_ - self.ServiceType_nsprefix_ = child_.prefix - elif nodeName_ == 'Count' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'Count') - ival_ = self.gds_validate_integer(ival_, node, 'Count') - self.Count = ival_ - self.Count_nsprefix_ = child_.prefix -# end class PackageType - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CarrierPickupScheduleResponse' - rootClass = CarrierPickupScheduleResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CarrierPickupScheduleResponse' - rootClass = CarrierPickupScheduleResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CarrierPickupScheduleResponse' - rootClass = CarrierPickupScheduleResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CarrierPickupScheduleResponse' - rootClass = CarrierPickupScheduleResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from carrier_pickup_schedule_response import *\n\n') - sys.stdout.write('import carrier_pickup_schedule_response as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "CarrierPickupScheduleResponse", - "PackageType" -] diff --git a/schemas/usps/karrio/schemas/usps/city_state_lookup_request.py b/schemas/usps/karrio/schemas/usps/city_state_lookup_request.py deleted file mode 100644 index ed874eed02..0000000000 --- a/schemas/usps/karrio/schemas/usps/city_state_lookup_request.py +++ /dev/null @@ -1,1416 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:06 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/city_state_lookup_request.py') -# -# Command line arguments: -# ./schemas/CityStateLookupRequest.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/city_state_lookup_request.py" ./schemas/CityStateLookupRequest.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class CityStateLookupRequest(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, USERID=None, ZipCode=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.USERID = _cast(None, USERID) - self.USERID_nsprefix_ = None - self.ZipCode = ZipCode - self.ZipCode_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, CityStateLookupRequest) - if subclass is not None: - return subclass(*args_, **kwargs_) - if CityStateLookupRequest.subclass: - return CityStateLookupRequest.subclass(*args_, **kwargs_) - else: - return CityStateLookupRequest(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_ZipCode(self): - return self.ZipCode - def set_ZipCode(self, ZipCode): - self.ZipCode = ZipCode - def get_USERID(self): - return self.USERID - def set_USERID(self, USERID): - self.USERID = USERID - def _hasContent(self): - if ( - self.ZipCode is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='CityStateLookupRequest', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('CityStateLookupRequest') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'CityStateLookupRequest': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='CityStateLookupRequest') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='CityStateLookupRequest', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='CityStateLookupRequest'): - if self.USERID is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - outfile.write(' USERID=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.USERID), input_name='USERID')), )) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='CityStateLookupRequest', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.ZipCode is not None: - namespaceprefix_ = self.ZipCode_nsprefix_ + ':' if (UseCapturedNS_ and self.ZipCode_nsprefix_) else '' - self.ZipCode.export(outfile, level, namespaceprefix_, namespacedef_='', name_='ZipCode', pretty_print=pretty_print) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('USERID', node) - if value is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - self.USERID = value - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'ZipCode': - obj_ = ZipCodeType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.ZipCode = obj_ - obj_.original_tagname_ = 'ZipCode' -# end class CityStateLookupRequest - - -class ZipCodeType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ID=None, Zip5=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.ID = _cast(int, ID) - self.ID_nsprefix_ = None - self.Zip5 = Zip5 - self.Zip5_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, ZipCodeType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if ZipCodeType.subclass: - return ZipCodeType.subclass(*args_, **kwargs_) - else: - return ZipCodeType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_Zip5(self): - return self.Zip5 - def set_Zip5(self, Zip5): - self.Zip5 = Zip5 - def get_ID(self): - return self.ID - def set_ID(self, ID): - self.ID = ID - def _hasContent(self): - if ( - self.Zip5 is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ZipCodeType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('ZipCodeType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'ZipCodeType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='ZipCodeType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='ZipCodeType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='ZipCodeType'): - if self.ID is not None and 'ID' not in already_processed: - already_processed.add('ID') - outfile.write(' ID="%s"' % self.gds_format_integer(self.ID, input_name='ID')) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ZipCodeType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.Zip5 is not None: - namespaceprefix_ = self.Zip5_nsprefix_ + ':' if (UseCapturedNS_ and self.Zip5_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sZip5>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.Zip5, input_name='Zip5'), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('ID', node) - if value is not None and 'ID' not in already_processed: - already_processed.add('ID') - self.ID = self.gds_parse_integer(value, node, 'ID') - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'Zip5' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'Zip5') - ival_ = self.gds_validate_integer(ival_, node, 'Zip5') - self.Zip5 = ival_ - self.Zip5_nsprefix_ = child_.prefix -# end class ZipCodeType - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CityStateLookupRequest' - rootClass = CityStateLookupRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CityStateLookupRequest' - rootClass = CityStateLookupRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CityStateLookupRequest' - rootClass = CityStateLookupRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CityStateLookupRequest' - rootClass = CityStateLookupRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from city_state_lookup_request import *\n\n') - sys.stdout.write('import city_state_lookup_request as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "CityStateLookupRequest", - "ZipCodeType" -] diff --git a/schemas/usps/karrio/schemas/usps/city_state_lookup_response.py b/schemas/usps/karrio/schemas/usps/city_state_lookup_response.py deleted file mode 100644 index 02d952f841..0000000000 --- a/schemas/usps/karrio/schemas/usps/city_state_lookup_response.py +++ /dev/null @@ -1,1448 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:06 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/city_state_lookup_response.py') -# -# Command line arguments: -# ./schemas/CityStateLookupResponse.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/city_state_lookup_response.py" ./schemas/CityStateLookupResponse.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class CityStateLookupResponse(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ZipCode=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - if ZipCode is None: - self.ZipCode = [] - else: - self.ZipCode = ZipCode - self.ZipCode_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, CityStateLookupResponse) - if subclass is not None: - return subclass(*args_, **kwargs_) - if CityStateLookupResponse.subclass: - return CityStateLookupResponse.subclass(*args_, **kwargs_) - else: - return CityStateLookupResponse(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_ZipCode(self): - return self.ZipCode - def set_ZipCode(self, ZipCode): - self.ZipCode = ZipCode - def add_ZipCode(self, value): - self.ZipCode.append(value) - def insert_ZipCode_at(self, index, value): - self.ZipCode.insert(index, value) - def replace_ZipCode_at(self, index, value): - self.ZipCode[index] = value - def _hasContent(self): - if ( - self.ZipCode - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='CityStateLookupResponse', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('CityStateLookupResponse') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'CityStateLookupResponse': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='CityStateLookupResponse') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='CityStateLookupResponse', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='CityStateLookupResponse'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='CityStateLookupResponse', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - for ZipCode_ in self.ZipCode: - namespaceprefix_ = self.ZipCode_nsprefix_ + ':' if (UseCapturedNS_ and self.ZipCode_nsprefix_) else '' - ZipCode_.export(outfile, level, namespaceprefix_, namespacedef_='', name_='ZipCode', pretty_print=pretty_print) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'ZipCode': - obj_ = ZipCodeType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.ZipCode.append(obj_) - obj_.original_tagname_ = 'ZipCode' -# end class CityStateLookupResponse - - -class ZipCodeType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ID=None, Zip5=None, City=None, State=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.ID = _cast(int, ID) - self.ID_nsprefix_ = None - self.Zip5 = Zip5 - self.Zip5_nsprefix_ = None - self.City = City - self.City_nsprefix_ = None - self.State = State - self.State_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, ZipCodeType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if ZipCodeType.subclass: - return ZipCodeType.subclass(*args_, **kwargs_) - else: - return ZipCodeType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_Zip5(self): - return self.Zip5 - def set_Zip5(self, Zip5): - self.Zip5 = Zip5 - def get_City(self): - return self.City - def set_City(self, City): - self.City = City - def get_State(self): - return self.State - def set_State(self, State): - self.State = State - def get_ID(self): - return self.ID - def set_ID(self, ID): - self.ID = ID - def _hasContent(self): - if ( - self.Zip5 is not None or - self.City is not None or - self.State is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ZipCodeType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('ZipCodeType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'ZipCodeType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='ZipCodeType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='ZipCodeType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='ZipCodeType'): - if self.ID is not None and 'ID' not in already_processed: - already_processed.add('ID') - outfile.write(' ID="%s"' % self.gds_format_integer(self.ID, input_name='ID')) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ZipCodeType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.Zip5 is not None: - namespaceprefix_ = self.Zip5_nsprefix_ + ':' if (UseCapturedNS_ and self.Zip5_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sZip5>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.Zip5, input_name='Zip5'), namespaceprefix_ , eol_)) - if self.City is not None: - namespaceprefix_ = self.City_nsprefix_ + ':' if (UseCapturedNS_ and self.City_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.City), input_name='City')), namespaceprefix_ , eol_)) - if self.State is not None: - namespaceprefix_ = self.State_nsprefix_ + ':' if (UseCapturedNS_ and self.State_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.State), input_name='State')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('ID', node) - if value is not None and 'ID' not in already_processed: - already_processed.add('ID') - self.ID = self.gds_parse_integer(value, node, 'ID') - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'Zip5' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'Zip5') - ival_ = self.gds_validate_integer(ival_, node, 'Zip5') - self.Zip5 = ival_ - self.Zip5_nsprefix_ = child_.prefix - elif nodeName_ == 'City': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'City') - value_ = self.gds_validate_string(value_, node, 'City') - self.City = value_ - self.City_nsprefix_ = child_.prefix - elif nodeName_ == 'State': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'State') - value_ = self.gds_validate_string(value_, node, 'State') - self.State = value_ - self.State_nsprefix_ = child_.prefix -# end class ZipCodeType - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CityStateLookupResponse' - rootClass = CityStateLookupResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CityStateLookupResponse' - rootClass = CityStateLookupResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CityStateLookupResponse' - rootClass = CityStateLookupResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'CityStateLookupResponse' - rootClass = CityStateLookupResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from city_state_lookup_response import *\n\n') - sys.stdout.write('import city_state_lookup_response as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "CityStateLookupResponse", - "ZipCodeType" -] diff --git a/schemas/usps/karrio/schemas/usps/emrsv4_0_bulk_request.py b/schemas/usps/karrio/schemas/usps/emrsv4_0_bulk_request.py deleted file mode 100644 index 67ab43fe0e..0000000000 --- a/schemas/usps/karrio/schemas/usps/emrsv4_0_bulk_request.py +++ /dev/null @@ -1,1822 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:06 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/emrsv4_0_bulk_request.py') -# -# Command line arguments: -# ./schemas/EMRSV4.0BulkRequest.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/emrsv4_0_bulk_request.py" ./schemas/EMRSV4.0BulkRequest.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class EMRSV4_0BulkRequest(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, USERID=None, Option=None, LabelCount=None, ImageParameters=None, RetailerName=None, RetailerAddress=None, PermitNumber=None, PermitIssuingPOCity=None, PermitIssuingPOState=None, PermitIssuingPOZip5=None, PDUFirmName=None, PDUPOBox=None, PDUCity=None, PDUState=None, PDUZip5=None, PDUZip4=None, ServiceType=None, DeliveryConfirmation=None, InsuranceValue=None, MailingAckPackageID=None, WeightInPounds=None, WeightInOunces=None, RMA=None, RMAPICFlag=None, ImageType=None, RMABarcode=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.USERID = _cast(None, USERID) - self.USERID_nsprefix_ = None - self.Option = Option - self.Option_nsprefix_ = None - self.LabelCount = LabelCount - self.LabelCount_nsprefix_ = None - self.ImageParameters = ImageParameters - self.ImageParameters_nsprefix_ = None - self.RetailerName = RetailerName - self.RetailerName_nsprefix_ = None - self.RetailerAddress = RetailerAddress - self.RetailerAddress_nsprefix_ = None - self.PermitNumber = PermitNumber - self.PermitNumber_nsprefix_ = None - self.PermitIssuingPOCity = PermitIssuingPOCity - self.PermitIssuingPOCity_nsprefix_ = None - self.PermitIssuingPOState = PermitIssuingPOState - self.PermitIssuingPOState_nsprefix_ = None - self.PermitIssuingPOZip5 = PermitIssuingPOZip5 - self.PermitIssuingPOZip5_nsprefix_ = None - self.PDUFirmName = PDUFirmName - self.PDUFirmName_nsprefix_ = None - self.PDUPOBox = PDUPOBox - self.PDUPOBox_nsprefix_ = None - self.PDUCity = PDUCity - self.PDUCity_nsprefix_ = None - self.PDUState = PDUState - self.PDUState_nsprefix_ = None - self.PDUZip5 = PDUZip5 - self.PDUZip5_nsprefix_ = None - self.PDUZip4 = PDUZip4 - self.PDUZip4_nsprefix_ = None - self.ServiceType = ServiceType - self.ServiceType_nsprefix_ = None - self.DeliveryConfirmation = DeliveryConfirmation - self.DeliveryConfirmation_nsprefix_ = None - self.InsuranceValue = InsuranceValue - self.InsuranceValue_nsprefix_ = None - self.MailingAckPackageID = MailingAckPackageID - self.MailingAckPackageID_nsprefix_ = None - self.WeightInPounds = WeightInPounds - self.WeightInPounds_nsprefix_ = None - self.WeightInOunces = WeightInOunces - self.WeightInOunces_nsprefix_ = None - self.RMA = RMA - self.RMA_nsprefix_ = None - self.RMAPICFlag = RMAPICFlag - self.RMAPICFlag_nsprefix_ = None - self.ImageType = ImageType - self.ImageType_nsprefix_ = None - self.RMABarcode = RMABarcode - self.RMABarcode_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, EMRSV4_0BulkRequest) - if subclass is not None: - return subclass(*args_, **kwargs_) - if EMRSV4_0BulkRequest.subclass: - return EMRSV4_0BulkRequest.subclass(*args_, **kwargs_) - else: - return EMRSV4_0BulkRequest(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_Option(self): - return self.Option - def set_Option(self, Option): - self.Option = Option - def get_LabelCount(self): - return self.LabelCount - def set_LabelCount(self, LabelCount): - self.LabelCount = LabelCount - def get_ImageParameters(self): - return self.ImageParameters - def set_ImageParameters(self, ImageParameters): - self.ImageParameters = ImageParameters - def get_RetailerName(self): - return self.RetailerName - def set_RetailerName(self, RetailerName): - self.RetailerName = RetailerName - def get_RetailerAddress(self): - return self.RetailerAddress - def set_RetailerAddress(self, RetailerAddress): - self.RetailerAddress = RetailerAddress - def get_PermitNumber(self): - return self.PermitNumber - def set_PermitNumber(self, PermitNumber): - self.PermitNumber = PermitNumber - def get_PermitIssuingPOCity(self): - return self.PermitIssuingPOCity - def set_PermitIssuingPOCity(self, PermitIssuingPOCity): - self.PermitIssuingPOCity = PermitIssuingPOCity - def get_PermitIssuingPOState(self): - return self.PermitIssuingPOState - def set_PermitIssuingPOState(self, PermitIssuingPOState): - self.PermitIssuingPOState = PermitIssuingPOState - def get_PermitIssuingPOZip5(self): - return self.PermitIssuingPOZip5 - def set_PermitIssuingPOZip5(self, PermitIssuingPOZip5): - self.PermitIssuingPOZip5 = PermitIssuingPOZip5 - def get_PDUFirmName(self): - return self.PDUFirmName - def set_PDUFirmName(self, PDUFirmName): - self.PDUFirmName = PDUFirmName - def get_PDUPOBox(self): - return self.PDUPOBox - def set_PDUPOBox(self, PDUPOBox): - self.PDUPOBox = PDUPOBox - def get_PDUCity(self): - return self.PDUCity - def set_PDUCity(self, PDUCity): - self.PDUCity = PDUCity - def get_PDUState(self): - return self.PDUState - def set_PDUState(self, PDUState): - self.PDUState = PDUState - def get_PDUZip5(self): - return self.PDUZip5 - def set_PDUZip5(self, PDUZip5): - self.PDUZip5 = PDUZip5 - def get_PDUZip4(self): - return self.PDUZip4 - def set_PDUZip4(self, PDUZip4): - self.PDUZip4 = PDUZip4 - def get_ServiceType(self): - return self.ServiceType - def set_ServiceType(self, ServiceType): - self.ServiceType = ServiceType - def get_DeliveryConfirmation(self): - return self.DeliveryConfirmation - def set_DeliveryConfirmation(self, DeliveryConfirmation): - self.DeliveryConfirmation = DeliveryConfirmation - def get_InsuranceValue(self): - return self.InsuranceValue - def set_InsuranceValue(self, InsuranceValue): - self.InsuranceValue = InsuranceValue - def get_MailingAckPackageID(self): - return self.MailingAckPackageID - def set_MailingAckPackageID(self, MailingAckPackageID): - self.MailingAckPackageID = MailingAckPackageID - def get_WeightInPounds(self): - return self.WeightInPounds - def set_WeightInPounds(self, WeightInPounds): - self.WeightInPounds = WeightInPounds - def get_WeightInOunces(self): - return self.WeightInOunces - def set_WeightInOunces(self, WeightInOunces): - self.WeightInOunces = WeightInOunces - def get_RMA(self): - return self.RMA - def set_RMA(self, RMA): - self.RMA = RMA - def get_RMAPICFlag(self): - return self.RMAPICFlag - def set_RMAPICFlag(self, RMAPICFlag): - self.RMAPICFlag = RMAPICFlag - def get_ImageType(self): - return self.ImageType - def set_ImageType(self, ImageType): - self.ImageType = ImageType - def get_RMABarcode(self): - return self.RMABarcode - def set_RMABarcode(self, RMABarcode): - self.RMABarcode = RMABarcode - def get_USERID(self): - return self.USERID - def set_USERID(self, USERID): - self.USERID = USERID - def _hasContent(self): - if ( - self.Option is not None or - self.LabelCount is not None or - self.ImageParameters is not None or - self.RetailerName is not None or - self.RetailerAddress is not None or - self.PermitNumber is not None or - self.PermitIssuingPOCity is not None or - self.PermitIssuingPOState is not None or - self.PermitIssuingPOZip5 is not None or - self.PDUFirmName is not None or - self.PDUPOBox is not None or - self.PDUCity is not None or - self.PDUState is not None or - self.PDUZip5 is not None or - self.PDUZip4 is not None or - self.ServiceType is not None or - self.DeliveryConfirmation is not None or - self.InsuranceValue is not None or - self.MailingAckPackageID is not None or - self.WeightInPounds is not None or - self.WeightInOunces is not None or - self.RMA is not None or - self.RMAPICFlag is not None or - self.ImageType is not None or - self.RMABarcode is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='EMRSV4.0BulkRequest', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('EMRSV4.0BulkRequest') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'EMRSV4.0BulkRequest': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='EMRSV4.0BulkRequest') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='EMRSV4.0BulkRequest', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='EMRSV4.0BulkRequest'): - if self.USERID is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - outfile.write(' USERID=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.USERID), input_name='USERID')), )) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='EMRSV4.0BulkRequest', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.Option is not None: - namespaceprefix_ = self.Option_nsprefix_ + ':' if (UseCapturedNS_ and self.Option_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sOption>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Option), input_name='Option')), namespaceprefix_ , eol_)) - if self.LabelCount is not None: - namespaceprefix_ = self.LabelCount_nsprefix_ + ':' if (UseCapturedNS_ and self.LabelCount_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sLabelCount>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.LabelCount, input_name='LabelCount'), namespaceprefix_ , eol_)) - if self.ImageParameters is not None: - namespaceprefix_ = self.ImageParameters_nsprefix_ + ':' if (UseCapturedNS_ and self.ImageParameters_nsprefix_) else '' - self.ImageParameters.export(outfile, level, namespaceprefix_, namespacedef_='', name_='ImageParameters', pretty_print=pretty_print) - if self.RetailerName is not None: - namespaceprefix_ = self.RetailerName_nsprefix_ + ':' if (UseCapturedNS_ and self.RetailerName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRetailerName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.RetailerName), input_name='RetailerName')), namespaceprefix_ , eol_)) - if self.RetailerAddress is not None: - namespaceprefix_ = self.RetailerAddress_nsprefix_ + ':' if (UseCapturedNS_ and self.RetailerAddress_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRetailerAddress>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.RetailerAddress), input_name='RetailerAddress')), namespaceprefix_ , eol_)) - if self.PermitNumber is not None: - namespaceprefix_ = self.PermitNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.PermitNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPermitNumber>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.PermitNumber, input_name='PermitNumber'), namespaceprefix_ , eol_)) - if self.PermitIssuingPOCity is not None: - namespaceprefix_ = self.PermitIssuingPOCity_nsprefix_ + ':' if (UseCapturedNS_ and self.PermitIssuingPOCity_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPermitIssuingPOCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PermitIssuingPOCity), input_name='PermitIssuingPOCity')), namespaceprefix_ , eol_)) - if self.PermitIssuingPOState is not None: - namespaceprefix_ = self.PermitIssuingPOState_nsprefix_ + ':' if (UseCapturedNS_ and self.PermitIssuingPOState_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPermitIssuingPOState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PermitIssuingPOState), input_name='PermitIssuingPOState')), namespaceprefix_ , eol_)) - if self.PermitIssuingPOZip5 is not None: - namespaceprefix_ = self.PermitIssuingPOZip5_nsprefix_ + ':' if (UseCapturedNS_ and self.PermitIssuingPOZip5_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPermitIssuingPOZip5>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.PermitIssuingPOZip5, input_name='PermitIssuingPOZip5'), namespaceprefix_ , eol_)) - if self.PDUFirmName is not None: - namespaceprefix_ = self.PDUFirmName_nsprefix_ + ':' if (UseCapturedNS_ and self.PDUFirmName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPDUFirmName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PDUFirmName), input_name='PDUFirmName')), namespaceprefix_ , eol_)) - if self.PDUPOBox is not None: - namespaceprefix_ = self.PDUPOBox_nsprefix_ + ':' if (UseCapturedNS_ and self.PDUPOBox_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPDUPOBox>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PDUPOBox), input_name='PDUPOBox')), namespaceprefix_ , eol_)) - if self.PDUCity is not None: - namespaceprefix_ = self.PDUCity_nsprefix_ + ':' if (UseCapturedNS_ and self.PDUCity_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPDUCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PDUCity), input_name='PDUCity')), namespaceprefix_ , eol_)) - if self.PDUState is not None: - namespaceprefix_ = self.PDUState_nsprefix_ + ':' if (UseCapturedNS_ and self.PDUState_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPDUState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PDUState), input_name='PDUState')), namespaceprefix_ , eol_)) - if self.PDUZip5 is not None: - namespaceprefix_ = self.PDUZip5_nsprefix_ + ':' if (UseCapturedNS_ and self.PDUZip5_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPDUZip5>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.PDUZip5, input_name='PDUZip5'), namespaceprefix_ , eol_)) - if self.PDUZip4 is not None: - namespaceprefix_ = self.PDUZip4_nsprefix_ + ':' if (UseCapturedNS_ and self.PDUZip4_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPDUZip4>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.PDUZip4, input_name='PDUZip4'), namespaceprefix_ , eol_)) - if self.ServiceType is not None: - namespaceprefix_ = self.ServiceType_nsprefix_ + ':' if (UseCapturedNS_ and self.ServiceType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sServiceType>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ServiceType), input_name='ServiceType')), namespaceprefix_ , eol_)) - if self.DeliveryConfirmation is not None: - namespaceprefix_ = self.DeliveryConfirmation_nsprefix_ + ':' if (UseCapturedNS_ and self.DeliveryConfirmation_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDeliveryConfirmation>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.DeliveryConfirmation), input_name='DeliveryConfirmation')), namespaceprefix_ , eol_)) - if self.InsuranceValue is not None: - namespaceprefix_ = self.InsuranceValue_nsprefix_ + ':' if (UseCapturedNS_ and self.InsuranceValue_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sInsuranceValue>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.InsuranceValue), input_name='InsuranceValue')), namespaceprefix_ , eol_)) - if self.MailingAckPackageID is not None: - namespaceprefix_ = self.MailingAckPackageID_nsprefix_ + ':' if (UseCapturedNS_ and self.MailingAckPackageID_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sMailingAckPackageID>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.MailingAckPackageID), input_name='MailingAckPackageID')), namespaceprefix_ , eol_)) - if self.WeightInPounds is not None: - namespaceprefix_ = self.WeightInPounds_nsprefix_ + ':' if (UseCapturedNS_ and self.WeightInPounds_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sWeightInPounds>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.WeightInPounds, input_name='WeightInPounds'), namespaceprefix_ , eol_)) - if self.WeightInOunces is not None: - namespaceprefix_ = self.WeightInOunces_nsprefix_ + ':' if (UseCapturedNS_ and self.WeightInOunces_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sWeightInOunces>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.WeightInOunces, input_name='WeightInOunces'), namespaceprefix_ , eol_)) - if self.RMA is not None: - namespaceprefix_ = self.RMA_nsprefix_ + ':' if (UseCapturedNS_ and self.RMA_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRMA>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.RMA), input_name='RMA')), namespaceprefix_ , eol_)) - if self.RMAPICFlag is not None: - namespaceprefix_ = self.RMAPICFlag_nsprefix_ + ':' if (UseCapturedNS_ and self.RMAPICFlag_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRMAPICFlag>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.RMAPICFlag), input_name='RMAPICFlag')), namespaceprefix_ , eol_)) - if self.ImageType is not None: - namespaceprefix_ = self.ImageType_nsprefix_ + ':' if (UseCapturedNS_ and self.ImageType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sImageType>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ImageType), input_name='ImageType')), namespaceprefix_ , eol_)) - if self.RMABarcode is not None: - namespaceprefix_ = self.RMABarcode_nsprefix_ + ':' if (UseCapturedNS_ and self.RMABarcode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRMABarcode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.RMABarcode), input_name='RMABarcode')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('USERID', node) - if value is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - self.USERID = value - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'Option': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Option') - value_ = self.gds_validate_string(value_, node, 'Option') - self.Option = value_ - self.Option_nsprefix_ = child_.prefix - elif nodeName_ == 'LabelCount' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'LabelCount') - ival_ = self.gds_validate_integer(ival_, node, 'LabelCount') - self.LabelCount = ival_ - self.LabelCount_nsprefix_ = child_.prefix - elif nodeName_ == 'ImageParameters': - obj_ = ImageParametersType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.ImageParameters = obj_ - obj_.original_tagname_ = 'ImageParameters' - elif nodeName_ == 'RetailerName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'RetailerName') - value_ = self.gds_validate_string(value_, node, 'RetailerName') - self.RetailerName = value_ - self.RetailerName_nsprefix_ = child_.prefix - elif nodeName_ == 'RetailerAddress': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'RetailerAddress') - value_ = self.gds_validate_string(value_, node, 'RetailerAddress') - self.RetailerAddress = value_ - self.RetailerAddress_nsprefix_ = child_.prefix - elif nodeName_ == 'PermitNumber' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'PermitNumber') - ival_ = self.gds_validate_integer(ival_, node, 'PermitNumber') - self.PermitNumber = ival_ - self.PermitNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'PermitIssuingPOCity': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PermitIssuingPOCity') - value_ = self.gds_validate_string(value_, node, 'PermitIssuingPOCity') - self.PermitIssuingPOCity = value_ - self.PermitIssuingPOCity_nsprefix_ = child_.prefix - elif nodeName_ == 'PermitIssuingPOState': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PermitIssuingPOState') - value_ = self.gds_validate_string(value_, node, 'PermitIssuingPOState') - self.PermitIssuingPOState = value_ - self.PermitIssuingPOState_nsprefix_ = child_.prefix - elif nodeName_ == 'PermitIssuingPOZip5' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'PermitIssuingPOZip5') - ival_ = self.gds_validate_integer(ival_, node, 'PermitIssuingPOZip5') - self.PermitIssuingPOZip5 = ival_ - self.PermitIssuingPOZip5_nsprefix_ = child_.prefix - elif nodeName_ == 'PDUFirmName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PDUFirmName') - value_ = self.gds_validate_string(value_, node, 'PDUFirmName') - self.PDUFirmName = value_ - self.PDUFirmName_nsprefix_ = child_.prefix - elif nodeName_ == 'PDUPOBox': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PDUPOBox') - value_ = self.gds_validate_string(value_, node, 'PDUPOBox') - self.PDUPOBox = value_ - self.PDUPOBox_nsprefix_ = child_.prefix - elif nodeName_ == 'PDUCity': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PDUCity') - value_ = self.gds_validate_string(value_, node, 'PDUCity') - self.PDUCity = value_ - self.PDUCity_nsprefix_ = child_.prefix - elif nodeName_ == 'PDUState': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PDUState') - value_ = self.gds_validate_string(value_, node, 'PDUState') - self.PDUState = value_ - self.PDUState_nsprefix_ = child_.prefix - elif nodeName_ == 'PDUZip5' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'PDUZip5') - ival_ = self.gds_validate_integer(ival_, node, 'PDUZip5') - self.PDUZip5 = ival_ - self.PDUZip5_nsprefix_ = child_.prefix - elif nodeName_ == 'PDUZip4' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'PDUZip4') - ival_ = self.gds_validate_integer(ival_, node, 'PDUZip4') - self.PDUZip4 = ival_ - self.PDUZip4_nsprefix_ = child_.prefix - elif nodeName_ == 'ServiceType': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ServiceType') - value_ = self.gds_validate_string(value_, node, 'ServiceType') - self.ServiceType = value_ - self.ServiceType_nsprefix_ = child_.prefix - elif nodeName_ == 'DeliveryConfirmation': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'DeliveryConfirmation') - value_ = self.gds_validate_string(value_, node, 'DeliveryConfirmation') - self.DeliveryConfirmation = value_ - self.DeliveryConfirmation_nsprefix_ = child_.prefix - elif nodeName_ == 'InsuranceValue': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'InsuranceValue') - value_ = self.gds_validate_string(value_, node, 'InsuranceValue') - self.InsuranceValue = value_ - self.InsuranceValue_nsprefix_ = child_.prefix - elif nodeName_ == 'MailingAckPackageID': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'MailingAckPackageID') - value_ = self.gds_validate_string(value_, node, 'MailingAckPackageID') - self.MailingAckPackageID = value_ - self.MailingAckPackageID_nsprefix_ = child_.prefix - elif nodeName_ == 'WeightInPounds' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'WeightInPounds') - ival_ = self.gds_validate_integer(ival_, node, 'WeightInPounds') - self.WeightInPounds = ival_ - self.WeightInPounds_nsprefix_ = child_.prefix - elif nodeName_ == 'WeightInOunces' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'WeightInOunces') - ival_ = self.gds_validate_integer(ival_, node, 'WeightInOunces') - self.WeightInOunces = ival_ - self.WeightInOunces_nsprefix_ = child_.prefix - elif nodeName_ == 'RMA': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'RMA') - value_ = self.gds_validate_string(value_, node, 'RMA') - self.RMA = value_ - self.RMA_nsprefix_ = child_.prefix - elif nodeName_ == 'RMAPICFlag': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'RMAPICFlag') - value_ = self.gds_validate_string(value_, node, 'RMAPICFlag') - self.RMAPICFlag = value_ - self.RMAPICFlag_nsprefix_ = child_.prefix - elif nodeName_ == 'ImageType': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ImageType') - value_ = self.gds_validate_string(value_, node, 'ImageType') - self.ImageType = value_ - self.ImageType_nsprefix_ = child_.prefix - elif nodeName_ == 'RMABarcode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'RMABarcode') - value_ = self.gds_validate_string(value_, node, 'RMABarcode') - self.RMABarcode = value_ - self.RMABarcode_nsprefix_ = child_.prefix -# end class EMRSV4_0BulkRequest - - -class ImageParametersType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ImageParameter=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - if ImageParameter is None: - self.ImageParameter = [] - else: - self.ImageParameter = ImageParameter - self.ImageParameter_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, ImageParametersType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if ImageParametersType.subclass: - return ImageParametersType.subclass(*args_, **kwargs_) - else: - return ImageParametersType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_ImageParameter(self): - return self.ImageParameter - def set_ImageParameter(self, ImageParameter): - self.ImageParameter = ImageParameter - def add_ImageParameter(self, value): - self.ImageParameter.append(value) - def insert_ImageParameter_at(self, index, value): - self.ImageParameter.insert(index, value) - def replace_ImageParameter_at(self, index, value): - self.ImageParameter[index] = value - def _hasContent(self): - if ( - self.ImageParameter - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ImageParametersType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('ImageParametersType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'ImageParametersType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='ImageParametersType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='ImageParametersType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='ImageParametersType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ImageParametersType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - for ImageParameter_ in self.ImageParameter: - namespaceprefix_ = self.ImageParameter_nsprefix_ + ':' if (UseCapturedNS_ and self.ImageParameter_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sImageParameter>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(ImageParameter_), input_name='ImageParameter')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'ImageParameter': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ImageParameter') - value_ = self.gds_validate_string(value_, node, 'ImageParameter') - self.ImageParameter.append(value_) - self.ImageParameter_nsprefix_ = child_.prefix -# end class ImageParametersType - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'EMRSV4_0BulkRequest' - rootClass = EMRSV4_0BulkRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'EMRSV4_0BulkRequest' - rootClass = EMRSV4_0BulkRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'EMRSV4_0BulkRequest' - rootClass = EMRSV4_0BulkRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'EMRSV4_0BulkRequest' - rootClass = EMRSV4_0BulkRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from emrsv4_0_bulk_request import *\n\n') - sys.stdout.write('import emrsv4_0_bulk_request as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "EMRSV4_0BulkRequest", - "ImageParametersType" -] diff --git a/schemas/usps/karrio/schemas/usps/error.py b/schemas/usps/karrio/schemas/usps/error.py deleted file mode 100644 index 5992ebb4ba..0000000000 --- a/schemas/usps/karrio/schemas/usps/error.py +++ /dev/null @@ -1,1368 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:06 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/error.py') -# -# Command line arguments: -# ./schemas/Error.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/error.py" ./schemas/Error.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class Error(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, Number=None, Source=None, Description=None, HelpFile=None, HelpContext=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.Number = Number - self.Number_nsprefix_ = None - self.Source = Source - self.Source_nsprefix_ = None - self.Description = Description - self.Description_nsprefix_ = None - self.HelpFile = HelpFile - self.HelpFile_nsprefix_ = None - self.HelpContext = HelpContext - self.HelpContext_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, Error) - if subclass is not None: - return subclass(*args_, **kwargs_) - if Error.subclass: - return Error.subclass(*args_, **kwargs_) - else: - return Error(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_Number(self): - return self.Number - def set_Number(self, Number): - self.Number = Number - def get_Source(self): - return self.Source - def set_Source(self, Source): - self.Source = Source - def get_Description(self): - return self.Description - def set_Description(self, Description): - self.Description = Description - def get_HelpFile(self): - return self.HelpFile - def set_HelpFile(self, HelpFile): - self.HelpFile = HelpFile - def get_HelpContext(self): - return self.HelpContext - def set_HelpContext(self, HelpContext): - self.HelpContext = HelpContext - def _hasContent(self): - if ( - self.Number is not None or - self.Source is not None or - self.Description is not None or - self.HelpFile is not None or - self.HelpContext is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='Error', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('Error') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'Error': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='Error') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='Error', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='Error'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='Error', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.Number is not None: - namespaceprefix_ = self.Number_nsprefix_ + ':' if (UseCapturedNS_ and self.Number_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Number), input_name='Number')), namespaceprefix_ , eol_)) - if self.Source is not None: - namespaceprefix_ = self.Source_nsprefix_ + ':' if (UseCapturedNS_ and self.Source_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSource>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Source), input_name='Source')), namespaceprefix_ , eol_)) - if self.Description is not None: - namespaceprefix_ = self.Description_nsprefix_ + ':' if (UseCapturedNS_ and self.Description_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDescription>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Description), input_name='Description')), namespaceprefix_ , eol_)) - if self.HelpFile is not None: - namespaceprefix_ = self.HelpFile_nsprefix_ + ':' if (UseCapturedNS_ and self.HelpFile_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sHelpFile>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.HelpFile), input_name='HelpFile')), namespaceprefix_ , eol_)) - if self.HelpContext is not None: - namespaceprefix_ = self.HelpContext_nsprefix_ + ':' if (UseCapturedNS_ and self.HelpContext_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sHelpContext>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.HelpContext), input_name='HelpContext')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'Number': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Number') - value_ = self.gds_validate_string(value_, node, 'Number') - self.Number = value_ - self.Number_nsprefix_ = child_.prefix - elif nodeName_ == 'Source': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Source') - value_ = self.gds_validate_string(value_, node, 'Source') - self.Source = value_ - self.Source_nsprefix_ = child_.prefix - elif nodeName_ == 'Description': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Description') - value_ = self.gds_validate_string(value_, node, 'Description') - self.Description = value_ - self.Description_nsprefix_ = child_.prefix - elif nodeName_ == 'HelpFile': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'HelpFile') - value_ = self.gds_validate_string(value_, node, 'HelpFile') - self.HelpFile = value_ - self.HelpFile_nsprefix_ = child_.prefix - elif nodeName_ == 'HelpContext': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'HelpContext') - value_ = self.gds_validate_string(value_, node, 'HelpContext') - self.HelpContext = value_ - self.HelpContext_nsprefix_ = child_.prefix -# end class Error - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'Error' - rootClass = Error - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'Error' - rootClass = Error - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'Error' - rootClass = Error - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'Error' - rootClass = Error - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from error import *\n\n') - sys.stdout.write('import error as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "Error" -] diff --git a/schemas/usps/karrio/schemas/usps/evs_cancel_request.py b/schemas/usps/karrio/schemas/usps/evs_cancel_request.py deleted file mode 100644 index 9bc87f7429..0000000000 --- a/schemas/usps/karrio/schemas/usps/evs_cancel_request.py +++ /dev/null @@ -1,1311 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:13 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/evs_cancel_request.py') -# -# Command line arguments: -# ./schemas/eVSCancelRequest.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/evs_cancel_request.py" ./schemas/eVSCancelRequest.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class eVSCancelRequest(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, USERID=None, BarcodeNumber=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.USERID = _cast(None, USERID) - self.USERID_nsprefix_ = None - self.BarcodeNumber = BarcodeNumber - self.BarcodeNumber_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, eVSCancelRequest) - if subclass is not None: - return subclass(*args_, **kwargs_) - if eVSCancelRequest.subclass: - return eVSCancelRequest.subclass(*args_, **kwargs_) - else: - return eVSCancelRequest(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_BarcodeNumber(self): - return self.BarcodeNumber - def set_BarcodeNumber(self, BarcodeNumber): - self.BarcodeNumber = BarcodeNumber - def get_USERID(self): - return self.USERID - def set_USERID(self, USERID): - self.USERID = USERID - def _hasContent(self): - if ( - self.BarcodeNumber is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='eVSCancelRequest', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('eVSCancelRequest') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'eVSCancelRequest': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='eVSCancelRequest') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='eVSCancelRequest', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='eVSCancelRequest'): - if self.USERID is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - outfile.write(' USERID=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.USERID), input_name='USERID')), )) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='eVSCancelRequest', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.BarcodeNumber is not None: - namespaceprefix_ = self.BarcodeNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.BarcodeNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sBarcodeNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.BarcodeNumber), input_name='BarcodeNumber')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('USERID', node) - if value is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - self.USERID = value - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'BarcodeNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'BarcodeNumber') - value_ = self.gds_validate_string(value_, node, 'BarcodeNumber') - self.BarcodeNumber = value_ - self.BarcodeNumber_nsprefix_ = child_.prefix -# end class eVSCancelRequest - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSCancelRequest' - rootClass = eVSCancelRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSCancelRequest' - rootClass = eVSCancelRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSCancelRequest' - rootClass = eVSCancelRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSCancelRequest' - rootClass = eVSCancelRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from evs_cancel_request import *\n\n') - sys.stdout.write('import evs_cancel_request as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "eVSCancelRequest" -] diff --git a/schemas/usps/karrio/schemas/usps/evs_cancel_response.py b/schemas/usps/karrio/schemas/usps/evs_cancel_response.py deleted file mode 100644 index 8a7b311db6..0000000000 --- a/schemas/usps/karrio/schemas/usps/evs_cancel_response.py +++ /dev/null @@ -1,1334 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:13 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/evs_cancel_response.py') -# -# Command line arguments: -# ./schemas/eVSCancelResponse.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/evs_cancel_response.py" ./schemas/eVSCancelResponse.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class eVSCancelResponse(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, BarcodeNumber=None, Status=None, Reason=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.BarcodeNumber = BarcodeNumber - self.BarcodeNumber_nsprefix_ = None - self.Status = Status - self.Status_nsprefix_ = None - self.Reason = Reason - self.Reason_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, eVSCancelResponse) - if subclass is not None: - return subclass(*args_, **kwargs_) - if eVSCancelResponse.subclass: - return eVSCancelResponse.subclass(*args_, **kwargs_) - else: - return eVSCancelResponse(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_BarcodeNumber(self): - return self.BarcodeNumber - def set_BarcodeNumber(self, BarcodeNumber): - self.BarcodeNumber = BarcodeNumber - def get_Status(self): - return self.Status - def set_Status(self, Status): - self.Status = Status - def get_Reason(self): - return self.Reason - def set_Reason(self, Reason): - self.Reason = Reason - def _hasContent(self): - if ( - self.BarcodeNumber is not None or - self.Status is not None or - self.Reason is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='eVSCancelResponse', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('eVSCancelResponse') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'eVSCancelResponse': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='eVSCancelResponse') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='eVSCancelResponse', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='eVSCancelResponse'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='eVSCancelResponse', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.BarcodeNumber is not None: - namespaceprefix_ = self.BarcodeNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.BarcodeNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sBarcodeNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.BarcodeNumber), input_name='BarcodeNumber')), namespaceprefix_ , eol_)) - if self.Status is not None: - namespaceprefix_ = self.Status_nsprefix_ + ':' if (UseCapturedNS_ and self.Status_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sStatus>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Status), input_name='Status')), namespaceprefix_ , eol_)) - if self.Reason is not None: - namespaceprefix_ = self.Reason_nsprefix_ + ':' if (UseCapturedNS_ and self.Reason_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sReason>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Reason), input_name='Reason')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'BarcodeNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'BarcodeNumber') - value_ = self.gds_validate_string(value_, node, 'BarcodeNumber') - self.BarcodeNumber = value_ - self.BarcodeNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'Status': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Status') - value_ = self.gds_validate_string(value_, node, 'Status') - self.Status = value_ - self.Status_nsprefix_ = child_.prefix - elif nodeName_ == 'Reason': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Reason') - value_ = self.gds_validate_string(value_, node, 'Reason') - self.Reason = value_ - self.Reason_nsprefix_ = child_.prefix -# end class eVSCancelResponse - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSCancelResponse' - rootClass = eVSCancelResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSCancelResponse' - rootClass = eVSCancelResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSCancelResponse' - rootClass = eVSCancelResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSCancelResponse' - rootClass = eVSCancelResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from evs_cancel_response import *\n\n') - sys.stdout.write('import evs_cancel_response as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "eVSCancelResponse" -] diff --git a/schemas/usps/karrio/schemas/usps/evs_express_mail_intl_request.py b/schemas/usps/karrio/schemas/usps/evs_express_mail_intl_request.py deleted file mode 100644 index 2834503bac..0000000000 --- a/schemas/usps/karrio/schemas/usps/evs_express_mail_intl_request.py +++ /dev/null @@ -1,3332 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:14 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/evs_express_mail_intl_request.py') -# -# Command line arguments: -# ./schemas/eVSExpressMailIntlRequest.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/evs_express_mail_intl_request.py" ./schemas/eVSExpressMailIntlRequest.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class eVSExpressMailIntlRequest(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, USERID=None, PASSWORD=None, Option=None, Revision=None, ImageParameters=None, FromFirstName=None, FromMiddleInitial=None, FromLastName=None, FromFirm=None, FromAddress1=None, FromAddress2=None, FromUrbanization=None, FromCity=None, FromState=None, FromZip5=None, FromZip4=None, FromPhone=None, FromCustomsReference=None, ToName=None, ToFirstName=None, ToLastName=None, ToFirm=None, ToAddress1=None, ToAddress2=None, ToAddress3=None, ToCity=None, ToProvince=None, ToCountry=None, ToPostalCode=None, ToPOBoxFlag=None, ToPhone=None, ToFax=None, ToEmail=None, ImportersReferenceNumber=None, NonDeliveryOption=None, RedirectName=None, RedirectEmail=None, RedirectSMS=None, RedirectAddress=None, RedirectCity=None, RedirectState=None, RedirectZipCode=None, RedirectZip4=None, Container=None, ShippingContents=None, InsuredNumber=None, InsuredAmount=None, Postage=None, GrossPounds=None, GrossOunces=None, ContentType=None, ContentTypeOther=None, Agreement=None, Comments=None, LicenseNumber=None, CertificateNumber=None, InvoiceNumber=None, ImageType=None, ImageLayout=None, CustomerRefNo=None, CustomerRefNo2=None, POZipCode=None, LabelDate=None, EMCAAccount=None, HoldForManifest=None, EELPFC=None, PriceOptions=None, Length=None, Width=None, Height=None, Girth=None, LabelTime=None, MeterPaymentFlag=None, ActionCode=None, OptOutOfSPE=None, PermitNumber=None, AccountZipCode=None, ImportersReferenceType=None, ImportersTelephoneNumber=None, ImportersFaxNumber=None, ImportersEmail=None, Machinable=None, DestinationRateIndicator=None, MID=None, LogisticsManagerMID=None, CRID=None, VendorCode=None, VendorProductVersionNumber=None, ePostageMailerReporting=None, SenderFirstName=None, SenderLastName=None, SenderBusinessName=None, SenderAddress1=None, SenderCity=None, SenderState=None, SenderZip5=None, SenderPhone=None, SenderEmail=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.USERID = _cast(None, USERID) - self.USERID_nsprefix_ = None - self.PASSWORD = _cast(None, PASSWORD) - self.PASSWORD_nsprefix_ = None - self.Option = Option - self.Option_nsprefix_ = None - self.Revision = Revision - self.Revision_nsprefix_ = None - self.ImageParameters = ImageParameters - self.ImageParameters_nsprefix_ = None - self.FromFirstName = FromFirstName - self.FromFirstName_nsprefix_ = None - self.FromMiddleInitial = FromMiddleInitial - self.FromMiddleInitial_nsprefix_ = None - self.FromLastName = FromLastName - self.FromLastName_nsprefix_ = None - self.FromFirm = FromFirm - self.FromFirm_nsprefix_ = None - self.FromAddress1 = FromAddress1 - self.FromAddress1_nsprefix_ = None - self.FromAddress2 = FromAddress2 - self.FromAddress2_nsprefix_ = None - self.FromUrbanization = FromUrbanization - self.FromUrbanization_nsprefix_ = None - self.FromCity = FromCity - self.FromCity_nsprefix_ = None - self.FromState = FromState - self.FromState_nsprefix_ = None - self.FromZip5 = FromZip5 - self.FromZip5_nsprefix_ = None - self.FromZip4 = FromZip4 - self.FromZip4_nsprefix_ = None - self.FromPhone = FromPhone - self.FromPhone_nsprefix_ = None - self.FromCustomsReference = FromCustomsReference - self.FromCustomsReference_nsprefix_ = None - self.ToName = ToName - self.ToName_nsprefix_ = None - self.ToFirstName = ToFirstName - self.ToFirstName_nsprefix_ = None - self.ToLastName = ToLastName - self.ToLastName_nsprefix_ = None - self.ToFirm = ToFirm - self.ToFirm_nsprefix_ = None - self.ToAddress1 = ToAddress1 - self.ToAddress1_nsprefix_ = None - self.ToAddress2 = ToAddress2 - self.ToAddress2_nsprefix_ = None - self.ToAddress3 = ToAddress3 - self.ToAddress3_nsprefix_ = None - self.ToCity = ToCity - self.ToCity_nsprefix_ = None - self.ToProvince = ToProvince - self.ToProvince_nsprefix_ = None - self.ToCountry = ToCountry - self.ToCountry_nsprefix_ = None - self.ToPostalCode = ToPostalCode - self.ToPostalCode_nsprefix_ = None - self.ToPOBoxFlag = ToPOBoxFlag - self.ToPOBoxFlag_nsprefix_ = None - self.ToPhone = ToPhone - self.ToPhone_nsprefix_ = None - self.ToFax = ToFax - self.ToFax_nsprefix_ = None - self.ToEmail = ToEmail - self.ToEmail_nsprefix_ = None - self.ImportersReferenceNumber = ImportersReferenceNumber - self.ImportersReferenceNumber_nsprefix_ = None - self.NonDeliveryOption = NonDeliveryOption - self.NonDeliveryOption_nsprefix_ = None - self.RedirectName = RedirectName - self.RedirectName_nsprefix_ = None - self.RedirectEmail = RedirectEmail - self.RedirectEmail_nsprefix_ = None - self.RedirectSMS = RedirectSMS - self.RedirectSMS_nsprefix_ = None - self.RedirectAddress = RedirectAddress - self.RedirectAddress_nsprefix_ = None - self.RedirectCity = RedirectCity - self.RedirectCity_nsprefix_ = None - self.RedirectState = RedirectState - self.RedirectState_nsprefix_ = None - self.RedirectZipCode = RedirectZipCode - self.RedirectZipCode_nsprefix_ = None - self.RedirectZip4 = RedirectZip4 - self.RedirectZip4_nsprefix_ = None - self.Container = Container - self.Container_nsprefix_ = None - self.ShippingContents = ShippingContents - self.ShippingContents_nsprefix_ = None - self.InsuredNumber = InsuredNumber - self.InsuredNumber_nsprefix_ = None - self.InsuredAmount = InsuredAmount - self.InsuredAmount_nsprefix_ = None - self.Postage = Postage - self.Postage_nsprefix_ = None - self.GrossPounds = GrossPounds - self.GrossPounds_nsprefix_ = None - self.GrossOunces = GrossOunces - self.GrossOunces_nsprefix_ = None - self.ContentType = ContentType - self.ContentType_nsprefix_ = None - self.ContentTypeOther = ContentTypeOther - self.ContentTypeOther_nsprefix_ = None - self.Agreement = Agreement - self.Agreement_nsprefix_ = None - self.Comments = Comments - self.Comments_nsprefix_ = None - self.LicenseNumber = LicenseNumber - self.LicenseNumber_nsprefix_ = None - self.CertificateNumber = CertificateNumber - self.CertificateNumber_nsprefix_ = None - self.InvoiceNumber = InvoiceNumber - self.InvoiceNumber_nsprefix_ = None - self.ImageType = ImageType - self.ImageType_nsprefix_ = None - self.ImageLayout = ImageLayout - self.ImageLayout_nsprefix_ = None - self.CustomerRefNo = CustomerRefNo - self.CustomerRefNo_nsprefix_ = None - self.CustomerRefNo2 = CustomerRefNo2 - self.CustomerRefNo2_nsprefix_ = None - self.POZipCode = POZipCode - self.POZipCode_nsprefix_ = None - self.LabelDate = LabelDate - self.LabelDate_nsprefix_ = None - self.EMCAAccount = EMCAAccount - self.EMCAAccount_nsprefix_ = None - self.HoldForManifest = HoldForManifest - self.HoldForManifest_nsprefix_ = None - self.EELPFC = EELPFC - self.EELPFC_nsprefix_ = None - self.PriceOptions = PriceOptions - self.PriceOptions_nsprefix_ = None - self.Length = Length - self.Length_nsprefix_ = None - self.Width = Width - self.Width_nsprefix_ = None - self.Height = Height - self.Height_nsprefix_ = None - self.Girth = Girth - self.Girth_nsprefix_ = None - self.LabelTime = LabelTime - self.LabelTime_nsprefix_ = None - self.MeterPaymentFlag = MeterPaymentFlag - self.MeterPaymentFlag_nsprefix_ = None - self.ActionCode = ActionCode - self.ActionCode_nsprefix_ = None - self.OptOutOfSPE = OptOutOfSPE - self.OptOutOfSPE_nsprefix_ = None - self.PermitNumber = PermitNumber - self.PermitNumber_nsprefix_ = None - self.AccountZipCode = AccountZipCode - self.AccountZipCode_nsprefix_ = None - self.ImportersReferenceType = ImportersReferenceType - self.ImportersReferenceType_nsprefix_ = None - self.ImportersTelephoneNumber = ImportersTelephoneNumber - self.ImportersTelephoneNumber_nsprefix_ = None - self.ImportersFaxNumber = ImportersFaxNumber - self.ImportersFaxNumber_nsprefix_ = None - self.ImportersEmail = ImportersEmail - self.ImportersEmail_nsprefix_ = None - self.Machinable = Machinable - self.Machinable_nsprefix_ = None - self.DestinationRateIndicator = DestinationRateIndicator - self.DestinationRateIndicator_nsprefix_ = None - self.MID = MID - self.MID_nsprefix_ = None - self.LogisticsManagerMID = LogisticsManagerMID - self.LogisticsManagerMID_nsprefix_ = None - self.CRID = CRID - self.CRID_nsprefix_ = None - self.VendorCode = VendorCode - self.VendorCode_nsprefix_ = None - self.VendorProductVersionNumber = VendorProductVersionNumber - self.VendorProductVersionNumber_nsprefix_ = None - self.ePostageMailerReporting = ePostageMailerReporting - self.ePostageMailerReporting_nsprefix_ = None - self.SenderFirstName = SenderFirstName - self.SenderFirstName_nsprefix_ = None - self.SenderLastName = SenderLastName - self.SenderLastName_nsprefix_ = None - self.SenderBusinessName = SenderBusinessName - self.SenderBusinessName_nsprefix_ = None - self.SenderAddress1 = SenderAddress1 - self.SenderAddress1_nsprefix_ = None - self.SenderCity = SenderCity - self.SenderCity_nsprefix_ = None - self.SenderState = SenderState - self.SenderState_nsprefix_ = None - self.SenderZip5 = SenderZip5 - self.SenderZip5_nsprefix_ = None - self.SenderPhone = SenderPhone - self.SenderPhone_nsprefix_ = None - self.SenderEmail = SenderEmail - self.SenderEmail_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, eVSExpressMailIntlRequest) - if subclass is not None: - return subclass(*args_, **kwargs_) - if eVSExpressMailIntlRequest.subclass: - return eVSExpressMailIntlRequest.subclass(*args_, **kwargs_) - else: - return eVSExpressMailIntlRequest(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_Option(self): - return self.Option - def set_Option(self, Option): - self.Option = Option - def get_Revision(self): - return self.Revision - def set_Revision(self, Revision): - self.Revision = Revision - def get_ImageParameters(self): - return self.ImageParameters - def set_ImageParameters(self, ImageParameters): - self.ImageParameters = ImageParameters - def get_FromFirstName(self): - return self.FromFirstName - def set_FromFirstName(self, FromFirstName): - self.FromFirstName = FromFirstName - def get_FromMiddleInitial(self): - return self.FromMiddleInitial - def set_FromMiddleInitial(self, FromMiddleInitial): - self.FromMiddleInitial = FromMiddleInitial - def get_FromLastName(self): - return self.FromLastName - def set_FromLastName(self, FromLastName): - self.FromLastName = FromLastName - def get_FromFirm(self): - return self.FromFirm - def set_FromFirm(self, FromFirm): - self.FromFirm = FromFirm - def get_FromAddress1(self): - return self.FromAddress1 - def set_FromAddress1(self, FromAddress1): - self.FromAddress1 = FromAddress1 - def get_FromAddress2(self): - return self.FromAddress2 - def set_FromAddress2(self, FromAddress2): - self.FromAddress2 = FromAddress2 - def get_FromUrbanization(self): - return self.FromUrbanization - def set_FromUrbanization(self, FromUrbanization): - self.FromUrbanization = FromUrbanization - def get_FromCity(self): - return self.FromCity - def set_FromCity(self, FromCity): - self.FromCity = FromCity - def get_FromState(self): - return self.FromState - def set_FromState(self, FromState): - self.FromState = FromState - def get_FromZip5(self): - return self.FromZip5 - def set_FromZip5(self, FromZip5): - self.FromZip5 = FromZip5 - def get_FromZip4(self): - return self.FromZip4 - def set_FromZip4(self, FromZip4): - self.FromZip4 = FromZip4 - def get_FromPhone(self): - return self.FromPhone - def set_FromPhone(self, FromPhone): - self.FromPhone = FromPhone - def get_FromCustomsReference(self): - return self.FromCustomsReference - def set_FromCustomsReference(self, FromCustomsReference): - self.FromCustomsReference = FromCustomsReference - def get_ToName(self): - return self.ToName - def set_ToName(self, ToName): - self.ToName = ToName - def get_ToFirstName(self): - return self.ToFirstName - def set_ToFirstName(self, ToFirstName): - self.ToFirstName = ToFirstName - def get_ToLastName(self): - return self.ToLastName - def set_ToLastName(self, ToLastName): - self.ToLastName = ToLastName - def get_ToFirm(self): - return self.ToFirm - def set_ToFirm(self, ToFirm): - self.ToFirm = ToFirm - def get_ToAddress1(self): - return self.ToAddress1 - def set_ToAddress1(self, ToAddress1): - self.ToAddress1 = ToAddress1 - def get_ToAddress2(self): - return self.ToAddress2 - def set_ToAddress2(self, ToAddress2): - self.ToAddress2 = ToAddress2 - def get_ToAddress3(self): - return self.ToAddress3 - def set_ToAddress3(self, ToAddress3): - self.ToAddress3 = ToAddress3 - def get_ToCity(self): - return self.ToCity - def set_ToCity(self, ToCity): - self.ToCity = ToCity - def get_ToProvince(self): - return self.ToProvince - def set_ToProvince(self, ToProvince): - self.ToProvince = ToProvince - def get_ToCountry(self): - return self.ToCountry - def set_ToCountry(self, ToCountry): - self.ToCountry = ToCountry - def get_ToPostalCode(self): - return self.ToPostalCode - def set_ToPostalCode(self, ToPostalCode): - self.ToPostalCode = ToPostalCode - def get_ToPOBoxFlag(self): - return self.ToPOBoxFlag - def set_ToPOBoxFlag(self, ToPOBoxFlag): - self.ToPOBoxFlag = ToPOBoxFlag - def get_ToPhone(self): - return self.ToPhone - def set_ToPhone(self, ToPhone): - self.ToPhone = ToPhone - def get_ToFax(self): - return self.ToFax - def set_ToFax(self, ToFax): - self.ToFax = ToFax - def get_ToEmail(self): - return self.ToEmail - def set_ToEmail(self, ToEmail): - self.ToEmail = ToEmail - def get_ImportersReferenceNumber(self): - return self.ImportersReferenceNumber - def set_ImportersReferenceNumber(self, ImportersReferenceNumber): - self.ImportersReferenceNumber = ImportersReferenceNumber - def get_NonDeliveryOption(self): - return self.NonDeliveryOption - def set_NonDeliveryOption(self, NonDeliveryOption): - self.NonDeliveryOption = NonDeliveryOption - def get_RedirectName(self): - return self.RedirectName - def set_RedirectName(self, RedirectName): - self.RedirectName = RedirectName - def get_RedirectEmail(self): - return self.RedirectEmail - def set_RedirectEmail(self, RedirectEmail): - self.RedirectEmail = RedirectEmail - def get_RedirectSMS(self): - return self.RedirectSMS - def set_RedirectSMS(self, RedirectSMS): - self.RedirectSMS = RedirectSMS - def get_RedirectAddress(self): - return self.RedirectAddress - def set_RedirectAddress(self, RedirectAddress): - self.RedirectAddress = RedirectAddress - def get_RedirectCity(self): - return self.RedirectCity - def set_RedirectCity(self, RedirectCity): - self.RedirectCity = RedirectCity - def get_RedirectState(self): - return self.RedirectState - def set_RedirectState(self, RedirectState): - self.RedirectState = RedirectState - def get_RedirectZipCode(self): - return self.RedirectZipCode - def set_RedirectZipCode(self, RedirectZipCode): - self.RedirectZipCode = RedirectZipCode - def get_RedirectZip4(self): - return self.RedirectZip4 - def set_RedirectZip4(self, RedirectZip4): - self.RedirectZip4 = RedirectZip4 - def get_Container(self): - return self.Container - def set_Container(self, Container): - self.Container = Container - def get_ShippingContents(self): - return self.ShippingContents - def set_ShippingContents(self, ShippingContents): - self.ShippingContents = ShippingContents - def get_InsuredNumber(self): - return self.InsuredNumber - def set_InsuredNumber(self, InsuredNumber): - self.InsuredNumber = InsuredNumber - def get_InsuredAmount(self): - return self.InsuredAmount - def set_InsuredAmount(self, InsuredAmount): - self.InsuredAmount = InsuredAmount - def get_Postage(self): - return self.Postage - def set_Postage(self, Postage): - self.Postage = Postage - def get_GrossPounds(self): - return self.GrossPounds - def set_GrossPounds(self, GrossPounds): - self.GrossPounds = GrossPounds - def get_GrossOunces(self): - return self.GrossOunces - def set_GrossOunces(self, GrossOunces): - self.GrossOunces = GrossOunces - def get_ContentType(self): - return self.ContentType - def set_ContentType(self, ContentType): - self.ContentType = ContentType - def get_ContentTypeOther(self): - return self.ContentTypeOther - def set_ContentTypeOther(self, ContentTypeOther): - self.ContentTypeOther = ContentTypeOther - def get_Agreement(self): - return self.Agreement - def set_Agreement(self, Agreement): - self.Agreement = Agreement - def get_Comments(self): - return self.Comments - def set_Comments(self, Comments): - self.Comments = Comments - def get_LicenseNumber(self): - return self.LicenseNumber - def set_LicenseNumber(self, LicenseNumber): - self.LicenseNumber = LicenseNumber - def get_CertificateNumber(self): - return self.CertificateNumber - def set_CertificateNumber(self, CertificateNumber): - self.CertificateNumber = CertificateNumber - def get_InvoiceNumber(self): - return self.InvoiceNumber - def set_InvoiceNumber(self, InvoiceNumber): - self.InvoiceNumber = InvoiceNumber - def get_ImageType(self): - return self.ImageType - def set_ImageType(self, ImageType): - self.ImageType = ImageType - def get_ImageLayout(self): - return self.ImageLayout - def set_ImageLayout(self, ImageLayout): - self.ImageLayout = ImageLayout - def get_CustomerRefNo(self): - return self.CustomerRefNo - def set_CustomerRefNo(self, CustomerRefNo): - self.CustomerRefNo = CustomerRefNo - def get_CustomerRefNo2(self): - return self.CustomerRefNo2 - def set_CustomerRefNo2(self, CustomerRefNo2): - self.CustomerRefNo2 = CustomerRefNo2 - def get_POZipCode(self): - return self.POZipCode - def set_POZipCode(self, POZipCode): - self.POZipCode = POZipCode - def get_LabelDate(self): - return self.LabelDate - def set_LabelDate(self, LabelDate): - self.LabelDate = LabelDate - def get_EMCAAccount(self): - return self.EMCAAccount - def set_EMCAAccount(self, EMCAAccount): - self.EMCAAccount = EMCAAccount - def get_HoldForManifest(self): - return self.HoldForManifest - def set_HoldForManifest(self, HoldForManifest): - self.HoldForManifest = HoldForManifest - def get_EELPFC(self): - return self.EELPFC - def set_EELPFC(self, EELPFC): - self.EELPFC = EELPFC - def get_PriceOptions(self): - return self.PriceOptions - def set_PriceOptions(self, PriceOptions): - self.PriceOptions = PriceOptions - def get_Length(self): - return self.Length - def set_Length(self, Length): - self.Length = Length - def get_Width(self): - return self.Width - def set_Width(self, Width): - self.Width = Width - def get_Height(self): - return self.Height - def set_Height(self, Height): - self.Height = Height - def get_Girth(self): - return self.Girth - def set_Girth(self, Girth): - self.Girth = Girth - def get_LabelTime(self): - return self.LabelTime - def set_LabelTime(self, LabelTime): - self.LabelTime = LabelTime - def get_MeterPaymentFlag(self): - return self.MeterPaymentFlag - def set_MeterPaymentFlag(self, MeterPaymentFlag): - self.MeterPaymentFlag = MeterPaymentFlag - def get_ActionCode(self): - return self.ActionCode - def set_ActionCode(self, ActionCode): - self.ActionCode = ActionCode - def get_OptOutOfSPE(self): - return self.OptOutOfSPE - def set_OptOutOfSPE(self, OptOutOfSPE): - self.OptOutOfSPE = OptOutOfSPE - def get_PermitNumber(self): - return self.PermitNumber - def set_PermitNumber(self, PermitNumber): - self.PermitNumber = PermitNumber - def get_AccountZipCode(self): - return self.AccountZipCode - def set_AccountZipCode(self, AccountZipCode): - self.AccountZipCode = AccountZipCode - def get_ImportersReferenceType(self): - return self.ImportersReferenceType - def set_ImportersReferenceType(self, ImportersReferenceType): - self.ImportersReferenceType = ImportersReferenceType - def get_ImportersTelephoneNumber(self): - return self.ImportersTelephoneNumber - def set_ImportersTelephoneNumber(self, ImportersTelephoneNumber): - self.ImportersTelephoneNumber = ImportersTelephoneNumber - def get_ImportersFaxNumber(self): - return self.ImportersFaxNumber - def set_ImportersFaxNumber(self, ImportersFaxNumber): - self.ImportersFaxNumber = ImportersFaxNumber - def get_ImportersEmail(self): - return self.ImportersEmail - def set_ImportersEmail(self, ImportersEmail): - self.ImportersEmail = ImportersEmail - def get_Machinable(self): - return self.Machinable - def set_Machinable(self, Machinable): - self.Machinable = Machinable - def get_DestinationRateIndicator(self): - return self.DestinationRateIndicator - def set_DestinationRateIndicator(self, DestinationRateIndicator): - self.DestinationRateIndicator = DestinationRateIndicator - def get_MID(self): - return self.MID - def set_MID(self, MID): - self.MID = MID - def get_LogisticsManagerMID(self): - return self.LogisticsManagerMID - def set_LogisticsManagerMID(self, LogisticsManagerMID): - self.LogisticsManagerMID = LogisticsManagerMID - def get_CRID(self): - return self.CRID - def set_CRID(self, CRID): - self.CRID = CRID - def get_VendorCode(self): - return self.VendorCode - def set_VendorCode(self, VendorCode): - self.VendorCode = VendorCode - def get_VendorProductVersionNumber(self): - return self.VendorProductVersionNumber - def set_VendorProductVersionNumber(self, VendorProductVersionNumber): - self.VendorProductVersionNumber = VendorProductVersionNumber - def get_ePostageMailerReporting(self): - return self.ePostageMailerReporting - def set_ePostageMailerReporting(self, ePostageMailerReporting): - self.ePostageMailerReporting = ePostageMailerReporting - def get_SenderFirstName(self): - return self.SenderFirstName - def set_SenderFirstName(self, SenderFirstName): - self.SenderFirstName = SenderFirstName - def get_SenderLastName(self): - return self.SenderLastName - def set_SenderLastName(self, SenderLastName): - self.SenderLastName = SenderLastName - def get_SenderBusinessName(self): - return self.SenderBusinessName - def set_SenderBusinessName(self, SenderBusinessName): - self.SenderBusinessName = SenderBusinessName - def get_SenderAddress1(self): - return self.SenderAddress1 - def set_SenderAddress1(self, SenderAddress1): - self.SenderAddress1 = SenderAddress1 - def get_SenderCity(self): - return self.SenderCity - def set_SenderCity(self, SenderCity): - self.SenderCity = SenderCity - def get_SenderState(self): - return self.SenderState - def set_SenderState(self, SenderState): - self.SenderState = SenderState - def get_SenderZip5(self): - return self.SenderZip5 - def set_SenderZip5(self, SenderZip5): - self.SenderZip5 = SenderZip5 - def get_SenderPhone(self): - return self.SenderPhone - def set_SenderPhone(self, SenderPhone): - self.SenderPhone = SenderPhone - def get_SenderEmail(self): - return self.SenderEmail - def set_SenderEmail(self, SenderEmail): - self.SenderEmail = SenderEmail - def get_USERID(self): - return self.USERID - def set_USERID(self, USERID): - self.USERID = USERID - def get_PASSWORD(self): - return self.PASSWORD - def set_PASSWORD(self, PASSWORD): - self.PASSWORD = PASSWORD - def _hasContent(self): - if ( - self.Option is not None or - self.Revision is not None or - self.ImageParameters is not None or - self.FromFirstName is not None or - self.FromMiddleInitial is not None or - self.FromLastName is not None or - self.FromFirm is not None or - self.FromAddress1 is not None or - self.FromAddress2 is not None or - self.FromUrbanization is not None or - self.FromCity is not None or - self.FromState is not None or - self.FromZip5 is not None or - self.FromZip4 is not None or - self.FromPhone is not None or - self.FromCustomsReference is not None or - self.ToName is not None or - self.ToFirstName is not None or - self.ToLastName is not None or - self.ToFirm is not None or - self.ToAddress1 is not None or - self.ToAddress2 is not None or - self.ToAddress3 is not None or - self.ToCity is not None or - self.ToProvince is not None or - self.ToCountry is not None or - self.ToPostalCode is not None or - self.ToPOBoxFlag is not None or - self.ToPhone is not None or - self.ToFax is not None or - self.ToEmail is not None or - self.ImportersReferenceNumber is not None or - self.NonDeliveryOption is not None or - self.RedirectName is not None or - self.RedirectEmail is not None or - self.RedirectSMS is not None or - self.RedirectAddress is not None or - self.RedirectCity is not None or - self.RedirectState is not None or - self.RedirectZipCode is not None or - self.RedirectZip4 is not None or - self.Container is not None or - self.ShippingContents is not None or - self.InsuredNumber is not None or - self.InsuredAmount is not None or - self.Postage is not None or - self.GrossPounds is not None or - self.GrossOunces is not None or - self.ContentType is not None or - self.ContentTypeOther is not None or - self.Agreement is not None or - self.Comments is not None or - self.LicenseNumber is not None or - self.CertificateNumber is not None or - self.InvoiceNumber is not None or - self.ImageType is not None or - self.ImageLayout is not None or - self.CustomerRefNo is not None or - self.CustomerRefNo2 is not None or - self.POZipCode is not None or - self.LabelDate is not None or - self.EMCAAccount is not None or - self.HoldForManifest is not None or - self.EELPFC is not None or - self.PriceOptions is not None or - self.Length is not None or - self.Width is not None or - self.Height is not None or - self.Girth is not None or - self.LabelTime is not None or - self.MeterPaymentFlag is not None or - self.ActionCode is not None or - self.OptOutOfSPE is not None or - self.PermitNumber is not None or - self.AccountZipCode is not None or - self.ImportersReferenceType is not None or - self.ImportersTelephoneNumber is not None or - self.ImportersFaxNumber is not None or - self.ImportersEmail is not None or - self.Machinable is not None or - self.DestinationRateIndicator is not None or - self.MID is not None or - self.LogisticsManagerMID is not None or - self.CRID is not None or - self.VendorCode is not None or - self.VendorProductVersionNumber is not None or - self.ePostageMailerReporting is not None or - self.SenderFirstName is not None or - self.SenderLastName is not None or - self.SenderBusinessName is not None or - self.SenderAddress1 is not None or - self.SenderCity is not None or - self.SenderState is not None or - self.SenderZip5 is not None or - self.SenderPhone is not None or - self.SenderEmail is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='eVSExpressMailIntlRequest', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('eVSExpressMailIntlRequest') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'eVSExpressMailIntlRequest': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='eVSExpressMailIntlRequest') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='eVSExpressMailIntlRequest', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='eVSExpressMailIntlRequest'): - if self.USERID is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - outfile.write(' USERID=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.USERID), input_name='USERID')), )) - if self.PASSWORD is not None and 'PASSWORD' not in already_processed: - already_processed.add('PASSWORD') - outfile.write(' PASSWORD=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.PASSWORD), input_name='PASSWORD')), )) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='eVSExpressMailIntlRequest', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.Option is not None: - namespaceprefix_ = self.Option_nsprefix_ + ':' if (UseCapturedNS_ and self.Option_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sOption>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Option), input_name='Option')), namespaceprefix_ , eol_)) - if self.Revision is not None: - namespaceprefix_ = self.Revision_nsprefix_ + ':' if (UseCapturedNS_ and self.Revision_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRevision>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Revision), input_name='Revision')), namespaceprefix_ , eol_)) - if self.ImageParameters is not None: - namespaceprefix_ = self.ImageParameters_nsprefix_ + ':' if (UseCapturedNS_ and self.ImageParameters_nsprefix_) else '' - self.ImageParameters.export(outfile, level, namespaceprefix_, namespacedef_='', name_='ImageParameters', pretty_print=pretty_print) - if self.FromFirstName is not None: - namespaceprefix_ = self.FromFirstName_nsprefix_ + ':' if (UseCapturedNS_ and self.FromFirstName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromFirstName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromFirstName), input_name='FromFirstName')), namespaceprefix_ , eol_)) - if self.FromMiddleInitial is not None: - namespaceprefix_ = self.FromMiddleInitial_nsprefix_ + ':' if (UseCapturedNS_ and self.FromMiddleInitial_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromMiddleInitial>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromMiddleInitial), input_name='FromMiddleInitial')), namespaceprefix_ , eol_)) - if self.FromLastName is not None: - namespaceprefix_ = self.FromLastName_nsprefix_ + ':' if (UseCapturedNS_ and self.FromLastName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromLastName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromLastName), input_name='FromLastName')), namespaceprefix_ , eol_)) - if self.FromFirm is not None: - namespaceprefix_ = self.FromFirm_nsprefix_ + ':' if (UseCapturedNS_ and self.FromFirm_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromFirm>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromFirm), input_name='FromFirm')), namespaceprefix_ , eol_)) - if self.FromAddress1 is not None: - namespaceprefix_ = self.FromAddress1_nsprefix_ + ':' if (UseCapturedNS_ and self.FromAddress1_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromAddress1>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromAddress1), input_name='FromAddress1')), namespaceprefix_ , eol_)) - if self.FromAddress2 is not None: - namespaceprefix_ = self.FromAddress2_nsprefix_ + ':' if (UseCapturedNS_ and self.FromAddress2_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromAddress2>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromAddress2), input_name='FromAddress2')), namespaceprefix_ , eol_)) - if self.FromUrbanization is not None: - namespaceprefix_ = self.FromUrbanization_nsprefix_ + ':' if (UseCapturedNS_ and self.FromUrbanization_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromUrbanization>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromUrbanization), input_name='FromUrbanization')), namespaceprefix_ , eol_)) - if self.FromCity is not None: - namespaceprefix_ = self.FromCity_nsprefix_ + ':' if (UseCapturedNS_ and self.FromCity_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromCity), input_name='FromCity')), namespaceprefix_ , eol_)) - if self.FromState is not None: - namespaceprefix_ = self.FromState_nsprefix_ + ':' if (UseCapturedNS_ and self.FromState_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromState), input_name='FromState')), namespaceprefix_ , eol_)) - if self.FromZip5 is not None: - namespaceprefix_ = self.FromZip5_nsprefix_ + ':' if (UseCapturedNS_ and self.FromZip5_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromZip5>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromZip5), input_name='FromZip5')), namespaceprefix_ , eol_)) - if self.FromZip4 is not None: - namespaceprefix_ = self.FromZip4_nsprefix_ + ':' if (UseCapturedNS_ and self.FromZip4_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromZip4>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromZip4), input_name='FromZip4')), namespaceprefix_ , eol_)) - if self.FromPhone is not None: - namespaceprefix_ = self.FromPhone_nsprefix_ + ':' if (UseCapturedNS_ and self.FromPhone_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromPhone>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromPhone), input_name='FromPhone')), namespaceprefix_ , eol_)) - if self.FromCustomsReference is not None: - namespaceprefix_ = self.FromCustomsReference_nsprefix_ + ':' if (UseCapturedNS_ and self.FromCustomsReference_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromCustomsReference>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromCustomsReference), input_name='FromCustomsReference')), namespaceprefix_ , eol_)) - if self.ToName is not None: - namespaceprefix_ = self.ToName_nsprefix_ + ':' if (UseCapturedNS_ and self.ToName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToName), input_name='ToName')), namespaceprefix_ , eol_)) - if self.ToFirstName is not None: - namespaceprefix_ = self.ToFirstName_nsprefix_ + ':' if (UseCapturedNS_ and self.ToFirstName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToFirstName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToFirstName), input_name='ToFirstName')), namespaceprefix_ , eol_)) - if self.ToLastName is not None: - namespaceprefix_ = self.ToLastName_nsprefix_ + ':' if (UseCapturedNS_ and self.ToLastName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToLastName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToLastName), input_name='ToLastName')), namespaceprefix_ , eol_)) - if self.ToFirm is not None: - namespaceprefix_ = self.ToFirm_nsprefix_ + ':' if (UseCapturedNS_ and self.ToFirm_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToFirm>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToFirm), input_name='ToFirm')), namespaceprefix_ , eol_)) - if self.ToAddress1 is not None: - namespaceprefix_ = self.ToAddress1_nsprefix_ + ':' if (UseCapturedNS_ and self.ToAddress1_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToAddress1>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToAddress1), input_name='ToAddress1')), namespaceprefix_ , eol_)) - if self.ToAddress2 is not None: - namespaceprefix_ = self.ToAddress2_nsprefix_ + ':' if (UseCapturedNS_ and self.ToAddress2_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToAddress2>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToAddress2), input_name='ToAddress2')), namespaceprefix_ , eol_)) - if self.ToAddress3 is not None: - namespaceprefix_ = self.ToAddress3_nsprefix_ + ':' if (UseCapturedNS_ and self.ToAddress3_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToAddress3>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToAddress3), input_name='ToAddress3')), namespaceprefix_ , eol_)) - if self.ToCity is not None: - namespaceprefix_ = self.ToCity_nsprefix_ + ':' if (UseCapturedNS_ and self.ToCity_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToCity), input_name='ToCity')), namespaceprefix_ , eol_)) - if self.ToProvince is not None: - namespaceprefix_ = self.ToProvince_nsprefix_ + ':' if (UseCapturedNS_ and self.ToProvince_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToProvince>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToProvince), input_name='ToProvince')), namespaceprefix_ , eol_)) - if self.ToCountry is not None: - namespaceprefix_ = self.ToCountry_nsprefix_ + ':' if (UseCapturedNS_ and self.ToCountry_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToCountry>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToCountry), input_name='ToCountry')), namespaceprefix_ , eol_)) - if self.ToPostalCode is not None: - namespaceprefix_ = self.ToPostalCode_nsprefix_ + ':' if (UseCapturedNS_ and self.ToPostalCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToPostalCode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToPostalCode), input_name='ToPostalCode')), namespaceprefix_ , eol_)) - if self.ToPOBoxFlag is not None: - namespaceprefix_ = self.ToPOBoxFlag_nsprefix_ + ':' if (UseCapturedNS_ and self.ToPOBoxFlag_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToPOBoxFlag>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToPOBoxFlag), input_name='ToPOBoxFlag')), namespaceprefix_ , eol_)) - if self.ToPhone is not None: - namespaceprefix_ = self.ToPhone_nsprefix_ + ':' if (UseCapturedNS_ and self.ToPhone_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToPhone>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToPhone), input_name='ToPhone')), namespaceprefix_ , eol_)) - if self.ToFax is not None: - namespaceprefix_ = self.ToFax_nsprefix_ + ':' if (UseCapturedNS_ and self.ToFax_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToFax>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToFax), input_name='ToFax')), namespaceprefix_ , eol_)) - if self.ToEmail is not None: - namespaceprefix_ = self.ToEmail_nsprefix_ + ':' if (UseCapturedNS_ and self.ToEmail_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToEmail>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToEmail), input_name='ToEmail')), namespaceprefix_ , eol_)) - if self.ImportersReferenceNumber is not None: - namespaceprefix_ = self.ImportersReferenceNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.ImportersReferenceNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sImportersReferenceNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ImportersReferenceNumber), input_name='ImportersReferenceNumber')), namespaceprefix_ , eol_)) - if self.NonDeliveryOption is not None: - namespaceprefix_ = self.NonDeliveryOption_nsprefix_ + ':' if (UseCapturedNS_ and self.NonDeliveryOption_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sNonDeliveryOption>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.NonDeliveryOption), input_name='NonDeliveryOption')), namespaceprefix_ , eol_)) - if self.RedirectName is not None: - namespaceprefix_ = self.RedirectName_nsprefix_ + ':' if (UseCapturedNS_ and self.RedirectName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRedirectName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.RedirectName), input_name='RedirectName')), namespaceprefix_ , eol_)) - if self.RedirectEmail is not None: - namespaceprefix_ = self.RedirectEmail_nsprefix_ + ':' if (UseCapturedNS_ and self.RedirectEmail_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRedirectEmail>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.RedirectEmail), input_name='RedirectEmail')), namespaceprefix_ , eol_)) - if self.RedirectSMS is not None: - namespaceprefix_ = self.RedirectSMS_nsprefix_ + ':' if (UseCapturedNS_ and self.RedirectSMS_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRedirectSMS>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.RedirectSMS), input_name='RedirectSMS')), namespaceprefix_ , eol_)) - if self.RedirectAddress is not None: - namespaceprefix_ = self.RedirectAddress_nsprefix_ + ':' if (UseCapturedNS_ and self.RedirectAddress_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRedirectAddress>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.RedirectAddress), input_name='RedirectAddress')), namespaceprefix_ , eol_)) - if self.RedirectCity is not None: - namespaceprefix_ = self.RedirectCity_nsprefix_ + ':' if (UseCapturedNS_ and self.RedirectCity_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRedirectCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.RedirectCity), input_name='RedirectCity')), namespaceprefix_ , eol_)) - if self.RedirectState is not None: - namespaceprefix_ = self.RedirectState_nsprefix_ + ':' if (UseCapturedNS_ and self.RedirectState_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRedirectState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.RedirectState), input_name='RedirectState')), namespaceprefix_ , eol_)) - if self.RedirectZipCode is not None: - namespaceprefix_ = self.RedirectZipCode_nsprefix_ + ':' if (UseCapturedNS_ and self.RedirectZipCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRedirectZipCode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.RedirectZipCode), input_name='RedirectZipCode')), namespaceprefix_ , eol_)) - if self.RedirectZip4 is not None: - namespaceprefix_ = self.RedirectZip4_nsprefix_ + ':' if (UseCapturedNS_ and self.RedirectZip4_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRedirectZip4>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.RedirectZip4), input_name='RedirectZip4')), namespaceprefix_ , eol_)) - if self.Container is not None: - namespaceprefix_ = self.Container_nsprefix_ + ':' if (UseCapturedNS_ and self.Container_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sContainer>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Container), input_name='Container')), namespaceprefix_ , eol_)) - if self.ShippingContents is not None: - namespaceprefix_ = self.ShippingContents_nsprefix_ + ':' if (UseCapturedNS_ and self.ShippingContents_nsprefix_) else '' - self.ShippingContents.export(outfile, level, namespaceprefix_, namespacedef_='', name_='ShippingContents', pretty_print=pretty_print) - if self.InsuredNumber is not None: - namespaceprefix_ = self.InsuredNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.InsuredNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sInsuredNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.InsuredNumber), input_name='InsuredNumber')), namespaceprefix_ , eol_)) - if self.InsuredAmount is not None: - namespaceprefix_ = self.InsuredAmount_nsprefix_ + ':' if (UseCapturedNS_ and self.InsuredAmount_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sInsuredAmount>%s%s' % (namespaceprefix_ , self.gds_format_decimal(self.InsuredAmount, input_name='InsuredAmount'), namespaceprefix_ , eol_)) - if self.Postage is not None: - namespaceprefix_ = self.Postage_nsprefix_ + ':' if (UseCapturedNS_ and self.Postage_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPostage>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Postage), input_name='Postage')), namespaceprefix_ , eol_)) - if self.GrossPounds is not None: - namespaceprefix_ = self.GrossPounds_nsprefix_ + ':' if (UseCapturedNS_ and self.GrossPounds_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sGrossPounds>%s%s' % (namespaceprefix_ , self.gds_format_float(self.GrossPounds, input_name='GrossPounds'), namespaceprefix_ , eol_)) - if self.GrossOunces is not None: - namespaceprefix_ = self.GrossOunces_nsprefix_ + ':' if (UseCapturedNS_ and self.GrossOunces_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sGrossOunces>%s%s' % (namespaceprefix_ , self.gds_format_float(self.GrossOunces, input_name='GrossOunces'), namespaceprefix_ , eol_)) - if self.ContentType is not None: - namespaceprefix_ = self.ContentType_nsprefix_ + ':' if (UseCapturedNS_ and self.ContentType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sContentType>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ContentType), input_name='ContentType')), namespaceprefix_ , eol_)) - if self.ContentTypeOther is not None: - namespaceprefix_ = self.ContentTypeOther_nsprefix_ + ':' if (UseCapturedNS_ and self.ContentTypeOther_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sContentTypeOther>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ContentTypeOther), input_name='ContentTypeOther')), namespaceprefix_ , eol_)) - if self.Agreement is not None: - namespaceprefix_ = self.Agreement_nsprefix_ + ':' if (UseCapturedNS_ and self.Agreement_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAgreement>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Agreement), input_name='Agreement')), namespaceprefix_ , eol_)) - if self.Comments is not None: - namespaceprefix_ = self.Comments_nsprefix_ + ':' if (UseCapturedNS_ and self.Comments_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sComments>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Comments), input_name='Comments')), namespaceprefix_ , eol_)) - if self.LicenseNumber is not None: - namespaceprefix_ = self.LicenseNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.LicenseNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sLicenseNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.LicenseNumber), input_name='LicenseNumber')), namespaceprefix_ , eol_)) - if self.CertificateNumber is not None: - namespaceprefix_ = self.CertificateNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.CertificateNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCertificateNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CertificateNumber), input_name='CertificateNumber')), namespaceprefix_ , eol_)) - if self.InvoiceNumber is not None: - namespaceprefix_ = self.InvoiceNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.InvoiceNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sInvoiceNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.InvoiceNumber), input_name='InvoiceNumber')), namespaceprefix_ , eol_)) - if self.ImageType is not None: - namespaceprefix_ = self.ImageType_nsprefix_ + ':' if (UseCapturedNS_ and self.ImageType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sImageType>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ImageType), input_name='ImageType')), namespaceprefix_ , eol_)) - if self.ImageLayout is not None: - namespaceprefix_ = self.ImageLayout_nsprefix_ + ':' if (UseCapturedNS_ and self.ImageLayout_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sImageLayout>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ImageLayout), input_name='ImageLayout')), namespaceprefix_ , eol_)) - if self.CustomerRefNo is not None: - namespaceprefix_ = self.CustomerRefNo_nsprefix_ + ':' if (UseCapturedNS_ and self.CustomerRefNo_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCustomerRefNo>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CustomerRefNo), input_name='CustomerRefNo')), namespaceprefix_ , eol_)) - if self.CustomerRefNo2 is not None: - namespaceprefix_ = self.CustomerRefNo2_nsprefix_ + ':' if (UseCapturedNS_ and self.CustomerRefNo2_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCustomerRefNo2>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CustomerRefNo2), input_name='CustomerRefNo2')), namespaceprefix_ , eol_)) - if self.POZipCode is not None: - namespaceprefix_ = self.POZipCode_nsprefix_ + ':' if (UseCapturedNS_ and self.POZipCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPOZipCode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.POZipCode), input_name='POZipCode')), namespaceprefix_ , eol_)) - if self.LabelDate is not None: - namespaceprefix_ = self.LabelDate_nsprefix_ + ':' if (UseCapturedNS_ and self.LabelDate_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sLabelDate>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.LabelDate), input_name='LabelDate')), namespaceprefix_ , eol_)) - if self.EMCAAccount is not None: - namespaceprefix_ = self.EMCAAccount_nsprefix_ + ':' if (UseCapturedNS_ and self.EMCAAccount_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEMCAAccount>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.EMCAAccount), input_name='EMCAAccount')), namespaceprefix_ , eol_)) - if self.HoldForManifest is not None: - namespaceprefix_ = self.HoldForManifest_nsprefix_ + ':' if (UseCapturedNS_ and self.HoldForManifest_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sHoldForManifest>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.HoldForManifest), input_name='HoldForManifest')), namespaceprefix_ , eol_)) - if self.EELPFC is not None: - namespaceprefix_ = self.EELPFC_nsprefix_ + ':' if (UseCapturedNS_ and self.EELPFC_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEELPFC>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.EELPFC), input_name='EELPFC')), namespaceprefix_ , eol_)) - if self.PriceOptions is not None: - namespaceprefix_ = self.PriceOptions_nsprefix_ + ':' if (UseCapturedNS_ and self.PriceOptions_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPriceOptions>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PriceOptions), input_name='PriceOptions')), namespaceprefix_ , eol_)) - if self.Length is not None: - namespaceprefix_ = self.Length_nsprefix_ + ':' if (UseCapturedNS_ and self.Length_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sLength>%s%s' % (namespaceprefix_ , self.gds_format_float(self.Length, input_name='Length'), namespaceprefix_ , eol_)) - if self.Width is not None: - namespaceprefix_ = self.Width_nsprefix_ + ':' if (UseCapturedNS_ and self.Width_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sWidth>%s%s' % (namespaceprefix_ , self.gds_format_float(self.Width, input_name='Width'), namespaceprefix_ , eol_)) - if self.Height is not None: - namespaceprefix_ = self.Height_nsprefix_ + ':' if (UseCapturedNS_ and self.Height_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sHeight>%s%s' % (namespaceprefix_ , self.gds_format_float(self.Height, input_name='Height'), namespaceprefix_ , eol_)) - if self.Girth is not None: - namespaceprefix_ = self.Girth_nsprefix_ + ':' if (UseCapturedNS_ and self.Girth_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sGirth>%s%s' % (namespaceprefix_ , self.gds_format_float(self.Girth, input_name='Girth'), namespaceprefix_ , eol_)) - if self.LabelTime is not None: - namespaceprefix_ = self.LabelTime_nsprefix_ + ':' if (UseCapturedNS_ and self.LabelTime_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sLabelTime>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.LabelTime), input_name='LabelTime')), namespaceprefix_ , eol_)) - if self.MeterPaymentFlag is not None: - namespaceprefix_ = self.MeterPaymentFlag_nsprefix_ + ':' if (UseCapturedNS_ and self.MeterPaymentFlag_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sMeterPaymentFlag>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.MeterPaymentFlag), input_name='MeterPaymentFlag')), namespaceprefix_ , eol_)) - if self.ActionCode is not None: - namespaceprefix_ = self.ActionCode_nsprefix_ + ':' if (UseCapturedNS_ and self.ActionCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sActionCode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ActionCode), input_name='ActionCode')), namespaceprefix_ , eol_)) - if self.OptOutOfSPE is not None: - namespaceprefix_ = self.OptOutOfSPE_nsprefix_ + ':' if (UseCapturedNS_ and self.OptOutOfSPE_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sOptOutOfSPE>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.OptOutOfSPE, input_name='OptOutOfSPE'), namespaceprefix_ , eol_)) - if self.PermitNumber is not None: - namespaceprefix_ = self.PermitNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.PermitNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPermitNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PermitNumber), input_name='PermitNumber')), namespaceprefix_ , eol_)) - if self.AccountZipCode is not None: - namespaceprefix_ = self.AccountZipCode_nsprefix_ + ':' if (UseCapturedNS_ and self.AccountZipCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAccountZipCode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.AccountZipCode), input_name='AccountZipCode')), namespaceprefix_ , eol_)) - if self.ImportersReferenceType is not None: - namespaceprefix_ = self.ImportersReferenceType_nsprefix_ + ':' if (UseCapturedNS_ and self.ImportersReferenceType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sImportersReferenceType>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ImportersReferenceType), input_name='ImportersReferenceType')), namespaceprefix_ , eol_)) - if self.ImportersTelephoneNumber is not None: - namespaceprefix_ = self.ImportersTelephoneNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.ImportersTelephoneNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sImportersTelephoneNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ImportersTelephoneNumber), input_name='ImportersTelephoneNumber')), namespaceprefix_ , eol_)) - if self.ImportersFaxNumber is not None: - namespaceprefix_ = self.ImportersFaxNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.ImportersFaxNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sImportersFaxNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ImportersFaxNumber), input_name='ImportersFaxNumber')), namespaceprefix_ , eol_)) - if self.ImportersEmail is not None: - namespaceprefix_ = self.ImportersEmail_nsprefix_ + ':' if (UseCapturedNS_ and self.ImportersEmail_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sImportersEmail>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ImportersEmail), input_name='ImportersEmail')), namespaceprefix_ , eol_)) - if self.Machinable is not None: - namespaceprefix_ = self.Machinable_nsprefix_ + ':' if (UseCapturedNS_ and self.Machinable_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sMachinable>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.Machinable, input_name='Machinable'), namespaceprefix_ , eol_)) - if self.DestinationRateIndicator is not None: - namespaceprefix_ = self.DestinationRateIndicator_nsprefix_ + ':' if (UseCapturedNS_ and self.DestinationRateIndicator_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDestinationRateIndicator>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.DestinationRateIndicator), input_name='DestinationRateIndicator')), namespaceprefix_ , eol_)) - if self.MID is not None: - namespaceprefix_ = self.MID_nsprefix_ + ':' if (UseCapturedNS_ and self.MID_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sMID>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.MID), input_name='MID')), namespaceprefix_ , eol_)) - if self.LogisticsManagerMID is not None: - namespaceprefix_ = self.LogisticsManagerMID_nsprefix_ + ':' if (UseCapturedNS_ and self.LogisticsManagerMID_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sLogisticsManagerMID>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.LogisticsManagerMID), input_name='LogisticsManagerMID')), namespaceprefix_ , eol_)) - if self.CRID is not None: - namespaceprefix_ = self.CRID_nsprefix_ + ':' if (UseCapturedNS_ and self.CRID_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCRID>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CRID), input_name='CRID')), namespaceprefix_ , eol_)) - if self.VendorCode is not None: - namespaceprefix_ = self.VendorCode_nsprefix_ + ':' if (UseCapturedNS_ and self.VendorCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sVendorCode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.VendorCode), input_name='VendorCode')), namespaceprefix_ , eol_)) - if self.VendorProductVersionNumber is not None: - namespaceprefix_ = self.VendorProductVersionNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.VendorProductVersionNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sVendorProductVersionNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.VendorProductVersionNumber), input_name='VendorProductVersionNumber')), namespaceprefix_ , eol_)) - if self.ePostageMailerReporting is not None: - namespaceprefix_ = self.ePostageMailerReporting_nsprefix_ + ':' if (UseCapturedNS_ and self.ePostageMailerReporting_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sePostageMailerReporting>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ePostageMailerReporting), input_name='ePostageMailerReporting')), namespaceprefix_ , eol_)) - if self.SenderFirstName is not None: - namespaceprefix_ = self.SenderFirstName_nsprefix_ + ':' if (UseCapturedNS_ and self.SenderFirstName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSenderFirstName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SenderFirstName), input_name='SenderFirstName')), namespaceprefix_ , eol_)) - if self.SenderLastName is not None: - namespaceprefix_ = self.SenderLastName_nsprefix_ + ':' if (UseCapturedNS_ and self.SenderLastName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSenderLastName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SenderLastName), input_name='SenderLastName')), namespaceprefix_ , eol_)) - if self.SenderBusinessName is not None: - namespaceprefix_ = self.SenderBusinessName_nsprefix_ + ':' if (UseCapturedNS_ and self.SenderBusinessName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSenderBusinessName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SenderBusinessName), input_name='SenderBusinessName')), namespaceprefix_ , eol_)) - if self.SenderAddress1 is not None: - namespaceprefix_ = self.SenderAddress1_nsprefix_ + ':' if (UseCapturedNS_ and self.SenderAddress1_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSenderAddress1>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SenderAddress1), input_name='SenderAddress1')), namespaceprefix_ , eol_)) - if self.SenderCity is not None: - namespaceprefix_ = self.SenderCity_nsprefix_ + ':' if (UseCapturedNS_ and self.SenderCity_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSenderCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SenderCity), input_name='SenderCity')), namespaceprefix_ , eol_)) - if self.SenderState is not None: - namespaceprefix_ = self.SenderState_nsprefix_ + ':' if (UseCapturedNS_ and self.SenderState_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSenderState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SenderState), input_name='SenderState')), namespaceprefix_ , eol_)) - if self.SenderZip5 is not None: - namespaceprefix_ = self.SenderZip5_nsprefix_ + ':' if (UseCapturedNS_ and self.SenderZip5_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSenderZip5>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SenderZip5), input_name='SenderZip5')), namespaceprefix_ , eol_)) - if self.SenderPhone is not None: - namespaceprefix_ = self.SenderPhone_nsprefix_ + ':' if (UseCapturedNS_ and self.SenderPhone_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSenderPhone>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SenderPhone), input_name='SenderPhone')), namespaceprefix_ , eol_)) - if self.SenderEmail is not None: - namespaceprefix_ = self.SenderEmail_nsprefix_ + ':' if (UseCapturedNS_ and self.SenderEmail_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSenderEmail>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SenderEmail), input_name='SenderEmail')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('USERID', node) - if value is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - self.USERID = value - value = find_attr_value_('PASSWORD', node) - if value is not None and 'PASSWORD' not in already_processed: - already_processed.add('PASSWORD') - self.PASSWORD = value - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'Option': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Option') - value_ = self.gds_validate_string(value_, node, 'Option') - self.Option = value_ - self.Option_nsprefix_ = child_.prefix - elif nodeName_ == 'Revision': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Revision') - value_ = self.gds_validate_string(value_, node, 'Revision') - self.Revision = value_ - self.Revision_nsprefix_ = child_.prefix - elif nodeName_ == 'ImageParameters': - obj_ = ImageParametersType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.ImageParameters = obj_ - obj_.original_tagname_ = 'ImageParameters' - elif nodeName_ == 'FromFirstName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromFirstName') - value_ = self.gds_validate_string(value_, node, 'FromFirstName') - self.FromFirstName = value_ - self.FromFirstName_nsprefix_ = child_.prefix - elif nodeName_ == 'FromMiddleInitial': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromMiddleInitial') - value_ = self.gds_validate_string(value_, node, 'FromMiddleInitial') - self.FromMiddleInitial = value_ - self.FromMiddleInitial_nsprefix_ = child_.prefix - elif nodeName_ == 'FromLastName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromLastName') - value_ = self.gds_validate_string(value_, node, 'FromLastName') - self.FromLastName = value_ - self.FromLastName_nsprefix_ = child_.prefix - elif nodeName_ == 'FromFirm': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromFirm') - value_ = self.gds_validate_string(value_, node, 'FromFirm') - self.FromFirm = value_ - self.FromFirm_nsprefix_ = child_.prefix - elif nodeName_ == 'FromAddress1': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromAddress1') - value_ = self.gds_validate_string(value_, node, 'FromAddress1') - self.FromAddress1 = value_ - self.FromAddress1_nsprefix_ = child_.prefix - elif nodeName_ == 'FromAddress2': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromAddress2') - value_ = self.gds_validate_string(value_, node, 'FromAddress2') - self.FromAddress2 = value_ - self.FromAddress2_nsprefix_ = child_.prefix - elif nodeName_ == 'FromUrbanization': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromUrbanization') - value_ = self.gds_validate_string(value_, node, 'FromUrbanization') - self.FromUrbanization = value_ - self.FromUrbanization_nsprefix_ = child_.prefix - elif nodeName_ == 'FromCity': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromCity') - value_ = self.gds_validate_string(value_, node, 'FromCity') - self.FromCity = value_ - self.FromCity_nsprefix_ = child_.prefix - elif nodeName_ == 'FromState': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromState') - value_ = self.gds_validate_string(value_, node, 'FromState') - self.FromState = value_ - self.FromState_nsprefix_ = child_.prefix - elif nodeName_ == 'FromZip5': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromZip5') - value_ = self.gds_validate_string(value_, node, 'FromZip5') - self.FromZip5 = value_ - self.FromZip5_nsprefix_ = child_.prefix - elif nodeName_ == 'FromZip4': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromZip4') - value_ = self.gds_validate_string(value_, node, 'FromZip4') - self.FromZip4 = value_ - self.FromZip4_nsprefix_ = child_.prefix - elif nodeName_ == 'FromPhone': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromPhone') - value_ = self.gds_validate_string(value_, node, 'FromPhone') - self.FromPhone = value_ - self.FromPhone_nsprefix_ = child_.prefix - elif nodeName_ == 'FromCustomsReference': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromCustomsReference') - value_ = self.gds_validate_string(value_, node, 'FromCustomsReference') - self.FromCustomsReference = value_ - self.FromCustomsReference_nsprefix_ = child_.prefix - elif nodeName_ == 'ToName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToName') - value_ = self.gds_validate_string(value_, node, 'ToName') - self.ToName = value_ - self.ToName_nsprefix_ = child_.prefix - elif nodeName_ == 'ToFirstName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToFirstName') - value_ = self.gds_validate_string(value_, node, 'ToFirstName') - self.ToFirstName = value_ - self.ToFirstName_nsprefix_ = child_.prefix - elif nodeName_ == 'ToLastName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToLastName') - value_ = self.gds_validate_string(value_, node, 'ToLastName') - self.ToLastName = value_ - self.ToLastName_nsprefix_ = child_.prefix - elif nodeName_ == 'ToFirm': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToFirm') - value_ = self.gds_validate_string(value_, node, 'ToFirm') - self.ToFirm = value_ - self.ToFirm_nsprefix_ = child_.prefix - elif nodeName_ == 'ToAddress1': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToAddress1') - value_ = self.gds_validate_string(value_, node, 'ToAddress1') - self.ToAddress1 = value_ - self.ToAddress1_nsprefix_ = child_.prefix - elif nodeName_ == 'ToAddress2': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToAddress2') - value_ = self.gds_validate_string(value_, node, 'ToAddress2') - self.ToAddress2 = value_ - self.ToAddress2_nsprefix_ = child_.prefix - elif nodeName_ == 'ToAddress3': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToAddress3') - value_ = self.gds_validate_string(value_, node, 'ToAddress3') - self.ToAddress3 = value_ - self.ToAddress3_nsprefix_ = child_.prefix - elif nodeName_ == 'ToCity': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToCity') - value_ = self.gds_validate_string(value_, node, 'ToCity') - self.ToCity = value_ - self.ToCity_nsprefix_ = child_.prefix - elif nodeName_ == 'ToProvince': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToProvince') - value_ = self.gds_validate_string(value_, node, 'ToProvince') - self.ToProvince = value_ - self.ToProvince_nsprefix_ = child_.prefix - elif nodeName_ == 'ToCountry': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToCountry') - value_ = self.gds_validate_string(value_, node, 'ToCountry') - self.ToCountry = value_ - self.ToCountry_nsprefix_ = child_.prefix - elif nodeName_ == 'ToPostalCode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToPostalCode') - value_ = self.gds_validate_string(value_, node, 'ToPostalCode') - self.ToPostalCode = value_ - self.ToPostalCode_nsprefix_ = child_.prefix - elif nodeName_ == 'ToPOBoxFlag': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToPOBoxFlag') - value_ = self.gds_validate_string(value_, node, 'ToPOBoxFlag') - self.ToPOBoxFlag = value_ - self.ToPOBoxFlag_nsprefix_ = child_.prefix - elif nodeName_ == 'ToPhone': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToPhone') - value_ = self.gds_validate_string(value_, node, 'ToPhone') - self.ToPhone = value_ - self.ToPhone_nsprefix_ = child_.prefix - elif nodeName_ == 'ToFax': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToFax') - value_ = self.gds_validate_string(value_, node, 'ToFax') - self.ToFax = value_ - self.ToFax_nsprefix_ = child_.prefix - elif nodeName_ == 'ToEmail': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToEmail') - value_ = self.gds_validate_string(value_, node, 'ToEmail') - self.ToEmail = value_ - self.ToEmail_nsprefix_ = child_.prefix - elif nodeName_ == 'ImportersReferenceNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ImportersReferenceNumber') - value_ = self.gds_validate_string(value_, node, 'ImportersReferenceNumber') - self.ImportersReferenceNumber = value_ - self.ImportersReferenceNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'NonDeliveryOption': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'NonDeliveryOption') - value_ = self.gds_validate_string(value_, node, 'NonDeliveryOption') - self.NonDeliveryOption = value_ - self.NonDeliveryOption_nsprefix_ = child_.prefix - elif nodeName_ == 'RedirectName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'RedirectName') - value_ = self.gds_validate_string(value_, node, 'RedirectName') - self.RedirectName = value_ - self.RedirectName_nsprefix_ = child_.prefix - elif nodeName_ == 'RedirectEmail': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'RedirectEmail') - value_ = self.gds_validate_string(value_, node, 'RedirectEmail') - self.RedirectEmail = value_ - self.RedirectEmail_nsprefix_ = child_.prefix - elif nodeName_ == 'RedirectSMS': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'RedirectSMS') - value_ = self.gds_validate_string(value_, node, 'RedirectSMS') - self.RedirectSMS = value_ - self.RedirectSMS_nsprefix_ = child_.prefix - elif nodeName_ == 'RedirectAddress': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'RedirectAddress') - value_ = self.gds_validate_string(value_, node, 'RedirectAddress') - self.RedirectAddress = value_ - self.RedirectAddress_nsprefix_ = child_.prefix - elif nodeName_ == 'RedirectCity': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'RedirectCity') - value_ = self.gds_validate_string(value_, node, 'RedirectCity') - self.RedirectCity = value_ - self.RedirectCity_nsprefix_ = child_.prefix - elif nodeName_ == 'RedirectState': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'RedirectState') - value_ = self.gds_validate_string(value_, node, 'RedirectState') - self.RedirectState = value_ - self.RedirectState_nsprefix_ = child_.prefix - elif nodeName_ == 'RedirectZipCode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'RedirectZipCode') - value_ = self.gds_validate_string(value_, node, 'RedirectZipCode') - self.RedirectZipCode = value_ - self.RedirectZipCode_nsprefix_ = child_.prefix - elif nodeName_ == 'RedirectZip4': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'RedirectZip4') - value_ = self.gds_validate_string(value_, node, 'RedirectZip4') - self.RedirectZip4 = value_ - self.RedirectZip4_nsprefix_ = child_.prefix - elif nodeName_ == 'Container': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Container') - value_ = self.gds_validate_string(value_, node, 'Container') - self.Container = value_ - self.Container_nsprefix_ = child_.prefix - elif nodeName_ == 'ShippingContents': - obj_ = ShippingContentsType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.ShippingContents = obj_ - obj_.original_tagname_ = 'ShippingContents' - elif nodeName_ == 'InsuredNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'InsuredNumber') - value_ = self.gds_validate_string(value_, node, 'InsuredNumber') - self.InsuredNumber = value_ - self.InsuredNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'InsuredAmount' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_decimal(sval_, node, 'InsuredAmount') - fval_ = self.gds_validate_decimal(fval_, node, 'InsuredAmount') - self.InsuredAmount = fval_ - self.InsuredAmount_nsprefix_ = child_.prefix - elif nodeName_ == 'Postage': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Postage') - value_ = self.gds_validate_string(value_, node, 'Postage') - self.Postage = value_ - self.Postage_nsprefix_ = child_.prefix - elif nodeName_ == 'GrossPounds' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'GrossPounds') - fval_ = self.gds_validate_float(fval_, node, 'GrossPounds') - self.GrossPounds = fval_ - self.GrossPounds_nsprefix_ = child_.prefix - elif nodeName_ == 'GrossOunces' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'GrossOunces') - fval_ = self.gds_validate_float(fval_, node, 'GrossOunces') - self.GrossOunces = fval_ - self.GrossOunces_nsprefix_ = child_.prefix - elif nodeName_ == 'ContentType': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ContentType') - value_ = self.gds_validate_string(value_, node, 'ContentType') - self.ContentType = value_ - self.ContentType_nsprefix_ = child_.prefix - elif nodeName_ == 'ContentTypeOther': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ContentTypeOther') - value_ = self.gds_validate_string(value_, node, 'ContentTypeOther') - self.ContentTypeOther = value_ - self.ContentTypeOther_nsprefix_ = child_.prefix - elif nodeName_ == 'Agreement': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Agreement') - value_ = self.gds_validate_string(value_, node, 'Agreement') - self.Agreement = value_ - self.Agreement_nsprefix_ = child_.prefix - elif nodeName_ == 'Comments': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Comments') - value_ = self.gds_validate_string(value_, node, 'Comments') - self.Comments = value_ - self.Comments_nsprefix_ = child_.prefix - elif nodeName_ == 'LicenseNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'LicenseNumber') - value_ = self.gds_validate_string(value_, node, 'LicenseNumber') - self.LicenseNumber = value_ - self.LicenseNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'CertificateNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CertificateNumber') - value_ = self.gds_validate_string(value_, node, 'CertificateNumber') - self.CertificateNumber = value_ - self.CertificateNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'InvoiceNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'InvoiceNumber') - value_ = self.gds_validate_string(value_, node, 'InvoiceNumber') - self.InvoiceNumber = value_ - self.InvoiceNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'ImageType': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ImageType') - value_ = self.gds_validate_string(value_, node, 'ImageType') - self.ImageType = value_ - self.ImageType_nsprefix_ = child_.prefix - elif nodeName_ == 'ImageLayout': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ImageLayout') - value_ = self.gds_validate_string(value_, node, 'ImageLayout') - self.ImageLayout = value_ - self.ImageLayout_nsprefix_ = child_.prefix - elif nodeName_ == 'CustomerRefNo': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CustomerRefNo') - value_ = self.gds_validate_string(value_, node, 'CustomerRefNo') - self.CustomerRefNo = value_ - self.CustomerRefNo_nsprefix_ = child_.prefix - elif nodeName_ == 'CustomerRefNo2': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CustomerRefNo2') - value_ = self.gds_validate_string(value_, node, 'CustomerRefNo2') - self.CustomerRefNo2 = value_ - self.CustomerRefNo2_nsprefix_ = child_.prefix - elif nodeName_ == 'POZipCode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'POZipCode') - value_ = self.gds_validate_string(value_, node, 'POZipCode') - self.POZipCode = value_ - self.POZipCode_nsprefix_ = child_.prefix - elif nodeName_ == 'LabelDate': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'LabelDate') - value_ = self.gds_validate_string(value_, node, 'LabelDate') - self.LabelDate = value_ - self.LabelDate_nsprefix_ = child_.prefix - elif nodeName_ == 'EMCAAccount': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'EMCAAccount') - value_ = self.gds_validate_string(value_, node, 'EMCAAccount') - self.EMCAAccount = value_ - self.EMCAAccount_nsprefix_ = child_.prefix - elif nodeName_ == 'HoldForManifest': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'HoldForManifest') - value_ = self.gds_validate_string(value_, node, 'HoldForManifest') - self.HoldForManifest = value_ - self.HoldForManifest_nsprefix_ = child_.prefix - elif nodeName_ == 'EELPFC': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'EELPFC') - value_ = self.gds_validate_string(value_, node, 'EELPFC') - self.EELPFC = value_ - self.EELPFC_nsprefix_ = child_.prefix - elif nodeName_ == 'PriceOptions': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PriceOptions') - value_ = self.gds_validate_string(value_, node, 'PriceOptions') - self.PriceOptions = value_ - self.PriceOptions_nsprefix_ = child_.prefix - elif nodeName_ == 'Length' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'Length') - fval_ = self.gds_validate_float(fval_, node, 'Length') - self.Length = fval_ - self.Length_nsprefix_ = child_.prefix - elif nodeName_ == 'Width' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'Width') - fval_ = self.gds_validate_float(fval_, node, 'Width') - self.Width = fval_ - self.Width_nsprefix_ = child_.prefix - elif nodeName_ == 'Height' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'Height') - fval_ = self.gds_validate_float(fval_, node, 'Height') - self.Height = fval_ - self.Height_nsprefix_ = child_.prefix - elif nodeName_ == 'Girth' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'Girth') - fval_ = self.gds_validate_float(fval_, node, 'Girth') - self.Girth = fval_ - self.Girth_nsprefix_ = child_.prefix - elif nodeName_ == 'LabelTime': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'LabelTime') - value_ = self.gds_validate_string(value_, node, 'LabelTime') - self.LabelTime = value_ - self.LabelTime_nsprefix_ = child_.prefix - elif nodeName_ == 'MeterPaymentFlag': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'MeterPaymentFlag') - value_ = self.gds_validate_string(value_, node, 'MeterPaymentFlag') - self.MeterPaymentFlag = value_ - self.MeterPaymentFlag_nsprefix_ = child_.prefix - elif nodeName_ == 'ActionCode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ActionCode') - value_ = self.gds_validate_string(value_, node, 'ActionCode') - self.ActionCode = value_ - self.ActionCode_nsprefix_ = child_.prefix - elif nodeName_ == 'OptOutOfSPE': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'OptOutOfSPE') - ival_ = self.gds_validate_boolean(ival_, node, 'OptOutOfSPE') - self.OptOutOfSPE = ival_ - self.OptOutOfSPE_nsprefix_ = child_.prefix - elif nodeName_ == 'PermitNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PermitNumber') - value_ = self.gds_validate_string(value_, node, 'PermitNumber') - self.PermitNumber = value_ - self.PermitNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'AccountZipCode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'AccountZipCode') - value_ = self.gds_validate_string(value_, node, 'AccountZipCode') - self.AccountZipCode = value_ - self.AccountZipCode_nsprefix_ = child_.prefix - elif nodeName_ == 'ImportersReferenceType': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ImportersReferenceType') - value_ = self.gds_validate_string(value_, node, 'ImportersReferenceType') - self.ImportersReferenceType = value_ - self.ImportersReferenceType_nsprefix_ = child_.prefix - elif nodeName_ == 'ImportersTelephoneNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ImportersTelephoneNumber') - value_ = self.gds_validate_string(value_, node, 'ImportersTelephoneNumber') - self.ImportersTelephoneNumber = value_ - self.ImportersTelephoneNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'ImportersFaxNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ImportersFaxNumber') - value_ = self.gds_validate_string(value_, node, 'ImportersFaxNumber') - self.ImportersFaxNumber = value_ - self.ImportersFaxNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'ImportersEmail': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ImportersEmail') - value_ = self.gds_validate_string(value_, node, 'ImportersEmail') - self.ImportersEmail = value_ - self.ImportersEmail_nsprefix_ = child_.prefix - elif nodeName_ == 'Machinable': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'Machinable') - ival_ = self.gds_validate_boolean(ival_, node, 'Machinable') - self.Machinable = ival_ - self.Machinable_nsprefix_ = child_.prefix - elif nodeName_ == 'DestinationRateIndicator': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'DestinationRateIndicator') - value_ = self.gds_validate_string(value_, node, 'DestinationRateIndicator') - self.DestinationRateIndicator = value_ - self.DestinationRateIndicator_nsprefix_ = child_.prefix - elif nodeName_ == 'MID': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'MID') - value_ = self.gds_validate_string(value_, node, 'MID') - self.MID = value_ - self.MID_nsprefix_ = child_.prefix - elif nodeName_ == 'LogisticsManagerMID': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'LogisticsManagerMID') - value_ = self.gds_validate_string(value_, node, 'LogisticsManagerMID') - self.LogisticsManagerMID = value_ - self.LogisticsManagerMID_nsprefix_ = child_.prefix - elif nodeName_ == 'CRID': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CRID') - value_ = self.gds_validate_string(value_, node, 'CRID') - self.CRID = value_ - self.CRID_nsprefix_ = child_.prefix - elif nodeName_ == 'VendorCode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'VendorCode') - value_ = self.gds_validate_string(value_, node, 'VendorCode') - self.VendorCode = value_ - self.VendorCode_nsprefix_ = child_.prefix - elif nodeName_ == 'VendorProductVersionNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'VendorProductVersionNumber') - value_ = self.gds_validate_string(value_, node, 'VendorProductVersionNumber') - self.VendorProductVersionNumber = value_ - self.VendorProductVersionNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'ePostageMailerReporting': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ePostageMailerReporting') - value_ = self.gds_validate_string(value_, node, 'ePostageMailerReporting') - self.ePostageMailerReporting = value_ - self.ePostageMailerReporting_nsprefix_ = child_.prefix - elif nodeName_ == 'SenderFirstName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SenderFirstName') - value_ = self.gds_validate_string(value_, node, 'SenderFirstName') - self.SenderFirstName = value_ - self.SenderFirstName_nsprefix_ = child_.prefix - elif nodeName_ == 'SenderLastName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SenderLastName') - value_ = self.gds_validate_string(value_, node, 'SenderLastName') - self.SenderLastName = value_ - self.SenderLastName_nsprefix_ = child_.prefix - elif nodeName_ == 'SenderBusinessName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SenderBusinessName') - value_ = self.gds_validate_string(value_, node, 'SenderBusinessName') - self.SenderBusinessName = value_ - self.SenderBusinessName_nsprefix_ = child_.prefix - elif nodeName_ == 'SenderAddress1': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SenderAddress1') - value_ = self.gds_validate_string(value_, node, 'SenderAddress1') - self.SenderAddress1 = value_ - self.SenderAddress1_nsprefix_ = child_.prefix - elif nodeName_ == 'SenderCity': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SenderCity') - value_ = self.gds_validate_string(value_, node, 'SenderCity') - self.SenderCity = value_ - self.SenderCity_nsprefix_ = child_.prefix - elif nodeName_ == 'SenderState': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SenderState') - value_ = self.gds_validate_string(value_, node, 'SenderState') - self.SenderState = value_ - self.SenderState_nsprefix_ = child_.prefix - elif nodeName_ == 'SenderZip5': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SenderZip5') - value_ = self.gds_validate_string(value_, node, 'SenderZip5') - self.SenderZip5 = value_ - self.SenderZip5_nsprefix_ = child_.prefix - elif nodeName_ == 'SenderPhone': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SenderPhone') - value_ = self.gds_validate_string(value_, node, 'SenderPhone') - self.SenderPhone = value_ - self.SenderPhone_nsprefix_ = child_.prefix - elif nodeName_ == 'SenderEmail': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SenderEmail') - value_ = self.gds_validate_string(value_, node, 'SenderEmail') - self.SenderEmail = value_ - self.SenderEmail_nsprefix_ = child_.prefix -# end class eVSExpressMailIntlRequest - - -class ImageParametersType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ImageParameter=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.ImageParameter = ImageParameter - self.ImageParameter_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, ImageParametersType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if ImageParametersType.subclass: - return ImageParametersType.subclass(*args_, **kwargs_) - else: - return ImageParametersType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_ImageParameter(self): - return self.ImageParameter - def set_ImageParameter(self, ImageParameter): - self.ImageParameter = ImageParameter - def _hasContent(self): - if ( - self.ImageParameter is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ImageParametersType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('ImageParametersType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'ImageParametersType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='ImageParametersType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='ImageParametersType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='ImageParametersType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ImageParametersType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.ImageParameter is not None: - namespaceprefix_ = self.ImageParameter_nsprefix_ + ':' if (UseCapturedNS_ and self.ImageParameter_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sImageParameter>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ImageParameter), input_name='ImageParameter')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'ImageParameter': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ImageParameter') - value_ = self.gds_validate_string(value_, node, 'ImageParameter') - self.ImageParameter = value_ - self.ImageParameter_nsprefix_ = child_.prefix -# end class ImageParametersType - - -class ShippingContentsType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ItemDetail=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - if ItemDetail is None: - self.ItemDetail = [] - else: - self.ItemDetail = ItemDetail - self.ItemDetail_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, ShippingContentsType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if ShippingContentsType.subclass: - return ShippingContentsType.subclass(*args_, **kwargs_) - else: - return ShippingContentsType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_ItemDetail(self): - return self.ItemDetail - def set_ItemDetail(self, ItemDetail): - self.ItemDetail = ItemDetail - def add_ItemDetail(self, value): - self.ItemDetail.append(value) - def insert_ItemDetail_at(self, index, value): - self.ItemDetail.insert(index, value) - def replace_ItemDetail_at(self, index, value): - self.ItemDetail[index] = value - def _hasContent(self): - if ( - self.ItemDetail - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ShippingContentsType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('ShippingContentsType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'ShippingContentsType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='ShippingContentsType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='ShippingContentsType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='ShippingContentsType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ShippingContentsType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - for ItemDetail_ in self.ItemDetail: - namespaceprefix_ = self.ItemDetail_nsprefix_ + ':' if (UseCapturedNS_ and self.ItemDetail_nsprefix_) else '' - ItemDetail_.export(outfile, level, namespaceprefix_, namespacedef_='', name_='ItemDetail', pretty_print=pretty_print) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'ItemDetail': - obj_ = ItemDetailType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.ItemDetail.append(obj_) - obj_.original_tagname_ = 'ItemDetail' -# end class ShippingContentsType - - -class ItemDetailType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, Description=None, Quantity=None, Value=None, NetPounds=None, NetOunces=None, HSTariffNumber=None, CountryOfOrigin=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.Description = Description - self.Description_nsprefix_ = None - self.Quantity = Quantity - self.Quantity_nsprefix_ = None - self.Value = Value - self.Value_nsprefix_ = None - self.NetPounds = NetPounds - self.NetPounds_nsprefix_ = None - self.NetOunces = NetOunces - self.NetOunces_nsprefix_ = None - self.HSTariffNumber = HSTariffNumber - self.HSTariffNumber_nsprefix_ = None - self.CountryOfOrigin = CountryOfOrigin - self.CountryOfOrigin_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, ItemDetailType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if ItemDetailType.subclass: - return ItemDetailType.subclass(*args_, **kwargs_) - else: - return ItemDetailType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_Description(self): - return self.Description - def set_Description(self, Description): - self.Description = Description - def get_Quantity(self): - return self.Quantity - def set_Quantity(self, Quantity): - self.Quantity = Quantity - def get_Value(self): - return self.Value - def set_Value(self, Value): - self.Value = Value - def get_NetPounds(self): - return self.NetPounds - def set_NetPounds(self, NetPounds): - self.NetPounds = NetPounds - def get_NetOunces(self): - return self.NetOunces - def set_NetOunces(self, NetOunces): - self.NetOunces = NetOunces - def get_HSTariffNumber(self): - return self.HSTariffNumber - def set_HSTariffNumber(self, HSTariffNumber): - self.HSTariffNumber = HSTariffNumber - def get_CountryOfOrigin(self): - return self.CountryOfOrigin - def set_CountryOfOrigin(self, CountryOfOrigin): - self.CountryOfOrigin = CountryOfOrigin - def _hasContent(self): - if ( - self.Description is not None or - self.Quantity is not None or - self.Value is not None or - self.NetPounds is not None or - self.NetOunces is not None or - self.HSTariffNumber is not None or - self.CountryOfOrigin is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ItemDetailType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('ItemDetailType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'ItemDetailType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='ItemDetailType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='ItemDetailType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='ItemDetailType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ItemDetailType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.Description is not None: - namespaceprefix_ = self.Description_nsprefix_ + ':' if (UseCapturedNS_ and self.Description_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDescription>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Description), input_name='Description')), namespaceprefix_ , eol_)) - if self.Quantity is not None: - namespaceprefix_ = self.Quantity_nsprefix_ + ':' if (UseCapturedNS_ and self.Quantity_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sQuantity>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.Quantity, input_name='Quantity'), namespaceprefix_ , eol_)) - if self.Value is not None: - namespaceprefix_ = self.Value_nsprefix_ + ':' if (UseCapturedNS_ and self.Value_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sValue>%s%s' % (namespaceprefix_ , self.gds_format_float(self.Value, input_name='Value'), namespaceprefix_ , eol_)) - if self.NetPounds is not None: - namespaceprefix_ = self.NetPounds_nsprefix_ + ':' if (UseCapturedNS_ and self.NetPounds_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sNetPounds>%s%s' % (namespaceprefix_ , self.gds_format_float(self.NetPounds, input_name='NetPounds'), namespaceprefix_ , eol_)) - if self.NetOunces is not None: - namespaceprefix_ = self.NetOunces_nsprefix_ + ':' if (UseCapturedNS_ and self.NetOunces_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sNetOunces>%s%s' % (namespaceprefix_ , self.gds_format_float(self.NetOunces, input_name='NetOunces'), namespaceprefix_ , eol_)) - if self.HSTariffNumber is not None: - namespaceprefix_ = self.HSTariffNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.HSTariffNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sHSTariffNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.HSTariffNumber), input_name='HSTariffNumber')), namespaceprefix_ , eol_)) - if self.CountryOfOrigin is not None: - namespaceprefix_ = self.CountryOfOrigin_nsprefix_ + ':' if (UseCapturedNS_ and self.CountryOfOrigin_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCountryOfOrigin>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CountryOfOrigin), input_name='CountryOfOrigin')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'Description': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Description') - value_ = self.gds_validate_string(value_, node, 'Description') - self.Description = value_ - self.Description_nsprefix_ = child_.prefix - elif nodeName_ == 'Quantity' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'Quantity') - ival_ = self.gds_validate_integer(ival_, node, 'Quantity') - self.Quantity = ival_ - self.Quantity_nsprefix_ = child_.prefix - elif nodeName_ == 'Value' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'Value') - fval_ = self.gds_validate_float(fval_, node, 'Value') - self.Value = fval_ - self.Value_nsprefix_ = child_.prefix - elif nodeName_ == 'NetPounds' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'NetPounds') - fval_ = self.gds_validate_float(fval_, node, 'NetPounds') - self.NetPounds = fval_ - self.NetPounds_nsprefix_ = child_.prefix - elif nodeName_ == 'NetOunces' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'NetOunces') - fval_ = self.gds_validate_float(fval_, node, 'NetOunces') - self.NetOunces = fval_ - self.NetOunces_nsprefix_ = child_.prefix - elif nodeName_ == 'HSTariffNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'HSTariffNumber') - value_ = self.gds_validate_string(value_, node, 'HSTariffNumber') - self.HSTariffNumber = value_ - self.HSTariffNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'CountryOfOrigin': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CountryOfOrigin') - value_ = self.gds_validate_string(value_, node, 'CountryOfOrigin') - self.CountryOfOrigin = value_ - self.CountryOfOrigin_nsprefix_ = child_.prefix -# end class ItemDetailType - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSExpressMailIntlRequest' - rootClass = eVSExpressMailIntlRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSExpressMailIntlRequest' - rootClass = eVSExpressMailIntlRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSExpressMailIntlRequest' - rootClass = eVSExpressMailIntlRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSExpressMailIntlRequest' - rootClass = eVSExpressMailIntlRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from evs_express_mail_intl_request import *\n\n') - sys.stdout.write('import evs_express_mail_intl_request as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "ImageParametersType", - "ItemDetailType", - "ShippingContentsType", - "eVSExpressMailIntlRequest" -] diff --git a/schemas/usps/karrio/schemas/usps/evs_express_mail_intl_response.py b/schemas/usps/karrio/schemas/usps/evs_express_mail_intl_response.py deleted file mode 100644 index 3ff0580772..0000000000 --- a/schemas/usps/karrio/schemas/usps/evs_express_mail_intl_response.py +++ /dev/null @@ -1,1589 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:14 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/evs_express_mail_intl_response.py') -# -# Command line arguments: -# ./schemas/eVSExpressMailIntlResponse.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/evs_express_mail_intl_response.py" ./schemas/eVSExpressMailIntlResponse.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class eVSExpressMailIntlResponse(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, Postage=None, TotalValue=None, SDRValue=None, BarcodeNumber=None, LabelImage=None, Page2Image=None, Page3Image=None, Page4Image=None, Page5Image=None, Page6Image=None, Prohibitions=None, Restrictions=None, Observations=None, Regulations=None, AdditionalRestrictions=None, InsuranceFee=None, GuaranteeAvailability=None, RemainingBarcodes=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.Postage = Postage - self.Postage_nsprefix_ = None - self.TotalValue = TotalValue - self.TotalValue_nsprefix_ = None - self.SDRValue = SDRValue - self.SDRValue_nsprefix_ = None - self.BarcodeNumber = BarcodeNumber - self.BarcodeNumber_nsprefix_ = None - self.LabelImage = LabelImage - self.LabelImage_nsprefix_ = None - self.Page2Image = Page2Image - self.Page2Image_nsprefix_ = None - self.Page3Image = Page3Image - self.Page3Image_nsprefix_ = None - self.Page4Image = Page4Image - self.Page4Image_nsprefix_ = None - self.Page5Image = Page5Image - self.Page5Image_nsprefix_ = None - self.Page6Image = Page6Image - self.Page6Image_nsprefix_ = None - self.Prohibitions = Prohibitions - self.Prohibitions_nsprefix_ = None - self.Restrictions = Restrictions - self.Restrictions_nsprefix_ = None - self.Observations = Observations - self.Observations_nsprefix_ = None - self.Regulations = Regulations - self.Regulations_nsprefix_ = None - self.AdditionalRestrictions = AdditionalRestrictions - self.AdditionalRestrictions_nsprefix_ = None - self.InsuranceFee = InsuranceFee - self.InsuranceFee_nsprefix_ = None - self.GuaranteeAvailability = GuaranteeAvailability - self.GuaranteeAvailability_nsprefix_ = None - self.RemainingBarcodes = RemainingBarcodes - self.RemainingBarcodes_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, eVSExpressMailIntlResponse) - if subclass is not None: - return subclass(*args_, **kwargs_) - if eVSExpressMailIntlResponse.subclass: - return eVSExpressMailIntlResponse.subclass(*args_, **kwargs_) - else: - return eVSExpressMailIntlResponse(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_Postage(self): - return self.Postage - def set_Postage(self, Postage): - self.Postage = Postage - def get_TotalValue(self): - return self.TotalValue - def set_TotalValue(self, TotalValue): - self.TotalValue = TotalValue - def get_SDRValue(self): - return self.SDRValue - def set_SDRValue(self, SDRValue): - self.SDRValue = SDRValue - def get_BarcodeNumber(self): - return self.BarcodeNumber - def set_BarcodeNumber(self, BarcodeNumber): - self.BarcodeNumber = BarcodeNumber - def get_LabelImage(self): - return self.LabelImage - def set_LabelImage(self, LabelImage): - self.LabelImage = LabelImage - def get_Page2Image(self): - return self.Page2Image - def set_Page2Image(self, Page2Image): - self.Page2Image = Page2Image - def get_Page3Image(self): - return self.Page3Image - def set_Page3Image(self, Page3Image): - self.Page3Image = Page3Image - def get_Page4Image(self): - return self.Page4Image - def set_Page4Image(self, Page4Image): - self.Page4Image = Page4Image - def get_Page5Image(self): - return self.Page5Image - def set_Page5Image(self, Page5Image): - self.Page5Image = Page5Image - def get_Page6Image(self): - return self.Page6Image - def set_Page6Image(self, Page6Image): - self.Page6Image = Page6Image - def get_Prohibitions(self): - return self.Prohibitions - def set_Prohibitions(self, Prohibitions): - self.Prohibitions = Prohibitions - def get_Restrictions(self): - return self.Restrictions - def set_Restrictions(self, Restrictions): - self.Restrictions = Restrictions - def get_Observations(self): - return self.Observations - def set_Observations(self, Observations): - self.Observations = Observations - def get_Regulations(self): - return self.Regulations - def set_Regulations(self, Regulations): - self.Regulations = Regulations - def get_AdditionalRestrictions(self): - return self.AdditionalRestrictions - def set_AdditionalRestrictions(self, AdditionalRestrictions): - self.AdditionalRestrictions = AdditionalRestrictions - def get_InsuranceFee(self): - return self.InsuranceFee - def set_InsuranceFee(self, InsuranceFee): - self.InsuranceFee = InsuranceFee - def get_GuaranteeAvailability(self): - return self.GuaranteeAvailability - def set_GuaranteeAvailability(self, GuaranteeAvailability): - self.GuaranteeAvailability = GuaranteeAvailability - def get_RemainingBarcodes(self): - return self.RemainingBarcodes - def set_RemainingBarcodes(self, RemainingBarcodes): - self.RemainingBarcodes = RemainingBarcodes - def _hasContent(self): - if ( - self.Postage is not None or - self.TotalValue is not None or - self.SDRValue is not None or - self.BarcodeNumber is not None or - self.LabelImage is not None or - self.Page2Image is not None or - self.Page3Image is not None or - self.Page4Image is not None or - self.Page5Image is not None or - self.Page6Image is not None or - self.Prohibitions is not None or - self.Restrictions is not None or - self.Observations is not None or - self.Regulations is not None or - self.AdditionalRestrictions is not None or - self.InsuranceFee is not None or - self.GuaranteeAvailability is not None or - self.RemainingBarcodes is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='eVSExpressMailIntlResponse', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('eVSExpressMailIntlResponse') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'eVSExpressMailIntlResponse': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='eVSExpressMailIntlResponse') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='eVSExpressMailIntlResponse', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='eVSExpressMailIntlResponse'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='eVSExpressMailIntlResponse', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.Postage is not None: - namespaceprefix_ = self.Postage_nsprefix_ + ':' if (UseCapturedNS_ and self.Postage_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPostage>%s%s' % (namespaceprefix_ , self.gds_format_float(self.Postage, input_name='Postage'), namespaceprefix_ , eol_)) - if self.TotalValue is not None: - namespaceprefix_ = self.TotalValue_nsprefix_ + ':' if (UseCapturedNS_ and self.TotalValue_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sTotalValue>%s%s' % (namespaceprefix_ , self.gds_format_float(self.TotalValue, input_name='TotalValue'), namespaceprefix_ , eol_)) - if self.SDRValue is not None: - namespaceprefix_ = self.SDRValue_nsprefix_ + ':' if (UseCapturedNS_ and self.SDRValue_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSDRValue>%s%s' % (namespaceprefix_ , self.gds_format_float(self.SDRValue, input_name='SDRValue'), namespaceprefix_ , eol_)) - if self.BarcodeNumber is not None: - namespaceprefix_ = self.BarcodeNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.BarcodeNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sBarcodeNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.BarcodeNumber), input_name='BarcodeNumber')), namespaceprefix_ , eol_)) - if self.LabelImage is not None: - namespaceprefix_ = self.LabelImage_nsprefix_ + ':' if (UseCapturedNS_ and self.LabelImage_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sLabelImage>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.LabelImage), input_name='LabelImage')), namespaceprefix_ , eol_)) - if self.Page2Image is not None: - namespaceprefix_ = self.Page2Image_nsprefix_ + ':' if (UseCapturedNS_ and self.Page2Image_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPage2Image>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Page2Image), input_name='Page2Image')), namespaceprefix_ , eol_)) - if self.Page3Image is not None: - namespaceprefix_ = self.Page3Image_nsprefix_ + ':' if (UseCapturedNS_ and self.Page3Image_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPage3Image>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Page3Image), input_name='Page3Image')), namespaceprefix_ , eol_)) - if self.Page4Image is not None: - namespaceprefix_ = self.Page4Image_nsprefix_ + ':' if (UseCapturedNS_ and self.Page4Image_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPage4Image>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Page4Image), input_name='Page4Image')), namespaceprefix_ , eol_)) - if self.Page5Image is not None: - namespaceprefix_ = self.Page5Image_nsprefix_ + ':' if (UseCapturedNS_ and self.Page5Image_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPage5Image>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Page5Image), input_name='Page5Image')), namespaceprefix_ , eol_)) - if self.Page6Image is not None: - namespaceprefix_ = self.Page6Image_nsprefix_ + ':' if (UseCapturedNS_ and self.Page6Image_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPage6Image>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Page6Image), input_name='Page6Image')), namespaceprefix_ , eol_)) - if self.Prohibitions is not None: - namespaceprefix_ = self.Prohibitions_nsprefix_ + ':' if (UseCapturedNS_ and self.Prohibitions_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sProhibitions>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Prohibitions), input_name='Prohibitions')), namespaceprefix_ , eol_)) - if self.Restrictions is not None: - namespaceprefix_ = self.Restrictions_nsprefix_ + ':' if (UseCapturedNS_ and self.Restrictions_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRestrictions>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Restrictions), input_name='Restrictions')), namespaceprefix_ , eol_)) - if self.Observations is not None: - namespaceprefix_ = self.Observations_nsprefix_ + ':' if (UseCapturedNS_ and self.Observations_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sObservations>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Observations), input_name='Observations')), namespaceprefix_ , eol_)) - if self.Regulations is not None: - namespaceprefix_ = self.Regulations_nsprefix_ + ':' if (UseCapturedNS_ and self.Regulations_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRegulations>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Regulations), input_name='Regulations')), namespaceprefix_ , eol_)) - if self.AdditionalRestrictions is not None: - namespaceprefix_ = self.AdditionalRestrictions_nsprefix_ + ':' if (UseCapturedNS_ and self.AdditionalRestrictions_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAdditionalRestrictions>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.AdditionalRestrictions), input_name='AdditionalRestrictions')), namespaceprefix_ , eol_)) - if self.InsuranceFee is not None: - namespaceprefix_ = self.InsuranceFee_nsprefix_ + ':' if (UseCapturedNS_ and self.InsuranceFee_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sInsuranceFee>%s%s' % (namespaceprefix_ , self.gds_format_float(self.InsuranceFee, input_name='InsuranceFee'), namespaceprefix_ , eol_)) - if self.GuaranteeAvailability is not None: - namespaceprefix_ = self.GuaranteeAvailability_nsprefix_ + ':' if (UseCapturedNS_ and self.GuaranteeAvailability_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sGuaranteeAvailability>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.GuaranteeAvailability), input_name='GuaranteeAvailability')), namespaceprefix_ , eol_)) - if self.RemainingBarcodes is not None: - namespaceprefix_ = self.RemainingBarcodes_nsprefix_ + ':' if (UseCapturedNS_ and self.RemainingBarcodes_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRemainingBarcodes>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.RemainingBarcodes), input_name='RemainingBarcodes')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'Postage' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'Postage') - fval_ = self.gds_validate_float(fval_, node, 'Postage') - self.Postage = fval_ - self.Postage_nsprefix_ = child_.prefix - elif nodeName_ == 'TotalValue' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'TotalValue') - fval_ = self.gds_validate_float(fval_, node, 'TotalValue') - self.TotalValue = fval_ - self.TotalValue_nsprefix_ = child_.prefix - elif nodeName_ == 'SDRValue' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'SDRValue') - fval_ = self.gds_validate_float(fval_, node, 'SDRValue') - self.SDRValue = fval_ - self.SDRValue_nsprefix_ = child_.prefix - elif nodeName_ == 'BarcodeNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'BarcodeNumber') - value_ = self.gds_validate_string(value_, node, 'BarcodeNumber') - self.BarcodeNumber = value_ - self.BarcodeNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'LabelImage': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'LabelImage') - value_ = self.gds_validate_string(value_, node, 'LabelImage') - self.LabelImage = value_ - self.LabelImage_nsprefix_ = child_.prefix - elif nodeName_ == 'Page2Image': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Page2Image') - value_ = self.gds_validate_string(value_, node, 'Page2Image') - self.Page2Image = value_ - self.Page2Image_nsprefix_ = child_.prefix - elif nodeName_ == 'Page3Image': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Page3Image') - value_ = self.gds_validate_string(value_, node, 'Page3Image') - self.Page3Image = value_ - self.Page3Image_nsprefix_ = child_.prefix - elif nodeName_ == 'Page4Image': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Page4Image') - value_ = self.gds_validate_string(value_, node, 'Page4Image') - self.Page4Image = value_ - self.Page4Image_nsprefix_ = child_.prefix - elif nodeName_ == 'Page5Image': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Page5Image') - value_ = self.gds_validate_string(value_, node, 'Page5Image') - self.Page5Image = value_ - self.Page5Image_nsprefix_ = child_.prefix - elif nodeName_ == 'Page6Image': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Page6Image') - value_ = self.gds_validate_string(value_, node, 'Page6Image') - self.Page6Image = value_ - self.Page6Image_nsprefix_ = child_.prefix - elif nodeName_ == 'Prohibitions': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Prohibitions') - value_ = self.gds_validate_string(value_, node, 'Prohibitions') - self.Prohibitions = value_ - self.Prohibitions_nsprefix_ = child_.prefix - elif nodeName_ == 'Restrictions': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Restrictions') - value_ = self.gds_validate_string(value_, node, 'Restrictions') - self.Restrictions = value_ - self.Restrictions_nsprefix_ = child_.prefix - elif nodeName_ == 'Observations': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Observations') - value_ = self.gds_validate_string(value_, node, 'Observations') - self.Observations = value_ - self.Observations_nsprefix_ = child_.prefix - elif nodeName_ == 'Regulations': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Regulations') - value_ = self.gds_validate_string(value_, node, 'Regulations') - self.Regulations = value_ - self.Regulations_nsprefix_ = child_.prefix - elif nodeName_ == 'AdditionalRestrictions': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'AdditionalRestrictions') - value_ = self.gds_validate_string(value_, node, 'AdditionalRestrictions') - self.AdditionalRestrictions = value_ - self.AdditionalRestrictions_nsprefix_ = child_.prefix - elif nodeName_ == 'InsuranceFee' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'InsuranceFee') - fval_ = self.gds_validate_float(fval_, node, 'InsuranceFee') - self.InsuranceFee = fval_ - self.InsuranceFee_nsprefix_ = child_.prefix - elif nodeName_ == 'GuaranteeAvailability': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'GuaranteeAvailability') - value_ = self.gds_validate_string(value_, node, 'GuaranteeAvailability') - self.GuaranteeAvailability = value_ - self.GuaranteeAvailability_nsprefix_ = child_.prefix - elif nodeName_ == 'RemainingBarcodes': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'RemainingBarcodes') - value_ = self.gds_validate_string(value_, node, 'RemainingBarcodes') - self.RemainingBarcodes = value_ - self.RemainingBarcodes_nsprefix_ = child_.prefix -# end class eVSExpressMailIntlResponse - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSExpressMailIntlResponse' - rootClass = eVSExpressMailIntlResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSExpressMailIntlResponse' - rootClass = eVSExpressMailIntlResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSExpressMailIntlResponse' - rootClass = eVSExpressMailIntlResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSExpressMailIntlResponse' - rootClass = eVSExpressMailIntlResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from evs_express_mail_intl_response import *\n\n') - sys.stdout.write('import evs_express_mail_intl_response as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "eVSExpressMailIntlResponse" -] diff --git a/schemas/usps/karrio/schemas/usps/evs_first_class_mail_intl_request.py b/schemas/usps/karrio/schemas/usps/evs_first_class_mail_intl_request.py deleted file mode 100644 index 16dfc9f05e..0000000000 --- a/schemas/usps/karrio/schemas/usps/evs_first_class_mail_intl_request.py +++ /dev/null @@ -1,3150 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:14 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/evs_first_class_mail_intl_request.py') -# -# Command line arguments: -# ./schemas/eVSFirstClassMailIntlRequest.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/evs_first_class_mail_intl_request.py" ./schemas/eVSFirstClassMailIntlRequest.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class eVSFirstClassMailIntlRequest(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, USERID=None, Option=None, Revision=None, ImageParameters=None, FromFirstName=None, FromMiddleInitial=None, FromLastName=None, FromFirm=None, FromAddress1=None, FromAddress2=None, FromUrbanization=None, FromCity=None, FromState=None, FromZip5=None, FromZip4=None, FromPhone=None, ToName=None, ToFirstName=None, ToLastName=None, ToFirm=None, ToAddress1=None, ToAddress2=None, ToAddress3=None, ToCity=None, ToProvince=None, ToCountry=None, ToPostalCode=None, ToPOBoxFlag=None, ToPhone=None, ToFax=None, ToEmail=None, FirstClassMailType=None, ShippingContents=None, Postage=None, GrossPounds=None, GrossOunces=None, ContentType=None, ContentTypeOther=None, Agreement=None, Comments=None, LicenseNumber=None, CertificateNumber=None, InvoiceNumber=None, ImageType=None, ImageLayout=None, CustomerRefNo=None, CustomerRefNo2=None, POZipCode=None, LabelDate=None, HoldForManifest=None, EELPFC=None, Container=None, Length=None, Width=None, Height=None, Girth=None, ExtraServices=None, PriceOptions=None, ActionCode=None, OptOutOfSPE=None, PermitNumber=None, AccountZipCode=None, Machinable=None, DestinationRateIndicator=None, MID=None, LogisticsManagerMID=None, CRID=None, VendorCode=None, VendorProductVersionNumber=None, ePostageMailerReporting=None, SenderFirstName=None, SenderLastName=None, SenderBusinessName=None, SenderAddress1=None, SenderCity=None, SenderState=None, SenderZip5=None, SenderPhone=None, SenderEmail=None, RemainingBarcodes=None, ChargebackCode=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.USERID = _cast(None, USERID) - self.USERID_nsprefix_ = None - self.Option = Option - self.Option_nsprefix_ = None - self.Revision = Revision - self.Revision_nsprefix_ = None - self.ImageParameters = ImageParameters - self.ImageParameters_nsprefix_ = None - self.FromFirstName = FromFirstName - self.FromFirstName_nsprefix_ = None - self.FromMiddleInitial = FromMiddleInitial - self.FromMiddleInitial_nsprefix_ = None - self.FromLastName = FromLastName - self.FromLastName_nsprefix_ = None - self.FromFirm = FromFirm - self.FromFirm_nsprefix_ = None - self.FromAddress1 = FromAddress1 - self.FromAddress1_nsprefix_ = None - self.FromAddress2 = FromAddress2 - self.FromAddress2_nsprefix_ = None - self.FromUrbanization = FromUrbanization - self.FromUrbanization_nsprefix_ = None - self.FromCity = FromCity - self.FromCity_nsprefix_ = None - self.FromState = FromState - self.FromState_nsprefix_ = None - self.FromZip5 = FromZip5 - self.FromZip5_nsprefix_ = None - self.FromZip4 = FromZip4 - self.FromZip4_nsprefix_ = None - self.FromPhone = FromPhone - self.FromPhone_nsprefix_ = None - self.ToName = ToName - self.ToName_nsprefix_ = None - self.ToFirstName = ToFirstName - self.ToFirstName_nsprefix_ = None - self.ToLastName = ToLastName - self.ToLastName_nsprefix_ = None - self.ToFirm = ToFirm - self.ToFirm_nsprefix_ = None - self.ToAddress1 = ToAddress1 - self.ToAddress1_nsprefix_ = None - self.ToAddress2 = ToAddress2 - self.ToAddress2_nsprefix_ = None - self.ToAddress3 = ToAddress3 - self.ToAddress3_nsprefix_ = None - self.ToCity = ToCity - self.ToCity_nsprefix_ = None - self.ToProvince = ToProvince - self.ToProvince_nsprefix_ = None - self.ToCountry = ToCountry - self.ToCountry_nsprefix_ = None - self.ToPostalCode = ToPostalCode - self.ToPostalCode_nsprefix_ = None - self.ToPOBoxFlag = ToPOBoxFlag - self.ToPOBoxFlag_nsprefix_ = None - self.ToPhone = ToPhone - self.ToPhone_nsprefix_ = None - self.ToFax = ToFax - self.ToFax_nsprefix_ = None - self.ToEmail = ToEmail - self.ToEmail_nsprefix_ = None - self.FirstClassMailType = FirstClassMailType - self.FirstClassMailType_nsprefix_ = None - self.ShippingContents = ShippingContents - self.ShippingContents_nsprefix_ = None - self.Postage = Postage - self.Postage_nsprefix_ = None - self.GrossPounds = GrossPounds - self.GrossPounds_nsprefix_ = None - self.GrossOunces = GrossOunces - self.GrossOunces_nsprefix_ = None - self.ContentType = ContentType - self.ContentType_nsprefix_ = None - self.ContentTypeOther = ContentTypeOther - self.ContentTypeOther_nsprefix_ = None - self.Agreement = Agreement - self.Agreement_nsprefix_ = None - self.Comments = Comments - self.Comments_nsprefix_ = None - self.LicenseNumber = LicenseNumber - self.LicenseNumber_nsprefix_ = None - self.CertificateNumber = CertificateNumber - self.CertificateNumber_nsprefix_ = None - self.InvoiceNumber = InvoiceNumber - self.InvoiceNumber_nsprefix_ = None - self.ImageType = ImageType - self.ImageType_nsprefix_ = None - self.ImageLayout = ImageLayout - self.ImageLayout_nsprefix_ = None - self.CustomerRefNo = CustomerRefNo - self.CustomerRefNo_nsprefix_ = None - self.CustomerRefNo2 = CustomerRefNo2 - self.CustomerRefNo2_nsprefix_ = None - self.POZipCode = POZipCode - self.POZipCode_nsprefix_ = None - self.LabelDate = LabelDate - self.LabelDate_nsprefix_ = None - self.HoldForManifest = HoldForManifest - self.HoldForManifest_nsprefix_ = None - self.EELPFC = EELPFC - self.EELPFC_nsprefix_ = None - self.Container = Container - self.Container_nsprefix_ = None - self.Length = Length - self.Length_nsprefix_ = None - self.Width = Width - self.Width_nsprefix_ = None - self.Height = Height - self.Height_nsprefix_ = None - self.Girth = Girth - self.Girth_nsprefix_ = None - self.ExtraServices = ExtraServices - self.ExtraServices_nsprefix_ = None - self.PriceOptions = PriceOptions - self.PriceOptions_nsprefix_ = None - self.ActionCode = ActionCode - self.ActionCode_nsprefix_ = None - self.OptOutOfSPE = OptOutOfSPE - self.OptOutOfSPE_nsprefix_ = None - self.PermitNumber = PermitNumber - self.PermitNumber_nsprefix_ = None - self.AccountZipCode = AccountZipCode - self.AccountZipCode_nsprefix_ = None - self.Machinable = Machinable - self.Machinable_nsprefix_ = None - self.DestinationRateIndicator = DestinationRateIndicator - self.DestinationRateIndicator_nsprefix_ = None - self.MID = MID - self.MID_nsprefix_ = None - self.LogisticsManagerMID = LogisticsManagerMID - self.LogisticsManagerMID_nsprefix_ = None - self.CRID = CRID - self.CRID_nsprefix_ = None - self.VendorCode = VendorCode - self.VendorCode_nsprefix_ = None - self.VendorProductVersionNumber = VendorProductVersionNumber - self.VendorProductVersionNumber_nsprefix_ = None - self.ePostageMailerReporting = ePostageMailerReporting - self.ePostageMailerReporting_nsprefix_ = None - self.SenderFirstName = SenderFirstName - self.SenderFirstName_nsprefix_ = None - self.SenderLastName = SenderLastName - self.SenderLastName_nsprefix_ = None - self.SenderBusinessName = SenderBusinessName - self.SenderBusinessName_nsprefix_ = None - self.SenderAddress1 = SenderAddress1 - self.SenderAddress1_nsprefix_ = None - self.SenderCity = SenderCity - self.SenderCity_nsprefix_ = None - self.SenderState = SenderState - self.SenderState_nsprefix_ = None - self.SenderZip5 = SenderZip5 - self.SenderZip5_nsprefix_ = None - self.SenderPhone = SenderPhone - self.SenderPhone_nsprefix_ = None - self.SenderEmail = SenderEmail - self.SenderEmail_nsprefix_ = None - self.RemainingBarcodes = RemainingBarcodes - self.RemainingBarcodes_nsprefix_ = None - self.ChargebackCode = ChargebackCode - self.ChargebackCode_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, eVSFirstClassMailIntlRequest) - if subclass is not None: - return subclass(*args_, **kwargs_) - if eVSFirstClassMailIntlRequest.subclass: - return eVSFirstClassMailIntlRequest.subclass(*args_, **kwargs_) - else: - return eVSFirstClassMailIntlRequest(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_Option(self): - return self.Option - def set_Option(self, Option): - self.Option = Option - def get_Revision(self): - return self.Revision - def set_Revision(self, Revision): - self.Revision = Revision - def get_ImageParameters(self): - return self.ImageParameters - def set_ImageParameters(self, ImageParameters): - self.ImageParameters = ImageParameters - def get_FromFirstName(self): - return self.FromFirstName - def set_FromFirstName(self, FromFirstName): - self.FromFirstName = FromFirstName - def get_FromMiddleInitial(self): - return self.FromMiddleInitial - def set_FromMiddleInitial(self, FromMiddleInitial): - self.FromMiddleInitial = FromMiddleInitial - def get_FromLastName(self): - return self.FromLastName - def set_FromLastName(self, FromLastName): - self.FromLastName = FromLastName - def get_FromFirm(self): - return self.FromFirm - def set_FromFirm(self, FromFirm): - self.FromFirm = FromFirm - def get_FromAddress1(self): - return self.FromAddress1 - def set_FromAddress1(self, FromAddress1): - self.FromAddress1 = FromAddress1 - def get_FromAddress2(self): - return self.FromAddress2 - def set_FromAddress2(self, FromAddress2): - self.FromAddress2 = FromAddress2 - def get_FromUrbanization(self): - return self.FromUrbanization - def set_FromUrbanization(self, FromUrbanization): - self.FromUrbanization = FromUrbanization - def get_FromCity(self): - return self.FromCity - def set_FromCity(self, FromCity): - self.FromCity = FromCity - def get_FromState(self): - return self.FromState - def set_FromState(self, FromState): - self.FromState = FromState - def get_FromZip5(self): - return self.FromZip5 - def set_FromZip5(self, FromZip5): - self.FromZip5 = FromZip5 - def get_FromZip4(self): - return self.FromZip4 - def set_FromZip4(self, FromZip4): - self.FromZip4 = FromZip4 - def get_FromPhone(self): - return self.FromPhone - def set_FromPhone(self, FromPhone): - self.FromPhone = FromPhone - def get_ToName(self): - return self.ToName - def set_ToName(self, ToName): - self.ToName = ToName - def get_ToFirstName(self): - return self.ToFirstName - def set_ToFirstName(self, ToFirstName): - self.ToFirstName = ToFirstName - def get_ToLastName(self): - return self.ToLastName - def set_ToLastName(self, ToLastName): - self.ToLastName = ToLastName - def get_ToFirm(self): - return self.ToFirm - def set_ToFirm(self, ToFirm): - self.ToFirm = ToFirm - def get_ToAddress1(self): - return self.ToAddress1 - def set_ToAddress1(self, ToAddress1): - self.ToAddress1 = ToAddress1 - def get_ToAddress2(self): - return self.ToAddress2 - def set_ToAddress2(self, ToAddress2): - self.ToAddress2 = ToAddress2 - def get_ToAddress3(self): - return self.ToAddress3 - def set_ToAddress3(self, ToAddress3): - self.ToAddress3 = ToAddress3 - def get_ToCity(self): - return self.ToCity - def set_ToCity(self, ToCity): - self.ToCity = ToCity - def get_ToProvince(self): - return self.ToProvince - def set_ToProvince(self, ToProvince): - self.ToProvince = ToProvince - def get_ToCountry(self): - return self.ToCountry - def set_ToCountry(self, ToCountry): - self.ToCountry = ToCountry - def get_ToPostalCode(self): - return self.ToPostalCode - def set_ToPostalCode(self, ToPostalCode): - self.ToPostalCode = ToPostalCode - def get_ToPOBoxFlag(self): - return self.ToPOBoxFlag - def set_ToPOBoxFlag(self, ToPOBoxFlag): - self.ToPOBoxFlag = ToPOBoxFlag - def get_ToPhone(self): - return self.ToPhone - def set_ToPhone(self, ToPhone): - self.ToPhone = ToPhone - def get_ToFax(self): - return self.ToFax - def set_ToFax(self, ToFax): - self.ToFax = ToFax - def get_ToEmail(self): - return self.ToEmail - def set_ToEmail(self, ToEmail): - self.ToEmail = ToEmail - def get_FirstClassMailType(self): - return self.FirstClassMailType - def set_FirstClassMailType(self, FirstClassMailType): - self.FirstClassMailType = FirstClassMailType - def get_ShippingContents(self): - return self.ShippingContents - def set_ShippingContents(self, ShippingContents): - self.ShippingContents = ShippingContents - def get_Postage(self): - return self.Postage - def set_Postage(self, Postage): - self.Postage = Postage - def get_GrossPounds(self): - return self.GrossPounds - def set_GrossPounds(self, GrossPounds): - self.GrossPounds = GrossPounds - def get_GrossOunces(self): - return self.GrossOunces - def set_GrossOunces(self, GrossOunces): - self.GrossOunces = GrossOunces - def get_ContentType(self): - return self.ContentType - def set_ContentType(self, ContentType): - self.ContentType = ContentType - def get_ContentTypeOther(self): - return self.ContentTypeOther - def set_ContentTypeOther(self, ContentTypeOther): - self.ContentTypeOther = ContentTypeOther - def get_Agreement(self): - return self.Agreement - def set_Agreement(self, Agreement): - self.Agreement = Agreement - def get_Comments(self): - return self.Comments - def set_Comments(self, Comments): - self.Comments = Comments - def get_LicenseNumber(self): - return self.LicenseNumber - def set_LicenseNumber(self, LicenseNumber): - self.LicenseNumber = LicenseNumber - def get_CertificateNumber(self): - return self.CertificateNumber - def set_CertificateNumber(self, CertificateNumber): - self.CertificateNumber = CertificateNumber - def get_InvoiceNumber(self): - return self.InvoiceNumber - def set_InvoiceNumber(self, InvoiceNumber): - self.InvoiceNumber = InvoiceNumber - def get_ImageType(self): - return self.ImageType - def set_ImageType(self, ImageType): - self.ImageType = ImageType - def get_ImageLayout(self): - return self.ImageLayout - def set_ImageLayout(self, ImageLayout): - self.ImageLayout = ImageLayout - def get_CustomerRefNo(self): - return self.CustomerRefNo - def set_CustomerRefNo(self, CustomerRefNo): - self.CustomerRefNo = CustomerRefNo - def get_CustomerRefNo2(self): - return self.CustomerRefNo2 - def set_CustomerRefNo2(self, CustomerRefNo2): - self.CustomerRefNo2 = CustomerRefNo2 - def get_POZipCode(self): - return self.POZipCode - def set_POZipCode(self, POZipCode): - self.POZipCode = POZipCode - def get_LabelDate(self): - return self.LabelDate - def set_LabelDate(self, LabelDate): - self.LabelDate = LabelDate - def get_HoldForManifest(self): - return self.HoldForManifest - def set_HoldForManifest(self, HoldForManifest): - self.HoldForManifest = HoldForManifest - def get_EELPFC(self): - return self.EELPFC - def set_EELPFC(self, EELPFC): - self.EELPFC = EELPFC - def get_Container(self): - return self.Container - def set_Container(self, Container): - self.Container = Container - def get_Length(self): - return self.Length - def set_Length(self, Length): - self.Length = Length - def get_Width(self): - return self.Width - def set_Width(self, Width): - self.Width = Width - def get_Height(self): - return self.Height - def set_Height(self, Height): - self.Height = Height - def get_Girth(self): - return self.Girth - def set_Girth(self, Girth): - self.Girth = Girth - def get_ExtraServices(self): - return self.ExtraServices - def set_ExtraServices(self, ExtraServices): - self.ExtraServices = ExtraServices - def get_PriceOptions(self): - return self.PriceOptions - def set_PriceOptions(self, PriceOptions): - self.PriceOptions = PriceOptions - def get_ActionCode(self): - return self.ActionCode - def set_ActionCode(self, ActionCode): - self.ActionCode = ActionCode - def get_OptOutOfSPE(self): - return self.OptOutOfSPE - def set_OptOutOfSPE(self, OptOutOfSPE): - self.OptOutOfSPE = OptOutOfSPE - def get_PermitNumber(self): - return self.PermitNumber - def set_PermitNumber(self, PermitNumber): - self.PermitNumber = PermitNumber - def get_AccountZipCode(self): - return self.AccountZipCode - def set_AccountZipCode(self, AccountZipCode): - self.AccountZipCode = AccountZipCode - def get_Machinable(self): - return self.Machinable - def set_Machinable(self, Machinable): - self.Machinable = Machinable - def get_DestinationRateIndicator(self): - return self.DestinationRateIndicator - def set_DestinationRateIndicator(self, DestinationRateIndicator): - self.DestinationRateIndicator = DestinationRateIndicator - def get_MID(self): - return self.MID - def set_MID(self, MID): - self.MID = MID - def get_LogisticsManagerMID(self): - return self.LogisticsManagerMID - def set_LogisticsManagerMID(self, LogisticsManagerMID): - self.LogisticsManagerMID = LogisticsManagerMID - def get_CRID(self): - return self.CRID - def set_CRID(self, CRID): - self.CRID = CRID - def get_VendorCode(self): - return self.VendorCode - def set_VendorCode(self, VendorCode): - self.VendorCode = VendorCode - def get_VendorProductVersionNumber(self): - return self.VendorProductVersionNumber - def set_VendorProductVersionNumber(self, VendorProductVersionNumber): - self.VendorProductVersionNumber = VendorProductVersionNumber - def get_ePostageMailerReporting(self): - return self.ePostageMailerReporting - def set_ePostageMailerReporting(self, ePostageMailerReporting): - self.ePostageMailerReporting = ePostageMailerReporting - def get_SenderFirstName(self): - return self.SenderFirstName - def set_SenderFirstName(self, SenderFirstName): - self.SenderFirstName = SenderFirstName - def get_SenderLastName(self): - return self.SenderLastName - def set_SenderLastName(self, SenderLastName): - self.SenderLastName = SenderLastName - def get_SenderBusinessName(self): - return self.SenderBusinessName - def set_SenderBusinessName(self, SenderBusinessName): - self.SenderBusinessName = SenderBusinessName - def get_SenderAddress1(self): - return self.SenderAddress1 - def set_SenderAddress1(self, SenderAddress1): - self.SenderAddress1 = SenderAddress1 - def get_SenderCity(self): - return self.SenderCity - def set_SenderCity(self, SenderCity): - self.SenderCity = SenderCity - def get_SenderState(self): - return self.SenderState - def set_SenderState(self, SenderState): - self.SenderState = SenderState - def get_SenderZip5(self): - return self.SenderZip5 - def set_SenderZip5(self, SenderZip5): - self.SenderZip5 = SenderZip5 - def get_SenderPhone(self): - return self.SenderPhone - def set_SenderPhone(self, SenderPhone): - self.SenderPhone = SenderPhone - def get_SenderEmail(self): - return self.SenderEmail - def set_SenderEmail(self, SenderEmail): - self.SenderEmail = SenderEmail - def get_RemainingBarcodes(self): - return self.RemainingBarcodes - def set_RemainingBarcodes(self, RemainingBarcodes): - self.RemainingBarcodes = RemainingBarcodes - def get_ChargebackCode(self): - return self.ChargebackCode - def set_ChargebackCode(self, ChargebackCode): - self.ChargebackCode = ChargebackCode - def get_USERID(self): - return self.USERID - def set_USERID(self, USERID): - self.USERID = USERID - def _hasContent(self): - if ( - self.Option is not None or - self.Revision is not None or - self.ImageParameters is not None or - self.FromFirstName is not None or - self.FromMiddleInitial is not None or - self.FromLastName is not None or - self.FromFirm is not None or - self.FromAddress1 is not None or - self.FromAddress2 is not None or - self.FromUrbanization is not None or - self.FromCity is not None or - self.FromState is not None or - self.FromZip5 is not None or - self.FromZip4 is not None or - self.FromPhone is not None or - self.ToName is not None or - self.ToFirstName is not None or - self.ToLastName is not None or - self.ToFirm is not None or - self.ToAddress1 is not None or - self.ToAddress2 is not None or - self.ToAddress3 is not None or - self.ToCity is not None or - self.ToProvince is not None or - self.ToCountry is not None or - self.ToPostalCode is not None or - self.ToPOBoxFlag is not None or - self.ToPhone is not None or - self.ToFax is not None or - self.ToEmail is not None or - self.FirstClassMailType is not None or - self.ShippingContents is not None or - self.Postage is not None or - self.GrossPounds is not None or - self.GrossOunces is not None or - self.ContentType is not None or - self.ContentTypeOther is not None or - self.Agreement is not None or - self.Comments is not None or - self.LicenseNumber is not None or - self.CertificateNumber is not None or - self.InvoiceNumber is not None or - self.ImageType is not None or - self.ImageLayout is not None or - self.CustomerRefNo is not None or - self.CustomerRefNo2 is not None or - self.POZipCode is not None or - self.LabelDate is not None or - self.HoldForManifest is not None or - self.EELPFC is not None or - self.Container is not None or - self.Length is not None or - self.Width is not None or - self.Height is not None or - self.Girth is not None or - self.ExtraServices is not None or - self.PriceOptions is not None or - self.ActionCode is not None or - self.OptOutOfSPE is not None or - self.PermitNumber is not None or - self.AccountZipCode is not None or - self.Machinable is not None or - self.DestinationRateIndicator is not None or - self.MID is not None or - self.LogisticsManagerMID is not None or - self.CRID is not None or - self.VendorCode is not None or - self.VendorProductVersionNumber is not None or - self.ePostageMailerReporting is not None or - self.SenderFirstName is not None or - self.SenderLastName is not None or - self.SenderBusinessName is not None or - self.SenderAddress1 is not None or - self.SenderCity is not None or - self.SenderState is not None or - self.SenderZip5 is not None or - self.SenderPhone is not None or - self.SenderEmail is not None or - self.RemainingBarcodes is not None or - self.ChargebackCode is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='eVSFirstClassMailIntlRequest', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('eVSFirstClassMailIntlRequest') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'eVSFirstClassMailIntlRequest': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='eVSFirstClassMailIntlRequest') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='eVSFirstClassMailIntlRequest', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='eVSFirstClassMailIntlRequest'): - if self.USERID is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - outfile.write(' USERID=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.USERID), input_name='USERID')), )) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='eVSFirstClassMailIntlRequest', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.Option is not None: - namespaceprefix_ = self.Option_nsprefix_ + ':' if (UseCapturedNS_ and self.Option_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sOption>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Option), input_name='Option')), namespaceprefix_ , eol_)) - if self.Revision is not None: - namespaceprefix_ = self.Revision_nsprefix_ + ':' if (UseCapturedNS_ and self.Revision_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRevision>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.Revision, input_name='Revision'), namespaceprefix_ , eol_)) - if self.ImageParameters is not None: - namespaceprefix_ = self.ImageParameters_nsprefix_ + ':' if (UseCapturedNS_ and self.ImageParameters_nsprefix_) else '' - self.ImageParameters.export(outfile, level, namespaceprefix_, namespacedef_='', name_='ImageParameters', pretty_print=pretty_print) - if self.FromFirstName is not None: - namespaceprefix_ = self.FromFirstName_nsprefix_ + ':' if (UseCapturedNS_ and self.FromFirstName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromFirstName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromFirstName), input_name='FromFirstName')), namespaceprefix_ , eol_)) - if self.FromMiddleInitial is not None: - namespaceprefix_ = self.FromMiddleInitial_nsprefix_ + ':' if (UseCapturedNS_ and self.FromMiddleInitial_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromMiddleInitial>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromMiddleInitial), input_name='FromMiddleInitial')), namespaceprefix_ , eol_)) - if self.FromLastName is not None: - namespaceprefix_ = self.FromLastName_nsprefix_ + ':' if (UseCapturedNS_ and self.FromLastName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromLastName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromLastName), input_name='FromLastName')), namespaceprefix_ , eol_)) - if self.FromFirm is not None: - namespaceprefix_ = self.FromFirm_nsprefix_ + ':' if (UseCapturedNS_ and self.FromFirm_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromFirm>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromFirm), input_name='FromFirm')), namespaceprefix_ , eol_)) - if self.FromAddress1 is not None: - namespaceprefix_ = self.FromAddress1_nsprefix_ + ':' if (UseCapturedNS_ and self.FromAddress1_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromAddress1>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromAddress1), input_name='FromAddress1')), namespaceprefix_ , eol_)) - if self.FromAddress2 is not None: - namespaceprefix_ = self.FromAddress2_nsprefix_ + ':' if (UseCapturedNS_ and self.FromAddress2_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromAddress2>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromAddress2), input_name='FromAddress2')), namespaceprefix_ , eol_)) - if self.FromUrbanization is not None: - namespaceprefix_ = self.FromUrbanization_nsprefix_ + ':' if (UseCapturedNS_ and self.FromUrbanization_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromUrbanization>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromUrbanization), input_name='FromUrbanization')), namespaceprefix_ , eol_)) - if self.FromCity is not None: - namespaceprefix_ = self.FromCity_nsprefix_ + ':' if (UseCapturedNS_ and self.FromCity_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromCity), input_name='FromCity')), namespaceprefix_ , eol_)) - if self.FromState is not None: - namespaceprefix_ = self.FromState_nsprefix_ + ':' if (UseCapturedNS_ and self.FromState_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromState), input_name='FromState')), namespaceprefix_ , eol_)) - if self.FromZip5 is not None: - namespaceprefix_ = self.FromZip5_nsprefix_ + ':' if (UseCapturedNS_ and self.FromZip5_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromZip5>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromZip5), input_name='FromZip5')), namespaceprefix_ , eol_)) - if self.FromZip4 is not None: - namespaceprefix_ = self.FromZip4_nsprefix_ + ':' if (UseCapturedNS_ and self.FromZip4_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromZip4>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromZip4), input_name='FromZip4')), namespaceprefix_ , eol_)) - if self.FromPhone is not None: - namespaceprefix_ = self.FromPhone_nsprefix_ + ':' if (UseCapturedNS_ and self.FromPhone_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromPhone>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromPhone), input_name='FromPhone')), namespaceprefix_ , eol_)) - if self.ToName is not None: - namespaceprefix_ = self.ToName_nsprefix_ + ':' if (UseCapturedNS_ and self.ToName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToName), input_name='ToName')), namespaceprefix_ , eol_)) - if self.ToFirstName is not None: - namespaceprefix_ = self.ToFirstName_nsprefix_ + ':' if (UseCapturedNS_ and self.ToFirstName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToFirstName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToFirstName), input_name='ToFirstName')), namespaceprefix_ , eol_)) - if self.ToLastName is not None: - namespaceprefix_ = self.ToLastName_nsprefix_ + ':' if (UseCapturedNS_ and self.ToLastName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToLastName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToLastName), input_name='ToLastName')), namespaceprefix_ , eol_)) - if self.ToFirm is not None: - namespaceprefix_ = self.ToFirm_nsprefix_ + ':' if (UseCapturedNS_ and self.ToFirm_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToFirm>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToFirm), input_name='ToFirm')), namespaceprefix_ , eol_)) - if self.ToAddress1 is not None: - namespaceprefix_ = self.ToAddress1_nsprefix_ + ':' if (UseCapturedNS_ and self.ToAddress1_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToAddress1>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToAddress1), input_name='ToAddress1')), namespaceprefix_ , eol_)) - if self.ToAddress2 is not None: - namespaceprefix_ = self.ToAddress2_nsprefix_ + ':' if (UseCapturedNS_ and self.ToAddress2_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToAddress2>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToAddress2), input_name='ToAddress2')), namespaceprefix_ , eol_)) - if self.ToAddress3 is not None: - namespaceprefix_ = self.ToAddress3_nsprefix_ + ':' if (UseCapturedNS_ and self.ToAddress3_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToAddress3>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToAddress3), input_name='ToAddress3')), namespaceprefix_ , eol_)) - if self.ToCity is not None: - namespaceprefix_ = self.ToCity_nsprefix_ + ':' if (UseCapturedNS_ and self.ToCity_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToCity), input_name='ToCity')), namespaceprefix_ , eol_)) - if self.ToProvince is not None: - namespaceprefix_ = self.ToProvince_nsprefix_ + ':' if (UseCapturedNS_ and self.ToProvince_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToProvince>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToProvince), input_name='ToProvince')), namespaceprefix_ , eol_)) - if self.ToCountry is not None: - namespaceprefix_ = self.ToCountry_nsprefix_ + ':' if (UseCapturedNS_ and self.ToCountry_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToCountry>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToCountry), input_name='ToCountry')), namespaceprefix_ , eol_)) - if self.ToPostalCode is not None: - namespaceprefix_ = self.ToPostalCode_nsprefix_ + ':' if (UseCapturedNS_ and self.ToPostalCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToPostalCode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToPostalCode), input_name='ToPostalCode')), namespaceprefix_ , eol_)) - if self.ToPOBoxFlag is not None: - namespaceprefix_ = self.ToPOBoxFlag_nsprefix_ + ':' if (UseCapturedNS_ and self.ToPOBoxFlag_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToPOBoxFlag>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToPOBoxFlag), input_name='ToPOBoxFlag')), namespaceprefix_ , eol_)) - if self.ToPhone is not None: - namespaceprefix_ = self.ToPhone_nsprefix_ + ':' if (UseCapturedNS_ and self.ToPhone_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToPhone>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToPhone), input_name='ToPhone')), namespaceprefix_ , eol_)) - if self.ToFax is not None: - namespaceprefix_ = self.ToFax_nsprefix_ + ':' if (UseCapturedNS_ and self.ToFax_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToFax>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToFax), input_name='ToFax')), namespaceprefix_ , eol_)) - if self.ToEmail is not None: - namespaceprefix_ = self.ToEmail_nsprefix_ + ':' if (UseCapturedNS_ and self.ToEmail_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToEmail>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToEmail), input_name='ToEmail')), namespaceprefix_ , eol_)) - if self.FirstClassMailType is not None: - namespaceprefix_ = self.FirstClassMailType_nsprefix_ + ':' if (UseCapturedNS_ and self.FirstClassMailType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFirstClassMailType>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FirstClassMailType), input_name='FirstClassMailType')), namespaceprefix_ , eol_)) - if self.ShippingContents is not None: - namespaceprefix_ = self.ShippingContents_nsprefix_ + ':' if (UseCapturedNS_ and self.ShippingContents_nsprefix_) else '' - self.ShippingContents.export(outfile, level, namespaceprefix_, namespacedef_='', name_='ShippingContents', pretty_print=pretty_print) - if self.Postage is not None: - namespaceprefix_ = self.Postage_nsprefix_ + ':' if (UseCapturedNS_ and self.Postage_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPostage>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Postage), input_name='Postage')), namespaceprefix_ , eol_)) - if self.GrossPounds is not None: - namespaceprefix_ = self.GrossPounds_nsprefix_ + ':' if (UseCapturedNS_ and self.GrossPounds_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sGrossPounds>%s%s' % (namespaceprefix_ , self.gds_format_decimal(self.GrossPounds, input_name='GrossPounds'), namespaceprefix_ , eol_)) - if self.GrossOunces is not None: - namespaceprefix_ = self.GrossOunces_nsprefix_ + ':' if (UseCapturedNS_ and self.GrossOunces_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sGrossOunces>%s%s' % (namespaceprefix_ , self.gds_format_decimal(self.GrossOunces, input_name='GrossOunces'), namespaceprefix_ , eol_)) - if self.ContentType is not None: - namespaceprefix_ = self.ContentType_nsprefix_ + ':' if (UseCapturedNS_ and self.ContentType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sContentType>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ContentType), input_name='ContentType')), namespaceprefix_ , eol_)) - if self.ContentTypeOther is not None: - namespaceprefix_ = self.ContentTypeOther_nsprefix_ + ':' if (UseCapturedNS_ and self.ContentTypeOther_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sContentTypeOther>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ContentTypeOther), input_name='ContentTypeOther')), namespaceprefix_ , eol_)) - if self.Agreement is not None: - namespaceprefix_ = self.Agreement_nsprefix_ + ':' if (UseCapturedNS_ and self.Agreement_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAgreement>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Agreement), input_name='Agreement')), namespaceprefix_ , eol_)) - if self.Comments is not None: - namespaceprefix_ = self.Comments_nsprefix_ + ':' if (UseCapturedNS_ and self.Comments_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sComments>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Comments), input_name='Comments')), namespaceprefix_ , eol_)) - if self.LicenseNumber is not None: - namespaceprefix_ = self.LicenseNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.LicenseNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sLicenseNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.LicenseNumber), input_name='LicenseNumber')), namespaceprefix_ , eol_)) - if self.CertificateNumber is not None: - namespaceprefix_ = self.CertificateNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.CertificateNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCertificateNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CertificateNumber), input_name='CertificateNumber')), namespaceprefix_ , eol_)) - if self.InvoiceNumber is not None: - namespaceprefix_ = self.InvoiceNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.InvoiceNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sInvoiceNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.InvoiceNumber), input_name='InvoiceNumber')), namespaceprefix_ , eol_)) - if self.ImageType is not None: - namespaceprefix_ = self.ImageType_nsprefix_ + ':' if (UseCapturedNS_ and self.ImageType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sImageType>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ImageType), input_name='ImageType')), namespaceprefix_ , eol_)) - if self.ImageLayout is not None: - namespaceprefix_ = self.ImageLayout_nsprefix_ + ':' if (UseCapturedNS_ and self.ImageLayout_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sImageLayout>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ImageLayout), input_name='ImageLayout')), namespaceprefix_ , eol_)) - if self.CustomerRefNo is not None: - namespaceprefix_ = self.CustomerRefNo_nsprefix_ + ':' if (UseCapturedNS_ and self.CustomerRefNo_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCustomerRefNo>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CustomerRefNo), input_name='CustomerRefNo')), namespaceprefix_ , eol_)) - if self.CustomerRefNo2 is not None: - namespaceprefix_ = self.CustomerRefNo2_nsprefix_ + ':' if (UseCapturedNS_ and self.CustomerRefNo2_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCustomerRefNo2>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CustomerRefNo2), input_name='CustomerRefNo2')), namespaceprefix_ , eol_)) - if self.POZipCode is not None: - namespaceprefix_ = self.POZipCode_nsprefix_ + ':' if (UseCapturedNS_ and self.POZipCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPOZipCode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.POZipCode), input_name='POZipCode')), namespaceprefix_ , eol_)) - if self.LabelDate is not None: - namespaceprefix_ = self.LabelDate_nsprefix_ + ':' if (UseCapturedNS_ and self.LabelDate_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sLabelDate>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.LabelDate), input_name='LabelDate')), namespaceprefix_ , eol_)) - if self.HoldForManifest is not None: - namespaceprefix_ = self.HoldForManifest_nsprefix_ + ':' if (UseCapturedNS_ and self.HoldForManifest_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sHoldForManifest>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.HoldForManifest), input_name='HoldForManifest')), namespaceprefix_ , eol_)) - if self.EELPFC is not None: - namespaceprefix_ = self.EELPFC_nsprefix_ + ':' if (UseCapturedNS_ and self.EELPFC_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEELPFC>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.EELPFC), input_name='EELPFC')), namespaceprefix_ , eol_)) - if self.Container is not None: - namespaceprefix_ = self.Container_nsprefix_ + ':' if (UseCapturedNS_ and self.Container_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sContainer>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Container), input_name='Container')), namespaceprefix_ , eol_)) - if self.Length is not None: - namespaceprefix_ = self.Length_nsprefix_ + ':' if (UseCapturedNS_ and self.Length_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sLength>%s%s' % (namespaceprefix_ , self.gds_format_decimal(self.Length, input_name='Length'), namespaceprefix_ , eol_)) - if self.Width is not None: - namespaceprefix_ = self.Width_nsprefix_ + ':' if (UseCapturedNS_ and self.Width_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sWidth>%s%s' % (namespaceprefix_ , self.gds_format_decimal(self.Width, input_name='Width'), namespaceprefix_ , eol_)) - if self.Height is not None: - namespaceprefix_ = self.Height_nsprefix_ + ':' if (UseCapturedNS_ and self.Height_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sHeight>%s%s' % (namespaceprefix_ , self.gds_format_decimal(self.Height, input_name='Height'), namespaceprefix_ , eol_)) - if self.Girth is not None: - namespaceprefix_ = self.Girth_nsprefix_ + ':' if (UseCapturedNS_ and self.Girth_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sGirth>%s%s' % (namespaceprefix_ , self.gds_format_decimal(self.Girth, input_name='Girth'), namespaceprefix_ , eol_)) - if self.ExtraServices is not None: - namespaceprefix_ = self.ExtraServices_nsprefix_ + ':' if (UseCapturedNS_ and self.ExtraServices_nsprefix_) else '' - self.ExtraServices.export(outfile, level, namespaceprefix_, namespacedef_='', name_='ExtraServices', pretty_print=pretty_print) - if self.PriceOptions is not None: - namespaceprefix_ = self.PriceOptions_nsprefix_ + ':' if (UseCapturedNS_ and self.PriceOptions_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPriceOptions>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PriceOptions), input_name='PriceOptions')), namespaceprefix_ , eol_)) - if self.ActionCode is not None: - namespaceprefix_ = self.ActionCode_nsprefix_ + ':' if (UseCapturedNS_ and self.ActionCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sActionCode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ActionCode), input_name='ActionCode')), namespaceprefix_ , eol_)) - if self.OptOutOfSPE is not None: - namespaceprefix_ = self.OptOutOfSPE_nsprefix_ + ':' if (UseCapturedNS_ and self.OptOutOfSPE_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sOptOutOfSPE>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.OptOutOfSPE, input_name='OptOutOfSPE'), namespaceprefix_ , eol_)) - if self.PermitNumber is not None: - namespaceprefix_ = self.PermitNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.PermitNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPermitNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PermitNumber), input_name='PermitNumber')), namespaceprefix_ , eol_)) - if self.AccountZipCode is not None: - namespaceprefix_ = self.AccountZipCode_nsprefix_ + ':' if (UseCapturedNS_ and self.AccountZipCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAccountZipCode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.AccountZipCode), input_name='AccountZipCode')), namespaceprefix_ , eol_)) - if self.Machinable is not None: - namespaceprefix_ = self.Machinable_nsprefix_ + ':' if (UseCapturedNS_ and self.Machinable_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sMachinable>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.Machinable, input_name='Machinable'), namespaceprefix_ , eol_)) - if self.DestinationRateIndicator is not None: - namespaceprefix_ = self.DestinationRateIndicator_nsprefix_ + ':' if (UseCapturedNS_ and self.DestinationRateIndicator_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDestinationRateIndicator>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.DestinationRateIndicator), input_name='DestinationRateIndicator')), namespaceprefix_ , eol_)) - if self.MID is not None: - namespaceprefix_ = self.MID_nsprefix_ + ':' if (UseCapturedNS_ and self.MID_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sMID>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.MID), input_name='MID')), namespaceprefix_ , eol_)) - if self.LogisticsManagerMID is not None: - namespaceprefix_ = self.LogisticsManagerMID_nsprefix_ + ':' if (UseCapturedNS_ and self.LogisticsManagerMID_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sLogisticsManagerMID>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.LogisticsManagerMID), input_name='LogisticsManagerMID')), namespaceprefix_ , eol_)) - if self.CRID is not None: - namespaceprefix_ = self.CRID_nsprefix_ + ':' if (UseCapturedNS_ and self.CRID_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCRID>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CRID), input_name='CRID')), namespaceprefix_ , eol_)) - if self.VendorCode is not None: - namespaceprefix_ = self.VendorCode_nsprefix_ + ':' if (UseCapturedNS_ and self.VendorCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sVendorCode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.VendorCode), input_name='VendorCode')), namespaceprefix_ , eol_)) - if self.VendorProductVersionNumber is not None: - namespaceprefix_ = self.VendorProductVersionNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.VendorProductVersionNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sVendorProductVersionNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.VendorProductVersionNumber), input_name='VendorProductVersionNumber')), namespaceprefix_ , eol_)) - if self.ePostageMailerReporting is not None: - namespaceprefix_ = self.ePostageMailerReporting_nsprefix_ + ':' if (UseCapturedNS_ and self.ePostageMailerReporting_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sePostageMailerReporting>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ePostageMailerReporting), input_name='ePostageMailerReporting')), namespaceprefix_ , eol_)) - if self.SenderFirstName is not None: - namespaceprefix_ = self.SenderFirstName_nsprefix_ + ':' if (UseCapturedNS_ and self.SenderFirstName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSenderFirstName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SenderFirstName), input_name='SenderFirstName')), namespaceprefix_ , eol_)) - if self.SenderLastName is not None: - namespaceprefix_ = self.SenderLastName_nsprefix_ + ':' if (UseCapturedNS_ and self.SenderLastName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSenderLastName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SenderLastName), input_name='SenderLastName')), namespaceprefix_ , eol_)) - if self.SenderBusinessName is not None: - namespaceprefix_ = self.SenderBusinessName_nsprefix_ + ':' if (UseCapturedNS_ and self.SenderBusinessName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSenderBusinessName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SenderBusinessName), input_name='SenderBusinessName')), namespaceprefix_ , eol_)) - if self.SenderAddress1 is not None: - namespaceprefix_ = self.SenderAddress1_nsprefix_ + ':' if (UseCapturedNS_ and self.SenderAddress1_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSenderAddress1>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SenderAddress1), input_name='SenderAddress1')), namespaceprefix_ , eol_)) - if self.SenderCity is not None: - namespaceprefix_ = self.SenderCity_nsprefix_ + ':' if (UseCapturedNS_ and self.SenderCity_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSenderCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SenderCity), input_name='SenderCity')), namespaceprefix_ , eol_)) - if self.SenderState is not None: - namespaceprefix_ = self.SenderState_nsprefix_ + ':' if (UseCapturedNS_ and self.SenderState_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSenderState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SenderState), input_name='SenderState')), namespaceprefix_ , eol_)) - if self.SenderZip5 is not None: - namespaceprefix_ = self.SenderZip5_nsprefix_ + ':' if (UseCapturedNS_ and self.SenderZip5_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSenderZip5>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SenderZip5), input_name='SenderZip5')), namespaceprefix_ , eol_)) - if self.SenderPhone is not None: - namespaceprefix_ = self.SenderPhone_nsprefix_ + ':' if (UseCapturedNS_ and self.SenderPhone_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSenderPhone>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SenderPhone), input_name='SenderPhone')), namespaceprefix_ , eol_)) - if self.SenderEmail is not None: - namespaceprefix_ = self.SenderEmail_nsprefix_ + ':' if (UseCapturedNS_ and self.SenderEmail_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSenderEmail>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SenderEmail), input_name='SenderEmail')), namespaceprefix_ , eol_)) - if self.RemainingBarcodes is not None: - namespaceprefix_ = self.RemainingBarcodes_nsprefix_ + ':' if (UseCapturedNS_ and self.RemainingBarcodes_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRemainingBarcodes>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.RemainingBarcodes), input_name='RemainingBarcodes')), namespaceprefix_ , eol_)) - if self.ChargebackCode is not None: - namespaceprefix_ = self.ChargebackCode_nsprefix_ + ':' if (UseCapturedNS_ and self.ChargebackCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sChargebackCode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ChargebackCode), input_name='ChargebackCode')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('USERID', node) - if value is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - self.USERID = value - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'Option': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Option') - value_ = self.gds_validate_string(value_, node, 'Option') - self.Option = value_ - self.Option_nsprefix_ = child_.prefix - elif nodeName_ == 'Revision' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'Revision') - ival_ = self.gds_validate_integer(ival_, node, 'Revision') - self.Revision = ival_ - self.Revision_nsprefix_ = child_.prefix - elif nodeName_ == 'ImageParameters': - obj_ = ImageParametersType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.ImageParameters = obj_ - obj_.original_tagname_ = 'ImageParameters' - elif nodeName_ == 'FromFirstName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromFirstName') - value_ = self.gds_validate_string(value_, node, 'FromFirstName') - self.FromFirstName = value_ - self.FromFirstName_nsprefix_ = child_.prefix - elif nodeName_ == 'FromMiddleInitial': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromMiddleInitial') - value_ = self.gds_validate_string(value_, node, 'FromMiddleInitial') - self.FromMiddleInitial = value_ - self.FromMiddleInitial_nsprefix_ = child_.prefix - elif nodeName_ == 'FromLastName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromLastName') - value_ = self.gds_validate_string(value_, node, 'FromLastName') - self.FromLastName = value_ - self.FromLastName_nsprefix_ = child_.prefix - elif nodeName_ == 'FromFirm': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromFirm') - value_ = self.gds_validate_string(value_, node, 'FromFirm') - self.FromFirm = value_ - self.FromFirm_nsprefix_ = child_.prefix - elif nodeName_ == 'FromAddress1': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromAddress1') - value_ = self.gds_validate_string(value_, node, 'FromAddress1') - self.FromAddress1 = value_ - self.FromAddress1_nsprefix_ = child_.prefix - elif nodeName_ == 'FromAddress2': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromAddress2') - value_ = self.gds_validate_string(value_, node, 'FromAddress2') - self.FromAddress2 = value_ - self.FromAddress2_nsprefix_ = child_.prefix - elif nodeName_ == 'FromUrbanization': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromUrbanization') - value_ = self.gds_validate_string(value_, node, 'FromUrbanization') - self.FromUrbanization = value_ - self.FromUrbanization_nsprefix_ = child_.prefix - elif nodeName_ == 'FromCity': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromCity') - value_ = self.gds_validate_string(value_, node, 'FromCity') - self.FromCity = value_ - self.FromCity_nsprefix_ = child_.prefix - elif nodeName_ == 'FromState': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromState') - value_ = self.gds_validate_string(value_, node, 'FromState') - self.FromState = value_ - self.FromState_nsprefix_ = child_.prefix - elif nodeName_ == 'FromZip5': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromZip5') - value_ = self.gds_validate_string(value_, node, 'FromZip5') - self.FromZip5 = value_ - self.FromZip5_nsprefix_ = child_.prefix - elif nodeName_ == 'FromZip4': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromZip4') - value_ = self.gds_validate_string(value_, node, 'FromZip4') - self.FromZip4 = value_ - self.FromZip4_nsprefix_ = child_.prefix - elif nodeName_ == 'FromPhone': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromPhone') - value_ = self.gds_validate_string(value_, node, 'FromPhone') - self.FromPhone = value_ - self.FromPhone_nsprefix_ = child_.prefix - elif nodeName_ == 'ToName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToName') - value_ = self.gds_validate_string(value_, node, 'ToName') - self.ToName = value_ - self.ToName_nsprefix_ = child_.prefix - elif nodeName_ == 'ToFirstName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToFirstName') - value_ = self.gds_validate_string(value_, node, 'ToFirstName') - self.ToFirstName = value_ - self.ToFirstName_nsprefix_ = child_.prefix - elif nodeName_ == 'ToLastName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToLastName') - value_ = self.gds_validate_string(value_, node, 'ToLastName') - self.ToLastName = value_ - self.ToLastName_nsprefix_ = child_.prefix - elif nodeName_ == 'ToFirm': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToFirm') - value_ = self.gds_validate_string(value_, node, 'ToFirm') - self.ToFirm = value_ - self.ToFirm_nsprefix_ = child_.prefix - elif nodeName_ == 'ToAddress1': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToAddress1') - value_ = self.gds_validate_string(value_, node, 'ToAddress1') - self.ToAddress1 = value_ - self.ToAddress1_nsprefix_ = child_.prefix - elif nodeName_ == 'ToAddress2': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToAddress2') - value_ = self.gds_validate_string(value_, node, 'ToAddress2') - self.ToAddress2 = value_ - self.ToAddress2_nsprefix_ = child_.prefix - elif nodeName_ == 'ToAddress3': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToAddress3') - value_ = self.gds_validate_string(value_, node, 'ToAddress3') - self.ToAddress3 = value_ - self.ToAddress3_nsprefix_ = child_.prefix - elif nodeName_ == 'ToCity': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToCity') - value_ = self.gds_validate_string(value_, node, 'ToCity') - self.ToCity = value_ - self.ToCity_nsprefix_ = child_.prefix - elif nodeName_ == 'ToProvince': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToProvince') - value_ = self.gds_validate_string(value_, node, 'ToProvince') - self.ToProvince = value_ - self.ToProvince_nsprefix_ = child_.prefix - elif nodeName_ == 'ToCountry': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToCountry') - value_ = self.gds_validate_string(value_, node, 'ToCountry') - self.ToCountry = value_ - self.ToCountry_nsprefix_ = child_.prefix - elif nodeName_ == 'ToPostalCode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToPostalCode') - value_ = self.gds_validate_string(value_, node, 'ToPostalCode') - self.ToPostalCode = value_ - self.ToPostalCode_nsprefix_ = child_.prefix - elif nodeName_ == 'ToPOBoxFlag': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToPOBoxFlag') - value_ = self.gds_validate_string(value_, node, 'ToPOBoxFlag') - self.ToPOBoxFlag = value_ - self.ToPOBoxFlag_nsprefix_ = child_.prefix - elif nodeName_ == 'ToPhone': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToPhone') - value_ = self.gds_validate_string(value_, node, 'ToPhone') - self.ToPhone = value_ - self.ToPhone_nsprefix_ = child_.prefix - elif nodeName_ == 'ToFax': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToFax') - value_ = self.gds_validate_string(value_, node, 'ToFax') - self.ToFax = value_ - self.ToFax_nsprefix_ = child_.prefix - elif nodeName_ == 'ToEmail': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToEmail') - value_ = self.gds_validate_string(value_, node, 'ToEmail') - self.ToEmail = value_ - self.ToEmail_nsprefix_ = child_.prefix - elif nodeName_ == 'FirstClassMailType': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FirstClassMailType') - value_ = self.gds_validate_string(value_, node, 'FirstClassMailType') - self.FirstClassMailType = value_ - self.FirstClassMailType_nsprefix_ = child_.prefix - elif nodeName_ == 'ShippingContents': - obj_ = ShippingContentsType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.ShippingContents = obj_ - obj_.original_tagname_ = 'ShippingContents' - elif nodeName_ == 'Postage': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Postage') - value_ = self.gds_validate_string(value_, node, 'Postage') - self.Postage = value_ - self.Postage_nsprefix_ = child_.prefix - elif nodeName_ == 'GrossPounds' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_decimal(sval_, node, 'GrossPounds') - fval_ = self.gds_validate_decimal(fval_, node, 'GrossPounds') - self.GrossPounds = fval_ - self.GrossPounds_nsprefix_ = child_.prefix - elif nodeName_ == 'GrossOunces' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_decimal(sval_, node, 'GrossOunces') - fval_ = self.gds_validate_decimal(fval_, node, 'GrossOunces') - self.GrossOunces = fval_ - self.GrossOunces_nsprefix_ = child_.prefix - elif nodeName_ == 'ContentType': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ContentType') - value_ = self.gds_validate_string(value_, node, 'ContentType') - self.ContentType = value_ - self.ContentType_nsprefix_ = child_.prefix - elif nodeName_ == 'ContentTypeOther': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ContentTypeOther') - value_ = self.gds_validate_string(value_, node, 'ContentTypeOther') - self.ContentTypeOther = value_ - self.ContentTypeOther_nsprefix_ = child_.prefix - elif nodeName_ == 'Agreement': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Agreement') - value_ = self.gds_validate_string(value_, node, 'Agreement') - self.Agreement = value_ - self.Agreement_nsprefix_ = child_.prefix - elif nodeName_ == 'Comments': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Comments') - value_ = self.gds_validate_string(value_, node, 'Comments') - self.Comments = value_ - self.Comments_nsprefix_ = child_.prefix - elif nodeName_ == 'LicenseNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'LicenseNumber') - value_ = self.gds_validate_string(value_, node, 'LicenseNumber') - self.LicenseNumber = value_ - self.LicenseNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'CertificateNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CertificateNumber') - value_ = self.gds_validate_string(value_, node, 'CertificateNumber') - self.CertificateNumber = value_ - self.CertificateNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'InvoiceNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'InvoiceNumber') - value_ = self.gds_validate_string(value_, node, 'InvoiceNumber') - self.InvoiceNumber = value_ - self.InvoiceNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'ImageType': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ImageType') - value_ = self.gds_validate_string(value_, node, 'ImageType') - self.ImageType = value_ - self.ImageType_nsprefix_ = child_.prefix - elif nodeName_ == 'ImageLayout': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ImageLayout') - value_ = self.gds_validate_string(value_, node, 'ImageLayout') - self.ImageLayout = value_ - self.ImageLayout_nsprefix_ = child_.prefix - elif nodeName_ == 'CustomerRefNo': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CustomerRefNo') - value_ = self.gds_validate_string(value_, node, 'CustomerRefNo') - self.CustomerRefNo = value_ - self.CustomerRefNo_nsprefix_ = child_.prefix - elif nodeName_ == 'CustomerRefNo2': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CustomerRefNo2') - value_ = self.gds_validate_string(value_, node, 'CustomerRefNo2') - self.CustomerRefNo2 = value_ - self.CustomerRefNo2_nsprefix_ = child_.prefix - elif nodeName_ == 'POZipCode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'POZipCode') - value_ = self.gds_validate_string(value_, node, 'POZipCode') - self.POZipCode = value_ - self.POZipCode_nsprefix_ = child_.prefix - elif nodeName_ == 'LabelDate': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'LabelDate') - value_ = self.gds_validate_string(value_, node, 'LabelDate') - self.LabelDate = value_ - self.LabelDate_nsprefix_ = child_.prefix - elif nodeName_ == 'HoldForManifest': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'HoldForManifest') - value_ = self.gds_validate_string(value_, node, 'HoldForManifest') - self.HoldForManifest = value_ - self.HoldForManifest_nsprefix_ = child_.prefix - elif nodeName_ == 'EELPFC': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'EELPFC') - value_ = self.gds_validate_string(value_, node, 'EELPFC') - self.EELPFC = value_ - self.EELPFC_nsprefix_ = child_.prefix - elif nodeName_ == 'Container': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Container') - value_ = self.gds_validate_string(value_, node, 'Container') - self.Container = value_ - self.Container_nsprefix_ = child_.prefix - elif nodeName_ == 'Length' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_decimal(sval_, node, 'Length') - fval_ = self.gds_validate_decimal(fval_, node, 'Length') - self.Length = fval_ - self.Length_nsprefix_ = child_.prefix - elif nodeName_ == 'Width' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_decimal(sval_, node, 'Width') - fval_ = self.gds_validate_decimal(fval_, node, 'Width') - self.Width = fval_ - self.Width_nsprefix_ = child_.prefix - elif nodeName_ == 'Height' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_decimal(sval_, node, 'Height') - fval_ = self.gds_validate_decimal(fval_, node, 'Height') - self.Height = fval_ - self.Height_nsprefix_ = child_.prefix - elif nodeName_ == 'Girth' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_decimal(sval_, node, 'Girth') - fval_ = self.gds_validate_decimal(fval_, node, 'Girth') - self.Girth = fval_ - self.Girth_nsprefix_ = child_.prefix - elif nodeName_ == 'ExtraServices': - obj_ = ExtraServicesType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.ExtraServices = obj_ - obj_.original_tagname_ = 'ExtraServices' - elif nodeName_ == 'PriceOptions': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PriceOptions') - value_ = self.gds_validate_string(value_, node, 'PriceOptions') - self.PriceOptions = value_ - self.PriceOptions_nsprefix_ = child_.prefix - elif nodeName_ == 'ActionCode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ActionCode') - value_ = self.gds_validate_string(value_, node, 'ActionCode') - self.ActionCode = value_ - self.ActionCode_nsprefix_ = child_.prefix - elif nodeName_ == 'OptOutOfSPE': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'OptOutOfSPE') - ival_ = self.gds_validate_boolean(ival_, node, 'OptOutOfSPE') - self.OptOutOfSPE = ival_ - self.OptOutOfSPE_nsprefix_ = child_.prefix - elif nodeName_ == 'PermitNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PermitNumber') - value_ = self.gds_validate_string(value_, node, 'PermitNumber') - self.PermitNumber = value_ - self.PermitNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'AccountZipCode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'AccountZipCode') - value_ = self.gds_validate_string(value_, node, 'AccountZipCode') - self.AccountZipCode = value_ - self.AccountZipCode_nsprefix_ = child_.prefix - elif nodeName_ == 'Machinable': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'Machinable') - ival_ = self.gds_validate_boolean(ival_, node, 'Machinable') - self.Machinable = ival_ - self.Machinable_nsprefix_ = child_.prefix - elif nodeName_ == 'DestinationRateIndicator': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'DestinationRateIndicator') - value_ = self.gds_validate_string(value_, node, 'DestinationRateIndicator') - self.DestinationRateIndicator = value_ - self.DestinationRateIndicator_nsprefix_ = child_.prefix - elif nodeName_ == 'MID': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'MID') - value_ = self.gds_validate_string(value_, node, 'MID') - self.MID = value_ - self.MID_nsprefix_ = child_.prefix - elif nodeName_ == 'LogisticsManagerMID': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'LogisticsManagerMID') - value_ = self.gds_validate_string(value_, node, 'LogisticsManagerMID') - self.LogisticsManagerMID = value_ - self.LogisticsManagerMID_nsprefix_ = child_.prefix - elif nodeName_ == 'CRID': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CRID') - value_ = self.gds_validate_string(value_, node, 'CRID') - self.CRID = value_ - self.CRID_nsprefix_ = child_.prefix - elif nodeName_ == 'VendorCode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'VendorCode') - value_ = self.gds_validate_string(value_, node, 'VendorCode') - self.VendorCode = value_ - self.VendorCode_nsprefix_ = child_.prefix - elif nodeName_ == 'VendorProductVersionNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'VendorProductVersionNumber') - value_ = self.gds_validate_string(value_, node, 'VendorProductVersionNumber') - self.VendorProductVersionNumber = value_ - self.VendorProductVersionNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'ePostageMailerReporting': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ePostageMailerReporting') - value_ = self.gds_validate_string(value_, node, 'ePostageMailerReporting') - self.ePostageMailerReporting = value_ - self.ePostageMailerReporting_nsprefix_ = child_.prefix - elif nodeName_ == 'SenderFirstName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SenderFirstName') - value_ = self.gds_validate_string(value_, node, 'SenderFirstName') - self.SenderFirstName = value_ - self.SenderFirstName_nsprefix_ = child_.prefix - elif nodeName_ == 'SenderLastName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SenderLastName') - value_ = self.gds_validate_string(value_, node, 'SenderLastName') - self.SenderLastName = value_ - self.SenderLastName_nsprefix_ = child_.prefix - elif nodeName_ == 'SenderBusinessName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SenderBusinessName') - value_ = self.gds_validate_string(value_, node, 'SenderBusinessName') - self.SenderBusinessName = value_ - self.SenderBusinessName_nsprefix_ = child_.prefix - elif nodeName_ == 'SenderAddress1': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SenderAddress1') - value_ = self.gds_validate_string(value_, node, 'SenderAddress1') - self.SenderAddress1 = value_ - self.SenderAddress1_nsprefix_ = child_.prefix - elif nodeName_ == 'SenderCity': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SenderCity') - value_ = self.gds_validate_string(value_, node, 'SenderCity') - self.SenderCity = value_ - self.SenderCity_nsprefix_ = child_.prefix - elif nodeName_ == 'SenderState': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SenderState') - value_ = self.gds_validate_string(value_, node, 'SenderState') - self.SenderState = value_ - self.SenderState_nsprefix_ = child_.prefix - elif nodeName_ == 'SenderZip5': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SenderZip5') - value_ = self.gds_validate_string(value_, node, 'SenderZip5') - self.SenderZip5 = value_ - self.SenderZip5_nsprefix_ = child_.prefix - elif nodeName_ == 'SenderPhone': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SenderPhone') - value_ = self.gds_validate_string(value_, node, 'SenderPhone') - self.SenderPhone = value_ - self.SenderPhone_nsprefix_ = child_.prefix - elif nodeName_ == 'SenderEmail': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SenderEmail') - value_ = self.gds_validate_string(value_, node, 'SenderEmail') - self.SenderEmail = value_ - self.SenderEmail_nsprefix_ = child_.prefix - elif nodeName_ == 'RemainingBarcodes': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'RemainingBarcodes') - value_ = self.gds_validate_string(value_, node, 'RemainingBarcodes') - self.RemainingBarcodes = value_ - self.RemainingBarcodes_nsprefix_ = child_.prefix - elif nodeName_ == 'ChargebackCode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ChargebackCode') - value_ = self.gds_validate_string(value_, node, 'ChargebackCode') - self.ChargebackCode = value_ - self.ChargebackCode_nsprefix_ = child_.prefix -# end class eVSFirstClassMailIntlRequest - - -class ImageParametersType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ImageParameter=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.ImageParameter = ImageParameter - self.ImageParameter_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, ImageParametersType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if ImageParametersType.subclass: - return ImageParametersType.subclass(*args_, **kwargs_) - else: - return ImageParametersType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_ImageParameter(self): - return self.ImageParameter - def set_ImageParameter(self, ImageParameter): - self.ImageParameter = ImageParameter - def _hasContent(self): - if ( - self.ImageParameter is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ImageParametersType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('ImageParametersType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'ImageParametersType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='ImageParametersType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='ImageParametersType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='ImageParametersType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ImageParametersType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.ImageParameter is not None: - namespaceprefix_ = self.ImageParameter_nsprefix_ + ':' if (UseCapturedNS_ and self.ImageParameter_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sImageParameter>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ImageParameter), input_name='ImageParameter')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'ImageParameter': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ImageParameter') - value_ = self.gds_validate_string(value_, node, 'ImageParameter') - self.ImageParameter = value_ - self.ImageParameter_nsprefix_ = child_.prefix -# end class ImageParametersType - - -class ShippingContentsType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ItemDetail=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - if ItemDetail is None: - self.ItemDetail = [] - else: - self.ItemDetail = ItemDetail - self.ItemDetail_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, ShippingContentsType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if ShippingContentsType.subclass: - return ShippingContentsType.subclass(*args_, **kwargs_) - else: - return ShippingContentsType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_ItemDetail(self): - return self.ItemDetail - def set_ItemDetail(self, ItemDetail): - self.ItemDetail = ItemDetail - def add_ItemDetail(self, value): - self.ItemDetail.append(value) - def insert_ItemDetail_at(self, index, value): - self.ItemDetail.insert(index, value) - def replace_ItemDetail_at(self, index, value): - self.ItemDetail[index] = value - def _hasContent(self): - if ( - self.ItemDetail - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ShippingContentsType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('ShippingContentsType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'ShippingContentsType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='ShippingContentsType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='ShippingContentsType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='ShippingContentsType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ShippingContentsType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - for ItemDetail_ in self.ItemDetail: - namespaceprefix_ = self.ItemDetail_nsprefix_ + ':' if (UseCapturedNS_ and self.ItemDetail_nsprefix_) else '' - ItemDetail_.export(outfile, level, namespaceprefix_, namespacedef_='', name_='ItemDetail', pretty_print=pretty_print) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'ItemDetail': - obj_ = ItemDetailType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.ItemDetail.append(obj_) - obj_.original_tagname_ = 'ItemDetail' -# end class ShippingContentsType - - -class ItemDetailType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, Description=None, Quantity=None, Value=None, NetPounds=None, NetOunces=None, HSTariffNumber=None, CountryOfOrigin=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.Description = Description - self.Description_nsprefix_ = None - self.Quantity = Quantity - self.Quantity_nsprefix_ = None - self.Value = Value - self.Value_nsprefix_ = None - self.NetPounds = NetPounds - self.NetPounds_nsprefix_ = None - self.NetOunces = NetOunces - self.NetOunces_nsprefix_ = None - self.HSTariffNumber = HSTariffNumber - self.HSTariffNumber_nsprefix_ = None - self.CountryOfOrigin = CountryOfOrigin - self.CountryOfOrigin_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, ItemDetailType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if ItemDetailType.subclass: - return ItemDetailType.subclass(*args_, **kwargs_) - else: - return ItemDetailType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_Description(self): - return self.Description - def set_Description(self, Description): - self.Description = Description - def get_Quantity(self): - return self.Quantity - def set_Quantity(self, Quantity): - self.Quantity = Quantity - def get_Value(self): - return self.Value - def set_Value(self, Value): - self.Value = Value - def get_NetPounds(self): - return self.NetPounds - def set_NetPounds(self, NetPounds): - self.NetPounds = NetPounds - def get_NetOunces(self): - return self.NetOunces - def set_NetOunces(self, NetOunces): - self.NetOunces = NetOunces - def get_HSTariffNumber(self): - return self.HSTariffNumber - def set_HSTariffNumber(self, HSTariffNumber): - self.HSTariffNumber = HSTariffNumber - def get_CountryOfOrigin(self): - return self.CountryOfOrigin - def set_CountryOfOrigin(self, CountryOfOrigin): - self.CountryOfOrigin = CountryOfOrigin - def _hasContent(self): - if ( - self.Description is not None or - self.Quantity is not None or - self.Value is not None or - self.NetPounds is not None or - self.NetOunces is not None or - self.HSTariffNumber is not None or - self.CountryOfOrigin is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ItemDetailType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('ItemDetailType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'ItemDetailType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='ItemDetailType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='ItemDetailType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='ItemDetailType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ItemDetailType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.Description is not None: - namespaceprefix_ = self.Description_nsprefix_ + ':' if (UseCapturedNS_ and self.Description_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDescription>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Description), input_name='Description')), namespaceprefix_ , eol_)) - if self.Quantity is not None: - namespaceprefix_ = self.Quantity_nsprefix_ + ':' if (UseCapturedNS_ and self.Quantity_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sQuantity>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.Quantity, input_name='Quantity'), namespaceprefix_ , eol_)) - if self.Value is not None: - namespaceprefix_ = self.Value_nsprefix_ + ':' if (UseCapturedNS_ and self.Value_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sValue>%s%s' % (namespaceprefix_ , self.gds_format_decimal(self.Value, input_name='Value'), namespaceprefix_ , eol_)) - if self.NetPounds is not None: - namespaceprefix_ = self.NetPounds_nsprefix_ + ':' if (UseCapturedNS_ and self.NetPounds_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sNetPounds>%s%s' % (namespaceprefix_ , self.gds_format_decimal(self.NetPounds, input_name='NetPounds'), namespaceprefix_ , eol_)) - if self.NetOunces is not None: - namespaceprefix_ = self.NetOunces_nsprefix_ + ':' if (UseCapturedNS_ and self.NetOunces_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sNetOunces>%s%s' % (namespaceprefix_ , self.gds_format_decimal(self.NetOunces, input_name='NetOunces'), namespaceprefix_ , eol_)) - if self.HSTariffNumber is not None: - namespaceprefix_ = self.HSTariffNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.HSTariffNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sHSTariffNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.HSTariffNumber), input_name='HSTariffNumber')), namespaceprefix_ , eol_)) - if self.CountryOfOrigin is not None: - namespaceprefix_ = self.CountryOfOrigin_nsprefix_ + ':' if (UseCapturedNS_ and self.CountryOfOrigin_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCountryOfOrigin>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CountryOfOrigin), input_name='CountryOfOrigin')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'Description': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Description') - value_ = self.gds_validate_string(value_, node, 'Description') - self.Description = value_ - self.Description_nsprefix_ = child_.prefix - elif nodeName_ == 'Quantity' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'Quantity') - ival_ = self.gds_validate_integer(ival_, node, 'Quantity') - self.Quantity = ival_ - self.Quantity_nsprefix_ = child_.prefix - elif nodeName_ == 'Value' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_decimal(sval_, node, 'Value') - fval_ = self.gds_validate_decimal(fval_, node, 'Value') - self.Value = fval_ - self.Value_nsprefix_ = child_.prefix - elif nodeName_ == 'NetPounds' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_decimal(sval_, node, 'NetPounds') - fval_ = self.gds_validate_decimal(fval_, node, 'NetPounds') - self.NetPounds = fval_ - self.NetPounds_nsprefix_ = child_.prefix - elif nodeName_ == 'NetOunces' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_decimal(sval_, node, 'NetOunces') - fval_ = self.gds_validate_decimal(fval_, node, 'NetOunces') - self.NetOunces = fval_ - self.NetOunces_nsprefix_ = child_.prefix - elif nodeName_ == 'HSTariffNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'HSTariffNumber') - value_ = self.gds_validate_string(value_, node, 'HSTariffNumber') - self.HSTariffNumber = value_ - self.HSTariffNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'CountryOfOrigin': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CountryOfOrigin') - value_ = self.gds_validate_string(value_, node, 'CountryOfOrigin') - self.CountryOfOrigin = value_ - self.CountryOfOrigin_nsprefix_ = child_.prefix -# end class ItemDetailType - - -class ExtraServicesType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ExtraService=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - if ExtraService is None: - self.ExtraService = [] - else: - self.ExtraService = ExtraService - self.ExtraService_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, ExtraServicesType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if ExtraServicesType.subclass: - return ExtraServicesType.subclass(*args_, **kwargs_) - else: - return ExtraServicesType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_ExtraService(self): - return self.ExtraService - def set_ExtraService(self, ExtraService): - self.ExtraService = ExtraService - def add_ExtraService(self, value): - self.ExtraService.append(value) - def insert_ExtraService_at(self, index, value): - self.ExtraService.insert(index, value) - def replace_ExtraService_at(self, index, value): - self.ExtraService[index] = value - def _hasContent(self): - if ( - self.ExtraService - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ExtraServicesType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('ExtraServicesType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'ExtraServicesType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='ExtraServicesType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='ExtraServicesType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='ExtraServicesType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ExtraServicesType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - for ExtraService_ in self.ExtraService: - namespaceprefix_ = self.ExtraService_nsprefix_ + ':' if (UseCapturedNS_ and self.ExtraService_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sExtraService>%s%s' % (namespaceprefix_ , self.gds_format_integer(ExtraService_, input_name='ExtraService'), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'ExtraService' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'ExtraService') - ival_ = self.gds_validate_integer(ival_, node, 'ExtraService') - self.ExtraService.append(ival_) - self.ExtraService_nsprefix_ = child_.prefix -# end class ExtraServicesType - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSFirstClassMailIntlRequest' - rootClass = eVSFirstClassMailIntlRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSFirstClassMailIntlRequest' - rootClass = eVSFirstClassMailIntlRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSFirstClassMailIntlRequest' - rootClass = eVSFirstClassMailIntlRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSFirstClassMailIntlRequest' - rootClass = eVSFirstClassMailIntlRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from evs_first_class_mail_intl_request import *\n\n') - sys.stdout.write('import evs_first_class_mail_intl_request as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "ExtraServicesType", - "ImageParametersType", - "ItemDetailType", - "ShippingContentsType", - "eVSFirstClassMailIntlRequest" -] diff --git a/schemas/usps/karrio/schemas/usps/evs_first_class_mail_intl_response.py b/schemas/usps/karrio/schemas/usps/evs_first_class_mail_intl_response.py deleted file mode 100644 index 0df5917508..0000000000 --- a/schemas/usps/karrio/schemas/usps/evs_first_class_mail_intl_response.py +++ /dev/null @@ -1,1735 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:15 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/evs_first_class_mail_intl_response.py') -# -# Command line arguments: -# ./schemas/eVSFirstClassMailIntlResponse.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/evs_first_class_mail_intl_response.py" ./schemas/eVSFirstClassMailIntlResponse.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class eVSFirstClassMailIntlResponse(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, Postage=None, TotalValue=None, BarcodeNumber=None, LabelImage=None, Page2Image=None, Page3Image=None, Prohibitions=None, Restrictions=None, Observations=None, Regulations=None, AdditionalRestrictions=None, ExtraServices=None, RemainingBarcodes=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.Postage = Postage - self.Postage_nsprefix_ = None - self.TotalValue = TotalValue - self.TotalValue_nsprefix_ = None - self.BarcodeNumber = BarcodeNumber - self.BarcodeNumber_nsprefix_ = None - self.LabelImage = LabelImage - self.LabelImage_nsprefix_ = None - self.Page2Image = Page2Image - self.Page2Image_nsprefix_ = None - self.Page3Image = Page3Image - self.Page3Image_nsprefix_ = None - self.Prohibitions = Prohibitions - self.Prohibitions_nsprefix_ = None - self.Restrictions = Restrictions - self.Restrictions_nsprefix_ = None - self.Observations = Observations - self.Observations_nsprefix_ = None - self.Regulations = Regulations - self.Regulations_nsprefix_ = None - self.AdditionalRestrictions = AdditionalRestrictions - self.AdditionalRestrictions_nsprefix_ = None - self.ExtraServices = ExtraServices - self.ExtraServices_nsprefix_ = None - self.RemainingBarcodes = RemainingBarcodes - self.RemainingBarcodes_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, eVSFirstClassMailIntlResponse) - if subclass is not None: - return subclass(*args_, **kwargs_) - if eVSFirstClassMailIntlResponse.subclass: - return eVSFirstClassMailIntlResponse.subclass(*args_, **kwargs_) - else: - return eVSFirstClassMailIntlResponse(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_Postage(self): - return self.Postage - def set_Postage(self, Postage): - self.Postage = Postage - def get_TotalValue(self): - return self.TotalValue - def set_TotalValue(self, TotalValue): - self.TotalValue = TotalValue - def get_BarcodeNumber(self): - return self.BarcodeNumber - def set_BarcodeNumber(self, BarcodeNumber): - self.BarcodeNumber = BarcodeNumber - def get_LabelImage(self): - return self.LabelImage - def set_LabelImage(self, LabelImage): - self.LabelImage = LabelImage - def get_Page2Image(self): - return self.Page2Image - def set_Page2Image(self, Page2Image): - self.Page2Image = Page2Image - def get_Page3Image(self): - return self.Page3Image - def set_Page3Image(self, Page3Image): - self.Page3Image = Page3Image - def get_Prohibitions(self): - return self.Prohibitions - def set_Prohibitions(self, Prohibitions): - self.Prohibitions = Prohibitions - def get_Restrictions(self): - return self.Restrictions - def set_Restrictions(self, Restrictions): - self.Restrictions = Restrictions - def get_Observations(self): - return self.Observations - def set_Observations(self, Observations): - self.Observations = Observations - def get_Regulations(self): - return self.Regulations - def set_Regulations(self, Regulations): - self.Regulations = Regulations - def get_AdditionalRestrictions(self): - return self.AdditionalRestrictions - def set_AdditionalRestrictions(self, AdditionalRestrictions): - self.AdditionalRestrictions = AdditionalRestrictions - def get_ExtraServices(self): - return self.ExtraServices - def set_ExtraServices(self, ExtraServices): - self.ExtraServices = ExtraServices - def get_RemainingBarcodes(self): - return self.RemainingBarcodes - def set_RemainingBarcodes(self, RemainingBarcodes): - self.RemainingBarcodes = RemainingBarcodes - def _hasContent(self): - if ( - self.Postage is not None or - self.TotalValue is not None or - self.BarcodeNumber is not None or - self.LabelImage is not None or - self.Page2Image is not None or - self.Page3Image is not None or - self.Prohibitions is not None or - self.Restrictions is not None or - self.Observations is not None or - self.Regulations is not None or - self.AdditionalRestrictions is not None or - self.ExtraServices is not None or - self.RemainingBarcodes is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='eVSFirstClassMailIntlResponse', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('eVSFirstClassMailIntlResponse') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'eVSFirstClassMailIntlResponse': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='eVSFirstClassMailIntlResponse') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='eVSFirstClassMailIntlResponse', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='eVSFirstClassMailIntlResponse'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='eVSFirstClassMailIntlResponse', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.Postage is not None: - namespaceprefix_ = self.Postage_nsprefix_ + ':' if (UseCapturedNS_ and self.Postage_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPostage>%s%s' % (namespaceprefix_ , self.gds_format_float(self.Postage, input_name='Postage'), namespaceprefix_ , eol_)) - if self.TotalValue is not None: - namespaceprefix_ = self.TotalValue_nsprefix_ + ':' if (UseCapturedNS_ and self.TotalValue_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sTotalValue>%s%s' % (namespaceprefix_ , self.gds_format_float(self.TotalValue, input_name='TotalValue'), namespaceprefix_ , eol_)) - if self.BarcodeNumber is not None: - namespaceprefix_ = self.BarcodeNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.BarcodeNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sBarcodeNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.BarcodeNumber), input_name='BarcodeNumber')), namespaceprefix_ , eol_)) - if self.LabelImage is not None: - namespaceprefix_ = self.LabelImage_nsprefix_ + ':' if (UseCapturedNS_ and self.LabelImage_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sLabelImage>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.LabelImage), input_name='LabelImage')), namespaceprefix_ , eol_)) - if self.Page2Image is not None: - namespaceprefix_ = self.Page2Image_nsprefix_ + ':' if (UseCapturedNS_ and self.Page2Image_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPage2Image>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Page2Image), input_name='Page2Image')), namespaceprefix_ , eol_)) - if self.Page3Image is not None: - namespaceprefix_ = self.Page3Image_nsprefix_ + ':' if (UseCapturedNS_ and self.Page3Image_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPage3Image>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Page3Image), input_name='Page3Image')), namespaceprefix_ , eol_)) - if self.Prohibitions is not None: - namespaceprefix_ = self.Prohibitions_nsprefix_ + ':' if (UseCapturedNS_ and self.Prohibitions_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sProhibitions>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Prohibitions), input_name='Prohibitions')), namespaceprefix_ , eol_)) - if self.Restrictions is not None: - namespaceprefix_ = self.Restrictions_nsprefix_ + ':' if (UseCapturedNS_ and self.Restrictions_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRestrictions>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Restrictions), input_name='Restrictions')), namespaceprefix_ , eol_)) - if self.Observations is not None: - namespaceprefix_ = self.Observations_nsprefix_ + ':' if (UseCapturedNS_ and self.Observations_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sObservations>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Observations), input_name='Observations')), namespaceprefix_ , eol_)) - if self.Regulations is not None: - namespaceprefix_ = self.Regulations_nsprefix_ + ':' if (UseCapturedNS_ and self.Regulations_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRegulations>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Regulations), input_name='Regulations')), namespaceprefix_ , eol_)) - if self.AdditionalRestrictions is not None: - namespaceprefix_ = self.AdditionalRestrictions_nsprefix_ + ':' if (UseCapturedNS_ and self.AdditionalRestrictions_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAdditionalRestrictions>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.AdditionalRestrictions), input_name='AdditionalRestrictions')), namespaceprefix_ , eol_)) - if self.ExtraServices is not None: - namespaceprefix_ = self.ExtraServices_nsprefix_ + ':' if (UseCapturedNS_ and self.ExtraServices_nsprefix_) else '' - self.ExtraServices.export(outfile, level, namespaceprefix_, namespacedef_='', name_='ExtraServices', pretty_print=pretty_print) - if self.RemainingBarcodes is not None: - namespaceprefix_ = self.RemainingBarcodes_nsprefix_ + ':' if (UseCapturedNS_ and self.RemainingBarcodes_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRemainingBarcodes>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.RemainingBarcodes, input_name='RemainingBarcodes'), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'Postage' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'Postage') - fval_ = self.gds_validate_float(fval_, node, 'Postage') - self.Postage = fval_ - self.Postage_nsprefix_ = child_.prefix - elif nodeName_ == 'TotalValue' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'TotalValue') - fval_ = self.gds_validate_float(fval_, node, 'TotalValue') - self.TotalValue = fval_ - self.TotalValue_nsprefix_ = child_.prefix - elif nodeName_ == 'BarcodeNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'BarcodeNumber') - value_ = self.gds_validate_string(value_, node, 'BarcodeNumber') - self.BarcodeNumber = value_ - self.BarcodeNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'LabelImage': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'LabelImage') - value_ = self.gds_validate_string(value_, node, 'LabelImage') - self.LabelImage = value_ - self.LabelImage_nsprefix_ = child_.prefix - elif nodeName_ == 'Page2Image': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Page2Image') - value_ = self.gds_validate_string(value_, node, 'Page2Image') - self.Page2Image = value_ - self.Page2Image_nsprefix_ = child_.prefix - elif nodeName_ == 'Page3Image': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Page3Image') - value_ = self.gds_validate_string(value_, node, 'Page3Image') - self.Page3Image = value_ - self.Page3Image_nsprefix_ = child_.prefix - elif nodeName_ == 'Prohibitions': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Prohibitions') - value_ = self.gds_validate_string(value_, node, 'Prohibitions') - self.Prohibitions = value_ - self.Prohibitions_nsprefix_ = child_.prefix - elif nodeName_ == 'Restrictions': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Restrictions') - value_ = self.gds_validate_string(value_, node, 'Restrictions') - self.Restrictions = value_ - self.Restrictions_nsprefix_ = child_.prefix - elif nodeName_ == 'Observations': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Observations') - value_ = self.gds_validate_string(value_, node, 'Observations') - self.Observations = value_ - self.Observations_nsprefix_ = child_.prefix - elif nodeName_ == 'Regulations': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Regulations') - value_ = self.gds_validate_string(value_, node, 'Regulations') - self.Regulations = value_ - self.Regulations_nsprefix_ = child_.prefix - elif nodeName_ == 'AdditionalRestrictions': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'AdditionalRestrictions') - value_ = self.gds_validate_string(value_, node, 'AdditionalRestrictions') - self.AdditionalRestrictions = value_ - self.AdditionalRestrictions_nsprefix_ = child_.prefix - elif nodeName_ == 'ExtraServices': - obj_ = ExtraServicesType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.ExtraServices = obj_ - obj_.original_tagname_ = 'ExtraServices' - elif nodeName_ == 'RemainingBarcodes' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'RemainingBarcodes') - ival_ = self.gds_validate_integer(ival_, node, 'RemainingBarcodes') - self.RemainingBarcodes = ival_ - self.RemainingBarcodes_nsprefix_ = child_.prefix -# end class eVSFirstClassMailIntlResponse - - -class ExtraServicesType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ExtraService=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - if ExtraService is None: - self.ExtraService = [] - else: - self.ExtraService = ExtraService - self.ExtraService_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, ExtraServicesType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if ExtraServicesType.subclass: - return ExtraServicesType.subclass(*args_, **kwargs_) - else: - return ExtraServicesType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_ExtraService(self): - return self.ExtraService - def set_ExtraService(self, ExtraService): - self.ExtraService = ExtraService - def add_ExtraService(self, value): - self.ExtraService.append(value) - def insert_ExtraService_at(self, index, value): - self.ExtraService.insert(index, value) - def replace_ExtraService_at(self, index, value): - self.ExtraService[index] = value - def _hasContent(self): - if ( - self.ExtraService - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ExtraServicesType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('ExtraServicesType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'ExtraServicesType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='ExtraServicesType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='ExtraServicesType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='ExtraServicesType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ExtraServicesType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - for ExtraService_ in self.ExtraService: - namespaceprefix_ = self.ExtraService_nsprefix_ + ':' if (UseCapturedNS_ and self.ExtraService_nsprefix_) else '' - ExtraService_.export(outfile, level, namespaceprefix_, namespacedef_='', name_='ExtraService', pretty_print=pretty_print) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'ExtraService': - obj_ = ExtraServiceType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.ExtraService.append(obj_) - obj_.original_tagname_ = 'ExtraService' -# end class ExtraServicesType - - -class ExtraServiceType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ServiceID=None, ServiceName=None, Price=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.ServiceID = ServiceID - self.ServiceID_nsprefix_ = None - self.ServiceName = ServiceName - self.ServiceName_nsprefix_ = None - self.Price = Price - self.Price_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, ExtraServiceType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if ExtraServiceType.subclass: - return ExtraServiceType.subclass(*args_, **kwargs_) - else: - return ExtraServiceType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_ServiceID(self): - return self.ServiceID - def set_ServiceID(self, ServiceID): - self.ServiceID = ServiceID - def get_ServiceName(self): - return self.ServiceName - def set_ServiceName(self, ServiceName): - self.ServiceName = ServiceName - def get_Price(self): - return self.Price - def set_Price(self, Price): - self.Price = Price - def _hasContent(self): - if ( - self.ServiceID is not None or - self.ServiceName is not None or - self.Price is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ExtraServiceType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('ExtraServiceType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'ExtraServiceType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='ExtraServiceType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='ExtraServiceType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='ExtraServiceType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ExtraServiceType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.ServiceID is not None: - namespaceprefix_ = self.ServiceID_nsprefix_ + ':' if (UseCapturedNS_ and self.ServiceID_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sServiceID>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.ServiceID, input_name='ServiceID'), namespaceprefix_ , eol_)) - if self.ServiceName is not None: - namespaceprefix_ = self.ServiceName_nsprefix_ + ':' if (UseCapturedNS_ and self.ServiceName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sServiceName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ServiceName), input_name='ServiceName')), namespaceprefix_ , eol_)) - if self.Price is not None: - namespaceprefix_ = self.Price_nsprefix_ + ':' if (UseCapturedNS_ and self.Price_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPrice>%s%s' % (namespaceprefix_ , self.gds_format_float(self.Price, input_name='Price'), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'ServiceID' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'ServiceID') - ival_ = self.gds_validate_integer(ival_, node, 'ServiceID') - self.ServiceID = ival_ - self.ServiceID_nsprefix_ = child_.prefix - elif nodeName_ == 'ServiceName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ServiceName') - value_ = self.gds_validate_string(value_, node, 'ServiceName') - self.ServiceName = value_ - self.ServiceName_nsprefix_ = child_.prefix - elif nodeName_ == 'Price' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'Price') - fval_ = self.gds_validate_float(fval_, node, 'Price') - self.Price = fval_ - self.Price_nsprefix_ = child_.prefix -# end class ExtraServiceType - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSFirstClassMailIntlResponse' - rootClass = eVSFirstClassMailIntlResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSFirstClassMailIntlResponse' - rootClass = eVSFirstClassMailIntlResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSFirstClassMailIntlResponse' - rootClass = eVSFirstClassMailIntlResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSFirstClassMailIntlResponse' - rootClass = eVSFirstClassMailIntlResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from evs_first_class_mail_intl_response import *\n\n') - sys.stdout.write('import evs_first_class_mail_intl_response as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "ExtraServiceType", - "ExtraServicesType", - "eVSFirstClassMailIntlResponse" -] diff --git a/schemas/usps/karrio/schemas/usps/evs_gxg_get_label_request.py b/schemas/usps/karrio/schemas/usps/evs_gxg_get_label_request.py deleted file mode 100644 index 4c3d74a116..0000000000 --- a/schemas/usps/karrio/schemas/usps/evs_gxg_get_label_request.py +++ /dev/null @@ -1,3341 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:15 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/evs_gxg_get_label_request.py') -# -# Command line arguments: -# ./schemas/eVSGXGGetLabelRequest.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/evs_gxg_get_label_request.py" ./schemas/eVSGXGGetLabelRequest.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class eVSGXGGetLabelRequest(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, USERID=None, PASSWORD=None, Option=None, Revision=None, ImageParameters=None, FromFirstName=None, FromMiddleInitial=None, FromLastName=None, FromFirm=None, FromAddress1=None, FromAddress2=None, FromUrbanization=None, FromCity=None, FromState=None, FromZIP5=None, FromZIP4=None, FromPhone=None, ShipFromZIP=None, SenderEMail=None, ToFirstName=None, ToLastName=None, ToFirm=None, ToAddress1=None, ToAddress2=None, ToAddress3=None, ToPostalCode=None, ToPhone=None, RecipientEMail=None, ToDPID=None, ToProvince=None, ToTaxID=None, Container=None, ContentType=None, ShippingContents=None, PurposeOfShipment=None, PartiesToTransaction=None, Agreement=None, Postage=None, InsuredValue=None, GrossPounds=None, GrossOunces=None, Length=None, Width=None, Height=None, Girth=None, Shape=None, CIRequired=None, InvoiceDate=None, InvoiceNumber=None, CustomerOrderNumber=None, CustOrderNumber=None, TermsDelivery=None, TermsDeliveryOther=None, PackingCost=None, CountryUltDest=None, CIAgreement=None, ImageType=None, ImageLayout=None, CustomerRefNo=None, CustomerRefNo2=None, ShipDate=None, HoldForManifest=None, PriceOptions=None, CommercialShipment=None, BuyerFirstName=None, BuyerLastName=None, BuyerAddress1=None, BuyerAddress2=None, BuyerAddress3=None, BuyerCity=None, BuyerState=None, BuyerPostalCode=None, BuyerCountry=None, BuyerTaxID=None, BuyerRecipient=None, TermsPayment=None, ActionCode=None, OptOutOfSPE=None, PermitNumber=None, AccountZipCode=None, Machinable=None, DestinationRateIndicator=None, MID=None, LogisticsManagerMID=None, CRID=None, VendorCode=None, VendorProductVersionNumber=None, OverrideMID=None, ChargebackCode=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.USERID = _cast(None, USERID) - self.USERID_nsprefix_ = None - self.PASSWORD = _cast(None, PASSWORD) - self.PASSWORD_nsprefix_ = None - self.Option = Option - self.Option_nsprefix_ = None - self.Revision = Revision - self.Revision_nsprefix_ = None - self.ImageParameters = ImageParameters - self.ImageParameters_nsprefix_ = None - self.FromFirstName = FromFirstName - self.FromFirstName_nsprefix_ = None - self.FromMiddleInitial = FromMiddleInitial - self.FromMiddleInitial_nsprefix_ = None - self.FromLastName = FromLastName - self.FromLastName_nsprefix_ = None - self.FromFirm = FromFirm - self.FromFirm_nsprefix_ = None - self.FromAddress1 = FromAddress1 - self.FromAddress1_nsprefix_ = None - self.FromAddress2 = FromAddress2 - self.FromAddress2_nsprefix_ = None - self.FromUrbanization = FromUrbanization - self.FromUrbanization_nsprefix_ = None - self.FromCity = FromCity - self.FromCity_nsprefix_ = None - self.FromState = FromState - self.FromState_nsprefix_ = None - self.FromZIP5 = FromZIP5 - self.FromZIP5_nsprefix_ = None - self.FromZIP4 = FromZIP4 - self.FromZIP4_nsprefix_ = None - self.FromPhone = FromPhone - self.FromPhone_nsprefix_ = None - self.ShipFromZIP = ShipFromZIP - self.ShipFromZIP_nsprefix_ = None - self.SenderEMail = SenderEMail - self.SenderEMail_nsprefix_ = None - self.ToFirstName = ToFirstName - self.ToFirstName_nsprefix_ = None - self.ToLastName = ToLastName - self.ToLastName_nsprefix_ = None - self.ToFirm = ToFirm - self.ToFirm_nsprefix_ = None - self.ToAddress1 = ToAddress1 - self.ToAddress1_nsprefix_ = None - self.ToAddress2 = ToAddress2 - self.ToAddress2_nsprefix_ = None - self.ToAddress3 = ToAddress3 - self.ToAddress3_nsprefix_ = None - self.ToPostalCode = ToPostalCode - self.ToPostalCode_nsprefix_ = None - self.ToPhone = ToPhone - self.ToPhone_nsprefix_ = None - self.RecipientEMail = RecipientEMail - self.RecipientEMail_nsprefix_ = None - self.ToDPID = ToDPID - self.ToDPID_nsprefix_ = None - self.ToProvince = ToProvince - self.ToProvince_nsprefix_ = None - self.ToTaxID = ToTaxID - self.ToTaxID_nsprefix_ = None - self.Container = Container - self.Container_nsprefix_ = None - self.ContentType = ContentType - self.ContentType_nsprefix_ = None - self.ShippingContents = ShippingContents - self.ShippingContents_nsprefix_ = None - self.PurposeOfShipment = PurposeOfShipment - self.PurposeOfShipment_nsprefix_ = None - self.PartiesToTransaction = PartiesToTransaction - self.PartiesToTransaction_nsprefix_ = None - self.Agreement = Agreement - self.Agreement_nsprefix_ = None - self.Postage = Postage - self.Postage_nsprefix_ = None - self.InsuredValue = InsuredValue - self.InsuredValue_nsprefix_ = None - self.GrossPounds = GrossPounds - self.GrossPounds_nsprefix_ = None - self.GrossOunces = GrossOunces - self.GrossOunces_nsprefix_ = None - self.Length = Length - self.Length_nsprefix_ = None - self.Width = Width - self.Width_nsprefix_ = None - self.Height = Height - self.Height_nsprefix_ = None - self.Girth = Girth - self.Girth_nsprefix_ = None - self.Shape = Shape - self.Shape_nsprefix_ = None - self.CIRequired = CIRequired - self.CIRequired_nsprefix_ = None - self.InvoiceDate = InvoiceDate - self.InvoiceDate_nsprefix_ = None - self.InvoiceNumber = InvoiceNumber - self.InvoiceNumber_nsprefix_ = None - self.CustomerOrderNumber = CustomerOrderNumber - self.CustomerOrderNumber_nsprefix_ = None - self.CustOrderNumber = CustOrderNumber - self.CustOrderNumber_nsprefix_ = None - self.TermsDelivery = TermsDelivery - self.TermsDelivery_nsprefix_ = None - self.TermsDeliveryOther = TermsDeliveryOther - self.TermsDeliveryOther_nsprefix_ = None - self.PackingCost = PackingCost - self.PackingCost_nsprefix_ = None - self.CountryUltDest = CountryUltDest - self.CountryUltDest_nsprefix_ = None - self.CIAgreement = CIAgreement - self.CIAgreement_nsprefix_ = None - self.ImageType = ImageType - self.ImageType_nsprefix_ = None - self.ImageLayout = ImageLayout - self.ImageLayout_nsprefix_ = None - self.CustomerRefNo = CustomerRefNo - self.CustomerRefNo_nsprefix_ = None - self.CustomerRefNo2 = CustomerRefNo2 - self.CustomerRefNo2_nsprefix_ = None - self.ShipDate = ShipDate - self.ShipDate_nsprefix_ = None - self.HoldForManifest = HoldForManifest - self.HoldForManifest_nsprefix_ = None - self.PriceOptions = PriceOptions - self.PriceOptions_nsprefix_ = None - self.CommercialShipment = CommercialShipment - self.CommercialShipment_nsprefix_ = None - self.BuyerFirstName = BuyerFirstName - self.BuyerFirstName_nsprefix_ = None - self.BuyerLastName = BuyerLastName - self.BuyerLastName_nsprefix_ = None - self.BuyerAddress1 = BuyerAddress1 - self.BuyerAddress1_nsprefix_ = None - self.BuyerAddress2 = BuyerAddress2 - self.BuyerAddress2_nsprefix_ = None - self.BuyerAddress3 = BuyerAddress3 - self.BuyerAddress3_nsprefix_ = None - self.BuyerCity = BuyerCity - self.BuyerCity_nsprefix_ = None - self.BuyerState = BuyerState - self.BuyerState_nsprefix_ = None - self.BuyerPostalCode = BuyerPostalCode - self.BuyerPostalCode_nsprefix_ = None - self.BuyerCountry = BuyerCountry - self.BuyerCountry_nsprefix_ = None - self.BuyerTaxID = BuyerTaxID - self.BuyerTaxID_nsprefix_ = None - self.BuyerRecipient = BuyerRecipient - self.BuyerRecipient_nsprefix_ = None - self.TermsPayment = TermsPayment - self.TermsPayment_nsprefix_ = None - self.ActionCode = ActionCode - self.ActionCode_nsprefix_ = None - self.OptOutOfSPE = OptOutOfSPE - self.OptOutOfSPE_nsprefix_ = None - self.PermitNumber = PermitNumber - self.PermitNumber_nsprefix_ = None - self.AccountZipCode = AccountZipCode - self.AccountZipCode_nsprefix_ = None - self.Machinable = Machinable - self.Machinable_nsprefix_ = None - self.DestinationRateIndicator = DestinationRateIndicator - self.DestinationRateIndicator_nsprefix_ = None - self.MID = MID - self.MID_nsprefix_ = None - self.LogisticsManagerMID = LogisticsManagerMID - self.LogisticsManagerMID_nsprefix_ = None - self.CRID = CRID - self.CRID_nsprefix_ = None - self.VendorCode = VendorCode - self.VendorCode_nsprefix_ = None - self.VendorProductVersionNumber = VendorProductVersionNumber - self.VendorProductVersionNumber_nsprefix_ = None - self.OverrideMID = OverrideMID - self.OverrideMID_nsprefix_ = None - self.ChargebackCode = ChargebackCode - self.ChargebackCode_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, eVSGXGGetLabelRequest) - if subclass is not None: - return subclass(*args_, **kwargs_) - if eVSGXGGetLabelRequest.subclass: - return eVSGXGGetLabelRequest.subclass(*args_, **kwargs_) - else: - return eVSGXGGetLabelRequest(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_Option(self): - return self.Option - def set_Option(self, Option): - self.Option = Option - def get_Revision(self): - return self.Revision - def set_Revision(self, Revision): - self.Revision = Revision - def get_ImageParameters(self): - return self.ImageParameters - def set_ImageParameters(self, ImageParameters): - self.ImageParameters = ImageParameters - def get_FromFirstName(self): - return self.FromFirstName - def set_FromFirstName(self, FromFirstName): - self.FromFirstName = FromFirstName - def get_FromMiddleInitial(self): - return self.FromMiddleInitial - def set_FromMiddleInitial(self, FromMiddleInitial): - self.FromMiddleInitial = FromMiddleInitial - def get_FromLastName(self): - return self.FromLastName - def set_FromLastName(self, FromLastName): - self.FromLastName = FromLastName - def get_FromFirm(self): - return self.FromFirm - def set_FromFirm(self, FromFirm): - self.FromFirm = FromFirm - def get_FromAddress1(self): - return self.FromAddress1 - def set_FromAddress1(self, FromAddress1): - self.FromAddress1 = FromAddress1 - def get_FromAddress2(self): - return self.FromAddress2 - def set_FromAddress2(self, FromAddress2): - self.FromAddress2 = FromAddress2 - def get_FromUrbanization(self): - return self.FromUrbanization - def set_FromUrbanization(self, FromUrbanization): - self.FromUrbanization = FromUrbanization - def get_FromCity(self): - return self.FromCity - def set_FromCity(self, FromCity): - self.FromCity = FromCity - def get_FromState(self): - return self.FromState - def set_FromState(self, FromState): - self.FromState = FromState - def get_FromZIP5(self): - return self.FromZIP5 - def set_FromZIP5(self, FromZIP5): - self.FromZIP5 = FromZIP5 - def get_FromZIP4(self): - return self.FromZIP4 - def set_FromZIP4(self, FromZIP4): - self.FromZIP4 = FromZIP4 - def get_FromPhone(self): - return self.FromPhone - def set_FromPhone(self, FromPhone): - self.FromPhone = FromPhone - def get_ShipFromZIP(self): - return self.ShipFromZIP - def set_ShipFromZIP(self, ShipFromZIP): - self.ShipFromZIP = ShipFromZIP - def get_SenderEMail(self): - return self.SenderEMail - def set_SenderEMail(self, SenderEMail): - self.SenderEMail = SenderEMail - def get_ToFirstName(self): - return self.ToFirstName - def set_ToFirstName(self, ToFirstName): - self.ToFirstName = ToFirstName - def get_ToLastName(self): - return self.ToLastName - def set_ToLastName(self, ToLastName): - self.ToLastName = ToLastName - def get_ToFirm(self): - return self.ToFirm - def set_ToFirm(self, ToFirm): - self.ToFirm = ToFirm - def get_ToAddress1(self): - return self.ToAddress1 - def set_ToAddress1(self, ToAddress1): - self.ToAddress1 = ToAddress1 - def get_ToAddress2(self): - return self.ToAddress2 - def set_ToAddress2(self, ToAddress2): - self.ToAddress2 = ToAddress2 - def get_ToAddress3(self): - return self.ToAddress3 - def set_ToAddress3(self, ToAddress3): - self.ToAddress3 = ToAddress3 - def get_ToPostalCode(self): - return self.ToPostalCode - def set_ToPostalCode(self, ToPostalCode): - self.ToPostalCode = ToPostalCode - def get_ToPhone(self): - return self.ToPhone - def set_ToPhone(self, ToPhone): - self.ToPhone = ToPhone - def get_RecipientEMail(self): - return self.RecipientEMail - def set_RecipientEMail(self, RecipientEMail): - self.RecipientEMail = RecipientEMail - def get_ToDPID(self): - return self.ToDPID - def set_ToDPID(self, ToDPID): - self.ToDPID = ToDPID - def get_ToProvince(self): - return self.ToProvince - def set_ToProvince(self, ToProvince): - self.ToProvince = ToProvince - def get_ToTaxID(self): - return self.ToTaxID - def set_ToTaxID(self, ToTaxID): - self.ToTaxID = ToTaxID - def get_Container(self): - return self.Container - def set_Container(self, Container): - self.Container = Container - def get_ContentType(self): - return self.ContentType - def set_ContentType(self, ContentType): - self.ContentType = ContentType - def get_ShippingContents(self): - return self.ShippingContents - def set_ShippingContents(self, ShippingContents): - self.ShippingContents = ShippingContents - def get_PurposeOfShipment(self): - return self.PurposeOfShipment - def set_PurposeOfShipment(self, PurposeOfShipment): - self.PurposeOfShipment = PurposeOfShipment - def get_PartiesToTransaction(self): - return self.PartiesToTransaction - def set_PartiesToTransaction(self, PartiesToTransaction): - self.PartiesToTransaction = PartiesToTransaction - def get_Agreement(self): - return self.Agreement - def set_Agreement(self, Agreement): - self.Agreement = Agreement - def get_Postage(self): - return self.Postage - def set_Postage(self, Postage): - self.Postage = Postage - def get_InsuredValue(self): - return self.InsuredValue - def set_InsuredValue(self, InsuredValue): - self.InsuredValue = InsuredValue - def get_GrossPounds(self): - return self.GrossPounds - def set_GrossPounds(self, GrossPounds): - self.GrossPounds = GrossPounds - def get_GrossOunces(self): - return self.GrossOunces - def set_GrossOunces(self, GrossOunces): - self.GrossOunces = GrossOunces - def get_Length(self): - return self.Length - def set_Length(self, Length): - self.Length = Length - def get_Width(self): - return self.Width - def set_Width(self, Width): - self.Width = Width - def get_Height(self): - return self.Height - def set_Height(self, Height): - self.Height = Height - def get_Girth(self): - return self.Girth - def set_Girth(self, Girth): - self.Girth = Girth - def get_Shape(self): - return self.Shape - def set_Shape(self, Shape): - self.Shape = Shape - def get_CIRequired(self): - return self.CIRequired - def set_CIRequired(self, CIRequired): - self.CIRequired = CIRequired - def get_InvoiceDate(self): - return self.InvoiceDate - def set_InvoiceDate(self, InvoiceDate): - self.InvoiceDate = InvoiceDate - def get_InvoiceNumber(self): - return self.InvoiceNumber - def set_InvoiceNumber(self, InvoiceNumber): - self.InvoiceNumber = InvoiceNumber - def get_CustomerOrderNumber(self): - return self.CustomerOrderNumber - def set_CustomerOrderNumber(self, CustomerOrderNumber): - self.CustomerOrderNumber = CustomerOrderNumber - def get_CustOrderNumber(self): - return self.CustOrderNumber - def set_CustOrderNumber(self, CustOrderNumber): - self.CustOrderNumber = CustOrderNumber - def get_TermsDelivery(self): - return self.TermsDelivery - def set_TermsDelivery(self, TermsDelivery): - self.TermsDelivery = TermsDelivery - def get_TermsDeliveryOther(self): - return self.TermsDeliveryOther - def set_TermsDeliveryOther(self, TermsDeliveryOther): - self.TermsDeliveryOther = TermsDeliveryOther - def get_PackingCost(self): - return self.PackingCost - def set_PackingCost(self, PackingCost): - self.PackingCost = PackingCost - def get_CountryUltDest(self): - return self.CountryUltDest - def set_CountryUltDest(self, CountryUltDest): - self.CountryUltDest = CountryUltDest - def get_CIAgreement(self): - return self.CIAgreement - def set_CIAgreement(self, CIAgreement): - self.CIAgreement = CIAgreement - def get_ImageType(self): - return self.ImageType - def set_ImageType(self, ImageType): - self.ImageType = ImageType - def get_ImageLayout(self): - return self.ImageLayout - def set_ImageLayout(self, ImageLayout): - self.ImageLayout = ImageLayout - def get_CustomerRefNo(self): - return self.CustomerRefNo - def set_CustomerRefNo(self, CustomerRefNo): - self.CustomerRefNo = CustomerRefNo - def get_CustomerRefNo2(self): - return self.CustomerRefNo2 - def set_CustomerRefNo2(self, CustomerRefNo2): - self.CustomerRefNo2 = CustomerRefNo2 - def get_ShipDate(self): - return self.ShipDate - def set_ShipDate(self, ShipDate): - self.ShipDate = ShipDate - def get_HoldForManifest(self): - return self.HoldForManifest - def set_HoldForManifest(self, HoldForManifest): - self.HoldForManifest = HoldForManifest - def get_PriceOptions(self): - return self.PriceOptions - def set_PriceOptions(self, PriceOptions): - self.PriceOptions = PriceOptions - def get_CommercialShipment(self): - return self.CommercialShipment - def set_CommercialShipment(self, CommercialShipment): - self.CommercialShipment = CommercialShipment - def get_BuyerFirstName(self): - return self.BuyerFirstName - def set_BuyerFirstName(self, BuyerFirstName): - self.BuyerFirstName = BuyerFirstName - def get_BuyerLastName(self): - return self.BuyerLastName - def set_BuyerLastName(self, BuyerLastName): - self.BuyerLastName = BuyerLastName - def get_BuyerAddress1(self): - return self.BuyerAddress1 - def set_BuyerAddress1(self, BuyerAddress1): - self.BuyerAddress1 = BuyerAddress1 - def get_BuyerAddress2(self): - return self.BuyerAddress2 - def set_BuyerAddress2(self, BuyerAddress2): - self.BuyerAddress2 = BuyerAddress2 - def get_BuyerAddress3(self): - return self.BuyerAddress3 - def set_BuyerAddress3(self, BuyerAddress3): - self.BuyerAddress3 = BuyerAddress3 - def get_BuyerCity(self): - return self.BuyerCity - def set_BuyerCity(self, BuyerCity): - self.BuyerCity = BuyerCity - def get_BuyerState(self): - return self.BuyerState - def set_BuyerState(self, BuyerState): - self.BuyerState = BuyerState - def get_BuyerPostalCode(self): - return self.BuyerPostalCode - def set_BuyerPostalCode(self, BuyerPostalCode): - self.BuyerPostalCode = BuyerPostalCode - def get_BuyerCountry(self): - return self.BuyerCountry - def set_BuyerCountry(self, BuyerCountry): - self.BuyerCountry = BuyerCountry - def get_BuyerTaxID(self): - return self.BuyerTaxID - def set_BuyerTaxID(self, BuyerTaxID): - self.BuyerTaxID = BuyerTaxID - def get_BuyerRecipient(self): - return self.BuyerRecipient - def set_BuyerRecipient(self, BuyerRecipient): - self.BuyerRecipient = BuyerRecipient - def get_TermsPayment(self): - return self.TermsPayment - def set_TermsPayment(self, TermsPayment): - self.TermsPayment = TermsPayment - def get_ActionCode(self): - return self.ActionCode - def set_ActionCode(self, ActionCode): - self.ActionCode = ActionCode - def get_OptOutOfSPE(self): - return self.OptOutOfSPE - def set_OptOutOfSPE(self, OptOutOfSPE): - self.OptOutOfSPE = OptOutOfSPE - def get_PermitNumber(self): - return self.PermitNumber - def set_PermitNumber(self, PermitNumber): - self.PermitNumber = PermitNumber - def get_AccountZipCode(self): - return self.AccountZipCode - def set_AccountZipCode(self, AccountZipCode): - self.AccountZipCode = AccountZipCode - def get_Machinable(self): - return self.Machinable - def set_Machinable(self, Machinable): - self.Machinable = Machinable - def get_DestinationRateIndicator(self): - return self.DestinationRateIndicator - def set_DestinationRateIndicator(self, DestinationRateIndicator): - self.DestinationRateIndicator = DestinationRateIndicator - def get_MID(self): - return self.MID - def set_MID(self, MID): - self.MID = MID - def get_LogisticsManagerMID(self): - return self.LogisticsManagerMID - def set_LogisticsManagerMID(self, LogisticsManagerMID): - self.LogisticsManagerMID = LogisticsManagerMID - def get_CRID(self): - return self.CRID - def set_CRID(self, CRID): - self.CRID = CRID - def get_VendorCode(self): - return self.VendorCode - def set_VendorCode(self, VendorCode): - self.VendorCode = VendorCode - def get_VendorProductVersionNumber(self): - return self.VendorProductVersionNumber - def set_VendorProductVersionNumber(self, VendorProductVersionNumber): - self.VendorProductVersionNumber = VendorProductVersionNumber - def get_OverrideMID(self): - return self.OverrideMID - def set_OverrideMID(self, OverrideMID): - self.OverrideMID = OverrideMID - def get_ChargebackCode(self): - return self.ChargebackCode - def set_ChargebackCode(self, ChargebackCode): - self.ChargebackCode = ChargebackCode - def get_USERID(self): - return self.USERID - def set_USERID(self, USERID): - self.USERID = USERID - def get_PASSWORD(self): - return self.PASSWORD - def set_PASSWORD(self, PASSWORD): - self.PASSWORD = PASSWORD - def _hasContent(self): - if ( - self.Option is not None or - self.Revision is not None or - self.ImageParameters is not None or - self.FromFirstName is not None or - self.FromMiddleInitial is not None or - self.FromLastName is not None or - self.FromFirm is not None or - self.FromAddress1 is not None or - self.FromAddress2 is not None or - self.FromUrbanization is not None or - self.FromCity is not None or - self.FromState is not None or - self.FromZIP5 is not None or - self.FromZIP4 is not None or - self.FromPhone is not None or - self.ShipFromZIP is not None or - self.SenderEMail is not None or - self.ToFirstName is not None or - self.ToLastName is not None or - self.ToFirm is not None or - self.ToAddress1 is not None or - self.ToAddress2 is not None or - self.ToAddress3 is not None or - self.ToPostalCode is not None or - self.ToPhone is not None or - self.RecipientEMail is not None or - self.ToDPID is not None or - self.ToProvince is not None or - self.ToTaxID is not None or - self.Container is not None or - self.ContentType is not None or - self.ShippingContents is not None or - self.PurposeOfShipment is not None or - self.PartiesToTransaction is not None or - self.Agreement is not None or - self.Postage is not None or - self.InsuredValue is not None or - self.GrossPounds is not None or - self.GrossOunces is not None or - self.Length is not None or - self.Width is not None or - self.Height is not None or - self.Girth is not None or - self.Shape is not None or - self.CIRequired is not None or - self.InvoiceDate is not None or - self.InvoiceNumber is not None or - self.CustomerOrderNumber is not None or - self.CustOrderNumber is not None or - self.TermsDelivery is not None or - self.TermsDeliveryOther is not None or - self.PackingCost is not None or - self.CountryUltDest is not None or - self.CIAgreement is not None or - self.ImageType is not None or - self.ImageLayout is not None or - self.CustomerRefNo is not None or - self.CustomerRefNo2 is not None or - self.ShipDate is not None or - self.HoldForManifest is not None or - self.PriceOptions is not None or - self.CommercialShipment is not None or - self.BuyerFirstName is not None or - self.BuyerLastName is not None or - self.BuyerAddress1 is not None or - self.BuyerAddress2 is not None or - self.BuyerAddress3 is not None or - self.BuyerCity is not None or - self.BuyerState is not None or - self.BuyerPostalCode is not None or - self.BuyerCountry is not None or - self.BuyerTaxID is not None or - self.BuyerRecipient is not None or - self.TermsPayment is not None or - self.ActionCode is not None or - self.OptOutOfSPE is not None or - self.PermitNumber is not None or - self.AccountZipCode is not None or - self.Machinable is not None or - self.DestinationRateIndicator is not None or - self.MID is not None or - self.LogisticsManagerMID is not None or - self.CRID is not None or - self.VendorCode is not None or - self.VendorProductVersionNumber is not None or - self.OverrideMID is not None or - self.ChargebackCode is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='eVSGXGGetLabelRequest', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('eVSGXGGetLabelRequest') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'eVSGXGGetLabelRequest': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='eVSGXGGetLabelRequest') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='eVSGXGGetLabelRequest', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='eVSGXGGetLabelRequest'): - if self.USERID is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - outfile.write(' USERID=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.USERID), input_name='USERID')), )) - if self.PASSWORD is not None and 'PASSWORD' not in already_processed: - already_processed.add('PASSWORD') - outfile.write(' PASSWORD=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.PASSWORD), input_name='PASSWORD')), )) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='eVSGXGGetLabelRequest', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.Option is not None: - namespaceprefix_ = self.Option_nsprefix_ + ':' if (UseCapturedNS_ and self.Option_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sOption>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Option), input_name='Option')), namespaceprefix_ , eol_)) - if self.Revision is not None: - namespaceprefix_ = self.Revision_nsprefix_ + ':' if (UseCapturedNS_ and self.Revision_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRevision>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Revision), input_name='Revision')), namespaceprefix_ , eol_)) - if self.ImageParameters is not None: - namespaceprefix_ = self.ImageParameters_nsprefix_ + ':' if (UseCapturedNS_ and self.ImageParameters_nsprefix_) else '' - self.ImageParameters.export(outfile, level, namespaceprefix_, namespacedef_='', name_='ImageParameters', pretty_print=pretty_print) - if self.FromFirstName is not None: - namespaceprefix_ = self.FromFirstName_nsprefix_ + ':' if (UseCapturedNS_ and self.FromFirstName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromFirstName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromFirstName), input_name='FromFirstName')), namespaceprefix_ , eol_)) - if self.FromMiddleInitial is not None: - namespaceprefix_ = self.FromMiddleInitial_nsprefix_ + ':' if (UseCapturedNS_ and self.FromMiddleInitial_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromMiddleInitial>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromMiddleInitial), input_name='FromMiddleInitial')), namespaceprefix_ , eol_)) - if self.FromLastName is not None: - namespaceprefix_ = self.FromLastName_nsprefix_ + ':' if (UseCapturedNS_ and self.FromLastName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromLastName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromLastName), input_name='FromLastName')), namespaceprefix_ , eol_)) - if self.FromFirm is not None: - namespaceprefix_ = self.FromFirm_nsprefix_ + ':' if (UseCapturedNS_ and self.FromFirm_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromFirm>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromFirm), input_name='FromFirm')), namespaceprefix_ , eol_)) - if self.FromAddress1 is not None: - namespaceprefix_ = self.FromAddress1_nsprefix_ + ':' if (UseCapturedNS_ and self.FromAddress1_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromAddress1>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromAddress1), input_name='FromAddress1')), namespaceprefix_ , eol_)) - if self.FromAddress2 is not None: - namespaceprefix_ = self.FromAddress2_nsprefix_ + ':' if (UseCapturedNS_ and self.FromAddress2_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromAddress2>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromAddress2), input_name='FromAddress2')), namespaceprefix_ , eol_)) - if self.FromUrbanization is not None: - namespaceprefix_ = self.FromUrbanization_nsprefix_ + ':' if (UseCapturedNS_ and self.FromUrbanization_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromUrbanization>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromUrbanization), input_name='FromUrbanization')), namespaceprefix_ , eol_)) - if self.FromCity is not None: - namespaceprefix_ = self.FromCity_nsprefix_ + ':' if (UseCapturedNS_ and self.FromCity_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromCity), input_name='FromCity')), namespaceprefix_ , eol_)) - if self.FromState is not None: - namespaceprefix_ = self.FromState_nsprefix_ + ':' if (UseCapturedNS_ and self.FromState_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromState), input_name='FromState')), namespaceprefix_ , eol_)) - if self.FromZIP5 is not None: - namespaceprefix_ = self.FromZIP5_nsprefix_ + ':' if (UseCapturedNS_ and self.FromZIP5_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromZIP5>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromZIP5), input_name='FromZIP5')), namespaceprefix_ , eol_)) - if self.FromZIP4 is not None: - namespaceprefix_ = self.FromZIP4_nsprefix_ + ':' if (UseCapturedNS_ and self.FromZIP4_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromZIP4>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromZIP4), input_name='FromZIP4')), namespaceprefix_ , eol_)) - if self.FromPhone is not None: - namespaceprefix_ = self.FromPhone_nsprefix_ + ':' if (UseCapturedNS_ and self.FromPhone_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromPhone>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromPhone), input_name='FromPhone')), namespaceprefix_ , eol_)) - if self.ShipFromZIP is not None: - namespaceprefix_ = self.ShipFromZIP_nsprefix_ + ':' if (UseCapturedNS_ and self.ShipFromZIP_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sShipFromZIP>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ShipFromZIP), input_name='ShipFromZIP')), namespaceprefix_ , eol_)) - if self.SenderEMail is not None: - namespaceprefix_ = self.SenderEMail_nsprefix_ + ':' if (UseCapturedNS_ and self.SenderEMail_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSenderEMail>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SenderEMail), input_name='SenderEMail')), namespaceprefix_ , eol_)) - if self.ToFirstName is not None: - namespaceprefix_ = self.ToFirstName_nsprefix_ + ':' if (UseCapturedNS_ and self.ToFirstName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToFirstName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToFirstName), input_name='ToFirstName')), namespaceprefix_ , eol_)) - if self.ToLastName is not None: - namespaceprefix_ = self.ToLastName_nsprefix_ + ':' if (UseCapturedNS_ and self.ToLastName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToLastName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToLastName), input_name='ToLastName')), namespaceprefix_ , eol_)) - if self.ToFirm is not None: - namespaceprefix_ = self.ToFirm_nsprefix_ + ':' if (UseCapturedNS_ and self.ToFirm_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToFirm>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToFirm), input_name='ToFirm')), namespaceprefix_ , eol_)) - if self.ToAddress1 is not None: - namespaceprefix_ = self.ToAddress1_nsprefix_ + ':' if (UseCapturedNS_ and self.ToAddress1_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToAddress1>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToAddress1), input_name='ToAddress1')), namespaceprefix_ , eol_)) - if self.ToAddress2 is not None: - namespaceprefix_ = self.ToAddress2_nsprefix_ + ':' if (UseCapturedNS_ and self.ToAddress2_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToAddress2>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToAddress2), input_name='ToAddress2')), namespaceprefix_ , eol_)) - if self.ToAddress3 is not None: - namespaceprefix_ = self.ToAddress3_nsprefix_ + ':' if (UseCapturedNS_ and self.ToAddress3_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToAddress3>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToAddress3), input_name='ToAddress3')), namespaceprefix_ , eol_)) - if self.ToPostalCode is not None: - namespaceprefix_ = self.ToPostalCode_nsprefix_ + ':' if (UseCapturedNS_ and self.ToPostalCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToPostalCode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToPostalCode), input_name='ToPostalCode')), namespaceprefix_ , eol_)) - if self.ToPhone is not None: - namespaceprefix_ = self.ToPhone_nsprefix_ + ':' if (UseCapturedNS_ and self.ToPhone_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToPhone>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToPhone), input_name='ToPhone')), namespaceprefix_ , eol_)) - if self.RecipientEMail is not None: - namespaceprefix_ = self.RecipientEMail_nsprefix_ + ':' if (UseCapturedNS_ and self.RecipientEMail_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRecipientEMail>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.RecipientEMail), input_name='RecipientEMail')), namespaceprefix_ , eol_)) - if self.ToDPID is not None: - namespaceprefix_ = self.ToDPID_nsprefix_ + ':' if (UseCapturedNS_ and self.ToDPID_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToDPID>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToDPID), input_name='ToDPID')), namespaceprefix_ , eol_)) - if self.ToProvince is not None: - namespaceprefix_ = self.ToProvince_nsprefix_ + ':' if (UseCapturedNS_ and self.ToProvince_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToProvince>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToProvince), input_name='ToProvince')), namespaceprefix_ , eol_)) - if self.ToTaxID is not None: - namespaceprefix_ = self.ToTaxID_nsprefix_ + ':' if (UseCapturedNS_ and self.ToTaxID_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToTaxID>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToTaxID), input_name='ToTaxID')), namespaceprefix_ , eol_)) - if self.Container is not None: - namespaceprefix_ = self.Container_nsprefix_ + ':' if (UseCapturedNS_ and self.Container_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sContainer>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Container), input_name='Container')), namespaceprefix_ , eol_)) - if self.ContentType is not None: - namespaceprefix_ = self.ContentType_nsprefix_ + ':' if (UseCapturedNS_ and self.ContentType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sContentType>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ContentType), input_name='ContentType')), namespaceprefix_ , eol_)) - if self.ShippingContents is not None: - namespaceprefix_ = self.ShippingContents_nsprefix_ + ':' if (UseCapturedNS_ and self.ShippingContents_nsprefix_) else '' - self.ShippingContents.export(outfile, level, namespaceprefix_, namespacedef_='', name_='ShippingContents', pretty_print=pretty_print) - if self.PurposeOfShipment is not None: - namespaceprefix_ = self.PurposeOfShipment_nsprefix_ + ':' if (UseCapturedNS_ and self.PurposeOfShipment_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPurposeOfShipment>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PurposeOfShipment), input_name='PurposeOfShipment')), namespaceprefix_ , eol_)) - if self.PartiesToTransaction is not None: - namespaceprefix_ = self.PartiesToTransaction_nsprefix_ + ':' if (UseCapturedNS_ and self.PartiesToTransaction_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPartiesToTransaction>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PartiesToTransaction), input_name='PartiesToTransaction')), namespaceprefix_ , eol_)) - if self.Agreement is not None: - namespaceprefix_ = self.Agreement_nsprefix_ + ':' if (UseCapturedNS_ and self.Agreement_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAgreement>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Agreement), input_name='Agreement')), namespaceprefix_ , eol_)) - if self.Postage is not None: - namespaceprefix_ = self.Postage_nsprefix_ + ':' if (UseCapturedNS_ and self.Postage_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPostage>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Postage), input_name='Postage')), namespaceprefix_ , eol_)) - if self.InsuredValue is not None: - namespaceprefix_ = self.InsuredValue_nsprefix_ + ':' if (UseCapturedNS_ and self.InsuredValue_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sInsuredValue>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.InsuredValue), input_name='InsuredValue')), namespaceprefix_ , eol_)) - if self.GrossPounds is not None: - namespaceprefix_ = self.GrossPounds_nsprefix_ + ':' if (UseCapturedNS_ and self.GrossPounds_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sGrossPounds>%s%s' % (namespaceprefix_ , self.gds_format_decimal(self.GrossPounds, input_name='GrossPounds'), namespaceprefix_ , eol_)) - if self.GrossOunces is not None: - namespaceprefix_ = self.GrossOunces_nsprefix_ + ':' if (UseCapturedNS_ and self.GrossOunces_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sGrossOunces>%s%s' % (namespaceprefix_ , self.gds_format_decimal(self.GrossOunces, input_name='GrossOunces'), namespaceprefix_ , eol_)) - if self.Length is not None: - namespaceprefix_ = self.Length_nsprefix_ + ':' if (UseCapturedNS_ and self.Length_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sLength>%s%s' % (namespaceprefix_ , self.gds_format_decimal(self.Length, input_name='Length'), namespaceprefix_ , eol_)) - if self.Width is not None: - namespaceprefix_ = self.Width_nsprefix_ + ':' if (UseCapturedNS_ and self.Width_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sWidth>%s%s' % (namespaceprefix_ , self.gds_format_decimal(self.Width, input_name='Width'), namespaceprefix_ , eol_)) - if self.Height is not None: - namespaceprefix_ = self.Height_nsprefix_ + ':' if (UseCapturedNS_ and self.Height_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sHeight>%s%s' % (namespaceprefix_ , self.gds_format_decimal(self.Height, input_name='Height'), namespaceprefix_ , eol_)) - if self.Girth is not None: - namespaceprefix_ = self.Girth_nsprefix_ + ':' if (UseCapturedNS_ and self.Girth_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sGirth>%s%s' % (namespaceprefix_ , self.gds_format_decimal(self.Girth, input_name='Girth'), namespaceprefix_ , eol_)) - if self.Shape is not None: - namespaceprefix_ = self.Shape_nsprefix_ + ':' if (UseCapturedNS_ and self.Shape_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sShape>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Shape), input_name='Shape')), namespaceprefix_ , eol_)) - if self.CIRequired is not None: - namespaceprefix_ = self.CIRequired_nsprefix_ + ':' if (UseCapturedNS_ and self.CIRequired_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCIRequired>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.CIRequired, input_name='CIRequired'), namespaceprefix_ , eol_)) - if self.InvoiceDate is not None: - namespaceprefix_ = self.InvoiceDate_nsprefix_ + ':' if (UseCapturedNS_ and self.InvoiceDate_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sInvoiceDate>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.InvoiceDate), input_name='InvoiceDate')), namespaceprefix_ , eol_)) - if self.InvoiceNumber is not None: - namespaceprefix_ = self.InvoiceNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.InvoiceNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sInvoiceNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.InvoiceNumber), input_name='InvoiceNumber')), namespaceprefix_ , eol_)) - if self.CustomerOrderNumber is not None: - namespaceprefix_ = self.CustomerOrderNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.CustomerOrderNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCustomerOrderNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CustomerOrderNumber), input_name='CustomerOrderNumber')), namespaceprefix_ , eol_)) - if self.CustOrderNumber is not None: - namespaceprefix_ = self.CustOrderNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.CustOrderNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCustOrderNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CustOrderNumber), input_name='CustOrderNumber')), namespaceprefix_ , eol_)) - if self.TermsDelivery is not None: - namespaceprefix_ = self.TermsDelivery_nsprefix_ + ':' if (UseCapturedNS_ and self.TermsDelivery_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sTermsDelivery>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.TermsDelivery), input_name='TermsDelivery')), namespaceprefix_ , eol_)) - if self.TermsDeliveryOther is not None: - namespaceprefix_ = self.TermsDeliveryOther_nsprefix_ + ':' if (UseCapturedNS_ and self.TermsDeliveryOther_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sTermsDeliveryOther>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.TermsDeliveryOther), input_name='TermsDeliveryOther')), namespaceprefix_ , eol_)) - if self.PackingCost is not None: - namespaceprefix_ = self.PackingCost_nsprefix_ + ':' if (UseCapturedNS_ and self.PackingCost_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPackingCost>%s%s' % (namespaceprefix_ , self.gds_format_decimal(self.PackingCost, input_name='PackingCost'), namespaceprefix_ , eol_)) - if self.CountryUltDest is not None: - namespaceprefix_ = self.CountryUltDest_nsprefix_ + ':' if (UseCapturedNS_ and self.CountryUltDest_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCountryUltDest>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CountryUltDest), input_name='CountryUltDest')), namespaceprefix_ , eol_)) - if self.CIAgreement is not None: - namespaceprefix_ = self.CIAgreement_nsprefix_ + ':' if (UseCapturedNS_ and self.CIAgreement_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCIAgreement>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CIAgreement), input_name='CIAgreement')), namespaceprefix_ , eol_)) - if self.ImageType is not None: - namespaceprefix_ = self.ImageType_nsprefix_ + ':' if (UseCapturedNS_ and self.ImageType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sImageType>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ImageType), input_name='ImageType')), namespaceprefix_ , eol_)) - if self.ImageLayout is not None: - namespaceprefix_ = self.ImageLayout_nsprefix_ + ':' if (UseCapturedNS_ and self.ImageLayout_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sImageLayout>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ImageLayout), input_name='ImageLayout')), namespaceprefix_ , eol_)) - if self.CustomerRefNo is not None: - namespaceprefix_ = self.CustomerRefNo_nsprefix_ + ':' if (UseCapturedNS_ and self.CustomerRefNo_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCustomerRefNo>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CustomerRefNo), input_name='CustomerRefNo')), namespaceprefix_ , eol_)) - if self.CustomerRefNo2 is not None: - namespaceprefix_ = self.CustomerRefNo2_nsprefix_ + ':' if (UseCapturedNS_ and self.CustomerRefNo2_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCustomerRefNo2>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CustomerRefNo2), input_name='CustomerRefNo2')), namespaceprefix_ , eol_)) - if self.ShipDate is not None: - namespaceprefix_ = self.ShipDate_nsprefix_ + ':' if (UseCapturedNS_ and self.ShipDate_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sShipDate>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ShipDate), input_name='ShipDate')), namespaceprefix_ , eol_)) - if self.HoldForManifest is not None: - namespaceprefix_ = self.HoldForManifest_nsprefix_ + ':' if (UseCapturedNS_ and self.HoldForManifest_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sHoldForManifest>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.HoldForManifest), input_name='HoldForManifest')), namespaceprefix_ , eol_)) - if self.PriceOptions is not None: - namespaceprefix_ = self.PriceOptions_nsprefix_ + ':' if (UseCapturedNS_ and self.PriceOptions_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPriceOptions>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PriceOptions), input_name='PriceOptions')), namespaceprefix_ , eol_)) - if self.CommercialShipment is not None: - namespaceprefix_ = self.CommercialShipment_nsprefix_ + ':' if (UseCapturedNS_ and self.CommercialShipment_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCommercialShipment>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.CommercialShipment, input_name='CommercialShipment'), namespaceprefix_ , eol_)) - if self.BuyerFirstName is not None: - namespaceprefix_ = self.BuyerFirstName_nsprefix_ + ':' if (UseCapturedNS_ and self.BuyerFirstName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sBuyerFirstName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.BuyerFirstName), input_name='BuyerFirstName')), namespaceprefix_ , eol_)) - if self.BuyerLastName is not None: - namespaceprefix_ = self.BuyerLastName_nsprefix_ + ':' if (UseCapturedNS_ and self.BuyerLastName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sBuyerLastName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.BuyerLastName), input_name='BuyerLastName')), namespaceprefix_ , eol_)) - if self.BuyerAddress1 is not None: - namespaceprefix_ = self.BuyerAddress1_nsprefix_ + ':' if (UseCapturedNS_ and self.BuyerAddress1_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sBuyerAddress1>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.BuyerAddress1), input_name='BuyerAddress1')), namespaceprefix_ , eol_)) - if self.BuyerAddress2 is not None: - namespaceprefix_ = self.BuyerAddress2_nsprefix_ + ':' if (UseCapturedNS_ and self.BuyerAddress2_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sBuyerAddress2>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.BuyerAddress2), input_name='BuyerAddress2')), namespaceprefix_ , eol_)) - if self.BuyerAddress3 is not None: - namespaceprefix_ = self.BuyerAddress3_nsprefix_ + ':' if (UseCapturedNS_ and self.BuyerAddress3_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sBuyerAddress3>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.BuyerAddress3), input_name='BuyerAddress3')), namespaceprefix_ , eol_)) - if self.BuyerCity is not None: - namespaceprefix_ = self.BuyerCity_nsprefix_ + ':' if (UseCapturedNS_ and self.BuyerCity_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sBuyerCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.BuyerCity), input_name='BuyerCity')), namespaceprefix_ , eol_)) - if self.BuyerState is not None: - namespaceprefix_ = self.BuyerState_nsprefix_ + ':' if (UseCapturedNS_ and self.BuyerState_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sBuyerState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.BuyerState), input_name='BuyerState')), namespaceprefix_ , eol_)) - if self.BuyerPostalCode is not None: - namespaceprefix_ = self.BuyerPostalCode_nsprefix_ + ':' if (UseCapturedNS_ and self.BuyerPostalCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sBuyerPostalCode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.BuyerPostalCode), input_name='BuyerPostalCode')), namespaceprefix_ , eol_)) - if self.BuyerCountry is not None: - namespaceprefix_ = self.BuyerCountry_nsprefix_ + ':' if (UseCapturedNS_ and self.BuyerCountry_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sBuyerCountry>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.BuyerCountry), input_name='BuyerCountry')), namespaceprefix_ , eol_)) - if self.BuyerTaxID is not None: - namespaceprefix_ = self.BuyerTaxID_nsprefix_ + ':' if (UseCapturedNS_ and self.BuyerTaxID_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sBuyerTaxID>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.BuyerTaxID), input_name='BuyerTaxID')), namespaceprefix_ , eol_)) - if self.BuyerRecipient is not None: - namespaceprefix_ = self.BuyerRecipient_nsprefix_ + ':' if (UseCapturedNS_ and self.BuyerRecipient_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sBuyerRecipient>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.BuyerRecipient), input_name='BuyerRecipient')), namespaceprefix_ , eol_)) - if self.TermsPayment is not None: - namespaceprefix_ = self.TermsPayment_nsprefix_ + ':' if (UseCapturedNS_ and self.TermsPayment_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sTermsPayment>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.TermsPayment), input_name='TermsPayment')), namespaceprefix_ , eol_)) - if self.ActionCode is not None: - namespaceprefix_ = self.ActionCode_nsprefix_ + ':' if (UseCapturedNS_ and self.ActionCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sActionCode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ActionCode), input_name='ActionCode')), namespaceprefix_ , eol_)) - if self.OptOutOfSPE is not None: - namespaceprefix_ = self.OptOutOfSPE_nsprefix_ + ':' if (UseCapturedNS_ and self.OptOutOfSPE_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sOptOutOfSPE>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.OptOutOfSPE, input_name='OptOutOfSPE'), namespaceprefix_ , eol_)) - if self.PermitNumber is not None: - namespaceprefix_ = self.PermitNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.PermitNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPermitNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PermitNumber), input_name='PermitNumber')), namespaceprefix_ , eol_)) - if self.AccountZipCode is not None: - namespaceprefix_ = self.AccountZipCode_nsprefix_ + ':' if (UseCapturedNS_ and self.AccountZipCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAccountZipCode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.AccountZipCode), input_name='AccountZipCode')), namespaceprefix_ , eol_)) - if self.Machinable is not None: - namespaceprefix_ = self.Machinable_nsprefix_ + ':' if (UseCapturedNS_ and self.Machinable_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sMachinable>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.Machinable, input_name='Machinable'), namespaceprefix_ , eol_)) - if self.DestinationRateIndicator is not None: - namespaceprefix_ = self.DestinationRateIndicator_nsprefix_ + ':' if (UseCapturedNS_ and self.DestinationRateIndicator_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDestinationRateIndicator>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.DestinationRateIndicator), input_name='DestinationRateIndicator')), namespaceprefix_ , eol_)) - if self.MID is not None: - namespaceprefix_ = self.MID_nsprefix_ + ':' if (UseCapturedNS_ and self.MID_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sMID>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.MID), input_name='MID')), namespaceprefix_ , eol_)) - if self.LogisticsManagerMID is not None: - namespaceprefix_ = self.LogisticsManagerMID_nsprefix_ + ':' if (UseCapturedNS_ and self.LogisticsManagerMID_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sLogisticsManagerMID>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.LogisticsManagerMID), input_name='LogisticsManagerMID')), namespaceprefix_ , eol_)) - if self.CRID is not None: - namespaceprefix_ = self.CRID_nsprefix_ + ':' if (UseCapturedNS_ and self.CRID_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCRID>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CRID), input_name='CRID')), namespaceprefix_ , eol_)) - if self.VendorCode is not None: - namespaceprefix_ = self.VendorCode_nsprefix_ + ':' if (UseCapturedNS_ and self.VendorCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sVendorCode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.VendorCode), input_name='VendorCode')), namespaceprefix_ , eol_)) - if self.VendorProductVersionNumber is not None: - namespaceprefix_ = self.VendorProductVersionNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.VendorProductVersionNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sVendorProductVersionNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.VendorProductVersionNumber), input_name='VendorProductVersionNumber')), namespaceprefix_ , eol_)) - if self.OverrideMID is not None: - namespaceprefix_ = self.OverrideMID_nsprefix_ + ':' if (UseCapturedNS_ and self.OverrideMID_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sOverrideMID>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.OverrideMID), input_name='OverrideMID')), namespaceprefix_ , eol_)) - if self.ChargebackCode is not None: - namespaceprefix_ = self.ChargebackCode_nsprefix_ + ':' if (UseCapturedNS_ and self.ChargebackCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sChargebackCode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ChargebackCode), input_name='ChargebackCode')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('USERID', node) - if value is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - self.USERID = value - value = find_attr_value_('PASSWORD', node) - if value is not None and 'PASSWORD' not in already_processed: - already_processed.add('PASSWORD') - self.PASSWORD = value - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'Option': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Option') - value_ = self.gds_validate_string(value_, node, 'Option') - self.Option = value_ - self.Option_nsprefix_ = child_.prefix - elif nodeName_ == 'Revision': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Revision') - value_ = self.gds_validate_string(value_, node, 'Revision') - self.Revision = value_ - self.Revision_nsprefix_ = child_.prefix - elif nodeName_ == 'ImageParameters': - obj_ = ImageParametersType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.ImageParameters = obj_ - obj_.original_tagname_ = 'ImageParameters' - elif nodeName_ == 'FromFirstName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromFirstName') - value_ = self.gds_validate_string(value_, node, 'FromFirstName') - self.FromFirstName = value_ - self.FromFirstName_nsprefix_ = child_.prefix - elif nodeName_ == 'FromMiddleInitial': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromMiddleInitial') - value_ = self.gds_validate_string(value_, node, 'FromMiddleInitial') - self.FromMiddleInitial = value_ - self.FromMiddleInitial_nsprefix_ = child_.prefix - elif nodeName_ == 'FromLastName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromLastName') - value_ = self.gds_validate_string(value_, node, 'FromLastName') - self.FromLastName = value_ - self.FromLastName_nsprefix_ = child_.prefix - elif nodeName_ == 'FromFirm': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromFirm') - value_ = self.gds_validate_string(value_, node, 'FromFirm') - self.FromFirm = value_ - self.FromFirm_nsprefix_ = child_.prefix - elif nodeName_ == 'FromAddress1': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromAddress1') - value_ = self.gds_validate_string(value_, node, 'FromAddress1') - self.FromAddress1 = value_ - self.FromAddress1_nsprefix_ = child_.prefix - elif nodeName_ == 'FromAddress2': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromAddress2') - value_ = self.gds_validate_string(value_, node, 'FromAddress2') - self.FromAddress2 = value_ - self.FromAddress2_nsprefix_ = child_.prefix - elif nodeName_ == 'FromUrbanization': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromUrbanization') - value_ = self.gds_validate_string(value_, node, 'FromUrbanization') - self.FromUrbanization = value_ - self.FromUrbanization_nsprefix_ = child_.prefix - elif nodeName_ == 'FromCity': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromCity') - value_ = self.gds_validate_string(value_, node, 'FromCity') - self.FromCity = value_ - self.FromCity_nsprefix_ = child_.prefix - elif nodeName_ == 'FromState': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromState') - value_ = self.gds_validate_string(value_, node, 'FromState') - self.FromState = value_ - self.FromState_nsprefix_ = child_.prefix - elif nodeName_ == 'FromZIP5': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromZIP5') - value_ = self.gds_validate_string(value_, node, 'FromZIP5') - self.FromZIP5 = value_ - self.FromZIP5_nsprefix_ = child_.prefix - elif nodeName_ == 'FromZIP4': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromZIP4') - value_ = self.gds_validate_string(value_, node, 'FromZIP4') - self.FromZIP4 = value_ - self.FromZIP4_nsprefix_ = child_.prefix - elif nodeName_ == 'FromPhone': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromPhone') - value_ = self.gds_validate_string(value_, node, 'FromPhone') - self.FromPhone = value_ - self.FromPhone_nsprefix_ = child_.prefix - elif nodeName_ == 'ShipFromZIP': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ShipFromZIP') - value_ = self.gds_validate_string(value_, node, 'ShipFromZIP') - self.ShipFromZIP = value_ - self.ShipFromZIP_nsprefix_ = child_.prefix - elif nodeName_ == 'SenderEMail': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SenderEMail') - value_ = self.gds_validate_string(value_, node, 'SenderEMail') - self.SenderEMail = value_ - self.SenderEMail_nsprefix_ = child_.prefix - elif nodeName_ == 'ToFirstName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToFirstName') - value_ = self.gds_validate_string(value_, node, 'ToFirstName') - self.ToFirstName = value_ - self.ToFirstName_nsprefix_ = child_.prefix - elif nodeName_ == 'ToLastName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToLastName') - value_ = self.gds_validate_string(value_, node, 'ToLastName') - self.ToLastName = value_ - self.ToLastName_nsprefix_ = child_.prefix - elif nodeName_ == 'ToFirm': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToFirm') - value_ = self.gds_validate_string(value_, node, 'ToFirm') - self.ToFirm = value_ - self.ToFirm_nsprefix_ = child_.prefix - elif nodeName_ == 'ToAddress1': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToAddress1') - value_ = self.gds_validate_string(value_, node, 'ToAddress1') - self.ToAddress1 = value_ - self.ToAddress1_nsprefix_ = child_.prefix - elif nodeName_ == 'ToAddress2': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToAddress2') - value_ = self.gds_validate_string(value_, node, 'ToAddress2') - self.ToAddress2 = value_ - self.ToAddress2_nsprefix_ = child_.prefix - elif nodeName_ == 'ToAddress3': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToAddress3') - value_ = self.gds_validate_string(value_, node, 'ToAddress3') - self.ToAddress3 = value_ - self.ToAddress3_nsprefix_ = child_.prefix - elif nodeName_ == 'ToPostalCode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToPostalCode') - value_ = self.gds_validate_string(value_, node, 'ToPostalCode') - self.ToPostalCode = value_ - self.ToPostalCode_nsprefix_ = child_.prefix - elif nodeName_ == 'ToPhone': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToPhone') - value_ = self.gds_validate_string(value_, node, 'ToPhone') - self.ToPhone = value_ - self.ToPhone_nsprefix_ = child_.prefix - elif nodeName_ == 'RecipientEMail': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'RecipientEMail') - value_ = self.gds_validate_string(value_, node, 'RecipientEMail') - self.RecipientEMail = value_ - self.RecipientEMail_nsprefix_ = child_.prefix - elif nodeName_ == 'ToDPID': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToDPID') - value_ = self.gds_validate_string(value_, node, 'ToDPID') - self.ToDPID = value_ - self.ToDPID_nsprefix_ = child_.prefix - elif nodeName_ == 'ToProvince': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToProvince') - value_ = self.gds_validate_string(value_, node, 'ToProvince') - self.ToProvince = value_ - self.ToProvince_nsprefix_ = child_.prefix - elif nodeName_ == 'ToTaxID': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToTaxID') - value_ = self.gds_validate_string(value_, node, 'ToTaxID') - self.ToTaxID = value_ - self.ToTaxID_nsprefix_ = child_.prefix - elif nodeName_ == 'Container': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Container') - value_ = self.gds_validate_string(value_, node, 'Container') - self.Container = value_ - self.Container_nsprefix_ = child_.prefix - elif nodeName_ == 'ContentType': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ContentType') - value_ = self.gds_validate_string(value_, node, 'ContentType') - self.ContentType = value_ - self.ContentType_nsprefix_ = child_.prefix - elif nodeName_ == 'ShippingContents': - obj_ = ShippingContentsType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.ShippingContents = obj_ - obj_.original_tagname_ = 'ShippingContents' - elif nodeName_ == 'PurposeOfShipment': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PurposeOfShipment') - value_ = self.gds_validate_string(value_, node, 'PurposeOfShipment') - self.PurposeOfShipment = value_ - self.PurposeOfShipment_nsprefix_ = child_.prefix - elif nodeName_ == 'PartiesToTransaction': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PartiesToTransaction') - value_ = self.gds_validate_string(value_, node, 'PartiesToTransaction') - self.PartiesToTransaction = value_ - self.PartiesToTransaction_nsprefix_ = child_.prefix - elif nodeName_ == 'Agreement': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Agreement') - value_ = self.gds_validate_string(value_, node, 'Agreement') - self.Agreement = value_ - self.Agreement_nsprefix_ = child_.prefix - elif nodeName_ == 'Postage': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Postage') - value_ = self.gds_validate_string(value_, node, 'Postage') - self.Postage = value_ - self.Postage_nsprefix_ = child_.prefix - elif nodeName_ == 'InsuredValue': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'InsuredValue') - value_ = self.gds_validate_string(value_, node, 'InsuredValue') - self.InsuredValue = value_ - self.InsuredValue_nsprefix_ = child_.prefix - elif nodeName_ == 'GrossPounds' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_decimal(sval_, node, 'GrossPounds') - fval_ = self.gds_validate_decimal(fval_, node, 'GrossPounds') - self.GrossPounds = fval_ - self.GrossPounds_nsprefix_ = child_.prefix - elif nodeName_ == 'GrossOunces' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_decimal(sval_, node, 'GrossOunces') - fval_ = self.gds_validate_decimal(fval_, node, 'GrossOunces') - self.GrossOunces = fval_ - self.GrossOunces_nsprefix_ = child_.prefix - elif nodeName_ == 'Length' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_decimal(sval_, node, 'Length') - fval_ = self.gds_validate_decimal(fval_, node, 'Length') - self.Length = fval_ - self.Length_nsprefix_ = child_.prefix - elif nodeName_ == 'Width' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_decimal(sval_, node, 'Width') - fval_ = self.gds_validate_decimal(fval_, node, 'Width') - self.Width = fval_ - self.Width_nsprefix_ = child_.prefix - elif nodeName_ == 'Height' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_decimal(sval_, node, 'Height') - fval_ = self.gds_validate_decimal(fval_, node, 'Height') - self.Height = fval_ - self.Height_nsprefix_ = child_.prefix - elif nodeName_ == 'Girth' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_decimal(sval_, node, 'Girth') - fval_ = self.gds_validate_decimal(fval_, node, 'Girth') - self.Girth = fval_ - self.Girth_nsprefix_ = child_.prefix - elif nodeName_ == 'Shape': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Shape') - value_ = self.gds_validate_string(value_, node, 'Shape') - self.Shape = value_ - self.Shape_nsprefix_ = child_.prefix - elif nodeName_ == 'CIRequired': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'CIRequired') - ival_ = self.gds_validate_boolean(ival_, node, 'CIRequired') - self.CIRequired = ival_ - self.CIRequired_nsprefix_ = child_.prefix - elif nodeName_ == 'InvoiceDate': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'InvoiceDate') - value_ = self.gds_validate_string(value_, node, 'InvoiceDate') - self.InvoiceDate = value_ - self.InvoiceDate_nsprefix_ = child_.prefix - elif nodeName_ == 'InvoiceNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'InvoiceNumber') - value_ = self.gds_validate_string(value_, node, 'InvoiceNumber') - self.InvoiceNumber = value_ - self.InvoiceNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'CustomerOrderNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CustomerOrderNumber') - value_ = self.gds_validate_string(value_, node, 'CustomerOrderNumber') - self.CustomerOrderNumber = value_ - self.CustomerOrderNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'CustOrderNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CustOrderNumber') - value_ = self.gds_validate_string(value_, node, 'CustOrderNumber') - self.CustOrderNumber = value_ - self.CustOrderNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'TermsDelivery': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'TermsDelivery') - value_ = self.gds_validate_string(value_, node, 'TermsDelivery') - self.TermsDelivery = value_ - self.TermsDelivery_nsprefix_ = child_.prefix - elif nodeName_ == 'TermsDeliveryOther': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'TermsDeliveryOther') - value_ = self.gds_validate_string(value_, node, 'TermsDeliveryOther') - self.TermsDeliveryOther = value_ - self.TermsDeliveryOther_nsprefix_ = child_.prefix - elif nodeName_ == 'PackingCost' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_decimal(sval_, node, 'PackingCost') - fval_ = self.gds_validate_decimal(fval_, node, 'PackingCost') - self.PackingCost = fval_ - self.PackingCost_nsprefix_ = child_.prefix - elif nodeName_ == 'CountryUltDest': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CountryUltDest') - value_ = self.gds_validate_string(value_, node, 'CountryUltDest') - self.CountryUltDest = value_ - self.CountryUltDest_nsprefix_ = child_.prefix - elif nodeName_ == 'CIAgreement': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CIAgreement') - value_ = self.gds_validate_string(value_, node, 'CIAgreement') - self.CIAgreement = value_ - self.CIAgreement_nsprefix_ = child_.prefix - elif nodeName_ == 'ImageType': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ImageType') - value_ = self.gds_validate_string(value_, node, 'ImageType') - self.ImageType = value_ - self.ImageType_nsprefix_ = child_.prefix - elif nodeName_ == 'ImageLayout': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ImageLayout') - value_ = self.gds_validate_string(value_, node, 'ImageLayout') - self.ImageLayout = value_ - self.ImageLayout_nsprefix_ = child_.prefix - elif nodeName_ == 'CustomerRefNo': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CustomerRefNo') - value_ = self.gds_validate_string(value_, node, 'CustomerRefNo') - self.CustomerRefNo = value_ - self.CustomerRefNo_nsprefix_ = child_.prefix - elif nodeName_ == 'CustomerRefNo2': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CustomerRefNo2') - value_ = self.gds_validate_string(value_, node, 'CustomerRefNo2') - self.CustomerRefNo2 = value_ - self.CustomerRefNo2_nsprefix_ = child_.prefix - elif nodeName_ == 'ShipDate': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ShipDate') - value_ = self.gds_validate_string(value_, node, 'ShipDate') - self.ShipDate = value_ - self.ShipDate_nsprefix_ = child_.prefix - elif nodeName_ == 'HoldForManifest': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'HoldForManifest') - value_ = self.gds_validate_string(value_, node, 'HoldForManifest') - self.HoldForManifest = value_ - self.HoldForManifest_nsprefix_ = child_.prefix - elif nodeName_ == 'PriceOptions': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PriceOptions') - value_ = self.gds_validate_string(value_, node, 'PriceOptions') - self.PriceOptions = value_ - self.PriceOptions_nsprefix_ = child_.prefix - elif nodeName_ == 'CommercialShipment': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'CommercialShipment') - ival_ = self.gds_validate_boolean(ival_, node, 'CommercialShipment') - self.CommercialShipment = ival_ - self.CommercialShipment_nsprefix_ = child_.prefix - elif nodeName_ == 'BuyerFirstName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'BuyerFirstName') - value_ = self.gds_validate_string(value_, node, 'BuyerFirstName') - self.BuyerFirstName = value_ - self.BuyerFirstName_nsprefix_ = child_.prefix - elif nodeName_ == 'BuyerLastName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'BuyerLastName') - value_ = self.gds_validate_string(value_, node, 'BuyerLastName') - self.BuyerLastName = value_ - self.BuyerLastName_nsprefix_ = child_.prefix - elif nodeName_ == 'BuyerAddress1': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'BuyerAddress1') - value_ = self.gds_validate_string(value_, node, 'BuyerAddress1') - self.BuyerAddress1 = value_ - self.BuyerAddress1_nsprefix_ = child_.prefix - elif nodeName_ == 'BuyerAddress2': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'BuyerAddress2') - value_ = self.gds_validate_string(value_, node, 'BuyerAddress2') - self.BuyerAddress2 = value_ - self.BuyerAddress2_nsprefix_ = child_.prefix - elif nodeName_ == 'BuyerAddress3': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'BuyerAddress3') - value_ = self.gds_validate_string(value_, node, 'BuyerAddress3') - self.BuyerAddress3 = value_ - self.BuyerAddress3_nsprefix_ = child_.prefix - elif nodeName_ == 'BuyerCity': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'BuyerCity') - value_ = self.gds_validate_string(value_, node, 'BuyerCity') - self.BuyerCity = value_ - self.BuyerCity_nsprefix_ = child_.prefix - elif nodeName_ == 'BuyerState': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'BuyerState') - value_ = self.gds_validate_string(value_, node, 'BuyerState') - self.BuyerState = value_ - self.BuyerState_nsprefix_ = child_.prefix - elif nodeName_ == 'BuyerPostalCode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'BuyerPostalCode') - value_ = self.gds_validate_string(value_, node, 'BuyerPostalCode') - self.BuyerPostalCode = value_ - self.BuyerPostalCode_nsprefix_ = child_.prefix - elif nodeName_ == 'BuyerCountry': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'BuyerCountry') - value_ = self.gds_validate_string(value_, node, 'BuyerCountry') - self.BuyerCountry = value_ - self.BuyerCountry_nsprefix_ = child_.prefix - elif nodeName_ == 'BuyerTaxID': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'BuyerTaxID') - value_ = self.gds_validate_string(value_, node, 'BuyerTaxID') - self.BuyerTaxID = value_ - self.BuyerTaxID_nsprefix_ = child_.prefix - elif nodeName_ == 'BuyerRecipient': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'BuyerRecipient') - value_ = self.gds_validate_string(value_, node, 'BuyerRecipient') - self.BuyerRecipient = value_ - self.BuyerRecipient_nsprefix_ = child_.prefix - elif nodeName_ == 'TermsPayment': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'TermsPayment') - value_ = self.gds_validate_string(value_, node, 'TermsPayment') - self.TermsPayment = value_ - self.TermsPayment_nsprefix_ = child_.prefix - elif nodeName_ == 'ActionCode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ActionCode') - value_ = self.gds_validate_string(value_, node, 'ActionCode') - self.ActionCode = value_ - self.ActionCode_nsprefix_ = child_.prefix - elif nodeName_ == 'OptOutOfSPE': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'OptOutOfSPE') - ival_ = self.gds_validate_boolean(ival_, node, 'OptOutOfSPE') - self.OptOutOfSPE = ival_ - self.OptOutOfSPE_nsprefix_ = child_.prefix - elif nodeName_ == 'PermitNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PermitNumber') - value_ = self.gds_validate_string(value_, node, 'PermitNumber') - self.PermitNumber = value_ - self.PermitNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'AccountZipCode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'AccountZipCode') - value_ = self.gds_validate_string(value_, node, 'AccountZipCode') - self.AccountZipCode = value_ - self.AccountZipCode_nsprefix_ = child_.prefix - elif nodeName_ == 'Machinable': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'Machinable') - ival_ = self.gds_validate_boolean(ival_, node, 'Machinable') - self.Machinable = ival_ - self.Machinable_nsprefix_ = child_.prefix - elif nodeName_ == 'DestinationRateIndicator': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'DestinationRateIndicator') - value_ = self.gds_validate_string(value_, node, 'DestinationRateIndicator') - self.DestinationRateIndicator = value_ - self.DestinationRateIndicator_nsprefix_ = child_.prefix - elif nodeName_ == 'MID': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'MID') - value_ = self.gds_validate_string(value_, node, 'MID') - self.MID = value_ - self.MID_nsprefix_ = child_.prefix - elif nodeName_ == 'LogisticsManagerMID': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'LogisticsManagerMID') - value_ = self.gds_validate_string(value_, node, 'LogisticsManagerMID') - self.LogisticsManagerMID = value_ - self.LogisticsManagerMID_nsprefix_ = child_.prefix - elif nodeName_ == 'CRID': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CRID') - value_ = self.gds_validate_string(value_, node, 'CRID') - self.CRID = value_ - self.CRID_nsprefix_ = child_.prefix - elif nodeName_ == 'VendorCode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'VendorCode') - value_ = self.gds_validate_string(value_, node, 'VendorCode') - self.VendorCode = value_ - self.VendorCode_nsprefix_ = child_.prefix - elif nodeName_ == 'VendorProductVersionNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'VendorProductVersionNumber') - value_ = self.gds_validate_string(value_, node, 'VendorProductVersionNumber') - self.VendorProductVersionNumber = value_ - self.VendorProductVersionNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'OverrideMID': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'OverrideMID') - value_ = self.gds_validate_string(value_, node, 'OverrideMID') - self.OverrideMID = value_ - self.OverrideMID_nsprefix_ = child_.prefix - elif nodeName_ == 'ChargebackCode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ChargebackCode') - value_ = self.gds_validate_string(value_, node, 'ChargebackCode') - self.ChargebackCode = value_ - self.ChargebackCode_nsprefix_ = child_.prefix -# end class eVSGXGGetLabelRequest - - -class ImageParametersType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ImageParameter=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.ImageParameter = ImageParameter - self.ImageParameter_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, ImageParametersType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if ImageParametersType.subclass: - return ImageParametersType.subclass(*args_, **kwargs_) - else: - return ImageParametersType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_ImageParameter(self): - return self.ImageParameter - def set_ImageParameter(self, ImageParameter): - self.ImageParameter = ImageParameter - def _hasContent(self): - if ( - self.ImageParameter is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ImageParametersType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('ImageParametersType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'ImageParametersType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='ImageParametersType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='ImageParametersType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='ImageParametersType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ImageParametersType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.ImageParameter is not None: - namespaceprefix_ = self.ImageParameter_nsprefix_ + ':' if (UseCapturedNS_ and self.ImageParameter_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sImageParameter>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ImageParameter), input_name='ImageParameter')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'ImageParameter': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ImageParameter') - value_ = self.gds_validate_string(value_, node, 'ImageParameter') - self.ImageParameter = value_ - self.ImageParameter_nsprefix_ = child_.prefix -# end class ImageParametersType - - -class ShippingContentsType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ItemDetail=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - if ItemDetail is None: - self.ItemDetail = [] - else: - self.ItemDetail = ItemDetail - self.ItemDetail_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, ShippingContentsType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if ShippingContentsType.subclass: - return ShippingContentsType.subclass(*args_, **kwargs_) - else: - return ShippingContentsType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_ItemDetail(self): - return self.ItemDetail - def set_ItemDetail(self, ItemDetail): - self.ItemDetail = ItemDetail - def add_ItemDetail(self, value): - self.ItemDetail.append(value) - def insert_ItemDetail_at(self, index, value): - self.ItemDetail.insert(index, value) - def replace_ItemDetail_at(self, index, value): - self.ItemDetail[index] = value - def _hasContent(self): - if ( - self.ItemDetail - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ShippingContentsType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('ShippingContentsType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'ShippingContentsType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='ShippingContentsType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='ShippingContentsType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='ShippingContentsType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ShippingContentsType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - for ItemDetail_ in self.ItemDetail: - namespaceprefix_ = self.ItemDetail_nsprefix_ + ':' if (UseCapturedNS_ and self.ItemDetail_nsprefix_) else '' - ItemDetail_.export(outfile, level, namespaceprefix_, namespacedef_='', name_='ItemDetail', pretty_print=pretty_print) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'ItemDetail': - obj_ = ItemDetailType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.ItemDetail.append(obj_) - obj_.original_tagname_ = 'ItemDetail' -# end class ShippingContentsType - - -class ItemDetailType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, Description=None, Commodity=None, Restriction=None, Quantity=None, UnitValue=None, NetPounds=None, NetOunces=None, UnitOfMeasure=None, HSTariffNumber=None, CountryofManufacture=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.Description = Description - self.Description_nsprefix_ = None - self.Commodity = Commodity - self.Commodity_nsprefix_ = None - self.Restriction = Restriction - self.Restriction_nsprefix_ = None - self.Quantity = Quantity - self.Quantity_nsprefix_ = None - self.UnitValue = UnitValue - self.UnitValue_nsprefix_ = None - self.NetPounds = NetPounds - self.NetPounds_nsprefix_ = None - self.NetOunces = NetOunces - self.NetOunces_nsprefix_ = None - self.UnitOfMeasure = UnitOfMeasure - self.UnitOfMeasure_nsprefix_ = None - self.HSTariffNumber = HSTariffNumber - self.HSTariffNumber_nsprefix_ = None - self.CountryofManufacture = CountryofManufacture - self.CountryofManufacture_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, ItemDetailType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if ItemDetailType.subclass: - return ItemDetailType.subclass(*args_, **kwargs_) - else: - return ItemDetailType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_Description(self): - return self.Description - def set_Description(self, Description): - self.Description = Description - def get_Commodity(self): - return self.Commodity - def set_Commodity(self, Commodity): - self.Commodity = Commodity - def get_Restriction(self): - return self.Restriction - def set_Restriction(self, Restriction): - self.Restriction = Restriction - def get_Quantity(self): - return self.Quantity - def set_Quantity(self, Quantity): - self.Quantity = Quantity - def get_UnitValue(self): - return self.UnitValue - def set_UnitValue(self, UnitValue): - self.UnitValue = UnitValue - def get_NetPounds(self): - return self.NetPounds - def set_NetPounds(self, NetPounds): - self.NetPounds = NetPounds - def get_NetOunces(self): - return self.NetOunces - def set_NetOunces(self, NetOunces): - self.NetOunces = NetOunces - def get_UnitOfMeasure(self): - return self.UnitOfMeasure - def set_UnitOfMeasure(self, UnitOfMeasure): - self.UnitOfMeasure = UnitOfMeasure - def get_HSTariffNumber(self): - return self.HSTariffNumber - def set_HSTariffNumber(self, HSTariffNumber): - self.HSTariffNumber = HSTariffNumber - def get_CountryofManufacture(self): - return self.CountryofManufacture - def set_CountryofManufacture(self, CountryofManufacture): - self.CountryofManufacture = CountryofManufacture - def _hasContent(self): - if ( - self.Description is not None or - self.Commodity is not None or - self.Restriction is not None or - self.Quantity is not None or - self.UnitValue is not None or - self.NetPounds is not None or - self.NetOunces is not None or - self.UnitOfMeasure is not None or - self.HSTariffNumber is not None or - self.CountryofManufacture is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ItemDetailType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('ItemDetailType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'ItemDetailType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='ItemDetailType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='ItemDetailType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='ItemDetailType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ItemDetailType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.Description is not None: - namespaceprefix_ = self.Description_nsprefix_ + ':' if (UseCapturedNS_ and self.Description_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDescription>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Description), input_name='Description')), namespaceprefix_ , eol_)) - if self.Commodity is not None: - namespaceprefix_ = self.Commodity_nsprefix_ + ':' if (UseCapturedNS_ and self.Commodity_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCommodity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Commodity), input_name='Commodity')), namespaceprefix_ , eol_)) - if self.Restriction is not None: - namespaceprefix_ = self.Restriction_nsprefix_ + ':' if (UseCapturedNS_ and self.Restriction_nsprefix_) else '' - self.Restriction.export(outfile, level, namespaceprefix_, namespacedef_='', name_='Restriction', pretty_print=pretty_print) - if self.Quantity is not None: - namespaceprefix_ = self.Quantity_nsprefix_ + ':' if (UseCapturedNS_ and self.Quantity_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sQuantity>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.Quantity, input_name='Quantity'), namespaceprefix_ , eol_)) - if self.UnitValue is not None: - namespaceprefix_ = self.UnitValue_nsprefix_ + ':' if (UseCapturedNS_ and self.UnitValue_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sUnitValue>%s%s' % (namespaceprefix_ , self.gds_format_decimal(self.UnitValue, input_name='UnitValue'), namespaceprefix_ , eol_)) - if self.NetPounds is not None: - namespaceprefix_ = self.NetPounds_nsprefix_ + ':' if (UseCapturedNS_ and self.NetPounds_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sNetPounds>%s%s' % (namespaceprefix_ , self.gds_format_decimal(self.NetPounds, input_name='NetPounds'), namespaceprefix_ , eol_)) - if self.NetOunces is not None: - namespaceprefix_ = self.NetOunces_nsprefix_ + ':' if (UseCapturedNS_ and self.NetOunces_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sNetOunces>%s%s' % (namespaceprefix_ , self.gds_format_decimal(self.NetOunces, input_name='NetOunces'), namespaceprefix_ , eol_)) - if self.UnitOfMeasure is not None: - namespaceprefix_ = self.UnitOfMeasure_nsprefix_ + ':' if (UseCapturedNS_ and self.UnitOfMeasure_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sUnitOfMeasure>%s%s' % (namespaceprefix_ , self.gds_format_decimal(self.UnitOfMeasure, input_name='UnitOfMeasure'), namespaceprefix_ , eol_)) - if self.HSTariffNumber is not None: - namespaceprefix_ = self.HSTariffNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.HSTariffNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sHSTariffNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.HSTariffNumber), input_name='HSTariffNumber')), namespaceprefix_ , eol_)) - if self.CountryofManufacture is not None: - namespaceprefix_ = self.CountryofManufacture_nsprefix_ + ':' if (UseCapturedNS_ and self.CountryofManufacture_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCountryofManufacture>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CountryofManufacture), input_name='CountryofManufacture')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'Description': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Description') - value_ = self.gds_validate_string(value_, node, 'Description') - self.Description = value_ - self.Description_nsprefix_ = child_.prefix - elif nodeName_ == 'Commodity': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Commodity') - value_ = self.gds_validate_string(value_, node, 'Commodity') - self.Commodity = value_ - self.Commodity_nsprefix_ = child_.prefix - elif nodeName_ == 'Restriction': - obj_ = RestrictionType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.Restriction = obj_ - obj_.original_tagname_ = 'Restriction' - elif nodeName_ == 'Quantity' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'Quantity') - ival_ = self.gds_validate_integer(ival_, node, 'Quantity') - self.Quantity = ival_ - self.Quantity_nsprefix_ = child_.prefix - elif nodeName_ == 'UnitValue' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_decimal(sval_, node, 'UnitValue') - fval_ = self.gds_validate_decimal(fval_, node, 'UnitValue') - self.UnitValue = fval_ - self.UnitValue_nsprefix_ = child_.prefix - elif nodeName_ == 'NetPounds' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_decimal(sval_, node, 'NetPounds') - fval_ = self.gds_validate_decimal(fval_, node, 'NetPounds') - self.NetPounds = fval_ - self.NetPounds_nsprefix_ = child_.prefix - elif nodeName_ == 'NetOunces' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_decimal(sval_, node, 'NetOunces') - fval_ = self.gds_validate_decimal(fval_, node, 'NetOunces') - self.NetOunces = fval_ - self.NetOunces_nsprefix_ = child_.prefix - elif nodeName_ == 'UnitOfMeasure' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_decimal(sval_, node, 'UnitOfMeasure') - fval_ = self.gds_validate_decimal(fval_, node, 'UnitOfMeasure') - self.UnitOfMeasure = fval_ - self.UnitOfMeasure_nsprefix_ = child_.prefix - elif nodeName_ == 'HSTariffNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'HSTariffNumber') - value_ = self.gds_validate_string(value_, node, 'HSTariffNumber') - self.HSTariffNumber = value_ - self.HSTariffNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'CountryofManufacture': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CountryofManufacture') - value_ = self.gds_validate_string(value_, node, 'CountryofManufacture') - self.CountryofManufacture = value_ - self.CountryofManufacture_nsprefix_ = child_.prefix -# end class ItemDetailType - - -class RestrictionType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, FootnoteNumber=None, Response=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.FootnoteNumber = FootnoteNumber - self.FootnoteNumber_nsprefix_ = None - self.Response = Response - self.Response_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, RestrictionType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if RestrictionType.subclass: - return RestrictionType.subclass(*args_, **kwargs_) - else: - return RestrictionType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_FootnoteNumber(self): - return self.FootnoteNumber - def set_FootnoteNumber(self, FootnoteNumber): - self.FootnoteNumber = FootnoteNumber - def get_Response(self): - return self.Response - def set_Response(self, Response): - self.Response = Response - def _hasContent(self): - if ( - self.FootnoteNumber is not None or - self.Response is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='RestrictionType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('RestrictionType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'RestrictionType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='RestrictionType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='RestrictionType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='RestrictionType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='RestrictionType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.FootnoteNumber is not None: - namespaceprefix_ = self.FootnoteNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.FootnoteNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFootnoteNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FootnoteNumber), input_name='FootnoteNumber')), namespaceprefix_ , eol_)) - if self.Response is not None: - namespaceprefix_ = self.Response_nsprefix_ + ':' if (UseCapturedNS_ and self.Response_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sResponse>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Response), input_name='Response')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'FootnoteNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FootnoteNumber') - value_ = self.gds_validate_string(value_, node, 'FootnoteNumber') - self.FootnoteNumber = value_ - self.FootnoteNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'Response': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Response') - value_ = self.gds_validate_string(value_, node, 'Response') - self.Response = value_ - self.Response_nsprefix_ = child_.prefix -# end class RestrictionType - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSGXGGetLabelRequest' - rootClass = eVSGXGGetLabelRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSGXGGetLabelRequest' - rootClass = eVSGXGGetLabelRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSGXGGetLabelRequest' - rootClass = eVSGXGGetLabelRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSGXGGetLabelRequest' - rootClass = eVSGXGGetLabelRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from evs_gxg_get_label_request import *\n\n') - sys.stdout.write('import evs_gxg_get_label_request as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "ImageParametersType", - "ItemDetailType", - "RestrictionType", - "ShippingContentsType", - "eVSGXGGetLabelRequest" -] diff --git a/schemas/usps/karrio/schemas/usps/evs_gxg_get_label_response.py b/schemas/usps/karrio/schemas/usps/evs_gxg_get_label_response.py deleted file mode 100644 index 2df8f45ac8..0000000000 --- a/schemas/usps/karrio/schemas/usps/evs_gxg_get_label_response.py +++ /dev/null @@ -1,1683 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:15 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/evs_gxg_get_label_response.py') -# -# Command line arguments: -# ./schemas/eVSGXGGetLabelResponse.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/evs_gxg_get_label_response.py" ./schemas/eVSGXGGetLabelResponse.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class eVSGXGGetLabelResponse(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, Postage=None, CommodityGuarantee=None, Insurance=None, USPSBarcodeNumber=None, FedExBarcodeNumber=None, LabelImage=None, LabelImagePage2=None, LabelImagePage3=None, LabelImagePage4=None, CIImage=None, CIImagePage2=None, CIImagePage3=None, CIImagePage4=None, InsuranceFee=None, DimensionalWeight=None, LogMessage=None, RemainingBarcodes=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.Postage = Postage - self.Postage_nsprefix_ = None - self.CommodityGuarantee = CommodityGuarantee - self.CommodityGuarantee_nsprefix_ = None - self.Insurance = Insurance - self.Insurance_nsprefix_ = None - self.USPSBarcodeNumber = USPSBarcodeNumber - self.USPSBarcodeNumber_nsprefix_ = None - self.FedExBarcodeNumber = FedExBarcodeNumber - self.FedExBarcodeNumber_nsprefix_ = None - self.LabelImage = LabelImage - self.LabelImage_nsprefix_ = None - self.LabelImagePage2 = LabelImagePage2 - self.LabelImagePage2_nsprefix_ = None - self.LabelImagePage3 = LabelImagePage3 - self.LabelImagePage3_nsprefix_ = None - self.LabelImagePage4 = LabelImagePage4 - self.LabelImagePage4_nsprefix_ = None - self.CIImage = CIImage - self.CIImage_nsprefix_ = None - self.CIImagePage2 = CIImagePage2 - self.CIImagePage2_nsprefix_ = None - self.CIImagePage3 = CIImagePage3 - self.CIImagePage3_nsprefix_ = None - self.CIImagePage4 = CIImagePage4 - self.CIImagePage4_nsprefix_ = None - self.InsuranceFee = InsuranceFee - self.InsuranceFee_nsprefix_ = None - self.DimensionalWeight = DimensionalWeight - self.DimensionalWeight_nsprefix_ = None - self.LogMessage = LogMessage - self.LogMessage_nsprefix_ = None - self.RemainingBarcodes = RemainingBarcodes - self.RemainingBarcodes_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, eVSGXGGetLabelResponse) - if subclass is not None: - return subclass(*args_, **kwargs_) - if eVSGXGGetLabelResponse.subclass: - return eVSGXGGetLabelResponse.subclass(*args_, **kwargs_) - else: - return eVSGXGGetLabelResponse(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_Postage(self): - return self.Postage - def set_Postage(self, Postage): - self.Postage = Postage - def get_CommodityGuarantee(self): - return self.CommodityGuarantee - def set_CommodityGuarantee(self, CommodityGuarantee): - self.CommodityGuarantee = CommodityGuarantee - def get_Insurance(self): - return self.Insurance - def set_Insurance(self, Insurance): - self.Insurance = Insurance - def get_USPSBarcodeNumber(self): - return self.USPSBarcodeNumber - def set_USPSBarcodeNumber(self, USPSBarcodeNumber): - self.USPSBarcodeNumber = USPSBarcodeNumber - def get_FedExBarcodeNumber(self): - return self.FedExBarcodeNumber - def set_FedExBarcodeNumber(self, FedExBarcodeNumber): - self.FedExBarcodeNumber = FedExBarcodeNumber - def get_LabelImage(self): - return self.LabelImage - def set_LabelImage(self, LabelImage): - self.LabelImage = LabelImage - def get_LabelImagePage2(self): - return self.LabelImagePage2 - def set_LabelImagePage2(self, LabelImagePage2): - self.LabelImagePage2 = LabelImagePage2 - def get_LabelImagePage3(self): - return self.LabelImagePage3 - def set_LabelImagePage3(self, LabelImagePage3): - self.LabelImagePage3 = LabelImagePage3 - def get_LabelImagePage4(self): - return self.LabelImagePage4 - def set_LabelImagePage4(self, LabelImagePage4): - self.LabelImagePage4 = LabelImagePage4 - def get_CIImage(self): - return self.CIImage - def set_CIImage(self, CIImage): - self.CIImage = CIImage - def get_CIImagePage2(self): - return self.CIImagePage2 - def set_CIImagePage2(self, CIImagePage2): - self.CIImagePage2 = CIImagePage2 - def get_CIImagePage3(self): - return self.CIImagePage3 - def set_CIImagePage3(self, CIImagePage3): - self.CIImagePage3 = CIImagePage3 - def get_CIImagePage4(self): - return self.CIImagePage4 - def set_CIImagePage4(self, CIImagePage4): - self.CIImagePage4 = CIImagePage4 - def get_InsuranceFee(self): - return self.InsuranceFee - def set_InsuranceFee(self, InsuranceFee): - self.InsuranceFee = InsuranceFee - def get_DimensionalWeight(self): - return self.DimensionalWeight - def set_DimensionalWeight(self, DimensionalWeight): - self.DimensionalWeight = DimensionalWeight - def get_LogMessage(self): - return self.LogMessage - def set_LogMessage(self, LogMessage): - self.LogMessage = LogMessage - def get_RemainingBarcodes(self): - return self.RemainingBarcodes - def set_RemainingBarcodes(self, RemainingBarcodes): - self.RemainingBarcodes = RemainingBarcodes - def _hasContent(self): - if ( - self.Postage is not None or - self.CommodityGuarantee is not None or - self.Insurance is not None or - self.USPSBarcodeNumber is not None or - self.FedExBarcodeNumber is not None or - self.LabelImage is not None or - self.LabelImagePage2 is not None or - self.LabelImagePage3 is not None or - self.LabelImagePage4 is not None or - self.CIImage is not None or - self.CIImagePage2 is not None or - self.CIImagePage3 is not None or - self.CIImagePage4 is not None or - self.InsuranceFee is not None or - self.DimensionalWeight is not None or - self.LogMessage is not None or - self.RemainingBarcodes is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='eVSGXGGetLabelResponse', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('eVSGXGGetLabelResponse') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'eVSGXGGetLabelResponse': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='eVSGXGGetLabelResponse') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='eVSGXGGetLabelResponse', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='eVSGXGGetLabelResponse'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='eVSGXGGetLabelResponse', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.Postage is not None: - namespaceprefix_ = self.Postage_nsprefix_ + ':' if (UseCapturedNS_ and self.Postage_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPostage>%s%s' % (namespaceprefix_ , self.gds_format_float(self.Postage, input_name='Postage'), namespaceprefix_ , eol_)) - if self.CommodityGuarantee is not None: - namespaceprefix_ = self.CommodityGuarantee_nsprefix_ + ':' if (UseCapturedNS_ and self.CommodityGuarantee_nsprefix_) else '' - self.CommodityGuarantee.export(outfile, level, namespaceprefix_, namespacedef_='', name_='CommodityGuarantee', pretty_print=pretty_print) - if self.Insurance is not None: - namespaceprefix_ = self.Insurance_nsprefix_ + ':' if (UseCapturedNS_ and self.Insurance_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sInsurance>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Insurance), input_name='Insurance')), namespaceprefix_ , eol_)) - if self.USPSBarcodeNumber is not None: - namespaceprefix_ = self.USPSBarcodeNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.USPSBarcodeNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sUSPSBarcodeNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.USPSBarcodeNumber), input_name='USPSBarcodeNumber')), namespaceprefix_ , eol_)) - if self.FedExBarcodeNumber is not None: - namespaceprefix_ = self.FedExBarcodeNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.FedExBarcodeNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFedExBarcodeNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FedExBarcodeNumber), input_name='FedExBarcodeNumber')), namespaceprefix_ , eol_)) - if self.LabelImage is not None: - namespaceprefix_ = self.LabelImage_nsprefix_ + ':' if (UseCapturedNS_ and self.LabelImage_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sLabelImage>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.LabelImage), input_name='LabelImage')), namespaceprefix_ , eol_)) - if self.LabelImagePage2 is not None: - namespaceprefix_ = self.LabelImagePage2_nsprefix_ + ':' if (UseCapturedNS_ and self.LabelImagePage2_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sLabelImagePage2>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.LabelImagePage2), input_name='LabelImagePage2')), namespaceprefix_ , eol_)) - if self.LabelImagePage3 is not None: - namespaceprefix_ = self.LabelImagePage3_nsprefix_ + ':' if (UseCapturedNS_ and self.LabelImagePage3_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sLabelImagePage3>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.LabelImagePage3), input_name='LabelImagePage3')), namespaceprefix_ , eol_)) - if self.LabelImagePage4 is not None: - namespaceprefix_ = self.LabelImagePage4_nsprefix_ + ':' if (UseCapturedNS_ and self.LabelImagePage4_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sLabelImagePage4>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.LabelImagePage4), input_name='LabelImagePage4')), namespaceprefix_ , eol_)) - if self.CIImage is not None: - namespaceprefix_ = self.CIImage_nsprefix_ + ':' if (UseCapturedNS_ and self.CIImage_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCIImage>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CIImage), input_name='CIImage')), namespaceprefix_ , eol_)) - if self.CIImagePage2 is not None: - namespaceprefix_ = self.CIImagePage2_nsprefix_ + ':' if (UseCapturedNS_ and self.CIImagePage2_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCIImagePage2>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CIImagePage2), input_name='CIImagePage2')), namespaceprefix_ , eol_)) - if self.CIImagePage3 is not None: - namespaceprefix_ = self.CIImagePage3_nsprefix_ + ':' if (UseCapturedNS_ and self.CIImagePage3_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCIImagePage3>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CIImagePage3), input_name='CIImagePage3')), namespaceprefix_ , eol_)) - if self.CIImagePage4 is not None: - namespaceprefix_ = self.CIImagePage4_nsprefix_ + ':' if (UseCapturedNS_ and self.CIImagePage4_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCIImagePage4>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CIImagePage4), input_name='CIImagePage4')), namespaceprefix_ , eol_)) - if self.InsuranceFee is not None: - namespaceprefix_ = self.InsuranceFee_nsprefix_ + ':' if (UseCapturedNS_ and self.InsuranceFee_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sInsuranceFee>%s%s' % (namespaceprefix_ , self.gds_format_float(self.InsuranceFee, input_name='InsuranceFee'), namespaceprefix_ , eol_)) - if self.DimensionalWeight is not None: - namespaceprefix_ = self.DimensionalWeight_nsprefix_ + ':' if (UseCapturedNS_ and self.DimensionalWeight_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDimensionalWeight>%s%s' % (namespaceprefix_ , self.gds_format_float(self.DimensionalWeight, input_name='DimensionalWeight'), namespaceprefix_ , eol_)) - if self.LogMessage is not None: - namespaceprefix_ = self.LogMessage_nsprefix_ + ':' if (UseCapturedNS_ and self.LogMessage_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sLogMessage>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.LogMessage), input_name='LogMessage')), namespaceprefix_ , eol_)) - if self.RemainingBarcodes is not None: - namespaceprefix_ = self.RemainingBarcodes_nsprefix_ + ':' if (UseCapturedNS_ and self.RemainingBarcodes_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRemainingBarcodes>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.RemainingBarcodes, input_name='RemainingBarcodes'), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'Postage' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'Postage') - fval_ = self.gds_validate_float(fval_, node, 'Postage') - self.Postage = fval_ - self.Postage_nsprefix_ = child_.prefix - elif nodeName_ == 'CommodityGuarantee': - obj_ = CommodityGuaranteeType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.CommodityGuarantee = obj_ - obj_.original_tagname_ = 'CommodityGuarantee' - elif nodeName_ == 'Insurance': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Insurance') - value_ = self.gds_validate_string(value_, node, 'Insurance') - self.Insurance = value_ - self.Insurance_nsprefix_ = child_.prefix - elif nodeName_ == 'USPSBarcodeNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'USPSBarcodeNumber') - value_ = self.gds_validate_string(value_, node, 'USPSBarcodeNumber') - self.USPSBarcodeNumber = value_ - self.USPSBarcodeNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'FedExBarcodeNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FedExBarcodeNumber') - value_ = self.gds_validate_string(value_, node, 'FedExBarcodeNumber') - self.FedExBarcodeNumber = value_ - self.FedExBarcodeNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'LabelImage': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'LabelImage') - value_ = self.gds_validate_string(value_, node, 'LabelImage') - self.LabelImage = value_ - self.LabelImage_nsprefix_ = child_.prefix - elif nodeName_ == 'LabelImagePage2': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'LabelImagePage2') - value_ = self.gds_validate_string(value_, node, 'LabelImagePage2') - self.LabelImagePage2 = value_ - self.LabelImagePage2_nsprefix_ = child_.prefix - elif nodeName_ == 'LabelImagePage3': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'LabelImagePage3') - value_ = self.gds_validate_string(value_, node, 'LabelImagePage3') - self.LabelImagePage3 = value_ - self.LabelImagePage3_nsprefix_ = child_.prefix - elif nodeName_ == 'LabelImagePage4': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'LabelImagePage4') - value_ = self.gds_validate_string(value_, node, 'LabelImagePage4') - self.LabelImagePage4 = value_ - self.LabelImagePage4_nsprefix_ = child_.prefix - elif nodeName_ == 'CIImage': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CIImage') - value_ = self.gds_validate_string(value_, node, 'CIImage') - self.CIImage = value_ - self.CIImage_nsprefix_ = child_.prefix - elif nodeName_ == 'CIImagePage2': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CIImagePage2') - value_ = self.gds_validate_string(value_, node, 'CIImagePage2') - self.CIImagePage2 = value_ - self.CIImagePage2_nsprefix_ = child_.prefix - elif nodeName_ == 'CIImagePage3': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CIImagePage3') - value_ = self.gds_validate_string(value_, node, 'CIImagePage3') - self.CIImagePage3 = value_ - self.CIImagePage3_nsprefix_ = child_.prefix - elif nodeName_ == 'CIImagePage4': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CIImagePage4') - value_ = self.gds_validate_string(value_, node, 'CIImagePage4') - self.CIImagePage4 = value_ - self.CIImagePage4_nsprefix_ = child_.prefix - elif nodeName_ == 'InsuranceFee' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'InsuranceFee') - fval_ = self.gds_validate_float(fval_, node, 'InsuranceFee') - self.InsuranceFee = fval_ - self.InsuranceFee_nsprefix_ = child_.prefix - elif nodeName_ == 'DimensionalWeight' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'DimensionalWeight') - fval_ = self.gds_validate_float(fval_, node, 'DimensionalWeight') - self.DimensionalWeight = fval_ - self.DimensionalWeight_nsprefix_ = child_.prefix - elif nodeName_ == 'LogMessage': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'LogMessage') - value_ = self.gds_validate_string(value_, node, 'LogMessage') - self.LogMessage = value_ - self.LogMessage_nsprefix_ = child_.prefix - elif nodeName_ == 'RemainingBarcodes' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'RemainingBarcodes') - ival_ = self.gds_validate_integer(ival_, node, 'RemainingBarcodes') - self.RemainingBarcodes = ival_ - self.RemainingBarcodes_nsprefix_ = child_.prefix -# end class eVSGXGGetLabelResponse - - -class CommodityGuaranteeType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, CommodityType=None, GuaranteeDate=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.CommodityType = CommodityType - self.CommodityType_nsprefix_ = None - self.GuaranteeDate = GuaranteeDate - self.GuaranteeDate_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, CommodityGuaranteeType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if CommodityGuaranteeType.subclass: - return CommodityGuaranteeType.subclass(*args_, **kwargs_) - else: - return CommodityGuaranteeType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_CommodityType(self): - return self.CommodityType - def set_CommodityType(self, CommodityType): - self.CommodityType = CommodityType - def get_GuaranteeDate(self): - return self.GuaranteeDate - def set_GuaranteeDate(self, GuaranteeDate): - self.GuaranteeDate = GuaranteeDate - def _hasContent(self): - if ( - self.CommodityType is not None or - self.GuaranteeDate is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='CommodityGuaranteeType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('CommodityGuaranteeType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'CommodityGuaranteeType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='CommodityGuaranteeType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='CommodityGuaranteeType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='CommodityGuaranteeType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='CommodityGuaranteeType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.CommodityType is not None: - namespaceprefix_ = self.CommodityType_nsprefix_ + ':' if (UseCapturedNS_ and self.CommodityType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCommodityType>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CommodityType), input_name='CommodityType')), namespaceprefix_ , eol_)) - if self.GuaranteeDate is not None: - namespaceprefix_ = self.GuaranteeDate_nsprefix_ + ':' if (UseCapturedNS_ and self.GuaranteeDate_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sGuaranteeDate>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.GuaranteeDate), input_name='GuaranteeDate')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'CommodityType': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CommodityType') - value_ = self.gds_validate_string(value_, node, 'CommodityType') - self.CommodityType = value_ - self.CommodityType_nsprefix_ = child_.prefix - elif nodeName_ == 'GuaranteeDate': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'GuaranteeDate') - value_ = self.gds_validate_string(value_, node, 'GuaranteeDate') - self.GuaranteeDate = value_ - self.GuaranteeDate_nsprefix_ = child_.prefix -# end class CommodityGuaranteeType - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSGXGGetLabelResponse' - rootClass = eVSGXGGetLabelResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSGXGGetLabelResponse' - rootClass = eVSGXGGetLabelResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSGXGGetLabelResponse' - rootClass = eVSGXGGetLabelResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSGXGGetLabelResponse' - rootClass = eVSGXGGetLabelResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from evs_gxg_get_label_response import *\n\n') - sys.stdout.write('import evs_gxg_get_label_response as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "CommodityGuaranteeType", - "eVSGXGGetLabelResponse" -] diff --git a/schemas/usps/karrio/schemas/usps/evs_priority_mail_intl_request.py b/schemas/usps/karrio/schemas/usps/evs_priority_mail_intl_request.py deleted file mode 100644 index 7d021c3a38..0000000000 --- a/schemas/usps/karrio/schemas/usps/evs_priority_mail_intl_request.py +++ /dev/null @@ -1,3422 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:16 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/evs_priority_mail_intl_request.py') -# -# Command line arguments: -# ./schemas/eVSPriorityMailIntlRequest.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/evs_priority_mail_intl_request.py" ./schemas/eVSPriorityMailIntlRequest.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class eVSPriorityMailIntlRequest(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, USERID=None, Option=None, Revision=None, ImageParameters=None, FromFirstName=None, FromMiddleInitial=None, FromLastName=None, FromFirm=None, FromAddress1=None, FromAddress2=None, FromUrbanization=None, FromCity=None, FromState=None, FromZip5=None, FromZip4=None, FromPhone=None, FromCustomsReference=None, ToName=None, ToFirstName=None, ToLastName=None, ToFirm=None, ToAddress1=None, ToAddress2=None, ToAddress3=None, ToCity=None, ToProvince=None, ToCountry=None, ToPostalCode=None, ToPOBoxFlag=None, ToPhone=None, ToFax=None, ToEmail=None, ImportersReferenceNumber=None, NonDeliveryOption=None, RedirectName=None, RedirectEmail=None, RedirectSMS=None, RedirectAddress=None, RedirectCity=None, RedirectState=None, RedirectZipCode=None, RedirectZip4=None, Container=None, ShippingContents=None, Insured=None, InsuredNumber=None, InsuredAmount=None, GrossPounds=None, GrossOunces=None, ContentType=None, ContentTypeOther=None, Agreement=None, Comments=None, LicenseNumber=None, CertificateNumber=None, InvoiceNumber=None, ImageType=None, ImageLayout=None, CustomerRefNo=None, CustomerRefNo2=None, POZipCode=None, LabelDate=None, EMCAAccount=None, HoldForManifest=None, EELPFC=None, PriceOptions=None, Width=None, Length=None, Height=None, Girth=None, ExtraServices=None, ActionCode=None, OptOutOfSPE=None, PermitNumber=None, AccountZipCode=None, ImportersReferenceType=None, ImportersTelephoneNumber=None, ImportersFaxNumber=None, ImportersEmail=None, Machinable=None, DestinationRateIndicator=None, MID=None, LogisticsManagerMID=None, CRID=None, VendorCode=None, VendorProductVersionNumber=None, ePostageMailerReporting=None, SenderFirstName=None, SenderLastName=None, SenderBusinessName=None, SenderAddress1=None, SenderCity=None, SenderState=None, SenderZip5=None, SenderPhone=None, SenderEmail=None, ChargebackCode=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.USERID = _cast(None, USERID) - self.USERID_nsprefix_ = None - self.Option = Option - self.Option_nsprefix_ = None - self.Revision = Revision - self.Revision_nsprefix_ = None - self.ImageParameters = ImageParameters - self.ImageParameters_nsprefix_ = None - self.FromFirstName = FromFirstName - self.FromFirstName_nsprefix_ = None - self.FromMiddleInitial = FromMiddleInitial - self.FromMiddleInitial_nsprefix_ = None - self.FromLastName = FromLastName - self.FromLastName_nsprefix_ = None - self.FromFirm = FromFirm - self.FromFirm_nsprefix_ = None - self.FromAddress1 = FromAddress1 - self.FromAddress1_nsprefix_ = None - self.FromAddress2 = FromAddress2 - self.FromAddress2_nsprefix_ = None - self.FromUrbanization = FromUrbanization - self.FromUrbanization_nsprefix_ = None - self.FromCity = FromCity - self.FromCity_nsprefix_ = None - self.FromState = FromState - self.FromState_nsprefix_ = None - self.FromZip5 = FromZip5 - self.FromZip5_nsprefix_ = None - self.FromZip4 = FromZip4 - self.FromZip4_nsprefix_ = None - self.FromPhone = FromPhone - self.FromPhone_nsprefix_ = None - self.FromCustomsReference = FromCustomsReference - self.FromCustomsReference_nsprefix_ = None - self.ToName = ToName - self.ToName_nsprefix_ = None - self.ToFirstName = ToFirstName - self.ToFirstName_nsprefix_ = None - self.ToLastName = ToLastName - self.ToLastName_nsprefix_ = None - self.ToFirm = ToFirm - self.ToFirm_nsprefix_ = None - self.ToAddress1 = ToAddress1 - self.ToAddress1_nsprefix_ = None - self.ToAddress2 = ToAddress2 - self.ToAddress2_nsprefix_ = None - self.ToAddress3 = ToAddress3 - self.ToAddress3_nsprefix_ = None - self.ToCity = ToCity - self.ToCity_nsprefix_ = None - self.ToProvince = ToProvince - self.ToProvince_nsprefix_ = None - self.ToCountry = ToCountry - self.ToCountry_nsprefix_ = None - self.ToPostalCode = ToPostalCode - self.ToPostalCode_nsprefix_ = None - self.ToPOBoxFlag = ToPOBoxFlag - self.ToPOBoxFlag_nsprefix_ = None - self.ToPhone = ToPhone - self.ToPhone_nsprefix_ = None - self.ToFax = ToFax - self.ToFax_nsprefix_ = None - self.ToEmail = ToEmail - self.ToEmail_nsprefix_ = None - self.ImportersReferenceNumber = ImportersReferenceNumber - self.ImportersReferenceNumber_nsprefix_ = None - self.NonDeliveryOption = NonDeliveryOption - self.NonDeliveryOption_nsprefix_ = None - self.RedirectName = RedirectName - self.RedirectName_nsprefix_ = None - self.RedirectEmail = RedirectEmail - self.RedirectEmail_nsprefix_ = None - self.RedirectSMS = RedirectSMS - self.RedirectSMS_nsprefix_ = None - self.RedirectAddress = RedirectAddress - self.RedirectAddress_nsprefix_ = None - self.RedirectCity = RedirectCity - self.RedirectCity_nsprefix_ = None - self.RedirectState = RedirectState - self.RedirectState_nsprefix_ = None - self.RedirectZipCode = RedirectZipCode - self.RedirectZipCode_nsprefix_ = None - self.RedirectZip4 = RedirectZip4 - self.RedirectZip4_nsprefix_ = None - self.Container = Container - self.Container_nsprefix_ = None - self.ShippingContents = ShippingContents - self.ShippingContents_nsprefix_ = None - self.Insured = Insured - self.Insured_nsprefix_ = None - self.InsuredNumber = InsuredNumber - self.InsuredNumber_nsprefix_ = None - self.InsuredAmount = InsuredAmount - self.InsuredAmount_nsprefix_ = None - self.GrossPounds = GrossPounds - self.GrossPounds_nsprefix_ = None - self.GrossOunces = GrossOunces - self.GrossOunces_nsprefix_ = None - self.ContentType = ContentType - self.ContentType_nsprefix_ = None - self.ContentTypeOther = ContentTypeOther - self.ContentTypeOther_nsprefix_ = None - self.Agreement = Agreement - self.Agreement_nsprefix_ = None - self.Comments = Comments - self.Comments_nsprefix_ = None - self.LicenseNumber = LicenseNumber - self.LicenseNumber_nsprefix_ = None - self.CertificateNumber = CertificateNumber - self.CertificateNumber_nsprefix_ = None - self.InvoiceNumber = InvoiceNumber - self.InvoiceNumber_nsprefix_ = None - self.ImageType = ImageType - self.ImageType_nsprefix_ = None - self.ImageLayout = ImageLayout - self.ImageLayout_nsprefix_ = None - self.CustomerRefNo = CustomerRefNo - self.CustomerRefNo_nsprefix_ = None - self.CustomerRefNo2 = CustomerRefNo2 - self.CustomerRefNo2_nsprefix_ = None - self.POZipCode = POZipCode - self.POZipCode_nsprefix_ = None - self.LabelDate = LabelDate - self.LabelDate_nsprefix_ = None - self.EMCAAccount = EMCAAccount - self.EMCAAccount_nsprefix_ = None - self.HoldForManifest = HoldForManifest - self.HoldForManifest_nsprefix_ = None - self.EELPFC = EELPFC - self.EELPFC_nsprefix_ = None - self.PriceOptions = PriceOptions - self.PriceOptions_nsprefix_ = None - self.Width = Width - self.Width_nsprefix_ = None - self.Length = Length - self.Length_nsprefix_ = None - self.Height = Height - self.Height_nsprefix_ = None - self.Girth = Girth - self.Girth_nsprefix_ = None - self.ExtraServices = ExtraServices - self.ExtraServices_nsprefix_ = None - self.ActionCode = ActionCode - self.ActionCode_nsprefix_ = None - self.OptOutOfSPE = OptOutOfSPE - self.OptOutOfSPE_nsprefix_ = None - self.PermitNumber = PermitNumber - self.PermitNumber_nsprefix_ = None - self.AccountZipCode = AccountZipCode - self.AccountZipCode_nsprefix_ = None - self.ImportersReferenceType = ImportersReferenceType - self.ImportersReferenceType_nsprefix_ = None - self.ImportersTelephoneNumber = ImportersTelephoneNumber - self.ImportersTelephoneNumber_nsprefix_ = None - self.ImportersFaxNumber = ImportersFaxNumber - self.ImportersFaxNumber_nsprefix_ = None - self.ImportersEmail = ImportersEmail - self.ImportersEmail_nsprefix_ = None - self.Machinable = Machinable - self.Machinable_nsprefix_ = None - self.DestinationRateIndicator = DestinationRateIndicator - self.DestinationRateIndicator_nsprefix_ = None - self.MID = MID - self.MID_nsprefix_ = None - self.LogisticsManagerMID = LogisticsManagerMID - self.LogisticsManagerMID_nsprefix_ = None - self.CRID = CRID - self.CRID_nsprefix_ = None - self.VendorCode = VendorCode - self.VendorCode_nsprefix_ = None - self.VendorProductVersionNumber = VendorProductVersionNumber - self.VendorProductVersionNumber_nsprefix_ = None - self.ePostageMailerReporting = ePostageMailerReporting - self.ePostageMailerReporting_nsprefix_ = None - self.SenderFirstName = SenderFirstName - self.SenderFirstName_nsprefix_ = None - self.SenderLastName = SenderLastName - self.SenderLastName_nsprefix_ = None - self.SenderBusinessName = SenderBusinessName - self.SenderBusinessName_nsprefix_ = None - self.SenderAddress1 = SenderAddress1 - self.SenderAddress1_nsprefix_ = None - self.SenderCity = SenderCity - self.SenderCity_nsprefix_ = None - self.SenderState = SenderState - self.SenderState_nsprefix_ = None - self.SenderZip5 = SenderZip5 - self.SenderZip5_nsprefix_ = None - self.SenderPhone = SenderPhone - self.SenderPhone_nsprefix_ = None - self.SenderEmail = SenderEmail - self.SenderEmail_nsprefix_ = None - self.ChargebackCode = ChargebackCode - self.ChargebackCode_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, eVSPriorityMailIntlRequest) - if subclass is not None: - return subclass(*args_, **kwargs_) - if eVSPriorityMailIntlRequest.subclass: - return eVSPriorityMailIntlRequest.subclass(*args_, **kwargs_) - else: - return eVSPriorityMailIntlRequest(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_Option(self): - return self.Option - def set_Option(self, Option): - self.Option = Option - def get_Revision(self): - return self.Revision - def set_Revision(self, Revision): - self.Revision = Revision - def get_ImageParameters(self): - return self.ImageParameters - def set_ImageParameters(self, ImageParameters): - self.ImageParameters = ImageParameters - def get_FromFirstName(self): - return self.FromFirstName - def set_FromFirstName(self, FromFirstName): - self.FromFirstName = FromFirstName - def get_FromMiddleInitial(self): - return self.FromMiddleInitial - def set_FromMiddleInitial(self, FromMiddleInitial): - self.FromMiddleInitial = FromMiddleInitial - def get_FromLastName(self): - return self.FromLastName - def set_FromLastName(self, FromLastName): - self.FromLastName = FromLastName - def get_FromFirm(self): - return self.FromFirm - def set_FromFirm(self, FromFirm): - self.FromFirm = FromFirm - def get_FromAddress1(self): - return self.FromAddress1 - def set_FromAddress1(self, FromAddress1): - self.FromAddress1 = FromAddress1 - def get_FromAddress2(self): - return self.FromAddress2 - def set_FromAddress2(self, FromAddress2): - self.FromAddress2 = FromAddress2 - def get_FromUrbanization(self): - return self.FromUrbanization - def set_FromUrbanization(self, FromUrbanization): - self.FromUrbanization = FromUrbanization - def get_FromCity(self): - return self.FromCity - def set_FromCity(self, FromCity): - self.FromCity = FromCity - def get_FromState(self): - return self.FromState - def set_FromState(self, FromState): - self.FromState = FromState - def get_FromZip5(self): - return self.FromZip5 - def set_FromZip5(self, FromZip5): - self.FromZip5 = FromZip5 - def get_FromZip4(self): - return self.FromZip4 - def set_FromZip4(self, FromZip4): - self.FromZip4 = FromZip4 - def get_FromPhone(self): - return self.FromPhone - def set_FromPhone(self, FromPhone): - self.FromPhone = FromPhone - def get_FromCustomsReference(self): - return self.FromCustomsReference - def set_FromCustomsReference(self, FromCustomsReference): - self.FromCustomsReference = FromCustomsReference - def get_ToName(self): - return self.ToName - def set_ToName(self, ToName): - self.ToName = ToName - def get_ToFirstName(self): - return self.ToFirstName - def set_ToFirstName(self, ToFirstName): - self.ToFirstName = ToFirstName - def get_ToLastName(self): - return self.ToLastName - def set_ToLastName(self, ToLastName): - self.ToLastName = ToLastName - def get_ToFirm(self): - return self.ToFirm - def set_ToFirm(self, ToFirm): - self.ToFirm = ToFirm - def get_ToAddress1(self): - return self.ToAddress1 - def set_ToAddress1(self, ToAddress1): - self.ToAddress1 = ToAddress1 - def get_ToAddress2(self): - return self.ToAddress2 - def set_ToAddress2(self, ToAddress2): - self.ToAddress2 = ToAddress2 - def get_ToAddress3(self): - return self.ToAddress3 - def set_ToAddress3(self, ToAddress3): - self.ToAddress3 = ToAddress3 - def get_ToCity(self): - return self.ToCity - def set_ToCity(self, ToCity): - self.ToCity = ToCity - def get_ToProvince(self): - return self.ToProvince - def set_ToProvince(self, ToProvince): - self.ToProvince = ToProvince - def get_ToCountry(self): - return self.ToCountry - def set_ToCountry(self, ToCountry): - self.ToCountry = ToCountry - def get_ToPostalCode(self): - return self.ToPostalCode - def set_ToPostalCode(self, ToPostalCode): - self.ToPostalCode = ToPostalCode - def get_ToPOBoxFlag(self): - return self.ToPOBoxFlag - def set_ToPOBoxFlag(self, ToPOBoxFlag): - self.ToPOBoxFlag = ToPOBoxFlag - def get_ToPhone(self): - return self.ToPhone - def set_ToPhone(self, ToPhone): - self.ToPhone = ToPhone - def get_ToFax(self): - return self.ToFax - def set_ToFax(self, ToFax): - self.ToFax = ToFax - def get_ToEmail(self): - return self.ToEmail - def set_ToEmail(self, ToEmail): - self.ToEmail = ToEmail - def get_ImportersReferenceNumber(self): - return self.ImportersReferenceNumber - def set_ImportersReferenceNumber(self, ImportersReferenceNumber): - self.ImportersReferenceNumber = ImportersReferenceNumber - def get_NonDeliveryOption(self): - return self.NonDeliveryOption - def set_NonDeliveryOption(self, NonDeliveryOption): - self.NonDeliveryOption = NonDeliveryOption - def get_RedirectName(self): - return self.RedirectName - def set_RedirectName(self, RedirectName): - self.RedirectName = RedirectName - def get_RedirectEmail(self): - return self.RedirectEmail - def set_RedirectEmail(self, RedirectEmail): - self.RedirectEmail = RedirectEmail - def get_RedirectSMS(self): - return self.RedirectSMS - def set_RedirectSMS(self, RedirectSMS): - self.RedirectSMS = RedirectSMS - def get_RedirectAddress(self): - return self.RedirectAddress - def set_RedirectAddress(self, RedirectAddress): - self.RedirectAddress = RedirectAddress - def get_RedirectCity(self): - return self.RedirectCity - def set_RedirectCity(self, RedirectCity): - self.RedirectCity = RedirectCity - def get_RedirectState(self): - return self.RedirectState - def set_RedirectState(self, RedirectState): - self.RedirectState = RedirectState - def get_RedirectZipCode(self): - return self.RedirectZipCode - def set_RedirectZipCode(self, RedirectZipCode): - self.RedirectZipCode = RedirectZipCode - def get_RedirectZip4(self): - return self.RedirectZip4 - def set_RedirectZip4(self, RedirectZip4): - self.RedirectZip4 = RedirectZip4 - def get_Container(self): - return self.Container - def set_Container(self, Container): - self.Container = Container - def get_ShippingContents(self): - return self.ShippingContents - def set_ShippingContents(self, ShippingContents): - self.ShippingContents = ShippingContents - def get_Insured(self): - return self.Insured - def set_Insured(self, Insured): - self.Insured = Insured - def get_InsuredNumber(self): - return self.InsuredNumber - def set_InsuredNumber(self, InsuredNumber): - self.InsuredNumber = InsuredNumber - def get_InsuredAmount(self): - return self.InsuredAmount - def set_InsuredAmount(self, InsuredAmount): - self.InsuredAmount = InsuredAmount - def get_GrossPounds(self): - return self.GrossPounds - def set_GrossPounds(self, GrossPounds): - self.GrossPounds = GrossPounds - def get_GrossOunces(self): - return self.GrossOunces - def set_GrossOunces(self, GrossOunces): - self.GrossOunces = GrossOunces - def get_ContentType(self): - return self.ContentType - def set_ContentType(self, ContentType): - self.ContentType = ContentType - def get_ContentTypeOther(self): - return self.ContentTypeOther - def set_ContentTypeOther(self, ContentTypeOther): - self.ContentTypeOther = ContentTypeOther - def get_Agreement(self): - return self.Agreement - def set_Agreement(self, Agreement): - self.Agreement = Agreement - def get_Comments(self): - return self.Comments - def set_Comments(self, Comments): - self.Comments = Comments - def get_LicenseNumber(self): - return self.LicenseNumber - def set_LicenseNumber(self, LicenseNumber): - self.LicenseNumber = LicenseNumber - def get_CertificateNumber(self): - return self.CertificateNumber - def set_CertificateNumber(self, CertificateNumber): - self.CertificateNumber = CertificateNumber - def get_InvoiceNumber(self): - return self.InvoiceNumber - def set_InvoiceNumber(self, InvoiceNumber): - self.InvoiceNumber = InvoiceNumber - def get_ImageType(self): - return self.ImageType - def set_ImageType(self, ImageType): - self.ImageType = ImageType - def get_ImageLayout(self): - return self.ImageLayout - def set_ImageLayout(self, ImageLayout): - self.ImageLayout = ImageLayout - def get_CustomerRefNo(self): - return self.CustomerRefNo - def set_CustomerRefNo(self, CustomerRefNo): - self.CustomerRefNo = CustomerRefNo - def get_CustomerRefNo2(self): - return self.CustomerRefNo2 - def set_CustomerRefNo2(self, CustomerRefNo2): - self.CustomerRefNo2 = CustomerRefNo2 - def get_POZipCode(self): - return self.POZipCode - def set_POZipCode(self, POZipCode): - self.POZipCode = POZipCode - def get_LabelDate(self): - return self.LabelDate - def set_LabelDate(self, LabelDate): - self.LabelDate = LabelDate - def get_EMCAAccount(self): - return self.EMCAAccount - def set_EMCAAccount(self, EMCAAccount): - self.EMCAAccount = EMCAAccount - def get_HoldForManifest(self): - return self.HoldForManifest - def set_HoldForManifest(self, HoldForManifest): - self.HoldForManifest = HoldForManifest - def get_EELPFC(self): - return self.EELPFC - def set_EELPFC(self, EELPFC): - self.EELPFC = EELPFC - def get_PriceOptions(self): - return self.PriceOptions - def set_PriceOptions(self, PriceOptions): - self.PriceOptions = PriceOptions - def get_Width(self): - return self.Width - def set_Width(self, Width): - self.Width = Width - def get_Length(self): - return self.Length - def set_Length(self, Length): - self.Length = Length - def get_Height(self): - return self.Height - def set_Height(self, Height): - self.Height = Height - def get_Girth(self): - return self.Girth - def set_Girth(self, Girth): - self.Girth = Girth - def get_ExtraServices(self): - return self.ExtraServices - def set_ExtraServices(self, ExtraServices): - self.ExtraServices = ExtraServices - def get_ActionCode(self): - return self.ActionCode - def set_ActionCode(self, ActionCode): - self.ActionCode = ActionCode - def get_OptOutOfSPE(self): - return self.OptOutOfSPE - def set_OptOutOfSPE(self, OptOutOfSPE): - self.OptOutOfSPE = OptOutOfSPE - def get_PermitNumber(self): - return self.PermitNumber - def set_PermitNumber(self, PermitNumber): - self.PermitNumber = PermitNumber - def get_AccountZipCode(self): - return self.AccountZipCode - def set_AccountZipCode(self, AccountZipCode): - self.AccountZipCode = AccountZipCode - def get_ImportersReferenceType(self): - return self.ImportersReferenceType - def set_ImportersReferenceType(self, ImportersReferenceType): - self.ImportersReferenceType = ImportersReferenceType - def get_ImportersTelephoneNumber(self): - return self.ImportersTelephoneNumber - def set_ImportersTelephoneNumber(self, ImportersTelephoneNumber): - self.ImportersTelephoneNumber = ImportersTelephoneNumber - def get_ImportersFaxNumber(self): - return self.ImportersFaxNumber - def set_ImportersFaxNumber(self, ImportersFaxNumber): - self.ImportersFaxNumber = ImportersFaxNumber - def get_ImportersEmail(self): - return self.ImportersEmail - def set_ImportersEmail(self, ImportersEmail): - self.ImportersEmail = ImportersEmail - def get_Machinable(self): - return self.Machinable - def set_Machinable(self, Machinable): - self.Machinable = Machinable - def get_DestinationRateIndicator(self): - return self.DestinationRateIndicator - def set_DestinationRateIndicator(self, DestinationRateIndicator): - self.DestinationRateIndicator = DestinationRateIndicator - def get_MID(self): - return self.MID - def set_MID(self, MID): - self.MID = MID - def get_LogisticsManagerMID(self): - return self.LogisticsManagerMID - def set_LogisticsManagerMID(self, LogisticsManagerMID): - self.LogisticsManagerMID = LogisticsManagerMID - def get_CRID(self): - return self.CRID - def set_CRID(self, CRID): - self.CRID = CRID - def get_VendorCode(self): - return self.VendorCode - def set_VendorCode(self, VendorCode): - self.VendorCode = VendorCode - def get_VendorProductVersionNumber(self): - return self.VendorProductVersionNumber - def set_VendorProductVersionNumber(self, VendorProductVersionNumber): - self.VendorProductVersionNumber = VendorProductVersionNumber - def get_ePostageMailerReporting(self): - return self.ePostageMailerReporting - def set_ePostageMailerReporting(self, ePostageMailerReporting): - self.ePostageMailerReporting = ePostageMailerReporting - def get_SenderFirstName(self): - return self.SenderFirstName - def set_SenderFirstName(self, SenderFirstName): - self.SenderFirstName = SenderFirstName - def get_SenderLastName(self): - return self.SenderLastName - def set_SenderLastName(self, SenderLastName): - self.SenderLastName = SenderLastName - def get_SenderBusinessName(self): - return self.SenderBusinessName - def set_SenderBusinessName(self, SenderBusinessName): - self.SenderBusinessName = SenderBusinessName - def get_SenderAddress1(self): - return self.SenderAddress1 - def set_SenderAddress1(self, SenderAddress1): - self.SenderAddress1 = SenderAddress1 - def get_SenderCity(self): - return self.SenderCity - def set_SenderCity(self, SenderCity): - self.SenderCity = SenderCity - def get_SenderState(self): - return self.SenderState - def set_SenderState(self, SenderState): - self.SenderState = SenderState - def get_SenderZip5(self): - return self.SenderZip5 - def set_SenderZip5(self, SenderZip5): - self.SenderZip5 = SenderZip5 - def get_SenderPhone(self): - return self.SenderPhone - def set_SenderPhone(self, SenderPhone): - self.SenderPhone = SenderPhone - def get_SenderEmail(self): - return self.SenderEmail - def set_SenderEmail(self, SenderEmail): - self.SenderEmail = SenderEmail - def get_ChargebackCode(self): - return self.ChargebackCode - def set_ChargebackCode(self, ChargebackCode): - self.ChargebackCode = ChargebackCode - def get_USERID(self): - return self.USERID - def set_USERID(self, USERID): - self.USERID = USERID - def _hasContent(self): - if ( - self.Option is not None or - self.Revision is not None or - self.ImageParameters is not None or - self.FromFirstName is not None or - self.FromMiddleInitial is not None or - self.FromLastName is not None or - self.FromFirm is not None or - self.FromAddress1 is not None or - self.FromAddress2 is not None or - self.FromUrbanization is not None or - self.FromCity is not None or - self.FromState is not None or - self.FromZip5 is not None or - self.FromZip4 is not None or - self.FromPhone is not None or - self.FromCustomsReference is not None or - self.ToName is not None or - self.ToFirstName is not None or - self.ToLastName is not None or - self.ToFirm is not None or - self.ToAddress1 is not None or - self.ToAddress2 is not None or - self.ToAddress3 is not None or - self.ToCity is not None or - self.ToProvince is not None or - self.ToCountry is not None or - self.ToPostalCode is not None or - self.ToPOBoxFlag is not None or - self.ToPhone is not None or - self.ToFax is not None or - self.ToEmail is not None or - self.ImportersReferenceNumber is not None or - self.NonDeliveryOption is not None or - self.RedirectName is not None or - self.RedirectEmail is not None or - self.RedirectSMS is not None or - self.RedirectAddress is not None or - self.RedirectCity is not None or - self.RedirectState is not None or - self.RedirectZipCode is not None or - self.RedirectZip4 is not None or - self.Container is not None or - self.ShippingContents is not None or - self.Insured is not None or - self.InsuredNumber is not None or - self.InsuredAmount is not None or - self.GrossPounds is not None or - self.GrossOunces is not None or - self.ContentType is not None or - self.ContentTypeOther is not None or - self.Agreement is not None or - self.Comments is not None or - self.LicenseNumber is not None or - self.CertificateNumber is not None or - self.InvoiceNumber is not None or - self.ImageType is not None or - self.ImageLayout is not None or - self.CustomerRefNo is not None or - self.CustomerRefNo2 is not None or - self.POZipCode is not None or - self.LabelDate is not None or - self.EMCAAccount is not None or - self.HoldForManifest is not None or - self.EELPFC is not None or - self.PriceOptions is not None or - self.Width is not None or - self.Length is not None or - self.Height is not None or - self.Girth is not None or - self.ExtraServices is not None or - self.ActionCode is not None or - self.OptOutOfSPE is not None or - self.PermitNumber is not None or - self.AccountZipCode is not None or - self.ImportersReferenceType is not None or - self.ImportersTelephoneNumber is not None or - self.ImportersFaxNumber is not None or - self.ImportersEmail is not None or - self.Machinable is not None or - self.DestinationRateIndicator is not None or - self.MID is not None or - self.LogisticsManagerMID is not None or - self.CRID is not None or - self.VendorCode is not None or - self.VendorProductVersionNumber is not None or - self.ePostageMailerReporting is not None or - self.SenderFirstName is not None or - self.SenderLastName is not None or - self.SenderBusinessName is not None or - self.SenderAddress1 is not None or - self.SenderCity is not None or - self.SenderState is not None or - self.SenderZip5 is not None or - self.SenderPhone is not None or - self.SenderEmail is not None or - self.ChargebackCode is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='eVSPriorityMailIntlRequest', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('eVSPriorityMailIntlRequest') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'eVSPriorityMailIntlRequest': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='eVSPriorityMailIntlRequest') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='eVSPriorityMailIntlRequest', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='eVSPriorityMailIntlRequest'): - if self.USERID is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - outfile.write(' USERID=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.USERID), input_name='USERID')), )) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='eVSPriorityMailIntlRequest', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.Option is not None: - namespaceprefix_ = self.Option_nsprefix_ + ':' if (UseCapturedNS_ and self.Option_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sOption>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Option), input_name='Option')), namespaceprefix_ , eol_)) - if self.Revision is not None: - namespaceprefix_ = self.Revision_nsprefix_ + ':' if (UseCapturedNS_ and self.Revision_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRevision>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Revision), input_name='Revision')), namespaceprefix_ , eol_)) - if self.ImageParameters is not None: - namespaceprefix_ = self.ImageParameters_nsprefix_ + ':' if (UseCapturedNS_ and self.ImageParameters_nsprefix_) else '' - self.ImageParameters.export(outfile, level, namespaceprefix_, namespacedef_='', name_='ImageParameters', pretty_print=pretty_print) - if self.FromFirstName is not None: - namespaceprefix_ = self.FromFirstName_nsprefix_ + ':' if (UseCapturedNS_ and self.FromFirstName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromFirstName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromFirstName), input_name='FromFirstName')), namespaceprefix_ , eol_)) - if self.FromMiddleInitial is not None: - namespaceprefix_ = self.FromMiddleInitial_nsprefix_ + ':' if (UseCapturedNS_ and self.FromMiddleInitial_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromMiddleInitial>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromMiddleInitial), input_name='FromMiddleInitial')), namespaceprefix_ , eol_)) - if self.FromLastName is not None: - namespaceprefix_ = self.FromLastName_nsprefix_ + ':' if (UseCapturedNS_ and self.FromLastName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromLastName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromLastName), input_name='FromLastName')), namespaceprefix_ , eol_)) - if self.FromFirm is not None: - namespaceprefix_ = self.FromFirm_nsprefix_ + ':' if (UseCapturedNS_ and self.FromFirm_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromFirm>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromFirm), input_name='FromFirm')), namespaceprefix_ , eol_)) - if self.FromAddress1 is not None: - namespaceprefix_ = self.FromAddress1_nsprefix_ + ':' if (UseCapturedNS_ and self.FromAddress1_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromAddress1>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromAddress1), input_name='FromAddress1')), namespaceprefix_ , eol_)) - if self.FromAddress2 is not None: - namespaceprefix_ = self.FromAddress2_nsprefix_ + ':' if (UseCapturedNS_ and self.FromAddress2_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromAddress2>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromAddress2), input_name='FromAddress2')), namespaceprefix_ , eol_)) - if self.FromUrbanization is not None: - namespaceprefix_ = self.FromUrbanization_nsprefix_ + ':' if (UseCapturedNS_ and self.FromUrbanization_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromUrbanization>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromUrbanization), input_name='FromUrbanization')), namespaceprefix_ , eol_)) - if self.FromCity is not None: - namespaceprefix_ = self.FromCity_nsprefix_ + ':' if (UseCapturedNS_ and self.FromCity_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromCity), input_name='FromCity')), namespaceprefix_ , eol_)) - if self.FromState is not None: - namespaceprefix_ = self.FromState_nsprefix_ + ':' if (UseCapturedNS_ and self.FromState_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromState), input_name='FromState')), namespaceprefix_ , eol_)) - if self.FromZip5 is not None: - namespaceprefix_ = self.FromZip5_nsprefix_ + ':' if (UseCapturedNS_ and self.FromZip5_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromZip5>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromZip5), input_name='FromZip5')), namespaceprefix_ , eol_)) - if self.FromZip4 is not None: - namespaceprefix_ = self.FromZip4_nsprefix_ + ':' if (UseCapturedNS_ and self.FromZip4_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromZip4>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromZip4), input_name='FromZip4')), namespaceprefix_ , eol_)) - if self.FromPhone is not None: - namespaceprefix_ = self.FromPhone_nsprefix_ + ':' if (UseCapturedNS_ and self.FromPhone_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromPhone>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromPhone), input_name='FromPhone')), namespaceprefix_ , eol_)) - if self.FromCustomsReference is not None: - namespaceprefix_ = self.FromCustomsReference_nsprefix_ + ':' if (UseCapturedNS_ and self.FromCustomsReference_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromCustomsReference>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromCustomsReference), input_name='FromCustomsReference')), namespaceprefix_ , eol_)) - if self.ToName is not None: - namespaceprefix_ = self.ToName_nsprefix_ + ':' if (UseCapturedNS_ and self.ToName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToName), input_name='ToName')), namespaceprefix_ , eol_)) - if self.ToFirstName is not None: - namespaceprefix_ = self.ToFirstName_nsprefix_ + ':' if (UseCapturedNS_ and self.ToFirstName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToFirstName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToFirstName), input_name='ToFirstName')), namespaceprefix_ , eol_)) - if self.ToLastName is not None: - namespaceprefix_ = self.ToLastName_nsprefix_ + ':' if (UseCapturedNS_ and self.ToLastName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToLastName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToLastName), input_name='ToLastName')), namespaceprefix_ , eol_)) - if self.ToFirm is not None: - namespaceprefix_ = self.ToFirm_nsprefix_ + ':' if (UseCapturedNS_ and self.ToFirm_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToFirm>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToFirm), input_name='ToFirm')), namespaceprefix_ , eol_)) - if self.ToAddress1 is not None: - namespaceprefix_ = self.ToAddress1_nsprefix_ + ':' if (UseCapturedNS_ and self.ToAddress1_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToAddress1>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToAddress1), input_name='ToAddress1')), namespaceprefix_ , eol_)) - if self.ToAddress2 is not None: - namespaceprefix_ = self.ToAddress2_nsprefix_ + ':' if (UseCapturedNS_ and self.ToAddress2_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToAddress2>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToAddress2), input_name='ToAddress2')), namespaceprefix_ , eol_)) - if self.ToAddress3 is not None: - namespaceprefix_ = self.ToAddress3_nsprefix_ + ':' if (UseCapturedNS_ and self.ToAddress3_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToAddress3>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToAddress3), input_name='ToAddress3')), namespaceprefix_ , eol_)) - if self.ToCity is not None: - namespaceprefix_ = self.ToCity_nsprefix_ + ':' if (UseCapturedNS_ and self.ToCity_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToCity), input_name='ToCity')), namespaceprefix_ , eol_)) - if self.ToProvince is not None: - namespaceprefix_ = self.ToProvince_nsprefix_ + ':' if (UseCapturedNS_ and self.ToProvince_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToProvince>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToProvince), input_name='ToProvince')), namespaceprefix_ , eol_)) - if self.ToCountry is not None: - namespaceprefix_ = self.ToCountry_nsprefix_ + ':' if (UseCapturedNS_ and self.ToCountry_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToCountry>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToCountry), input_name='ToCountry')), namespaceprefix_ , eol_)) - if self.ToPostalCode is not None: - namespaceprefix_ = self.ToPostalCode_nsprefix_ + ':' if (UseCapturedNS_ and self.ToPostalCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToPostalCode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToPostalCode), input_name='ToPostalCode')), namespaceprefix_ , eol_)) - if self.ToPOBoxFlag is not None: - namespaceprefix_ = self.ToPOBoxFlag_nsprefix_ + ':' if (UseCapturedNS_ and self.ToPOBoxFlag_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToPOBoxFlag>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToPOBoxFlag), input_name='ToPOBoxFlag')), namespaceprefix_ , eol_)) - if self.ToPhone is not None: - namespaceprefix_ = self.ToPhone_nsprefix_ + ':' if (UseCapturedNS_ and self.ToPhone_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToPhone>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToPhone), input_name='ToPhone')), namespaceprefix_ , eol_)) - if self.ToFax is not None: - namespaceprefix_ = self.ToFax_nsprefix_ + ':' if (UseCapturedNS_ and self.ToFax_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToFax>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToFax), input_name='ToFax')), namespaceprefix_ , eol_)) - if self.ToEmail is not None: - namespaceprefix_ = self.ToEmail_nsprefix_ + ':' if (UseCapturedNS_ and self.ToEmail_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToEmail>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToEmail), input_name='ToEmail')), namespaceprefix_ , eol_)) - if self.ImportersReferenceNumber is not None: - namespaceprefix_ = self.ImportersReferenceNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.ImportersReferenceNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sImportersReferenceNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ImportersReferenceNumber), input_name='ImportersReferenceNumber')), namespaceprefix_ , eol_)) - if self.NonDeliveryOption is not None: - namespaceprefix_ = self.NonDeliveryOption_nsprefix_ + ':' if (UseCapturedNS_ and self.NonDeliveryOption_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sNonDeliveryOption>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.NonDeliveryOption), input_name='NonDeliveryOption')), namespaceprefix_ , eol_)) - if self.RedirectName is not None: - namespaceprefix_ = self.RedirectName_nsprefix_ + ':' if (UseCapturedNS_ and self.RedirectName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRedirectName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.RedirectName), input_name='RedirectName')), namespaceprefix_ , eol_)) - if self.RedirectEmail is not None: - namespaceprefix_ = self.RedirectEmail_nsprefix_ + ':' if (UseCapturedNS_ and self.RedirectEmail_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRedirectEmail>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.RedirectEmail), input_name='RedirectEmail')), namespaceprefix_ , eol_)) - if self.RedirectSMS is not None: - namespaceprefix_ = self.RedirectSMS_nsprefix_ + ':' if (UseCapturedNS_ and self.RedirectSMS_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRedirectSMS>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.RedirectSMS), input_name='RedirectSMS')), namespaceprefix_ , eol_)) - if self.RedirectAddress is not None: - namespaceprefix_ = self.RedirectAddress_nsprefix_ + ':' if (UseCapturedNS_ and self.RedirectAddress_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRedirectAddress>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.RedirectAddress), input_name='RedirectAddress')), namespaceprefix_ , eol_)) - if self.RedirectCity is not None: - namespaceprefix_ = self.RedirectCity_nsprefix_ + ':' if (UseCapturedNS_ and self.RedirectCity_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRedirectCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.RedirectCity), input_name='RedirectCity')), namespaceprefix_ , eol_)) - if self.RedirectState is not None: - namespaceprefix_ = self.RedirectState_nsprefix_ + ':' if (UseCapturedNS_ and self.RedirectState_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRedirectState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.RedirectState), input_name='RedirectState')), namespaceprefix_ , eol_)) - if self.RedirectZipCode is not None: - namespaceprefix_ = self.RedirectZipCode_nsprefix_ + ':' if (UseCapturedNS_ and self.RedirectZipCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRedirectZipCode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.RedirectZipCode), input_name='RedirectZipCode')), namespaceprefix_ , eol_)) - if self.RedirectZip4 is not None: - namespaceprefix_ = self.RedirectZip4_nsprefix_ + ':' if (UseCapturedNS_ and self.RedirectZip4_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRedirectZip4>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.RedirectZip4), input_name='RedirectZip4')), namespaceprefix_ , eol_)) - if self.Container is not None: - namespaceprefix_ = self.Container_nsprefix_ + ':' if (UseCapturedNS_ and self.Container_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sContainer>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Container), input_name='Container')), namespaceprefix_ , eol_)) - if self.ShippingContents is not None: - namespaceprefix_ = self.ShippingContents_nsprefix_ + ':' if (UseCapturedNS_ and self.ShippingContents_nsprefix_) else '' - self.ShippingContents.export(outfile, level, namespaceprefix_, namespacedef_='', name_='ShippingContents', pretty_print=pretty_print) - if self.Insured is not None: - namespaceprefix_ = self.Insured_nsprefix_ + ':' if (UseCapturedNS_ and self.Insured_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sInsured>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.Insured, input_name='Insured'), namespaceprefix_ , eol_)) - if self.InsuredNumber is not None: - namespaceprefix_ = self.InsuredNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.InsuredNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sInsuredNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.InsuredNumber), input_name='InsuredNumber')), namespaceprefix_ , eol_)) - if self.InsuredAmount is not None: - namespaceprefix_ = self.InsuredAmount_nsprefix_ + ':' if (UseCapturedNS_ and self.InsuredAmount_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sInsuredAmount>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.InsuredAmount), input_name='InsuredAmount')), namespaceprefix_ , eol_)) - if self.GrossPounds is not None: - namespaceprefix_ = self.GrossPounds_nsprefix_ + ':' if (UseCapturedNS_ and self.GrossPounds_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sGrossPounds>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.GrossPounds, input_name='GrossPounds'), namespaceprefix_ , eol_)) - if self.GrossOunces is not None: - namespaceprefix_ = self.GrossOunces_nsprefix_ + ':' if (UseCapturedNS_ and self.GrossOunces_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sGrossOunces>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.GrossOunces, input_name='GrossOunces'), namespaceprefix_ , eol_)) - if self.ContentType is not None: - namespaceprefix_ = self.ContentType_nsprefix_ + ':' if (UseCapturedNS_ and self.ContentType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sContentType>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ContentType), input_name='ContentType')), namespaceprefix_ , eol_)) - if self.ContentTypeOther is not None: - namespaceprefix_ = self.ContentTypeOther_nsprefix_ + ':' if (UseCapturedNS_ and self.ContentTypeOther_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sContentTypeOther>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ContentTypeOther), input_name='ContentTypeOther')), namespaceprefix_ , eol_)) - if self.Agreement is not None: - namespaceprefix_ = self.Agreement_nsprefix_ + ':' if (UseCapturedNS_ and self.Agreement_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAgreement>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Agreement), input_name='Agreement')), namespaceprefix_ , eol_)) - if self.Comments is not None: - namespaceprefix_ = self.Comments_nsprefix_ + ':' if (UseCapturedNS_ and self.Comments_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sComments>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Comments), input_name='Comments')), namespaceprefix_ , eol_)) - if self.LicenseNumber is not None: - namespaceprefix_ = self.LicenseNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.LicenseNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sLicenseNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.LicenseNumber), input_name='LicenseNumber')), namespaceprefix_ , eol_)) - if self.CertificateNumber is not None: - namespaceprefix_ = self.CertificateNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.CertificateNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCertificateNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CertificateNumber), input_name='CertificateNumber')), namespaceprefix_ , eol_)) - if self.InvoiceNumber is not None: - namespaceprefix_ = self.InvoiceNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.InvoiceNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sInvoiceNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.InvoiceNumber), input_name='InvoiceNumber')), namespaceprefix_ , eol_)) - if self.ImageType is not None: - namespaceprefix_ = self.ImageType_nsprefix_ + ':' if (UseCapturedNS_ and self.ImageType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sImageType>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ImageType), input_name='ImageType')), namespaceprefix_ , eol_)) - if self.ImageLayout is not None: - namespaceprefix_ = self.ImageLayout_nsprefix_ + ':' if (UseCapturedNS_ and self.ImageLayout_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sImageLayout>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ImageLayout), input_name='ImageLayout')), namespaceprefix_ , eol_)) - if self.CustomerRefNo is not None: - namespaceprefix_ = self.CustomerRefNo_nsprefix_ + ':' if (UseCapturedNS_ and self.CustomerRefNo_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCustomerRefNo>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CustomerRefNo), input_name='CustomerRefNo')), namespaceprefix_ , eol_)) - if self.CustomerRefNo2 is not None: - namespaceprefix_ = self.CustomerRefNo2_nsprefix_ + ':' if (UseCapturedNS_ and self.CustomerRefNo2_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCustomerRefNo2>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CustomerRefNo2), input_name='CustomerRefNo2')), namespaceprefix_ , eol_)) - if self.POZipCode is not None: - namespaceprefix_ = self.POZipCode_nsprefix_ + ':' if (UseCapturedNS_ and self.POZipCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPOZipCode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.POZipCode), input_name='POZipCode')), namespaceprefix_ , eol_)) - if self.LabelDate is not None: - namespaceprefix_ = self.LabelDate_nsprefix_ + ':' if (UseCapturedNS_ and self.LabelDate_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sLabelDate>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.LabelDate), input_name='LabelDate')), namespaceprefix_ , eol_)) - if self.EMCAAccount is not None: - namespaceprefix_ = self.EMCAAccount_nsprefix_ + ':' if (UseCapturedNS_ and self.EMCAAccount_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEMCAAccount>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.EMCAAccount), input_name='EMCAAccount')), namespaceprefix_ , eol_)) - if self.HoldForManifest is not None: - namespaceprefix_ = self.HoldForManifest_nsprefix_ + ':' if (UseCapturedNS_ and self.HoldForManifest_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sHoldForManifest>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.HoldForManifest), input_name='HoldForManifest')), namespaceprefix_ , eol_)) - if self.EELPFC is not None: - namespaceprefix_ = self.EELPFC_nsprefix_ + ':' if (UseCapturedNS_ and self.EELPFC_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEELPFC>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.EELPFC), input_name='EELPFC')), namespaceprefix_ , eol_)) - if self.PriceOptions is not None: - namespaceprefix_ = self.PriceOptions_nsprefix_ + ':' if (UseCapturedNS_ and self.PriceOptions_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPriceOptions>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PriceOptions), input_name='PriceOptions')), namespaceprefix_ , eol_)) - if self.Width is not None: - namespaceprefix_ = self.Width_nsprefix_ + ':' if (UseCapturedNS_ and self.Width_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sWidth>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Width), input_name='Width')), namespaceprefix_ , eol_)) - if self.Length is not None: - namespaceprefix_ = self.Length_nsprefix_ + ':' if (UseCapturedNS_ and self.Length_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sLength>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Length), input_name='Length')), namespaceprefix_ , eol_)) - if self.Height is not None: - namespaceprefix_ = self.Height_nsprefix_ + ':' if (UseCapturedNS_ and self.Height_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sHeight>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Height), input_name='Height')), namespaceprefix_ , eol_)) - if self.Girth is not None: - namespaceprefix_ = self.Girth_nsprefix_ + ':' if (UseCapturedNS_ and self.Girth_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sGirth>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Girth), input_name='Girth')), namespaceprefix_ , eol_)) - if self.ExtraServices is not None: - namespaceprefix_ = self.ExtraServices_nsprefix_ + ':' if (UseCapturedNS_ and self.ExtraServices_nsprefix_) else '' - self.ExtraServices.export(outfile, level, namespaceprefix_, namespacedef_='', name_='ExtraServices', pretty_print=pretty_print) - if self.ActionCode is not None: - namespaceprefix_ = self.ActionCode_nsprefix_ + ':' if (UseCapturedNS_ and self.ActionCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sActionCode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ActionCode), input_name='ActionCode')), namespaceprefix_ , eol_)) - if self.OptOutOfSPE is not None: - namespaceprefix_ = self.OptOutOfSPE_nsprefix_ + ':' if (UseCapturedNS_ and self.OptOutOfSPE_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sOptOutOfSPE>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.OptOutOfSPE, input_name='OptOutOfSPE'), namespaceprefix_ , eol_)) - if self.PermitNumber is not None: - namespaceprefix_ = self.PermitNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.PermitNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPermitNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PermitNumber), input_name='PermitNumber')), namespaceprefix_ , eol_)) - if self.AccountZipCode is not None: - namespaceprefix_ = self.AccountZipCode_nsprefix_ + ':' if (UseCapturedNS_ and self.AccountZipCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAccountZipCode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.AccountZipCode), input_name='AccountZipCode')), namespaceprefix_ , eol_)) - if self.ImportersReferenceType is not None: - namespaceprefix_ = self.ImportersReferenceType_nsprefix_ + ':' if (UseCapturedNS_ and self.ImportersReferenceType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sImportersReferenceType>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ImportersReferenceType), input_name='ImportersReferenceType')), namespaceprefix_ , eol_)) - if self.ImportersTelephoneNumber is not None: - namespaceprefix_ = self.ImportersTelephoneNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.ImportersTelephoneNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sImportersTelephoneNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ImportersTelephoneNumber), input_name='ImportersTelephoneNumber')), namespaceprefix_ , eol_)) - if self.ImportersFaxNumber is not None: - namespaceprefix_ = self.ImportersFaxNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.ImportersFaxNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sImportersFaxNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ImportersFaxNumber), input_name='ImportersFaxNumber')), namespaceprefix_ , eol_)) - if self.ImportersEmail is not None: - namespaceprefix_ = self.ImportersEmail_nsprefix_ + ':' if (UseCapturedNS_ and self.ImportersEmail_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sImportersEmail>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ImportersEmail), input_name='ImportersEmail')), namespaceprefix_ , eol_)) - if self.Machinable is not None: - namespaceprefix_ = self.Machinable_nsprefix_ + ':' if (UseCapturedNS_ and self.Machinable_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sMachinable>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.Machinable, input_name='Machinable'), namespaceprefix_ , eol_)) - if self.DestinationRateIndicator is not None: - namespaceprefix_ = self.DestinationRateIndicator_nsprefix_ + ':' if (UseCapturedNS_ and self.DestinationRateIndicator_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDestinationRateIndicator>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.DestinationRateIndicator), input_name='DestinationRateIndicator')), namespaceprefix_ , eol_)) - if self.MID is not None: - namespaceprefix_ = self.MID_nsprefix_ + ':' if (UseCapturedNS_ and self.MID_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sMID>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.MID), input_name='MID')), namespaceprefix_ , eol_)) - if self.LogisticsManagerMID is not None: - namespaceprefix_ = self.LogisticsManagerMID_nsprefix_ + ':' if (UseCapturedNS_ and self.LogisticsManagerMID_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sLogisticsManagerMID>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.LogisticsManagerMID), input_name='LogisticsManagerMID')), namespaceprefix_ , eol_)) - if self.CRID is not None: - namespaceprefix_ = self.CRID_nsprefix_ + ':' if (UseCapturedNS_ and self.CRID_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCRID>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CRID), input_name='CRID')), namespaceprefix_ , eol_)) - if self.VendorCode is not None: - namespaceprefix_ = self.VendorCode_nsprefix_ + ':' if (UseCapturedNS_ and self.VendorCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sVendorCode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.VendorCode), input_name='VendorCode')), namespaceprefix_ , eol_)) - if self.VendorProductVersionNumber is not None: - namespaceprefix_ = self.VendorProductVersionNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.VendorProductVersionNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sVendorProductVersionNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.VendorProductVersionNumber), input_name='VendorProductVersionNumber')), namespaceprefix_ , eol_)) - if self.ePostageMailerReporting is not None: - namespaceprefix_ = self.ePostageMailerReporting_nsprefix_ + ':' if (UseCapturedNS_ and self.ePostageMailerReporting_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sePostageMailerReporting>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ePostageMailerReporting), input_name='ePostageMailerReporting')), namespaceprefix_ , eol_)) - if self.SenderFirstName is not None: - namespaceprefix_ = self.SenderFirstName_nsprefix_ + ':' if (UseCapturedNS_ and self.SenderFirstName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSenderFirstName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SenderFirstName), input_name='SenderFirstName')), namespaceprefix_ , eol_)) - if self.SenderLastName is not None: - namespaceprefix_ = self.SenderLastName_nsprefix_ + ':' if (UseCapturedNS_ and self.SenderLastName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSenderLastName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SenderLastName), input_name='SenderLastName')), namespaceprefix_ , eol_)) - if self.SenderBusinessName is not None: - namespaceprefix_ = self.SenderBusinessName_nsprefix_ + ':' if (UseCapturedNS_ and self.SenderBusinessName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSenderBusinessName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SenderBusinessName), input_name='SenderBusinessName')), namespaceprefix_ , eol_)) - if self.SenderAddress1 is not None: - namespaceprefix_ = self.SenderAddress1_nsprefix_ + ':' if (UseCapturedNS_ and self.SenderAddress1_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSenderAddress1>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SenderAddress1), input_name='SenderAddress1')), namespaceprefix_ , eol_)) - if self.SenderCity is not None: - namespaceprefix_ = self.SenderCity_nsprefix_ + ':' if (UseCapturedNS_ and self.SenderCity_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSenderCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SenderCity), input_name='SenderCity')), namespaceprefix_ , eol_)) - if self.SenderState is not None: - namespaceprefix_ = self.SenderState_nsprefix_ + ':' if (UseCapturedNS_ and self.SenderState_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSenderState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SenderState), input_name='SenderState')), namespaceprefix_ , eol_)) - if self.SenderZip5 is not None: - namespaceprefix_ = self.SenderZip5_nsprefix_ + ':' if (UseCapturedNS_ and self.SenderZip5_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSenderZip5>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SenderZip5), input_name='SenderZip5')), namespaceprefix_ , eol_)) - if self.SenderPhone is not None: - namespaceprefix_ = self.SenderPhone_nsprefix_ + ':' if (UseCapturedNS_ and self.SenderPhone_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSenderPhone>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SenderPhone), input_name='SenderPhone')), namespaceprefix_ , eol_)) - if self.SenderEmail is not None: - namespaceprefix_ = self.SenderEmail_nsprefix_ + ':' if (UseCapturedNS_ and self.SenderEmail_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSenderEmail>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SenderEmail), input_name='SenderEmail')), namespaceprefix_ , eol_)) - if self.ChargebackCode is not None: - namespaceprefix_ = self.ChargebackCode_nsprefix_ + ':' if (UseCapturedNS_ and self.ChargebackCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sChargebackCode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ChargebackCode), input_name='ChargebackCode')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('USERID', node) - if value is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - self.USERID = value - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'Option': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Option') - value_ = self.gds_validate_string(value_, node, 'Option') - self.Option = value_ - self.Option_nsprefix_ = child_.prefix - elif nodeName_ == 'Revision': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Revision') - value_ = self.gds_validate_string(value_, node, 'Revision') - self.Revision = value_ - self.Revision_nsprefix_ = child_.prefix - elif nodeName_ == 'ImageParameters': - obj_ = ImageParametersType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.ImageParameters = obj_ - obj_.original_tagname_ = 'ImageParameters' - elif nodeName_ == 'FromFirstName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromFirstName') - value_ = self.gds_validate_string(value_, node, 'FromFirstName') - self.FromFirstName = value_ - self.FromFirstName_nsprefix_ = child_.prefix - elif nodeName_ == 'FromMiddleInitial': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromMiddleInitial') - value_ = self.gds_validate_string(value_, node, 'FromMiddleInitial') - self.FromMiddleInitial = value_ - self.FromMiddleInitial_nsprefix_ = child_.prefix - elif nodeName_ == 'FromLastName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromLastName') - value_ = self.gds_validate_string(value_, node, 'FromLastName') - self.FromLastName = value_ - self.FromLastName_nsprefix_ = child_.prefix - elif nodeName_ == 'FromFirm': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromFirm') - value_ = self.gds_validate_string(value_, node, 'FromFirm') - self.FromFirm = value_ - self.FromFirm_nsprefix_ = child_.prefix - elif nodeName_ == 'FromAddress1': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromAddress1') - value_ = self.gds_validate_string(value_, node, 'FromAddress1') - self.FromAddress1 = value_ - self.FromAddress1_nsprefix_ = child_.prefix - elif nodeName_ == 'FromAddress2': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromAddress2') - value_ = self.gds_validate_string(value_, node, 'FromAddress2') - self.FromAddress2 = value_ - self.FromAddress2_nsprefix_ = child_.prefix - elif nodeName_ == 'FromUrbanization': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromUrbanization') - value_ = self.gds_validate_string(value_, node, 'FromUrbanization') - self.FromUrbanization = value_ - self.FromUrbanization_nsprefix_ = child_.prefix - elif nodeName_ == 'FromCity': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromCity') - value_ = self.gds_validate_string(value_, node, 'FromCity') - self.FromCity = value_ - self.FromCity_nsprefix_ = child_.prefix - elif nodeName_ == 'FromState': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromState') - value_ = self.gds_validate_string(value_, node, 'FromState') - self.FromState = value_ - self.FromState_nsprefix_ = child_.prefix - elif nodeName_ == 'FromZip5': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromZip5') - value_ = self.gds_validate_string(value_, node, 'FromZip5') - self.FromZip5 = value_ - self.FromZip5_nsprefix_ = child_.prefix - elif nodeName_ == 'FromZip4': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromZip4') - value_ = self.gds_validate_string(value_, node, 'FromZip4') - self.FromZip4 = value_ - self.FromZip4_nsprefix_ = child_.prefix - elif nodeName_ == 'FromPhone': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromPhone') - value_ = self.gds_validate_string(value_, node, 'FromPhone') - self.FromPhone = value_ - self.FromPhone_nsprefix_ = child_.prefix - elif nodeName_ == 'FromCustomsReference': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromCustomsReference') - value_ = self.gds_validate_string(value_, node, 'FromCustomsReference') - self.FromCustomsReference = value_ - self.FromCustomsReference_nsprefix_ = child_.prefix - elif nodeName_ == 'ToName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToName') - value_ = self.gds_validate_string(value_, node, 'ToName') - self.ToName = value_ - self.ToName_nsprefix_ = child_.prefix - elif nodeName_ == 'ToFirstName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToFirstName') - value_ = self.gds_validate_string(value_, node, 'ToFirstName') - self.ToFirstName = value_ - self.ToFirstName_nsprefix_ = child_.prefix - elif nodeName_ == 'ToLastName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToLastName') - value_ = self.gds_validate_string(value_, node, 'ToLastName') - self.ToLastName = value_ - self.ToLastName_nsprefix_ = child_.prefix - elif nodeName_ == 'ToFirm': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToFirm') - value_ = self.gds_validate_string(value_, node, 'ToFirm') - self.ToFirm = value_ - self.ToFirm_nsprefix_ = child_.prefix - elif nodeName_ == 'ToAddress1': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToAddress1') - value_ = self.gds_validate_string(value_, node, 'ToAddress1') - self.ToAddress1 = value_ - self.ToAddress1_nsprefix_ = child_.prefix - elif nodeName_ == 'ToAddress2': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToAddress2') - value_ = self.gds_validate_string(value_, node, 'ToAddress2') - self.ToAddress2 = value_ - self.ToAddress2_nsprefix_ = child_.prefix - elif nodeName_ == 'ToAddress3': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToAddress3') - value_ = self.gds_validate_string(value_, node, 'ToAddress3') - self.ToAddress3 = value_ - self.ToAddress3_nsprefix_ = child_.prefix - elif nodeName_ == 'ToCity': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToCity') - value_ = self.gds_validate_string(value_, node, 'ToCity') - self.ToCity = value_ - self.ToCity_nsprefix_ = child_.prefix - elif nodeName_ == 'ToProvince': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToProvince') - value_ = self.gds_validate_string(value_, node, 'ToProvince') - self.ToProvince = value_ - self.ToProvince_nsprefix_ = child_.prefix - elif nodeName_ == 'ToCountry': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToCountry') - value_ = self.gds_validate_string(value_, node, 'ToCountry') - self.ToCountry = value_ - self.ToCountry_nsprefix_ = child_.prefix - elif nodeName_ == 'ToPostalCode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToPostalCode') - value_ = self.gds_validate_string(value_, node, 'ToPostalCode') - self.ToPostalCode = value_ - self.ToPostalCode_nsprefix_ = child_.prefix - elif nodeName_ == 'ToPOBoxFlag': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToPOBoxFlag') - value_ = self.gds_validate_string(value_, node, 'ToPOBoxFlag') - self.ToPOBoxFlag = value_ - self.ToPOBoxFlag_nsprefix_ = child_.prefix - elif nodeName_ == 'ToPhone': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToPhone') - value_ = self.gds_validate_string(value_, node, 'ToPhone') - self.ToPhone = value_ - self.ToPhone_nsprefix_ = child_.prefix - elif nodeName_ == 'ToFax': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToFax') - value_ = self.gds_validate_string(value_, node, 'ToFax') - self.ToFax = value_ - self.ToFax_nsprefix_ = child_.prefix - elif nodeName_ == 'ToEmail': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToEmail') - value_ = self.gds_validate_string(value_, node, 'ToEmail') - self.ToEmail = value_ - self.ToEmail_nsprefix_ = child_.prefix - elif nodeName_ == 'ImportersReferenceNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ImportersReferenceNumber') - value_ = self.gds_validate_string(value_, node, 'ImportersReferenceNumber') - self.ImportersReferenceNumber = value_ - self.ImportersReferenceNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'NonDeliveryOption': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'NonDeliveryOption') - value_ = self.gds_validate_string(value_, node, 'NonDeliveryOption') - self.NonDeliveryOption = value_ - self.NonDeliveryOption_nsprefix_ = child_.prefix - elif nodeName_ == 'RedirectName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'RedirectName') - value_ = self.gds_validate_string(value_, node, 'RedirectName') - self.RedirectName = value_ - self.RedirectName_nsprefix_ = child_.prefix - elif nodeName_ == 'RedirectEmail': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'RedirectEmail') - value_ = self.gds_validate_string(value_, node, 'RedirectEmail') - self.RedirectEmail = value_ - self.RedirectEmail_nsprefix_ = child_.prefix - elif nodeName_ == 'RedirectSMS': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'RedirectSMS') - value_ = self.gds_validate_string(value_, node, 'RedirectSMS') - self.RedirectSMS = value_ - self.RedirectSMS_nsprefix_ = child_.prefix - elif nodeName_ == 'RedirectAddress': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'RedirectAddress') - value_ = self.gds_validate_string(value_, node, 'RedirectAddress') - self.RedirectAddress = value_ - self.RedirectAddress_nsprefix_ = child_.prefix - elif nodeName_ == 'RedirectCity': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'RedirectCity') - value_ = self.gds_validate_string(value_, node, 'RedirectCity') - self.RedirectCity = value_ - self.RedirectCity_nsprefix_ = child_.prefix - elif nodeName_ == 'RedirectState': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'RedirectState') - value_ = self.gds_validate_string(value_, node, 'RedirectState') - self.RedirectState = value_ - self.RedirectState_nsprefix_ = child_.prefix - elif nodeName_ == 'RedirectZipCode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'RedirectZipCode') - value_ = self.gds_validate_string(value_, node, 'RedirectZipCode') - self.RedirectZipCode = value_ - self.RedirectZipCode_nsprefix_ = child_.prefix - elif nodeName_ == 'RedirectZip4': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'RedirectZip4') - value_ = self.gds_validate_string(value_, node, 'RedirectZip4') - self.RedirectZip4 = value_ - self.RedirectZip4_nsprefix_ = child_.prefix - elif nodeName_ == 'Container': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Container') - value_ = self.gds_validate_string(value_, node, 'Container') - self.Container = value_ - self.Container_nsprefix_ = child_.prefix - elif nodeName_ == 'ShippingContents': - obj_ = ShippingContentsType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.ShippingContents = obj_ - obj_.original_tagname_ = 'ShippingContents' - elif nodeName_ == 'Insured': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'Insured') - ival_ = self.gds_validate_boolean(ival_, node, 'Insured') - self.Insured = ival_ - self.Insured_nsprefix_ = child_.prefix - elif nodeName_ == 'InsuredNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'InsuredNumber') - value_ = self.gds_validate_string(value_, node, 'InsuredNumber') - self.InsuredNumber = value_ - self.InsuredNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'InsuredAmount': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'InsuredAmount') - value_ = self.gds_validate_string(value_, node, 'InsuredAmount') - self.InsuredAmount = value_ - self.InsuredAmount_nsprefix_ = child_.prefix - elif nodeName_ == 'GrossPounds' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'GrossPounds') - ival_ = self.gds_validate_integer(ival_, node, 'GrossPounds') - self.GrossPounds = ival_ - self.GrossPounds_nsprefix_ = child_.prefix - elif nodeName_ == 'GrossOunces' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'GrossOunces') - ival_ = self.gds_validate_integer(ival_, node, 'GrossOunces') - self.GrossOunces = ival_ - self.GrossOunces_nsprefix_ = child_.prefix - elif nodeName_ == 'ContentType': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ContentType') - value_ = self.gds_validate_string(value_, node, 'ContentType') - self.ContentType = value_ - self.ContentType_nsprefix_ = child_.prefix - elif nodeName_ == 'ContentTypeOther': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ContentTypeOther') - value_ = self.gds_validate_string(value_, node, 'ContentTypeOther') - self.ContentTypeOther = value_ - self.ContentTypeOther_nsprefix_ = child_.prefix - elif nodeName_ == 'Agreement': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Agreement') - value_ = self.gds_validate_string(value_, node, 'Agreement') - self.Agreement = value_ - self.Agreement_nsprefix_ = child_.prefix - elif nodeName_ == 'Comments': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Comments') - value_ = self.gds_validate_string(value_, node, 'Comments') - self.Comments = value_ - self.Comments_nsprefix_ = child_.prefix - elif nodeName_ == 'LicenseNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'LicenseNumber') - value_ = self.gds_validate_string(value_, node, 'LicenseNumber') - self.LicenseNumber = value_ - self.LicenseNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'CertificateNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CertificateNumber') - value_ = self.gds_validate_string(value_, node, 'CertificateNumber') - self.CertificateNumber = value_ - self.CertificateNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'InvoiceNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'InvoiceNumber') - value_ = self.gds_validate_string(value_, node, 'InvoiceNumber') - self.InvoiceNumber = value_ - self.InvoiceNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'ImageType': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ImageType') - value_ = self.gds_validate_string(value_, node, 'ImageType') - self.ImageType = value_ - self.ImageType_nsprefix_ = child_.prefix - elif nodeName_ == 'ImageLayout': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ImageLayout') - value_ = self.gds_validate_string(value_, node, 'ImageLayout') - self.ImageLayout = value_ - self.ImageLayout_nsprefix_ = child_.prefix - elif nodeName_ == 'CustomerRefNo': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CustomerRefNo') - value_ = self.gds_validate_string(value_, node, 'CustomerRefNo') - self.CustomerRefNo = value_ - self.CustomerRefNo_nsprefix_ = child_.prefix - elif nodeName_ == 'CustomerRefNo2': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CustomerRefNo2') - value_ = self.gds_validate_string(value_, node, 'CustomerRefNo2') - self.CustomerRefNo2 = value_ - self.CustomerRefNo2_nsprefix_ = child_.prefix - elif nodeName_ == 'POZipCode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'POZipCode') - value_ = self.gds_validate_string(value_, node, 'POZipCode') - self.POZipCode = value_ - self.POZipCode_nsprefix_ = child_.prefix - elif nodeName_ == 'LabelDate': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'LabelDate') - value_ = self.gds_validate_string(value_, node, 'LabelDate') - self.LabelDate = value_ - self.LabelDate_nsprefix_ = child_.prefix - elif nodeName_ == 'EMCAAccount': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'EMCAAccount') - value_ = self.gds_validate_string(value_, node, 'EMCAAccount') - self.EMCAAccount = value_ - self.EMCAAccount_nsprefix_ = child_.prefix - elif nodeName_ == 'HoldForManifest': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'HoldForManifest') - value_ = self.gds_validate_string(value_, node, 'HoldForManifest') - self.HoldForManifest = value_ - self.HoldForManifest_nsprefix_ = child_.prefix - elif nodeName_ == 'EELPFC': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'EELPFC') - value_ = self.gds_validate_string(value_, node, 'EELPFC') - self.EELPFC = value_ - self.EELPFC_nsprefix_ = child_.prefix - elif nodeName_ == 'PriceOptions': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PriceOptions') - value_ = self.gds_validate_string(value_, node, 'PriceOptions') - self.PriceOptions = value_ - self.PriceOptions_nsprefix_ = child_.prefix - elif nodeName_ == 'Width': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Width') - value_ = self.gds_validate_string(value_, node, 'Width') - self.Width = value_ - self.Width_nsprefix_ = child_.prefix - elif nodeName_ == 'Length': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Length') - value_ = self.gds_validate_string(value_, node, 'Length') - self.Length = value_ - self.Length_nsprefix_ = child_.prefix - elif nodeName_ == 'Height': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Height') - value_ = self.gds_validate_string(value_, node, 'Height') - self.Height = value_ - self.Height_nsprefix_ = child_.prefix - elif nodeName_ == 'Girth': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Girth') - value_ = self.gds_validate_string(value_, node, 'Girth') - self.Girth = value_ - self.Girth_nsprefix_ = child_.prefix - elif nodeName_ == 'ExtraServices': - obj_ = ExtraServicesType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.ExtraServices = obj_ - obj_.original_tagname_ = 'ExtraServices' - elif nodeName_ == 'ActionCode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ActionCode') - value_ = self.gds_validate_string(value_, node, 'ActionCode') - self.ActionCode = value_ - self.ActionCode_nsprefix_ = child_.prefix - elif nodeName_ == 'OptOutOfSPE': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'OptOutOfSPE') - ival_ = self.gds_validate_boolean(ival_, node, 'OptOutOfSPE') - self.OptOutOfSPE = ival_ - self.OptOutOfSPE_nsprefix_ = child_.prefix - elif nodeName_ == 'PermitNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PermitNumber') - value_ = self.gds_validate_string(value_, node, 'PermitNumber') - self.PermitNumber = value_ - self.PermitNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'AccountZipCode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'AccountZipCode') - value_ = self.gds_validate_string(value_, node, 'AccountZipCode') - self.AccountZipCode = value_ - self.AccountZipCode_nsprefix_ = child_.prefix - elif nodeName_ == 'ImportersReferenceType': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ImportersReferenceType') - value_ = self.gds_validate_string(value_, node, 'ImportersReferenceType') - self.ImportersReferenceType = value_ - self.ImportersReferenceType_nsprefix_ = child_.prefix - elif nodeName_ == 'ImportersTelephoneNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ImportersTelephoneNumber') - value_ = self.gds_validate_string(value_, node, 'ImportersTelephoneNumber') - self.ImportersTelephoneNumber = value_ - self.ImportersTelephoneNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'ImportersFaxNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ImportersFaxNumber') - value_ = self.gds_validate_string(value_, node, 'ImportersFaxNumber') - self.ImportersFaxNumber = value_ - self.ImportersFaxNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'ImportersEmail': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ImportersEmail') - value_ = self.gds_validate_string(value_, node, 'ImportersEmail') - self.ImportersEmail = value_ - self.ImportersEmail_nsprefix_ = child_.prefix - elif nodeName_ == 'Machinable': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'Machinable') - ival_ = self.gds_validate_boolean(ival_, node, 'Machinable') - self.Machinable = ival_ - self.Machinable_nsprefix_ = child_.prefix - elif nodeName_ == 'DestinationRateIndicator': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'DestinationRateIndicator') - value_ = self.gds_validate_string(value_, node, 'DestinationRateIndicator') - self.DestinationRateIndicator = value_ - self.DestinationRateIndicator_nsprefix_ = child_.prefix - elif nodeName_ == 'MID': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'MID') - value_ = self.gds_validate_string(value_, node, 'MID') - self.MID = value_ - self.MID_nsprefix_ = child_.prefix - elif nodeName_ == 'LogisticsManagerMID': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'LogisticsManagerMID') - value_ = self.gds_validate_string(value_, node, 'LogisticsManagerMID') - self.LogisticsManagerMID = value_ - self.LogisticsManagerMID_nsprefix_ = child_.prefix - elif nodeName_ == 'CRID': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CRID') - value_ = self.gds_validate_string(value_, node, 'CRID') - self.CRID = value_ - self.CRID_nsprefix_ = child_.prefix - elif nodeName_ == 'VendorCode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'VendorCode') - value_ = self.gds_validate_string(value_, node, 'VendorCode') - self.VendorCode = value_ - self.VendorCode_nsprefix_ = child_.prefix - elif nodeName_ == 'VendorProductVersionNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'VendorProductVersionNumber') - value_ = self.gds_validate_string(value_, node, 'VendorProductVersionNumber') - self.VendorProductVersionNumber = value_ - self.VendorProductVersionNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'ePostageMailerReporting': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ePostageMailerReporting') - value_ = self.gds_validate_string(value_, node, 'ePostageMailerReporting') - self.ePostageMailerReporting = value_ - self.ePostageMailerReporting_nsprefix_ = child_.prefix - elif nodeName_ == 'SenderFirstName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SenderFirstName') - value_ = self.gds_validate_string(value_, node, 'SenderFirstName') - self.SenderFirstName = value_ - self.SenderFirstName_nsprefix_ = child_.prefix - elif nodeName_ == 'SenderLastName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SenderLastName') - value_ = self.gds_validate_string(value_, node, 'SenderLastName') - self.SenderLastName = value_ - self.SenderLastName_nsprefix_ = child_.prefix - elif nodeName_ == 'SenderBusinessName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SenderBusinessName') - value_ = self.gds_validate_string(value_, node, 'SenderBusinessName') - self.SenderBusinessName = value_ - self.SenderBusinessName_nsprefix_ = child_.prefix - elif nodeName_ == 'SenderAddress1': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SenderAddress1') - value_ = self.gds_validate_string(value_, node, 'SenderAddress1') - self.SenderAddress1 = value_ - self.SenderAddress1_nsprefix_ = child_.prefix - elif nodeName_ == 'SenderCity': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SenderCity') - value_ = self.gds_validate_string(value_, node, 'SenderCity') - self.SenderCity = value_ - self.SenderCity_nsprefix_ = child_.prefix - elif nodeName_ == 'SenderState': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SenderState') - value_ = self.gds_validate_string(value_, node, 'SenderState') - self.SenderState = value_ - self.SenderState_nsprefix_ = child_.prefix - elif nodeName_ == 'SenderZip5': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SenderZip5') - value_ = self.gds_validate_string(value_, node, 'SenderZip5') - self.SenderZip5 = value_ - self.SenderZip5_nsprefix_ = child_.prefix - elif nodeName_ == 'SenderPhone': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SenderPhone') - value_ = self.gds_validate_string(value_, node, 'SenderPhone') - self.SenderPhone = value_ - self.SenderPhone_nsprefix_ = child_.prefix - elif nodeName_ == 'SenderEmail': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SenderEmail') - value_ = self.gds_validate_string(value_, node, 'SenderEmail') - self.SenderEmail = value_ - self.SenderEmail_nsprefix_ = child_.prefix - elif nodeName_ == 'ChargebackCode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ChargebackCode') - value_ = self.gds_validate_string(value_, node, 'ChargebackCode') - self.ChargebackCode = value_ - self.ChargebackCode_nsprefix_ = child_.prefix -# end class eVSPriorityMailIntlRequest - - -class ImageParametersType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ImageParameter=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.ImageParameter = ImageParameter - self.ImageParameter_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, ImageParametersType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if ImageParametersType.subclass: - return ImageParametersType.subclass(*args_, **kwargs_) - else: - return ImageParametersType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_ImageParameter(self): - return self.ImageParameter - def set_ImageParameter(self, ImageParameter): - self.ImageParameter = ImageParameter - def _hasContent(self): - if ( - self.ImageParameter is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ImageParametersType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('ImageParametersType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'ImageParametersType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='ImageParametersType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='ImageParametersType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='ImageParametersType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ImageParametersType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.ImageParameter is not None: - namespaceprefix_ = self.ImageParameter_nsprefix_ + ':' if (UseCapturedNS_ and self.ImageParameter_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sImageParameter>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ImageParameter), input_name='ImageParameter')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'ImageParameter': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ImageParameter') - value_ = self.gds_validate_string(value_, node, 'ImageParameter') - self.ImageParameter = value_ - self.ImageParameter_nsprefix_ = child_.prefix -# end class ImageParametersType - - -class ShippingContentsType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ItemDetail=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - if ItemDetail is None: - self.ItemDetail = [] - else: - self.ItemDetail = ItemDetail - self.ItemDetail_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, ShippingContentsType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if ShippingContentsType.subclass: - return ShippingContentsType.subclass(*args_, **kwargs_) - else: - return ShippingContentsType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_ItemDetail(self): - return self.ItemDetail - def set_ItemDetail(self, ItemDetail): - self.ItemDetail = ItemDetail - def add_ItemDetail(self, value): - self.ItemDetail.append(value) - def insert_ItemDetail_at(self, index, value): - self.ItemDetail.insert(index, value) - def replace_ItemDetail_at(self, index, value): - self.ItemDetail[index] = value - def _hasContent(self): - if ( - self.ItemDetail - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ShippingContentsType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('ShippingContentsType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'ShippingContentsType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='ShippingContentsType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='ShippingContentsType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='ShippingContentsType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ShippingContentsType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - for ItemDetail_ in self.ItemDetail: - namespaceprefix_ = self.ItemDetail_nsprefix_ + ':' if (UseCapturedNS_ and self.ItemDetail_nsprefix_) else '' - ItemDetail_.export(outfile, level, namespaceprefix_, namespacedef_='', name_='ItemDetail', pretty_print=pretty_print) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'ItemDetail': - obj_ = ItemDetailType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.ItemDetail.append(obj_) - obj_.original_tagname_ = 'ItemDetail' -# end class ShippingContentsType - - -class ItemDetailType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, Description=None, Quantity=None, Value=None, NetPounds=None, NetOunces=None, HSTariffNumber=None, CountryOfOrigin=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.Description = Description - self.Description_nsprefix_ = None - self.Quantity = Quantity - self.Quantity_nsprefix_ = None - self.Value = Value - self.Value_nsprefix_ = None - self.NetPounds = NetPounds - self.NetPounds_nsprefix_ = None - self.NetOunces = NetOunces - self.NetOunces_nsprefix_ = None - self.HSTariffNumber = HSTariffNumber - self.HSTariffNumber_nsprefix_ = None - self.CountryOfOrigin = CountryOfOrigin - self.CountryOfOrigin_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, ItemDetailType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if ItemDetailType.subclass: - return ItemDetailType.subclass(*args_, **kwargs_) - else: - return ItemDetailType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_Description(self): - return self.Description - def set_Description(self, Description): - self.Description = Description - def get_Quantity(self): - return self.Quantity - def set_Quantity(self, Quantity): - self.Quantity = Quantity - def get_Value(self): - return self.Value - def set_Value(self, Value): - self.Value = Value - def get_NetPounds(self): - return self.NetPounds - def set_NetPounds(self, NetPounds): - self.NetPounds = NetPounds - def get_NetOunces(self): - return self.NetOunces - def set_NetOunces(self, NetOunces): - self.NetOunces = NetOunces - def get_HSTariffNumber(self): - return self.HSTariffNumber - def set_HSTariffNumber(self, HSTariffNumber): - self.HSTariffNumber = HSTariffNumber - def get_CountryOfOrigin(self): - return self.CountryOfOrigin - def set_CountryOfOrigin(self, CountryOfOrigin): - self.CountryOfOrigin = CountryOfOrigin - def _hasContent(self): - if ( - self.Description is not None or - self.Quantity is not None or - self.Value is not None or - self.NetPounds is not None or - self.NetOunces is not None or - self.HSTariffNumber is not None or - self.CountryOfOrigin is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ItemDetailType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('ItemDetailType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'ItemDetailType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='ItemDetailType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='ItemDetailType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='ItemDetailType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ItemDetailType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.Description is not None: - namespaceprefix_ = self.Description_nsprefix_ + ':' if (UseCapturedNS_ and self.Description_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDescription>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Description), input_name='Description')), namespaceprefix_ , eol_)) - if self.Quantity is not None: - namespaceprefix_ = self.Quantity_nsprefix_ + ':' if (UseCapturedNS_ and self.Quantity_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sQuantity>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.Quantity, input_name='Quantity'), namespaceprefix_ , eol_)) - if self.Value is not None: - namespaceprefix_ = self.Value_nsprefix_ + ':' if (UseCapturedNS_ and self.Value_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sValue>%s%s' % (namespaceprefix_ , self.gds_format_float(self.Value, input_name='Value'), namespaceprefix_ , eol_)) - if self.NetPounds is not None: - namespaceprefix_ = self.NetPounds_nsprefix_ + ':' if (UseCapturedNS_ and self.NetPounds_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sNetPounds>%s%s' % (namespaceprefix_ , self.gds_format_float(self.NetPounds, input_name='NetPounds'), namespaceprefix_ , eol_)) - if self.NetOunces is not None: - namespaceprefix_ = self.NetOunces_nsprefix_ + ':' if (UseCapturedNS_ and self.NetOunces_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sNetOunces>%s%s' % (namespaceprefix_ , self.gds_format_float(self.NetOunces, input_name='NetOunces'), namespaceprefix_ , eol_)) - if self.HSTariffNumber is not None: - namespaceprefix_ = self.HSTariffNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.HSTariffNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sHSTariffNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.HSTariffNumber), input_name='HSTariffNumber')), namespaceprefix_ , eol_)) - if self.CountryOfOrigin is not None: - namespaceprefix_ = self.CountryOfOrigin_nsprefix_ + ':' if (UseCapturedNS_ and self.CountryOfOrigin_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCountryOfOrigin>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CountryOfOrigin), input_name='CountryOfOrigin')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'Description': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Description') - value_ = self.gds_validate_string(value_, node, 'Description') - self.Description = value_ - self.Description_nsprefix_ = child_.prefix - elif nodeName_ == 'Quantity' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'Quantity') - ival_ = self.gds_validate_integer(ival_, node, 'Quantity') - self.Quantity = ival_ - self.Quantity_nsprefix_ = child_.prefix - elif nodeName_ == 'Value' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'Value') - fval_ = self.gds_validate_float(fval_, node, 'Value') - self.Value = fval_ - self.Value_nsprefix_ = child_.prefix - elif nodeName_ == 'NetPounds' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'NetPounds') - fval_ = self.gds_validate_float(fval_, node, 'NetPounds') - self.NetPounds = fval_ - self.NetPounds_nsprefix_ = child_.prefix - elif nodeName_ == 'NetOunces' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'NetOunces') - fval_ = self.gds_validate_float(fval_, node, 'NetOunces') - self.NetOunces = fval_ - self.NetOunces_nsprefix_ = child_.prefix - elif nodeName_ == 'HSTariffNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'HSTariffNumber') - value_ = self.gds_validate_string(value_, node, 'HSTariffNumber') - self.HSTariffNumber = value_ - self.HSTariffNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'CountryOfOrigin': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CountryOfOrigin') - value_ = self.gds_validate_string(value_, node, 'CountryOfOrigin') - self.CountryOfOrigin = value_ - self.CountryOfOrigin_nsprefix_ = child_.prefix -# end class ItemDetailType - - -class ExtraServicesType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ExtraService=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - if ExtraService is None: - self.ExtraService = [] - else: - self.ExtraService = ExtraService - self.ExtraService_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, ExtraServicesType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if ExtraServicesType.subclass: - return ExtraServicesType.subclass(*args_, **kwargs_) - else: - return ExtraServicesType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_ExtraService(self): - return self.ExtraService - def set_ExtraService(self, ExtraService): - self.ExtraService = ExtraService - def add_ExtraService(self, value): - self.ExtraService.append(value) - def insert_ExtraService_at(self, index, value): - self.ExtraService.insert(index, value) - def replace_ExtraService_at(self, index, value): - self.ExtraService[index] = value - def _hasContent(self): - if ( - self.ExtraService - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ExtraServicesType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('ExtraServicesType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'ExtraServicesType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='ExtraServicesType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='ExtraServicesType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='ExtraServicesType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ExtraServicesType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - for ExtraService_ in self.ExtraService: - namespaceprefix_ = self.ExtraService_nsprefix_ + ':' if (UseCapturedNS_ and self.ExtraService_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sExtraService>%s%s' % (namespaceprefix_ , self.gds_format_integer(ExtraService_, input_name='ExtraService'), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'ExtraService' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'ExtraService') - ival_ = self.gds_validate_integer(ival_, node, 'ExtraService') - self.ExtraService.append(ival_) - self.ExtraService_nsprefix_ = child_.prefix -# end class ExtraServicesType - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSPriorityMailIntlRequest' - rootClass = eVSPriorityMailIntlRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSPriorityMailIntlRequest' - rootClass = eVSPriorityMailIntlRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSPriorityMailIntlRequest' - rootClass = eVSPriorityMailIntlRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSPriorityMailIntlRequest' - rootClass = eVSPriorityMailIntlRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from evs_priority_mail_intl_request import *\n\n') - sys.stdout.write('import evs_priority_mail_intl_request as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "ExtraServicesType", - "ImageParametersType", - "ItemDetailType", - "ShippingContentsType", - "eVSPriorityMailIntlRequest" -] diff --git a/schemas/usps/karrio/schemas/usps/evs_priority_mail_intl_response.py b/schemas/usps/karrio/schemas/usps/evs_priority_mail_intl_response.py deleted file mode 100644 index 0dedade718..0000000000 --- a/schemas/usps/karrio/schemas/usps/evs_priority_mail_intl_response.py +++ /dev/null @@ -1,1820 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:16 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/evs_priority_mail_intl_response.py') -# -# Command line arguments: -# ./schemas/eVSPriorityMailIntlResponse.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/evs_priority_mail_intl_response.py" ./schemas/eVSPriorityMailIntlResponse.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class eVSPriorityMailIntlResponse(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, Postage=None, TotalValue=None, SDRValue=None, BarcodeNumber=None, LabelImage=None, Page2Image=None, Page3Image=None, Page4Image=None, Page5Image=None, Page6Image=None, Prohibitions=None, Restrictions=None, Observations=None, Regulations=None, AdditionalRestrictions=None, ParcelIndemnityCoverage=None, ExtraServices=None, RemainingBarcodes=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.Postage = Postage - self.Postage_nsprefix_ = None - self.TotalValue = TotalValue - self.TotalValue_nsprefix_ = None - self.SDRValue = SDRValue - self.SDRValue_nsprefix_ = None - self.BarcodeNumber = BarcodeNumber - self.BarcodeNumber_nsprefix_ = None - self.LabelImage = LabelImage - self.LabelImage_nsprefix_ = None - self.Page2Image = Page2Image - self.Page2Image_nsprefix_ = None - self.Page3Image = Page3Image - self.Page3Image_nsprefix_ = None - self.Page4Image = Page4Image - self.Page4Image_nsprefix_ = None - self.Page5Image = Page5Image - self.Page5Image_nsprefix_ = None - self.Page6Image = Page6Image - self.Page6Image_nsprefix_ = None - self.Prohibitions = Prohibitions - self.Prohibitions_nsprefix_ = None - self.Restrictions = Restrictions - self.Restrictions_nsprefix_ = None - self.Observations = Observations - self.Observations_nsprefix_ = None - self.Regulations = Regulations - self.Regulations_nsprefix_ = None - self.AdditionalRestrictions = AdditionalRestrictions - self.AdditionalRestrictions_nsprefix_ = None - self.ParcelIndemnityCoverage = ParcelIndemnityCoverage - self.ParcelIndemnityCoverage_nsprefix_ = None - self.ExtraServices = ExtraServices - self.ExtraServices_nsprefix_ = None - self.RemainingBarcodes = RemainingBarcodes - self.RemainingBarcodes_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, eVSPriorityMailIntlResponse) - if subclass is not None: - return subclass(*args_, **kwargs_) - if eVSPriorityMailIntlResponse.subclass: - return eVSPriorityMailIntlResponse.subclass(*args_, **kwargs_) - else: - return eVSPriorityMailIntlResponse(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_Postage(self): - return self.Postage - def set_Postage(self, Postage): - self.Postage = Postage - def get_TotalValue(self): - return self.TotalValue - def set_TotalValue(self, TotalValue): - self.TotalValue = TotalValue - def get_SDRValue(self): - return self.SDRValue - def set_SDRValue(self, SDRValue): - self.SDRValue = SDRValue - def get_BarcodeNumber(self): - return self.BarcodeNumber - def set_BarcodeNumber(self, BarcodeNumber): - self.BarcodeNumber = BarcodeNumber - def get_LabelImage(self): - return self.LabelImage - def set_LabelImage(self, LabelImage): - self.LabelImage = LabelImage - def get_Page2Image(self): - return self.Page2Image - def set_Page2Image(self, Page2Image): - self.Page2Image = Page2Image - def get_Page3Image(self): - return self.Page3Image - def set_Page3Image(self, Page3Image): - self.Page3Image = Page3Image - def get_Page4Image(self): - return self.Page4Image - def set_Page4Image(self, Page4Image): - self.Page4Image = Page4Image - def get_Page5Image(self): - return self.Page5Image - def set_Page5Image(self, Page5Image): - self.Page5Image = Page5Image - def get_Page6Image(self): - return self.Page6Image - def set_Page6Image(self, Page6Image): - self.Page6Image = Page6Image - def get_Prohibitions(self): - return self.Prohibitions - def set_Prohibitions(self, Prohibitions): - self.Prohibitions = Prohibitions - def get_Restrictions(self): - return self.Restrictions - def set_Restrictions(self, Restrictions): - self.Restrictions = Restrictions - def get_Observations(self): - return self.Observations - def set_Observations(self, Observations): - self.Observations = Observations - def get_Regulations(self): - return self.Regulations - def set_Regulations(self, Regulations): - self.Regulations = Regulations - def get_AdditionalRestrictions(self): - return self.AdditionalRestrictions - def set_AdditionalRestrictions(self, AdditionalRestrictions): - self.AdditionalRestrictions = AdditionalRestrictions - def get_ParcelIndemnityCoverage(self): - return self.ParcelIndemnityCoverage - def set_ParcelIndemnityCoverage(self, ParcelIndemnityCoverage): - self.ParcelIndemnityCoverage = ParcelIndemnityCoverage - def get_ExtraServices(self): - return self.ExtraServices - def set_ExtraServices(self, ExtraServices): - self.ExtraServices = ExtraServices - def get_RemainingBarcodes(self): - return self.RemainingBarcodes - def set_RemainingBarcodes(self, RemainingBarcodes): - self.RemainingBarcodes = RemainingBarcodes - def _hasContent(self): - if ( - self.Postage is not None or - self.TotalValue is not None or - self.SDRValue is not None or - self.BarcodeNumber is not None or - self.LabelImage is not None or - self.Page2Image is not None or - self.Page3Image is not None or - self.Page4Image is not None or - self.Page5Image is not None or - self.Page6Image is not None or - self.Prohibitions is not None or - self.Restrictions is not None or - self.Observations is not None or - self.Regulations is not None or - self.AdditionalRestrictions is not None or - self.ParcelIndemnityCoverage is not None or - self.ExtraServices is not None or - self.RemainingBarcodes is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='eVSPriorityMailIntlResponse', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('eVSPriorityMailIntlResponse') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'eVSPriorityMailIntlResponse': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='eVSPriorityMailIntlResponse') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='eVSPriorityMailIntlResponse', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='eVSPriorityMailIntlResponse'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='eVSPriorityMailIntlResponse', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.Postage is not None: - namespaceprefix_ = self.Postage_nsprefix_ + ':' if (UseCapturedNS_ and self.Postage_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPostage>%s%s' % (namespaceprefix_ , self.gds_format_float(self.Postage, input_name='Postage'), namespaceprefix_ , eol_)) - if self.TotalValue is not None: - namespaceprefix_ = self.TotalValue_nsprefix_ + ':' if (UseCapturedNS_ and self.TotalValue_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sTotalValue>%s%s' % (namespaceprefix_ , self.gds_format_float(self.TotalValue, input_name='TotalValue'), namespaceprefix_ , eol_)) - if self.SDRValue is not None: - namespaceprefix_ = self.SDRValue_nsprefix_ + ':' if (UseCapturedNS_ and self.SDRValue_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSDRValue>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SDRValue), input_name='SDRValue')), namespaceprefix_ , eol_)) - if self.BarcodeNumber is not None: - namespaceprefix_ = self.BarcodeNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.BarcodeNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sBarcodeNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.BarcodeNumber), input_name='BarcodeNumber')), namespaceprefix_ , eol_)) - if self.LabelImage is not None: - namespaceprefix_ = self.LabelImage_nsprefix_ + ':' if (UseCapturedNS_ and self.LabelImage_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sLabelImage>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.LabelImage), input_name='LabelImage')), namespaceprefix_ , eol_)) - if self.Page2Image is not None: - namespaceprefix_ = self.Page2Image_nsprefix_ + ':' if (UseCapturedNS_ and self.Page2Image_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPage2Image>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Page2Image), input_name='Page2Image')), namespaceprefix_ , eol_)) - if self.Page3Image is not None: - namespaceprefix_ = self.Page3Image_nsprefix_ + ':' if (UseCapturedNS_ and self.Page3Image_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPage3Image>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Page3Image), input_name='Page3Image')), namespaceprefix_ , eol_)) - if self.Page4Image is not None: - namespaceprefix_ = self.Page4Image_nsprefix_ + ':' if (UseCapturedNS_ and self.Page4Image_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPage4Image>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Page4Image), input_name='Page4Image')), namespaceprefix_ , eol_)) - if self.Page5Image is not None: - namespaceprefix_ = self.Page5Image_nsprefix_ + ':' if (UseCapturedNS_ and self.Page5Image_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPage5Image>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Page5Image), input_name='Page5Image')), namespaceprefix_ , eol_)) - if self.Page6Image is not None: - namespaceprefix_ = self.Page6Image_nsprefix_ + ':' if (UseCapturedNS_ and self.Page6Image_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPage6Image>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Page6Image), input_name='Page6Image')), namespaceprefix_ , eol_)) - if self.Prohibitions is not None: - namespaceprefix_ = self.Prohibitions_nsprefix_ + ':' if (UseCapturedNS_ and self.Prohibitions_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sProhibitions>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Prohibitions), input_name='Prohibitions')), namespaceprefix_ , eol_)) - if self.Restrictions is not None: - namespaceprefix_ = self.Restrictions_nsprefix_ + ':' if (UseCapturedNS_ and self.Restrictions_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRestrictions>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Restrictions), input_name='Restrictions')), namespaceprefix_ , eol_)) - if self.Observations is not None: - namespaceprefix_ = self.Observations_nsprefix_ + ':' if (UseCapturedNS_ and self.Observations_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sObservations>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Observations), input_name='Observations')), namespaceprefix_ , eol_)) - if self.Regulations is not None: - namespaceprefix_ = self.Regulations_nsprefix_ + ':' if (UseCapturedNS_ and self.Regulations_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRegulations>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Regulations), input_name='Regulations')), namespaceprefix_ , eol_)) - if self.AdditionalRestrictions is not None: - namespaceprefix_ = self.AdditionalRestrictions_nsprefix_ + ':' if (UseCapturedNS_ and self.AdditionalRestrictions_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAdditionalRestrictions>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.AdditionalRestrictions), input_name='AdditionalRestrictions')), namespaceprefix_ , eol_)) - if self.ParcelIndemnityCoverage is not None: - namespaceprefix_ = self.ParcelIndemnityCoverage_nsprefix_ + ':' if (UseCapturedNS_ and self.ParcelIndemnityCoverage_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sParcelIndemnityCoverage>%s%s' % (namespaceprefix_ , self.gds_format_float(self.ParcelIndemnityCoverage, input_name='ParcelIndemnityCoverage'), namespaceprefix_ , eol_)) - if self.ExtraServices is not None: - namespaceprefix_ = self.ExtraServices_nsprefix_ + ':' if (UseCapturedNS_ and self.ExtraServices_nsprefix_) else '' - self.ExtraServices.export(outfile, level, namespaceprefix_, namespacedef_='', name_='ExtraServices', pretty_print=pretty_print) - if self.RemainingBarcodes is not None: - namespaceprefix_ = self.RemainingBarcodes_nsprefix_ + ':' if (UseCapturedNS_ and self.RemainingBarcodes_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRemainingBarcodes>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.RemainingBarcodes, input_name='RemainingBarcodes'), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'Postage' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'Postage') - fval_ = self.gds_validate_float(fval_, node, 'Postage') - self.Postage = fval_ - self.Postage_nsprefix_ = child_.prefix - elif nodeName_ == 'TotalValue' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'TotalValue') - fval_ = self.gds_validate_float(fval_, node, 'TotalValue') - self.TotalValue = fval_ - self.TotalValue_nsprefix_ = child_.prefix - elif nodeName_ == 'SDRValue': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SDRValue') - value_ = self.gds_validate_string(value_, node, 'SDRValue') - self.SDRValue = value_ - self.SDRValue_nsprefix_ = child_.prefix - elif nodeName_ == 'BarcodeNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'BarcodeNumber') - value_ = self.gds_validate_string(value_, node, 'BarcodeNumber') - self.BarcodeNumber = value_ - self.BarcodeNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'LabelImage': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'LabelImage') - value_ = self.gds_validate_string(value_, node, 'LabelImage') - self.LabelImage = value_ - self.LabelImage_nsprefix_ = child_.prefix - elif nodeName_ == 'Page2Image': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Page2Image') - value_ = self.gds_validate_string(value_, node, 'Page2Image') - self.Page2Image = value_ - self.Page2Image_nsprefix_ = child_.prefix - elif nodeName_ == 'Page3Image': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Page3Image') - value_ = self.gds_validate_string(value_, node, 'Page3Image') - self.Page3Image = value_ - self.Page3Image_nsprefix_ = child_.prefix - elif nodeName_ == 'Page4Image': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Page4Image') - value_ = self.gds_validate_string(value_, node, 'Page4Image') - self.Page4Image = value_ - self.Page4Image_nsprefix_ = child_.prefix - elif nodeName_ == 'Page5Image': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Page5Image') - value_ = self.gds_validate_string(value_, node, 'Page5Image') - self.Page5Image = value_ - self.Page5Image_nsprefix_ = child_.prefix - elif nodeName_ == 'Page6Image': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Page6Image') - value_ = self.gds_validate_string(value_, node, 'Page6Image') - self.Page6Image = value_ - self.Page6Image_nsprefix_ = child_.prefix - elif nodeName_ == 'Prohibitions': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Prohibitions') - value_ = self.gds_validate_string(value_, node, 'Prohibitions') - self.Prohibitions = value_ - self.Prohibitions_nsprefix_ = child_.prefix - elif nodeName_ == 'Restrictions': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Restrictions') - value_ = self.gds_validate_string(value_, node, 'Restrictions') - self.Restrictions = value_ - self.Restrictions_nsprefix_ = child_.prefix - elif nodeName_ == 'Observations': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Observations') - value_ = self.gds_validate_string(value_, node, 'Observations') - self.Observations = value_ - self.Observations_nsprefix_ = child_.prefix - elif nodeName_ == 'Regulations': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Regulations') - value_ = self.gds_validate_string(value_, node, 'Regulations') - self.Regulations = value_ - self.Regulations_nsprefix_ = child_.prefix - elif nodeName_ == 'AdditionalRestrictions': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'AdditionalRestrictions') - value_ = self.gds_validate_string(value_, node, 'AdditionalRestrictions') - self.AdditionalRestrictions = value_ - self.AdditionalRestrictions_nsprefix_ = child_.prefix - elif nodeName_ == 'ParcelIndemnityCoverage' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'ParcelIndemnityCoverage') - fval_ = self.gds_validate_float(fval_, node, 'ParcelIndemnityCoverage') - self.ParcelIndemnityCoverage = fval_ - self.ParcelIndemnityCoverage_nsprefix_ = child_.prefix - elif nodeName_ == 'ExtraServices': - obj_ = ExtraServicesType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.ExtraServices = obj_ - obj_.original_tagname_ = 'ExtraServices' - elif nodeName_ == 'RemainingBarcodes' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'RemainingBarcodes') - ival_ = self.gds_validate_integer(ival_, node, 'RemainingBarcodes') - self.RemainingBarcodes = ival_ - self.RemainingBarcodes_nsprefix_ = child_.prefix -# end class eVSPriorityMailIntlResponse - - -class ExtraServicesType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ExtraService=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - if ExtraService is None: - self.ExtraService = [] - else: - self.ExtraService = ExtraService - self.ExtraService_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, ExtraServicesType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if ExtraServicesType.subclass: - return ExtraServicesType.subclass(*args_, **kwargs_) - else: - return ExtraServicesType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_ExtraService(self): - return self.ExtraService - def set_ExtraService(self, ExtraService): - self.ExtraService = ExtraService - def add_ExtraService(self, value): - self.ExtraService.append(value) - def insert_ExtraService_at(self, index, value): - self.ExtraService.insert(index, value) - def replace_ExtraService_at(self, index, value): - self.ExtraService[index] = value - def _hasContent(self): - if ( - self.ExtraService - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ExtraServicesType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('ExtraServicesType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'ExtraServicesType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='ExtraServicesType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='ExtraServicesType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='ExtraServicesType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ExtraServicesType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - for ExtraService_ in self.ExtraService: - namespaceprefix_ = self.ExtraService_nsprefix_ + ':' if (UseCapturedNS_ and self.ExtraService_nsprefix_) else '' - ExtraService_.export(outfile, level, namespaceprefix_, namespacedef_='', name_='ExtraService', pretty_print=pretty_print) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'ExtraService': - obj_ = ExtraServiceType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.ExtraService.append(obj_) - obj_.original_tagname_ = 'ExtraService' -# end class ExtraServicesType - - -class ExtraServiceType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ServiceID=None, ServiceName=None, Price=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.ServiceID = ServiceID - self.ServiceID_nsprefix_ = None - self.ServiceName = ServiceName - self.ServiceName_nsprefix_ = None - self.Price = Price - self.Price_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, ExtraServiceType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if ExtraServiceType.subclass: - return ExtraServiceType.subclass(*args_, **kwargs_) - else: - return ExtraServiceType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_ServiceID(self): - return self.ServiceID - def set_ServiceID(self, ServiceID): - self.ServiceID = ServiceID - def get_ServiceName(self): - return self.ServiceName - def set_ServiceName(self, ServiceName): - self.ServiceName = ServiceName - def get_Price(self): - return self.Price - def set_Price(self, Price): - self.Price = Price - def _hasContent(self): - if ( - self.ServiceID is not None or - self.ServiceName is not None or - self.Price is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ExtraServiceType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('ExtraServiceType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'ExtraServiceType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='ExtraServiceType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='ExtraServiceType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='ExtraServiceType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ExtraServiceType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.ServiceID is not None: - namespaceprefix_ = self.ServiceID_nsprefix_ + ':' if (UseCapturedNS_ and self.ServiceID_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sServiceID>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.ServiceID, input_name='ServiceID'), namespaceprefix_ , eol_)) - if self.ServiceName is not None: - namespaceprefix_ = self.ServiceName_nsprefix_ + ':' if (UseCapturedNS_ and self.ServiceName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sServiceName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ServiceName), input_name='ServiceName')), namespaceprefix_ , eol_)) - if self.Price is not None: - namespaceprefix_ = self.Price_nsprefix_ + ':' if (UseCapturedNS_ and self.Price_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPrice>%s%s' % (namespaceprefix_ , self.gds_format_float(self.Price, input_name='Price'), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'ServiceID' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'ServiceID') - ival_ = self.gds_validate_integer(ival_, node, 'ServiceID') - self.ServiceID = ival_ - self.ServiceID_nsprefix_ = child_.prefix - elif nodeName_ == 'ServiceName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ServiceName') - value_ = self.gds_validate_string(value_, node, 'ServiceName') - self.ServiceName = value_ - self.ServiceName_nsprefix_ = child_.prefix - elif nodeName_ == 'Price' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'Price') - fval_ = self.gds_validate_float(fval_, node, 'Price') - self.Price = fval_ - self.Price_nsprefix_ = child_.prefix -# end class ExtraServiceType - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSPriorityMailIntlResponse' - rootClass = eVSPriorityMailIntlResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSPriorityMailIntlResponse' - rootClass = eVSPriorityMailIntlResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSPriorityMailIntlResponse' - rootClass = eVSPriorityMailIntlResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSPriorityMailIntlResponse' - rootClass = eVSPriorityMailIntlResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from evs_priority_mail_intl_response import *\n\n') - sys.stdout.write('import evs_priority_mail_intl_response as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "ExtraServiceType", - "ExtraServicesType", - "eVSPriorityMailIntlResponse" -] diff --git a/schemas/usps/karrio/schemas/usps/evs_request.py b/schemas/usps/karrio/schemas/usps/evs_request.py deleted file mode 100644 index abba89ba9f..0000000000 --- a/schemas/usps/karrio/schemas/usps/evs_request.py +++ /dev/null @@ -1,4010 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:14 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/evs_request.py') -# -# Command line arguments: -# ./schemas/eVSRequest.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/evs_request.py" ./schemas/eVSRequest.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class eVSRequest(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, USERID=None, Option=None, Revision=None, ImageParameters=None, FromName=None, FromFirm=None, FromAddress1=None, FromAddress2=None, FromCity=None, FromState=None, FromZip5=None, FromZip4=None, FromPhone=None, POZipCode=None, AllowNonCleansedOriginAddr=None, ToName=None, ToFirm=None, ToAddress1=None, ToAddress2=None, ToCity=None, ToState=None, ToZip5=None, ToZip4=None, ToPhone=None, POBox=None, ToContactPreference=None, ToContactMessaging=None, ToContactEmail=None, AllowNonCleansedDestAddr=None, WeightInOunces=None, ServiceType=None, Container=None, Width=None, Length=None, Height=None, Girth=None, Machinable=None, ProcessingCategory=None, PriceOptions=None, InsuredAmount=None, AddressServiceRequested=None, ExpressMailOptions=None, ShipDate=None, CustomerRefNo=None, CustomerRefNo2=None, ExtraServices=None, HoldForPickup=None, OpenDistribute=None, PermitNumber=None, PermitZIPCode=None, PermitHolderName=None, CRID=None, MID=None, LogisticsManagerMID=None, VendorCode=None, VendorProductVersionNumber=None, SenderName=None, SenderEMail=None, RecipientName=None, RecipientEMail=None, ReceiptOption=None, ImageType=None, HoldForManifest=None, NineDigitRoutingZip=None, ShipInfo=None, CarrierRelease=None, DropOffTime=None, ReturnCommitments=None, PrintCustomerRefNo=None, Content=None, ActionCode=None, OptOutOfSPE=None, SortationLevel=None, DestinationEntryFacilityType=None, ShippingContents=None, CustomsContentType=None, ContentComments=None, RestrictionType=None, RestrictionComments=None, AESITN=None, ImportersReference=None, ImportersContact=None, ExportersReference=None, ExportersContact=None, InvoiceNumber=None, LicenseNumber=None, CertificateNumber=None, NonDeliveryOption=None, AltReturnAddress1=None, AltReturnAddress2=None, AltReturnAddress3=None, AltReturnAddress4=None, AltReturnAddress5=None, AltReturnAddress6=None, AltReturnCountry=None, LabelImportType=None, ePostageMailerReporting=None, SenderFirstName=None, SenderLastName=None, SenderBusinessName=None, SenderAddress1=None, SenderCity=None, SenderState=None, SenderZip5=None, SenderPhone=None, ChargebackCode=None, TrackingRetentionPeriod=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.USERID = _cast(None, USERID) - self.USERID_nsprefix_ = None - self.Option = Option - self.Option_nsprefix_ = None - self.Revision = Revision - self.Revision_nsprefix_ = None - self.ImageParameters = ImageParameters - self.ImageParameters_nsprefix_ = None - self.FromName = FromName - self.FromName_nsprefix_ = None - self.FromFirm = FromFirm - self.FromFirm_nsprefix_ = None - self.FromAddress1 = FromAddress1 - self.FromAddress1_nsprefix_ = None - self.FromAddress2 = FromAddress2 - self.FromAddress2_nsprefix_ = None - self.FromCity = FromCity - self.FromCity_nsprefix_ = None - self.FromState = FromState - self.FromState_nsprefix_ = None - self.FromZip5 = FromZip5 - self.FromZip5_nsprefix_ = None - self.FromZip4 = FromZip4 - self.FromZip4_nsprefix_ = None - self.FromPhone = FromPhone - self.FromPhone_nsprefix_ = None - self.POZipCode = POZipCode - self.POZipCode_nsprefix_ = None - self.AllowNonCleansedOriginAddr = AllowNonCleansedOriginAddr - self.AllowNonCleansedOriginAddr_nsprefix_ = None - self.ToName = ToName - self.ToName_nsprefix_ = None - self.ToFirm = ToFirm - self.ToFirm_nsprefix_ = None - self.ToAddress1 = ToAddress1 - self.ToAddress1_nsprefix_ = None - self.ToAddress2 = ToAddress2 - self.ToAddress2_nsprefix_ = None - self.ToCity = ToCity - self.ToCity_nsprefix_ = None - self.ToState = ToState - self.ToState_nsprefix_ = None - self.ToZip5 = ToZip5 - self.ToZip5_nsprefix_ = None - self.ToZip4 = ToZip4 - self.ToZip4_nsprefix_ = None - self.ToPhone = ToPhone - self.ToPhone_nsprefix_ = None - self.POBox = POBox - self.POBox_nsprefix_ = None - self.ToContactPreference = ToContactPreference - self.ToContactPreference_nsprefix_ = None - self.ToContactMessaging = ToContactMessaging - self.ToContactMessaging_nsprefix_ = None - self.ToContactEmail = ToContactEmail - self.ToContactEmail_nsprefix_ = None - self.AllowNonCleansedDestAddr = AllowNonCleansedDestAddr - self.AllowNonCleansedDestAddr_nsprefix_ = None - self.WeightInOunces = WeightInOunces - self.WeightInOunces_nsprefix_ = None - self.ServiceType = ServiceType - self.ServiceType_nsprefix_ = None - self.Container = Container - self.Container_nsprefix_ = None - self.Width = Width - self.Width_nsprefix_ = None - self.Length = Length - self.Length_nsprefix_ = None - self.Height = Height - self.Height_nsprefix_ = None - self.Girth = Girth - self.Girth_nsprefix_ = None - self.Machinable = Machinable - self.Machinable_nsprefix_ = None - self.ProcessingCategory = ProcessingCategory - self.ProcessingCategory_nsprefix_ = None - self.PriceOptions = PriceOptions - self.PriceOptions_nsprefix_ = None - self.InsuredAmount = InsuredAmount - self.InsuredAmount_nsprefix_ = None - self.AddressServiceRequested = AddressServiceRequested - self.AddressServiceRequested_nsprefix_ = None - self.ExpressMailOptions = ExpressMailOptions - self.ExpressMailOptions_nsprefix_ = None - self.ShipDate = ShipDate - self.validate_ShipDateType(self.ShipDate) - self.ShipDate_nsprefix_ = None - self.CustomerRefNo = CustomerRefNo - self.CustomerRefNo_nsprefix_ = None - self.CustomerRefNo2 = CustomerRefNo2 - self.CustomerRefNo2_nsprefix_ = None - self.ExtraServices = ExtraServices - self.ExtraServices_nsprefix_ = None - self.HoldForPickup = HoldForPickup - self.HoldForPickup_nsprefix_ = None - self.OpenDistribute = OpenDistribute - self.OpenDistribute_nsprefix_ = None - self.PermitNumber = PermitNumber - self.PermitNumber_nsprefix_ = None - self.PermitZIPCode = PermitZIPCode - self.PermitZIPCode_nsprefix_ = None - self.PermitHolderName = PermitHolderName - self.PermitHolderName_nsprefix_ = None - self.CRID = CRID - self.CRID_nsprefix_ = None - self.MID = MID - self.MID_nsprefix_ = None - self.LogisticsManagerMID = LogisticsManagerMID - self.LogisticsManagerMID_nsprefix_ = None - self.VendorCode = VendorCode - self.VendorCode_nsprefix_ = None - self.VendorProductVersionNumber = VendorProductVersionNumber - self.VendorProductVersionNumber_nsprefix_ = None - self.SenderName = SenderName - self.SenderName_nsprefix_ = None - self.SenderEMail = SenderEMail - self.SenderEMail_nsprefix_ = None - self.RecipientName = RecipientName - self.RecipientName_nsprefix_ = None - self.RecipientEMail = RecipientEMail - self.RecipientEMail_nsprefix_ = None - self.ReceiptOption = ReceiptOption - self.ReceiptOption_nsprefix_ = None - self.ImageType = ImageType - self.ImageType_nsprefix_ = None - self.HoldForManifest = HoldForManifest - self.HoldForManifest_nsprefix_ = None - self.NineDigitRoutingZip = NineDigitRoutingZip - self.NineDigitRoutingZip_nsprefix_ = None - self.ShipInfo = ShipInfo - self.ShipInfo_nsprefix_ = None - self.CarrierRelease = CarrierRelease - self.CarrierRelease_nsprefix_ = None - self.DropOffTime = DropOffTime - self.DropOffTime_nsprefix_ = None - self.ReturnCommitments = ReturnCommitments - self.ReturnCommitments_nsprefix_ = None - self.PrintCustomerRefNo = PrintCustomerRefNo - self.PrintCustomerRefNo_nsprefix_ = None - self.Content = Content - self.Content_nsprefix_ = None - self.ActionCode = ActionCode - self.ActionCode_nsprefix_ = None - self.OptOutOfSPE = OptOutOfSPE - self.OptOutOfSPE_nsprefix_ = None - self.SortationLevel = SortationLevel - self.SortationLevel_nsprefix_ = None - self.DestinationEntryFacilityType = DestinationEntryFacilityType - self.DestinationEntryFacilityType_nsprefix_ = None - self.ShippingContents = ShippingContents - self.ShippingContents_nsprefix_ = None - self.CustomsContentType = CustomsContentType - self.CustomsContentType_nsprefix_ = None - self.ContentComments = ContentComments - self.ContentComments_nsprefix_ = None - self.RestrictionType = RestrictionType - self.RestrictionType_nsprefix_ = None - self.RestrictionComments = RestrictionComments - self.RestrictionComments_nsprefix_ = None - self.AESITN = AESITN - self.AESITN_nsprefix_ = None - self.ImportersReference = ImportersReference - self.ImportersReference_nsprefix_ = None - self.ImportersContact = ImportersContact - self.ImportersContact_nsprefix_ = None - self.ExportersReference = ExportersReference - self.ExportersReference_nsprefix_ = None - self.ExportersContact = ExportersContact - self.ExportersContact_nsprefix_ = None - self.InvoiceNumber = InvoiceNumber - self.InvoiceNumber_nsprefix_ = None - self.LicenseNumber = LicenseNumber - self.LicenseNumber_nsprefix_ = None - self.CertificateNumber = CertificateNumber - self.CertificateNumber_nsprefix_ = None - self.NonDeliveryOption = NonDeliveryOption - self.NonDeliveryOption_nsprefix_ = None - self.AltReturnAddress1 = AltReturnAddress1 - self.AltReturnAddress1_nsprefix_ = None - self.AltReturnAddress2 = AltReturnAddress2 - self.AltReturnAddress2_nsprefix_ = None - self.AltReturnAddress3 = AltReturnAddress3 - self.AltReturnAddress3_nsprefix_ = None - self.AltReturnAddress4 = AltReturnAddress4 - self.AltReturnAddress4_nsprefix_ = None - self.AltReturnAddress5 = AltReturnAddress5 - self.AltReturnAddress5_nsprefix_ = None - self.AltReturnAddress6 = AltReturnAddress6 - self.AltReturnAddress6_nsprefix_ = None - self.AltReturnCountry = AltReturnCountry - self.AltReturnCountry_nsprefix_ = None - self.LabelImportType = LabelImportType - self.LabelImportType_nsprefix_ = None - self.ePostageMailerReporting = ePostageMailerReporting - self.ePostageMailerReporting_nsprefix_ = None - self.SenderFirstName = SenderFirstName - self.SenderFirstName_nsprefix_ = None - self.SenderLastName = SenderLastName - self.SenderLastName_nsprefix_ = None - self.SenderBusinessName = SenderBusinessName - self.SenderBusinessName_nsprefix_ = None - self.SenderAddress1 = SenderAddress1 - self.SenderAddress1_nsprefix_ = None - self.SenderCity = SenderCity - self.SenderCity_nsprefix_ = None - self.SenderState = SenderState - self.SenderState_nsprefix_ = None - self.SenderZip5 = SenderZip5 - self.SenderZip5_nsprefix_ = None - self.SenderPhone = SenderPhone - self.SenderPhone_nsprefix_ = None - self.ChargebackCode = ChargebackCode - self.ChargebackCode_nsprefix_ = None - self.TrackingRetentionPeriod = TrackingRetentionPeriod - self.TrackingRetentionPeriod_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, eVSRequest) - if subclass is not None: - return subclass(*args_, **kwargs_) - if eVSRequest.subclass: - return eVSRequest.subclass(*args_, **kwargs_) - else: - return eVSRequest(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_Option(self): - return self.Option - def set_Option(self, Option): - self.Option = Option - def get_Revision(self): - return self.Revision - def set_Revision(self, Revision): - self.Revision = Revision - def get_ImageParameters(self): - return self.ImageParameters - def set_ImageParameters(self, ImageParameters): - self.ImageParameters = ImageParameters - def get_FromName(self): - return self.FromName - def set_FromName(self, FromName): - self.FromName = FromName - def get_FromFirm(self): - return self.FromFirm - def set_FromFirm(self, FromFirm): - self.FromFirm = FromFirm - def get_FromAddress1(self): - return self.FromAddress1 - def set_FromAddress1(self, FromAddress1): - self.FromAddress1 = FromAddress1 - def get_FromAddress2(self): - return self.FromAddress2 - def set_FromAddress2(self, FromAddress2): - self.FromAddress2 = FromAddress2 - def get_FromCity(self): - return self.FromCity - def set_FromCity(self, FromCity): - self.FromCity = FromCity - def get_FromState(self): - return self.FromState - def set_FromState(self, FromState): - self.FromState = FromState - def get_FromZip5(self): - return self.FromZip5 - def set_FromZip5(self, FromZip5): - self.FromZip5 = FromZip5 - def get_FromZip4(self): - return self.FromZip4 - def set_FromZip4(self, FromZip4): - self.FromZip4 = FromZip4 - def get_FromPhone(self): - return self.FromPhone - def set_FromPhone(self, FromPhone): - self.FromPhone = FromPhone - def get_POZipCode(self): - return self.POZipCode - def set_POZipCode(self, POZipCode): - self.POZipCode = POZipCode - def get_AllowNonCleansedOriginAddr(self): - return self.AllowNonCleansedOriginAddr - def set_AllowNonCleansedOriginAddr(self, AllowNonCleansedOriginAddr): - self.AllowNonCleansedOriginAddr = AllowNonCleansedOriginAddr - def get_ToName(self): - return self.ToName - def set_ToName(self, ToName): - self.ToName = ToName - def get_ToFirm(self): - return self.ToFirm - def set_ToFirm(self, ToFirm): - self.ToFirm = ToFirm - def get_ToAddress1(self): - return self.ToAddress1 - def set_ToAddress1(self, ToAddress1): - self.ToAddress1 = ToAddress1 - def get_ToAddress2(self): - return self.ToAddress2 - def set_ToAddress2(self, ToAddress2): - self.ToAddress2 = ToAddress2 - def get_ToCity(self): - return self.ToCity - def set_ToCity(self, ToCity): - self.ToCity = ToCity - def get_ToState(self): - return self.ToState - def set_ToState(self, ToState): - self.ToState = ToState - def get_ToZip5(self): - return self.ToZip5 - def set_ToZip5(self, ToZip5): - self.ToZip5 = ToZip5 - def get_ToZip4(self): - return self.ToZip4 - def set_ToZip4(self, ToZip4): - self.ToZip4 = ToZip4 - def get_ToPhone(self): - return self.ToPhone - def set_ToPhone(self, ToPhone): - self.ToPhone = ToPhone - def get_POBox(self): - return self.POBox - def set_POBox(self, POBox): - self.POBox = POBox - def get_ToContactPreference(self): - return self.ToContactPreference - def set_ToContactPreference(self, ToContactPreference): - self.ToContactPreference = ToContactPreference - def get_ToContactMessaging(self): - return self.ToContactMessaging - def set_ToContactMessaging(self, ToContactMessaging): - self.ToContactMessaging = ToContactMessaging - def get_ToContactEmail(self): - return self.ToContactEmail - def set_ToContactEmail(self, ToContactEmail): - self.ToContactEmail = ToContactEmail - def get_AllowNonCleansedDestAddr(self): - return self.AllowNonCleansedDestAddr - def set_AllowNonCleansedDestAddr(self, AllowNonCleansedDestAddr): - self.AllowNonCleansedDestAddr = AllowNonCleansedDestAddr - def get_WeightInOunces(self): - return self.WeightInOunces - def set_WeightInOunces(self, WeightInOunces): - self.WeightInOunces = WeightInOunces - def get_ServiceType(self): - return self.ServiceType - def set_ServiceType(self, ServiceType): - self.ServiceType = ServiceType - def get_Container(self): - return self.Container - def set_Container(self, Container): - self.Container = Container - def get_Width(self): - return self.Width - def set_Width(self, Width): - self.Width = Width - def get_Length(self): - return self.Length - def set_Length(self, Length): - self.Length = Length - def get_Height(self): - return self.Height - def set_Height(self, Height): - self.Height = Height - def get_Girth(self): - return self.Girth - def set_Girth(self, Girth): - self.Girth = Girth - def get_Machinable(self): - return self.Machinable - def set_Machinable(self, Machinable): - self.Machinable = Machinable - def get_ProcessingCategory(self): - return self.ProcessingCategory - def set_ProcessingCategory(self, ProcessingCategory): - self.ProcessingCategory = ProcessingCategory - def get_PriceOptions(self): - return self.PriceOptions - def set_PriceOptions(self, PriceOptions): - self.PriceOptions = PriceOptions - def get_InsuredAmount(self): - return self.InsuredAmount - def set_InsuredAmount(self, InsuredAmount): - self.InsuredAmount = InsuredAmount - def get_AddressServiceRequested(self): - return self.AddressServiceRequested - def set_AddressServiceRequested(self, AddressServiceRequested): - self.AddressServiceRequested = AddressServiceRequested - def get_ExpressMailOptions(self): - return self.ExpressMailOptions - def set_ExpressMailOptions(self, ExpressMailOptions): - self.ExpressMailOptions = ExpressMailOptions - def get_ShipDate(self): - return self.ShipDate - def set_ShipDate(self, ShipDate): - self.ShipDate = ShipDate - def get_CustomerRefNo(self): - return self.CustomerRefNo - def set_CustomerRefNo(self, CustomerRefNo): - self.CustomerRefNo = CustomerRefNo - def get_CustomerRefNo2(self): - return self.CustomerRefNo2 - def set_CustomerRefNo2(self, CustomerRefNo2): - self.CustomerRefNo2 = CustomerRefNo2 - def get_ExtraServices(self): - return self.ExtraServices - def set_ExtraServices(self, ExtraServices): - self.ExtraServices = ExtraServices - def get_HoldForPickup(self): - return self.HoldForPickup - def set_HoldForPickup(self, HoldForPickup): - self.HoldForPickup = HoldForPickup - def get_OpenDistribute(self): - return self.OpenDistribute - def set_OpenDistribute(self, OpenDistribute): - self.OpenDistribute = OpenDistribute - def get_PermitNumber(self): - return self.PermitNumber - def set_PermitNumber(self, PermitNumber): - self.PermitNumber = PermitNumber - def get_PermitZIPCode(self): - return self.PermitZIPCode - def set_PermitZIPCode(self, PermitZIPCode): - self.PermitZIPCode = PermitZIPCode - def get_PermitHolderName(self): - return self.PermitHolderName - def set_PermitHolderName(self, PermitHolderName): - self.PermitHolderName = PermitHolderName - def get_CRID(self): - return self.CRID - def set_CRID(self, CRID): - self.CRID = CRID - def get_MID(self): - return self.MID - def set_MID(self, MID): - self.MID = MID - def get_LogisticsManagerMID(self): - return self.LogisticsManagerMID - def set_LogisticsManagerMID(self, LogisticsManagerMID): - self.LogisticsManagerMID = LogisticsManagerMID - def get_VendorCode(self): - return self.VendorCode - def set_VendorCode(self, VendorCode): - self.VendorCode = VendorCode - def get_VendorProductVersionNumber(self): - return self.VendorProductVersionNumber - def set_VendorProductVersionNumber(self, VendorProductVersionNumber): - self.VendorProductVersionNumber = VendorProductVersionNumber - def get_SenderName(self): - return self.SenderName - def set_SenderName(self, SenderName): - self.SenderName = SenderName - def get_SenderEMail(self): - return self.SenderEMail - def set_SenderEMail(self, SenderEMail): - self.SenderEMail = SenderEMail - def get_RecipientName(self): - return self.RecipientName - def set_RecipientName(self, RecipientName): - self.RecipientName = RecipientName - def get_RecipientEMail(self): - return self.RecipientEMail - def set_RecipientEMail(self, RecipientEMail): - self.RecipientEMail = RecipientEMail - def get_ReceiptOption(self): - return self.ReceiptOption - def set_ReceiptOption(self, ReceiptOption): - self.ReceiptOption = ReceiptOption - def get_ImageType(self): - return self.ImageType - def set_ImageType(self, ImageType): - self.ImageType = ImageType - def get_HoldForManifest(self): - return self.HoldForManifest - def set_HoldForManifest(self, HoldForManifest): - self.HoldForManifest = HoldForManifest - def get_NineDigitRoutingZip(self): - return self.NineDigitRoutingZip - def set_NineDigitRoutingZip(self, NineDigitRoutingZip): - self.NineDigitRoutingZip = NineDigitRoutingZip - def get_ShipInfo(self): - return self.ShipInfo - def set_ShipInfo(self, ShipInfo): - self.ShipInfo = ShipInfo - def get_CarrierRelease(self): - return self.CarrierRelease - def set_CarrierRelease(self, CarrierRelease): - self.CarrierRelease = CarrierRelease - def get_DropOffTime(self): - return self.DropOffTime - def set_DropOffTime(self, DropOffTime): - self.DropOffTime = DropOffTime - def get_ReturnCommitments(self): - return self.ReturnCommitments - def set_ReturnCommitments(self, ReturnCommitments): - self.ReturnCommitments = ReturnCommitments - def get_PrintCustomerRefNo(self): - return self.PrintCustomerRefNo - def set_PrintCustomerRefNo(self, PrintCustomerRefNo): - self.PrintCustomerRefNo = PrintCustomerRefNo - def get_Content(self): - return self.Content - def set_Content(self, Content): - self.Content = Content - def get_ActionCode(self): - return self.ActionCode - def set_ActionCode(self, ActionCode): - self.ActionCode = ActionCode - def get_OptOutOfSPE(self): - return self.OptOutOfSPE - def set_OptOutOfSPE(self, OptOutOfSPE): - self.OptOutOfSPE = OptOutOfSPE - def get_SortationLevel(self): - return self.SortationLevel - def set_SortationLevel(self, SortationLevel): - self.SortationLevel = SortationLevel - def get_DestinationEntryFacilityType(self): - return self.DestinationEntryFacilityType - def set_DestinationEntryFacilityType(self, DestinationEntryFacilityType): - self.DestinationEntryFacilityType = DestinationEntryFacilityType - def get_ShippingContents(self): - return self.ShippingContents - def set_ShippingContents(self, ShippingContents): - self.ShippingContents = ShippingContents - def get_CustomsContentType(self): - return self.CustomsContentType - def set_CustomsContentType(self, CustomsContentType): - self.CustomsContentType = CustomsContentType - def get_ContentComments(self): - return self.ContentComments - def set_ContentComments(self, ContentComments): - self.ContentComments = ContentComments - def get_RestrictionType(self): - return self.RestrictionType - def set_RestrictionType(self, RestrictionType): - self.RestrictionType = RestrictionType - def get_RestrictionComments(self): - return self.RestrictionComments - def set_RestrictionComments(self, RestrictionComments): - self.RestrictionComments = RestrictionComments - def get_AESITN(self): - return self.AESITN - def set_AESITN(self, AESITN): - self.AESITN = AESITN - def get_ImportersReference(self): - return self.ImportersReference - def set_ImportersReference(self, ImportersReference): - self.ImportersReference = ImportersReference - def get_ImportersContact(self): - return self.ImportersContact - def set_ImportersContact(self, ImportersContact): - self.ImportersContact = ImportersContact - def get_ExportersReference(self): - return self.ExportersReference - def set_ExportersReference(self, ExportersReference): - self.ExportersReference = ExportersReference - def get_ExportersContact(self): - return self.ExportersContact - def set_ExportersContact(self, ExportersContact): - self.ExportersContact = ExportersContact - def get_InvoiceNumber(self): - return self.InvoiceNumber - def set_InvoiceNumber(self, InvoiceNumber): - self.InvoiceNumber = InvoiceNumber - def get_LicenseNumber(self): - return self.LicenseNumber - def set_LicenseNumber(self, LicenseNumber): - self.LicenseNumber = LicenseNumber - def get_CertificateNumber(self): - return self.CertificateNumber - def set_CertificateNumber(self, CertificateNumber): - self.CertificateNumber = CertificateNumber - def get_NonDeliveryOption(self): - return self.NonDeliveryOption - def set_NonDeliveryOption(self, NonDeliveryOption): - self.NonDeliveryOption = NonDeliveryOption - def get_AltReturnAddress1(self): - return self.AltReturnAddress1 - def set_AltReturnAddress1(self, AltReturnAddress1): - self.AltReturnAddress1 = AltReturnAddress1 - def get_AltReturnAddress2(self): - return self.AltReturnAddress2 - def set_AltReturnAddress2(self, AltReturnAddress2): - self.AltReturnAddress2 = AltReturnAddress2 - def get_AltReturnAddress3(self): - return self.AltReturnAddress3 - def set_AltReturnAddress3(self, AltReturnAddress3): - self.AltReturnAddress3 = AltReturnAddress3 - def get_AltReturnAddress4(self): - return self.AltReturnAddress4 - def set_AltReturnAddress4(self, AltReturnAddress4): - self.AltReturnAddress4 = AltReturnAddress4 - def get_AltReturnAddress5(self): - return self.AltReturnAddress5 - def set_AltReturnAddress5(self, AltReturnAddress5): - self.AltReturnAddress5 = AltReturnAddress5 - def get_AltReturnAddress6(self): - return self.AltReturnAddress6 - def set_AltReturnAddress6(self, AltReturnAddress6): - self.AltReturnAddress6 = AltReturnAddress6 - def get_AltReturnCountry(self): - return self.AltReturnCountry - def set_AltReturnCountry(self, AltReturnCountry): - self.AltReturnCountry = AltReturnCountry - def get_LabelImportType(self): - return self.LabelImportType - def set_LabelImportType(self, LabelImportType): - self.LabelImportType = LabelImportType - def get_ePostageMailerReporting(self): - return self.ePostageMailerReporting - def set_ePostageMailerReporting(self, ePostageMailerReporting): - self.ePostageMailerReporting = ePostageMailerReporting - def get_SenderFirstName(self): - return self.SenderFirstName - def set_SenderFirstName(self, SenderFirstName): - self.SenderFirstName = SenderFirstName - def get_SenderLastName(self): - return self.SenderLastName - def set_SenderLastName(self, SenderLastName): - self.SenderLastName = SenderLastName - def get_SenderBusinessName(self): - return self.SenderBusinessName - def set_SenderBusinessName(self, SenderBusinessName): - self.SenderBusinessName = SenderBusinessName - def get_SenderAddress1(self): - return self.SenderAddress1 - def set_SenderAddress1(self, SenderAddress1): - self.SenderAddress1 = SenderAddress1 - def get_SenderCity(self): - return self.SenderCity - def set_SenderCity(self, SenderCity): - self.SenderCity = SenderCity - def get_SenderState(self): - return self.SenderState - def set_SenderState(self, SenderState): - self.SenderState = SenderState - def get_SenderZip5(self): - return self.SenderZip5 - def set_SenderZip5(self, SenderZip5): - self.SenderZip5 = SenderZip5 - def get_SenderPhone(self): - return self.SenderPhone - def set_SenderPhone(self, SenderPhone): - self.SenderPhone = SenderPhone - def get_ChargebackCode(self): - return self.ChargebackCode - def set_ChargebackCode(self, ChargebackCode): - self.ChargebackCode = ChargebackCode - def get_TrackingRetentionPeriod(self): - return self.TrackingRetentionPeriod - def set_TrackingRetentionPeriod(self, TrackingRetentionPeriod): - self.TrackingRetentionPeriod = TrackingRetentionPeriod - def get_USERID(self): - return self.USERID - def set_USERID(self, USERID): - self.USERID = USERID - def validate_ShipDateType(self, value): - result = True - # Validate type ShipDateType, a restriction on xs:string. - if value is not None and Validate_simpletypes_ and self.gds_collector_ is not None: - if not isinstance(value, str): - lineno = self.gds_get_node_lineno_() - self.gds_collector_.add_message('Value "%(value)s"%(lineno)s is not of the correct base simple type (str)' % {"value": value, "lineno": lineno, }) - return False - if not self.gds_validate_simple_patterns( - self.validate_ShipDateType_patterns_, value): - self.gds_collector_.add_message('Value "%s" does not match xsd pattern restrictions: %s' % (encode_str_2_3(value), self.validate_ShipDateType_patterns_, )) - result = False - return result - validate_ShipDateType_patterns_ = [['^(\\d{1,2}/ \\d{1,2}/ \\d\\d(\\d\\d)?)$']] - def _hasContent(self): - if ( - self.Option is not None or - self.Revision is not None or - self.ImageParameters is not None or - self.FromName is not None or - self.FromFirm is not None or - self.FromAddress1 is not None or - self.FromAddress2 is not None or - self.FromCity is not None or - self.FromState is not None or - self.FromZip5 is not None or - self.FromZip4 is not None or - self.FromPhone is not None or - self.POZipCode is not None or - self.AllowNonCleansedOriginAddr is not None or - self.ToName is not None or - self.ToFirm is not None or - self.ToAddress1 is not None or - self.ToAddress2 is not None or - self.ToCity is not None or - self.ToState is not None or - self.ToZip5 is not None or - self.ToZip4 is not None or - self.ToPhone is not None or - self.POBox is not None or - self.ToContactPreference is not None or - self.ToContactMessaging is not None or - self.ToContactEmail is not None or - self.AllowNonCleansedDestAddr is not None or - self.WeightInOunces is not None or - self.ServiceType is not None or - self.Container is not None or - self.Width is not None or - self.Length is not None or - self.Height is not None or - self.Girth is not None or - self.Machinable is not None or - self.ProcessingCategory is not None or - self.PriceOptions is not None or - self.InsuredAmount is not None or - self.AddressServiceRequested is not None or - self.ExpressMailOptions is not None or - self.ShipDate is not None or - self.CustomerRefNo is not None or - self.CustomerRefNo2 is not None or - self.ExtraServices is not None or - self.HoldForPickup is not None or - self.OpenDistribute is not None or - self.PermitNumber is not None or - self.PermitZIPCode is not None or - self.PermitHolderName is not None or - self.CRID is not None or - self.MID is not None or - self.LogisticsManagerMID is not None or - self.VendorCode is not None or - self.VendorProductVersionNumber is not None or - self.SenderName is not None or - self.SenderEMail is not None or - self.RecipientName is not None or - self.RecipientEMail is not None or - self.ReceiptOption is not None or - self.ImageType is not None or - self.HoldForManifest is not None or - self.NineDigitRoutingZip is not None or - self.ShipInfo is not None or - self.CarrierRelease is not None or - self.DropOffTime is not None or - self.ReturnCommitments is not None or - self.PrintCustomerRefNo is not None or - self.Content is not None or - self.ActionCode is not None or - self.OptOutOfSPE is not None or - self.SortationLevel is not None or - self.DestinationEntryFacilityType is not None or - self.ShippingContents is not None or - self.CustomsContentType is not None or - self.ContentComments is not None or - self.RestrictionType is not None or - self.RestrictionComments is not None or - self.AESITN is not None or - self.ImportersReference is not None or - self.ImportersContact is not None or - self.ExportersReference is not None or - self.ExportersContact is not None or - self.InvoiceNumber is not None or - self.LicenseNumber is not None or - self.CertificateNumber is not None or - self.NonDeliveryOption is not None or - self.AltReturnAddress1 is not None or - self.AltReturnAddress2 is not None or - self.AltReturnAddress3 is not None or - self.AltReturnAddress4 is not None or - self.AltReturnAddress5 is not None or - self.AltReturnAddress6 is not None or - self.AltReturnCountry is not None or - self.LabelImportType is not None or - self.ePostageMailerReporting is not None or - self.SenderFirstName is not None or - self.SenderLastName is not None or - self.SenderBusinessName is not None or - self.SenderAddress1 is not None or - self.SenderCity is not None or - self.SenderState is not None or - self.SenderZip5 is not None or - self.SenderPhone is not None or - self.ChargebackCode is not None or - self.TrackingRetentionPeriod is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='eVSRequest', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('eVSRequest') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'eVSRequest': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='eVSRequest') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='eVSRequest', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='eVSRequest'): - if self.USERID is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - outfile.write(' USERID=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.USERID), input_name='USERID')), )) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='eVSRequest', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.Option is not None: - namespaceprefix_ = self.Option_nsprefix_ + ':' if (UseCapturedNS_ and self.Option_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sOption>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.Option, input_name='Option'), namespaceprefix_ , eol_)) - if self.Revision is not None: - namespaceprefix_ = self.Revision_nsprefix_ + ':' if (UseCapturedNS_ and self.Revision_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRevision>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Revision), input_name='Revision')), namespaceprefix_ , eol_)) - if self.ImageParameters is not None: - namespaceprefix_ = self.ImageParameters_nsprefix_ + ':' if (UseCapturedNS_ and self.ImageParameters_nsprefix_) else '' - self.ImageParameters.export(outfile, level, namespaceprefix_, namespacedef_='', name_='ImageParameters', pretty_print=pretty_print) - if self.FromName is not None: - namespaceprefix_ = self.FromName_nsprefix_ + ':' if (UseCapturedNS_ and self.FromName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromName), input_name='FromName')), namespaceprefix_ , eol_)) - if self.FromFirm is not None: - namespaceprefix_ = self.FromFirm_nsprefix_ + ':' if (UseCapturedNS_ and self.FromFirm_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromFirm>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromFirm), input_name='FromFirm')), namespaceprefix_ , eol_)) - if self.FromAddress1 is not None: - namespaceprefix_ = self.FromAddress1_nsprefix_ + ':' if (UseCapturedNS_ and self.FromAddress1_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromAddress1>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromAddress1), input_name='FromAddress1')), namespaceprefix_ , eol_)) - if self.FromAddress2 is not None: - namespaceprefix_ = self.FromAddress2_nsprefix_ + ':' if (UseCapturedNS_ and self.FromAddress2_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromAddress2>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromAddress2), input_name='FromAddress2')), namespaceprefix_ , eol_)) - if self.FromCity is not None: - namespaceprefix_ = self.FromCity_nsprefix_ + ':' if (UseCapturedNS_ and self.FromCity_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromCity), input_name='FromCity')), namespaceprefix_ , eol_)) - if self.FromState is not None: - namespaceprefix_ = self.FromState_nsprefix_ + ':' if (UseCapturedNS_ and self.FromState_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromState), input_name='FromState')), namespaceprefix_ , eol_)) - if self.FromZip5 is not None: - namespaceprefix_ = self.FromZip5_nsprefix_ + ':' if (UseCapturedNS_ and self.FromZip5_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromZip5>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromZip5), input_name='FromZip5')), namespaceprefix_ , eol_)) - if self.FromZip4 is not None: - namespaceprefix_ = self.FromZip4_nsprefix_ + ':' if (UseCapturedNS_ and self.FromZip4_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromZip4>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromZip4), input_name='FromZip4')), namespaceprefix_ , eol_)) - if self.FromPhone is not None: - namespaceprefix_ = self.FromPhone_nsprefix_ + ':' if (UseCapturedNS_ and self.FromPhone_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromPhone>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromPhone), input_name='FromPhone')), namespaceprefix_ , eol_)) - if self.POZipCode is not None: - namespaceprefix_ = self.POZipCode_nsprefix_ + ':' if (UseCapturedNS_ and self.POZipCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPOZipCode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.POZipCode), input_name='POZipCode')), namespaceprefix_ , eol_)) - if self.AllowNonCleansedOriginAddr is not None: - namespaceprefix_ = self.AllowNonCleansedOriginAddr_nsprefix_ + ':' if (UseCapturedNS_ and self.AllowNonCleansedOriginAddr_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAllowNonCleansedOriginAddr>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.AllowNonCleansedOriginAddr), input_name='AllowNonCleansedOriginAddr')), namespaceprefix_ , eol_)) - if self.ToName is not None: - namespaceprefix_ = self.ToName_nsprefix_ + ':' if (UseCapturedNS_ and self.ToName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToName), input_name='ToName')), namespaceprefix_ , eol_)) - if self.ToFirm is not None: - namespaceprefix_ = self.ToFirm_nsprefix_ + ':' if (UseCapturedNS_ and self.ToFirm_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToFirm>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToFirm), input_name='ToFirm')), namespaceprefix_ , eol_)) - if self.ToAddress1 is not None: - namespaceprefix_ = self.ToAddress1_nsprefix_ + ':' if (UseCapturedNS_ and self.ToAddress1_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToAddress1>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToAddress1), input_name='ToAddress1')), namespaceprefix_ , eol_)) - if self.ToAddress2 is not None: - namespaceprefix_ = self.ToAddress2_nsprefix_ + ':' if (UseCapturedNS_ and self.ToAddress2_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToAddress2>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToAddress2), input_name='ToAddress2')), namespaceprefix_ , eol_)) - if self.ToCity is not None: - namespaceprefix_ = self.ToCity_nsprefix_ + ':' if (UseCapturedNS_ and self.ToCity_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToCity), input_name='ToCity')), namespaceprefix_ , eol_)) - if self.ToState is not None: - namespaceprefix_ = self.ToState_nsprefix_ + ':' if (UseCapturedNS_ and self.ToState_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToState), input_name='ToState')), namespaceprefix_ , eol_)) - if self.ToZip5 is not None: - namespaceprefix_ = self.ToZip5_nsprefix_ + ':' if (UseCapturedNS_ and self.ToZip5_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToZip5>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToZip5), input_name='ToZip5')), namespaceprefix_ , eol_)) - if self.ToZip4 is not None: - namespaceprefix_ = self.ToZip4_nsprefix_ + ':' if (UseCapturedNS_ and self.ToZip4_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToZip4>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToZip4), input_name='ToZip4')), namespaceprefix_ , eol_)) - if self.ToPhone is not None: - namespaceprefix_ = self.ToPhone_nsprefix_ + ':' if (UseCapturedNS_ and self.ToPhone_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToPhone>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToPhone), input_name='ToPhone')), namespaceprefix_ , eol_)) - if self.POBox is not None: - namespaceprefix_ = self.POBox_nsprefix_ + ':' if (UseCapturedNS_ and self.POBox_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPOBox>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.POBox), input_name='POBox')), namespaceprefix_ , eol_)) - if self.ToContactPreference is not None: - namespaceprefix_ = self.ToContactPreference_nsprefix_ + ':' if (UseCapturedNS_ and self.ToContactPreference_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToContactPreference>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToContactPreference), input_name='ToContactPreference')), namespaceprefix_ , eol_)) - if self.ToContactMessaging is not None: - namespaceprefix_ = self.ToContactMessaging_nsprefix_ + ':' if (UseCapturedNS_ and self.ToContactMessaging_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToContactMessaging>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToContactMessaging), input_name='ToContactMessaging')), namespaceprefix_ , eol_)) - if self.ToContactEmail is not None: - namespaceprefix_ = self.ToContactEmail_nsprefix_ + ':' if (UseCapturedNS_ and self.ToContactEmail_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToContactEmail>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToContactEmail), input_name='ToContactEmail')), namespaceprefix_ , eol_)) - if self.AllowNonCleansedDestAddr is not None: - namespaceprefix_ = self.AllowNonCleansedDestAddr_nsprefix_ + ':' if (UseCapturedNS_ and self.AllowNonCleansedDestAddr_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAllowNonCleansedDestAddr>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.AllowNonCleansedDestAddr, input_name='AllowNonCleansedDestAddr'), namespaceprefix_ , eol_)) - if self.WeightInOunces is not None: - namespaceprefix_ = self.WeightInOunces_nsprefix_ + ':' if (UseCapturedNS_ and self.WeightInOunces_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sWeightInOunces>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.WeightInOunces), input_name='WeightInOunces')), namespaceprefix_ , eol_)) - if self.ServiceType is not None: - namespaceprefix_ = self.ServiceType_nsprefix_ + ':' if (UseCapturedNS_ and self.ServiceType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sServiceType>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ServiceType), input_name='ServiceType')), namespaceprefix_ , eol_)) - if self.Container is not None: - namespaceprefix_ = self.Container_nsprefix_ + ':' if (UseCapturedNS_ and self.Container_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sContainer>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Container), input_name='Container')), namespaceprefix_ , eol_)) - if self.Width is not None: - namespaceprefix_ = self.Width_nsprefix_ + ':' if (UseCapturedNS_ and self.Width_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sWidth>%s%s' % (namespaceprefix_ , self.gds_format_decimal(self.Width, input_name='Width'), namespaceprefix_ , eol_)) - if self.Length is not None: - namespaceprefix_ = self.Length_nsprefix_ + ':' if (UseCapturedNS_ and self.Length_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sLength>%s%s' % (namespaceprefix_ , self.gds_format_decimal(self.Length, input_name='Length'), namespaceprefix_ , eol_)) - if self.Height is not None: - namespaceprefix_ = self.Height_nsprefix_ + ':' if (UseCapturedNS_ and self.Height_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sHeight>%s%s' % (namespaceprefix_ , self.gds_format_decimal(self.Height, input_name='Height'), namespaceprefix_ , eol_)) - if self.Girth is not None: - namespaceprefix_ = self.Girth_nsprefix_ + ':' if (UseCapturedNS_ and self.Girth_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sGirth>%s%s' % (namespaceprefix_ , self.gds_format_decimal(self.Girth, input_name='Girth'), namespaceprefix_ , eol_)) - if self.Machinable is not None: - namespaceprefix_ = self.Machinable_nsprefix_ + ':' if (UseCapturedNS_ and self.Machinable_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sMachinable>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Machinable), input_name='Machinable')), namespaceprefix_ , eol_)) - if self.ProcessingCategory is not None: - namespaceprefix_ = self.ProcessingCategory_nsprefix_ + ':' if (UseCapturedNS_ and self.ProcessingCategory_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sProcessingCategory>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ProcessingCategory), input_name='ProcessingCategory')), namespaceprefix_ , eol_)) - if self.PriceOptions is not None: - namespaceprefix_ = self.PriceOptions_nsprefix_ + ':' if (UseCapturedNS_ and self.PriceOptions_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPriceOptions>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PriceOptions), input_name='PriceOptions')), namespaceprefix_ , eol_)) - if self.InsuredAmount is not None: - namespaceprefix_ = self.InsuredAmount_nsprefix_ + ':' if (UseCapturedNS_ and self.InsuredAmount_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sInsuredAmount>%s%s' % (namespaceprefix_ , self.gds_format_decimal(self.InsuredAmount, input_name='InsuredAmount'), namespaceprefix_ , eol_)) - if self.AddressServiceRequested is not None: - namespaceprefix_ = self.AddressServiceRequested_nsprefix_ + ':' if (UseCapturedNS_ and self.AddressServiceRequested_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAddressServiceRequested>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.AddressServiceRequested, input_name='AddressServiceRequested'), namespaceprefix_ , eol_)) - if self.ExpressMailOptions is not None: - namespaceprefix_ = self.ExpressMailOptions_nsprefix_ + ':' if (UseCapturedNS_ and self.ExpressMailOptions_nsprefix_) else '' - self.ExpressMailOptions.export(outfile, level, namespaceprefix_, namespacedef_='', name_='ExpressMailOptions', pretty_print=pretty_print) - if self.ShipDate is not None: - namespaceprefix_ = self.ShipDate_nsprefix_ + ':' if (UseCapturedNS_ and self.ShipDate_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sShipDate>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ShipDate), input_name='ShipDate')), namespaceprefix_ , eol_)) - if self.CustomerRefNo is not None: - namespaceprefix_ = self.CustomerRefNo_nsprefix_ + ':' if (UseCapturedNS_ and self.CustomerRefNo_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCustomerRefNo>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CustomerRefNo), input_name='CustomerRefNo')), namespaceprefix_ , eol_)) - if self.CustomerRefNo2 is not None: - namespaceprefix_ = self.CustomerRefNo2_nsprefix_ + ':' if (UseCapturedNS_ and self.CustomerRefNo2_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCustomerRefNo2>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CustomerRefNo2), input_name='CustomerRefNo2')), namespaceprefix_ , eol_)) - if self.ExtraServices is not None: - namespaceprefix_ = self.ExtraServices_nsprefix_ + ':' if (UseCapturedNS_ and self.ExtraServices_nsprefix_) else '' - self.ExtraServices.export(outfile, level, namespaceprefix_, namespacedef_='', name_='ExtraServices', pretty_print=pretty_print) - if self.HoldForPickup is not None: - namespaceprefix_ = self.HoldForPickup_nsprefix_ + ':' if (UseCapturedNS_ and self.HoldForPickup_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sHoldForPickup>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.HoldForPickup), input_name='HoldForPickup')), namespaceprefix_ , eol_)) - if self.OpenDistribute is not None: - namespaceprefix_ = self.OpenDistribute_nsprefix_ + ':' if (UseCapturedNS_ and self.OpenDistribute_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sOpenDistribute>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.OpenDistribute), input_name='OpenDistribute')), namespaceprefix_ , eol_)) - if self.PermitNumber is not None: - namespaceprefix_ = self.PermitNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.PermitNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPermitNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PermitNumber), input_name='PermitNumber')), namespaceprefix_ , eol_)) - if self.PermitZIPCode is not None: - namespaceprefix_ = self.PermitZIPCode_nsprefix_ + ':' if (UseCapturedNS_ and self.PermitZIPCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPermitZIPCode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PermitZIPCode), input_name='PermitZIPCode')), namespaceprefix_ , eol_)) - if self.PermitHolderName is not None: - namespaceprefix_ = self.PermitHolderName_nsprefix_ + ':' if (UseCapturedNS_ and self.PermitHolderName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPermitHolderName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PermitHolderName), input_name='PermitHolderName')), namespaceprefix_ , eol_)) - if self.CRID is not None: - namespaceprefix_ = self.CRID_nsprefix_ + ':' if (UseCapturedNS_ and self.CRID_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCRID>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CRID), input_name='CRID')), namespaceprefix_ , eol_)) - if self.MID is not None: - namespaceprefix_ = self.MID_nsprefix_ + ':' if (UseCapturedNS_ and self.MID_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sMID>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.MID), input_name='MID')), namespaceprefix_ , eol_)) - if self.LogisticsManagerMID is not None: - namespaceprefix_ = self.LogisticsManagerMID_nsprefix_ + ':' if (UseCapturedNS_ and self.LogisticsManagerMID_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sLogisticsManagerMID>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.LogisticsManagerMID), input_name='LogisticsManagerMID')), namespaceprefix_ , eol_)) - if self.VendorCode is not None: - namespaceprefix_ = self.VendorCode_nsprefix_ + ':' if (UseCapturedNS_ and self.VendorCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sVendorCode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.VendorCode), input_name='VendorCode')), namespaceprefix_ , eol_)) - if self.VendorProductVersionNumber is not None: - namespaceprefix_ = self.VendorProductVersionNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.VendorProductVersionNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sVendorProductVersionNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.VendorProductVersionNumber), input_name='VendorProductVersionNumber')), namespaceprefix_ , eol_)) - if self.SenderName is not None: - namespaceprefix_ = self.SenderName_nsprefix_ + ':' if (UseCapturedNS_ and self.SenderName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSenderName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SenderName), input_name='SenderName')), namespaceprefix_ , eol_)) - if self.SenderEMail is not None: - namespaceprefix_ = self.SenderEMail_nsprefix_ + ':' if (UseCapturedNS_ and self.SenderEMail_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSenderEMail>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SenderEMail), input_name='SenderEMail')), namespaceprefix_ , eol_)) - if self.RecipientName is not None: - namespaceprefix_ = self.RecipientName_nsprefix_ + ':' if (UseCapturedNS_ and self.RecipientName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRecipientName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.RecipientName), input_name='RecipientName')), namespaceprefix_ , eol_)) - if self.RecipientEMail is not None: - namespaceprefix_ = self.RecipientEMail_nsprefix_ + ':' if (UseCapturedNS_ and self.RecipientEMail_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRecipientEMail>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.RecipientEMail), input_name='RecipientEMail')), namespaceprefix_ , eol_)) - if self.ReceiptOption is not None: - namespaceprefix_ = self.ReceiptOption_nsprefix_ + ':' if (UseCapturedNS_ and self.ReceiptOption_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sReceiptOption>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ReceiptOption), input_name='ReceiptOption')), namespaceprefix_ , eol_)) - if self.ImageType is not None: - namespaceprefix_ = self.ImageType_nsprefix_ + ':' if (UseCapturedNS_ and self.ImageType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sImageType>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ImageType), input_name='ImageType')), namespaceprefix_ , eol_)) - if self.HoldForManifest is not None: - namespaceprefix_ = self.HoldForManifest_nsprefix_ + ':' if (UseCapturedNS_ and self.HoldForManifest_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sHoldForManifest>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.HoldForManifest), input_name='HoldForManifest')), namespaceprefix_ , eol_)) - if self.NineDigitRoutingZip is not None: - namespaceprefix_ = self.NineDigitRoutingZip_nsprefix_ + ':' if (UseCapturedNS_ and self.NineDigitRoutingZip_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sNineDigitRoutingZip>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.NineDigitRoutingZip, input_name='NineDigitRoutingZip'), namespaceprefix_ , eol_)) - if self.ShipInfo is not None: - namespaceprefix_ = self.ShipInfo_nsprefix_ + ':' if (UseCapturedNS_ and self.ShipInfo_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sShipInfo>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.ShipInfo, input_name='ShipInfo'), namespaceprefix_ , eol_)) - if self.CarrierRelease is not None: - namespaceprefix_ = self.CarrierRelease_nsprefix_ + ':' if (UseCapturedNS_ and self.CarrierRelease_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCarrierRelease>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.CarrierRelease, input_name='CarrierRelease'), namespaceprefix_ , eol_)) - if self.DropOffTime is not None: - namespaceprefix_ = self.DropOffTime_nsprefix_ + ':' if (UseCapturedNS_ and self.DropOffTime_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDropOffTime>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.DropOffTime, input_name='DropOffTime'), namespaceprefix_ , eol_)) - if self.ReturnCommitments is not None: - namespaceprefix_ = self.ReturnCommitments_nsprefix_ + ':' if (UseCapturedNS_ and self.ReturnCommitments_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sReturnCommitments>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.ReturnCommitments, input_name='ReturnCommitments'), namespaceprefix_ , eol_)) - if self.PrintCustomerRefNo is not None: - namespaceprefix_ = self.PrintCustomerRefNo_nsprefix_ + ':' if (UseCapturedNS_ and self.PrintCustomerRefNo_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPrintCustomerRefNo>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PrintCustomerRefNo), input_name='PrintCustomerRefNo')), namespaceprefix_ , eol_)) - if self.Content is not None: - namespaceprefix_ = self.Content_nsprefix_ + ':' if (UseCapturedNS_ and self.Content_nsprefix_) else '' - self.Content.export(outfile, level, namespaceprefix_, namespacedef_='', name_='Content', pretty_print=pretty_print) - if self.ActionCode is not None: - namespaceprefix_ = self.ActionCode_nsprefix_ + ':' if (UseCapturedNS_ and self.ActionCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sActionCode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ActionCode), input_name='ActionCode')), namespaceprefix_ , eol_)) - if self.OptOutOfSPE is not None: - namespaceprefix_ = self.OptOutOfSPE_nsprefix_ + ':' if (UseCapturedNS_ and self.OptOutOfSPE_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sOptOutOfSPE>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.OptOutOfSPE), input_name='OptOutOfSPE')), namespaceprefix_ , eol_)) - if self.SortationLevel is not None: - namespaceprefix_ = self.SortationLevel_nsprefix_ + ':' if (UseCapturedNS_ and self.SortationLevel_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSortationLevel>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SortationLevel), input_name='SortationLevel')), namespaceprefix_ , eol_)) - if self.DestinationEntryFacilityType is not None: - namespaceprefix_ = self.DestinationEntryFacilityType_nsprefix_ + ':' if (UseCapturedNS_ and self.DestinationEntryFacilityType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDestinationEntryFacilityType>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.DestinationEntryFacilityType), input_name='DestinationEntryFacilityType')), namespaceprefix_ , eol_)) - if self.ShippingContents is not None: - namespaceprefix_ = self.ShippingContents_nsprefix_ + ':' if (UseCapturedNS_ and self.ShippingContents_nsprefix_) else '' - self.ShippingContents.export(outfile, level, namespaceprefix_, namespacedef_='', name_='ShippingContents', pretty_print=pretty_print) - if self.CustomsContentType is not None: - namespaceprefix_ = self.CustomsContentType_nsprefix_ + ':' if (UseCapturedNS_ and self.CustomsContentType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCustomsContentType>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CustomsContentType), input_name='CustomsContentType')), namespaceprefix_ , eol_)) - if self.ContentComments is not None: - namespaceprefix_ = self.ContentComments_nsprefix_ + ':' if (UseCapturedNS_ and self.ContentComments_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sContentComments>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ContentComments), input_name='ContentComments')), namespaceprefix_ , eol_)) - if self.RestrictionType is not None: - namespaceprefix_ = self.RestrictionType_nsprefix_ + ':' if (UseCapturedNS_ and self.RestrictionType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRestrictionType>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.RestrictionType), input_name='RestrictionType')), namespaceprefix_ , eol_)) - if self.RestrictionComments is not None: - namespaceprefix_ = self.RestrictionComments_nsprefix_ + ':' if (UseCapturedNS_ and self.RestrictionComments_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRestrictionComments>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.RestrictionComments), input_name='RestrictionComments')), namespaceprefix_ , eol_)) - if self.AESITN is not None: - namespaceprefix_ = self.AESITN_nsprefix_ + ':' if (UseCapturedNS_ and self.AESITN_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAESITN>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.AESITN), input_name='AESITN')), namespaceprefix_ , eol_)) - if self.ImportersReference is not None: - namespaceprefix_ = self.ImportersReference_nsprefix_ + ':' if (UseCapturedNS_ and self.ImportersReference_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sImportersReference>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ImportersReference), input_name='ImportersReference')), namespaceprefix_ , eol_)) - if self.ImportersContact is not None: - namespaceprefix_ = self.ImportersContact_nsprefix_ + ':' if (UseCapturedNS_ and self.ImportersContact_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sImportersContact>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ImportersContact), input_name='ImportersContact')), namespaceprefix_ , eol_)) - if self.ExportersReference is not None: - namespaceprefix_ = self.ExportersReference_nsprefix_ + ':' if (UseCapturedNS_ and self.ExportersReference_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sExportersReference>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ExportersReference), input_name='ExportersReference')), namespaceprefix_ , eol_)) - if self.ExportersContact is not None: - namespaceprefix_ = self.ExportersContact_nsprefix_ + ':' if (UseCapturedNS_ and self.ExportersContact_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sExportersContact>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ExportersContact), input_name='ExportersContact')), namespaceprefix_ , eol_)) - if self.InvoiceNumber is not None: - namespaceprefix_ = self.InvoiceNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.InvoiceNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sInvoiceNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.InvoiceNumber), input_name='InvoiceNumber')), namespaceprefix_ , eol_)) - if self.LicenseNumber is not None: - namespaceprefix_ = self.LicenseNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.LicenseNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sLicenseNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.LicenseNumber), input_name='LicenseNumber')), namespaceprefix_ , eol_)) - if self.CertificateNumber is not None: - namespaceprefix_ = self.CertificateNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.CertificateNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCertificateNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CertificateNumber), input_name='CertificateNumber')), namespaceprefix_ , eol_)) - if self.NonDeliveryOption is not None: - namespaceprefix_ = self.NonDeliveryOption_nsprefix_ + ':' if (UseCapturedNS_ and self.NonDeliveryOption_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sNonDeliveryOption>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.NonDeliveryOption), input_name='NonDeliveryOption')), namespaceprefix_ , eol_)) - if self.AltReturnAddress1 is not None: - namespaceprefix_ = self.AltReturnAddress1_nsprefix_ + ':' if (UseCapturedNS_ and self.AltReturnAddress1_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAltReturnAddress1>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.AltReturnAddress1), input_name='AltReturnAddress1')), namespaceprefix_ , eol_)) - if self.AltReturnAddress2 is not None: - namespaceprefix_ = self.AltReturnAddress2_nsprefix_ + ':' if (UseCapturedNS_ and self.AltReturnAddress2_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAltReturnAddress2>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.AltReturnAddress2), input_name='AltReturnAddress2')), namespaceprefix_ , eol_)) - if self.AltReturnAddress3 is not None: - namespaceprefix_ = self.AltReturnAddress3_nsprefix_ + ':' if (UseCapturedNS_ and self.AltReturnAddress3_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAltReturnAddress3>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.AltReturnAddress3), input_name='AltReturnAddress3')), namespaceprefix_ , eol_)) - if self.AltReturnAddress4 is not None: - namespaceprefix_ = self.AltReturnAddress4_nsprefix_ + ':' if (UseCapturedNS_ and self.AltReturnAddress4_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAltReturnAddress4>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.AltReturnAddress4), input_name='AltReturnAddress4')), namespaceprefix_ , eol_)) - if self.AltReturnAddress5 is not None: - namespaceprefix_ = self.AltReturnAddress5_nsprefix_ + ':' if (UseCapturedNS_ and self.AltReturnAddress5_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAltReturnAddress5>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.AltReturnAddress5), input_name='AltReturnAddress5')), namespaceprefix_ , eol_)) - if self.AltReturnAddress6 is not None: - namespaceprefix_ = self.AltReturnAddress6_nsprefix_ + ':' if (UseCapturedNS_ and self.AltReturnAddress6_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAltReturnAddress6>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.AltReturnAddress6), input_name='AltReturnAddress6')), namespaceprefix_ , eol_)) - if self.AltReturnCountry is not None: - namespaceprefix_ = self.AltReturnCountry_nsprefix_ + ':' if (UseCapturedNS_ and self.AltReturnCountry_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAltReturnCountry>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.AltReturnCountry), input_name='AltReturnCountry')), namespaceprefix_ , eol_)) - if self.LabelImportType is not None: - namespaceprefix_ = self.LabelImportType_nsprefix_ + ':' if (UseCapturedNS_ and self.LabelImportType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sLabelImportType>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.LabelImportType), input_name='LabelImportType')), namespaceprefix_ , eol_)) - if self.ePostageMailerReporting is not None: - namespaceprefix_ = self.ePostageMailerReporting_nsprefix_ + ':' if (UseCapturedNS_ and self.ePostageMailerReporting_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sePostageMailerReporting>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ePostageMailerReporting), input_name='ePostageMailerReporting')), namespaceprefix_ , eol_)) - if self.SenderFirstName is not None: - namespaceprefix_ = self.SenderFirstName_nsprefix_ + ':' if (UseCapturedNS_ and self.SenderFirstName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSenderFirstName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SenderFirstName), input_name='SenderFirstName')), namespaceprefix_ , eol_)) - if self.SenderLastName is not None: - namespaceprefix_ = self.SenderLastName_nsprefix_ + ':' if (UseCapturedNS_ and self.SenderLastName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSenderLastName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SenderLastName), input_name='SenderLastName')), namespaceprefix_ , eol_)) - if self.SenderBusinessName is not None: - namespaceprefix_ = self.SenderBusinessName_nsprefix_ + ':' if (UseCapturedNS_ and self.SenderBusinessName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSenderBusinessName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SenderBusinessName), input_name='SenderBusinessName')), namespaceprefix_ , eol_)) - if self.SenderAddress1 is not None: - namespaceprefix_ = self.SenderAddress1_nsprefix_ + ':' if (UseCapturedNS_ and self.SenderAddress1_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSenderAddress1>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SenderAddress1), input_name='SenderAddress1')), namespaceprefix_ , eol_)) - if self.SenderCity is not None: - namespaceprefix_ = self.SenderCity_nsprefix_ + ':' if (UseCapturedNS_ and self.SenderCity_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSenderCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SenderCity), input_name='SenderCity')), namespaceprefix_ , eol_)) - if self.SenderState is not None: - namespaceprefix_ = self.SenderState_nsprefix_ + ':' if (UseCapturedNS_ and self.SenderState_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSenderState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SenderState), input_name='SenderState')), namespaceprefix_ , eol_)) - if self.SenderZip5 is not None: - namespaceprefix_ = self.SenderZip5_nsprefix_ + ':' if (UseCapturedNS_ and self.SenderZip5_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSenderZip5>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SenderZip5), input_name='SenderZip5')), namespaceprefix_ , eol_)) - if self.SenderPhone is not None: - namespaceprefix_ = self.SenderPhone_nsprefix_ + ':' if (UseCapturedNS_ and self.SenderPhone_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSenderPhone>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SenderPhone), input_name='SenderPhone')), namespaceprefix_ , eol_)) - if self.ChargebackCode is not None: - namespaceprefix_ = self.ChargebackCode_nsprefix_ + ':' if (UseCapturedNS_ and self.ChargebackCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sChargebackCode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ChargebackCode), input_name='ChargebackCode')), namespaceprefix_ , eol_)) - if self.TrackingRetentionPeriod is not None: - namespaceprefix_ = self.TrackingRetentionPeriod_nsprefix_ + ':' if (UseCapturedNS_ and self.TrackingRetentionPeriod_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sTrackingRetentionPeriod>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.TrackingRetentionPeriod), input_name='TrackingRetentionPeriod')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('USERID', node) - if value is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - self.USERID = value - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'Option' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'Option') - ival_ = self.gds_validate_integer(ival_, node, 'Option') - self.Option = ival_ - self.Option_nsprefix_ = child_.prefix - elif nodeName_ == 'Revision': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Revision') - value_ = self.gds_validate_string(value_, node, 'Revision') - self.Revision = value_ - self.Revision_nsprefix_ = child_.prefix - elif nodeName_ == 'ImageParameters': - obj_ = ImageParametersType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.ImageParameters = obj_ - obj_.original_tagname_ = 'ImageParameters' - elif nodeName_ == 'FromName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromName') - value_ = self.gds_validate_string(value_, node, 'FromName') - self.FromName = value_ - self.FromName_nsprefix_ = child_.prefix - elif nodeName_ == 'FromFirm': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromFirm') - value_ = self.gds_validate_string(value_, node, 'FromFirm') - self.FromFirm = value_ - self.FromFirm_nsprefix_ = child_.prefix - elif nodeName_ == 'FromAddress1': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromAddress1') - value_ = self.gds_validate_string(value_, node, 'FromAddress1') - self.FromAddress1 = value_ - self.FromAddress1_nsprefix_ = child_.prefix - elif nodeName_ == 'FromAddress2': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromAddress2') - value_ = self.gds_validate_string(value_, node, 'FromAddress2') - self.FromAddress2 = value_ - self.FromAddress2_nsprefix_ = child_.prefix - elif nodeName_ == 'FromCity': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromCity') - value_ = self.gds_validate_string(value_, node, 'FromCity') - self.FromCity = value_ - self.FromCity_nsprefix_ = child_.prefix - elif nodeName_ == 'FromState': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromState') - value_ = self.gds_validate_string(value_, node, 'FromState') - self.FromState = value_ - self.FromState_nsprefix_ = child_.prefix - elif nodeName_ == 'FromZip5': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromZip5') - value_ = self.gds_validate_string(value_, node, 'FromZip5') - self.FromZip5 = value_ - self.FromZip5_nsprefix_ = child_.prefix - elif nodeName_ == 'FromZip4': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromZip4') - value_ = self.gds_validate_string(value_, node, 'FromZip4') - self.FromZip4 = value_ - self.FromZip4_nsprefix_ = child_.prefix - elif nodeName_ == 'FromPhone': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromPhone') - value_ = self.gds_validate_string(value_, node, 'FromPhone') - self.FromPhone = value_ - self.FromPhone_nsprefix_ = child_.prefix - elif nodeName_ == 'POZipCode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'POZipCode') - value_ = self.gds_validate_string(value_, node, 'POZipCode') - self.POZipCode = value_ - self.POZipCode_nsprefix_ = child_.prefix - elif nodeName_ == 'AllowNonCleansedOriginAddr': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'AllowNonCleansedOriginAddr') - value_ = self.gds_validate_string(value_, node, 'AllowNonCleansedOriginAddr') - self.AllowNonCleansedOriginAddr = value_ - self.AllowNonCleansedOriginAddr_nsprefix_ = child_.prefix - elif nodeName_ == 'ToName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToName') - value_ = self.gds_validate_string(value_, node, 'ToName') - self.ToName = value_ - self.ToName_nsprefix_ = child_.prefix - elif nodeName_ == 'ToFirm': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToFirm') - value_ = self.gds_validate_string(value_, node, 'ToFirm') - self.ToFirm = value_ - self.ToFirm_nsprefix_ = child_.prefix - elif nodeName_ == 'ToAddress1': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToAddress1') - value_ = self.gds_validate_string(value_, node, 'ToAddress1') - self.ToAddress1 = value_ - self.ToAddress1_nsprefix_ = child_.prefix - elif nodeName_ == 'ToAddress2': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToAddress2') - value_ = self.gds_validate_string(value_, node, 'ToAddress2') - self.ToAddress2 = value_ - self.ToAddress2_nsprefix_ = child_.prefix - elif nodeName_ == 'ToCity': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToCity') - value_ = self.gds_validate_string(value_, node, 'ToCity') - self.ToCity = value_ - self.ToCity_nsprefix_ = child_.prefix - elif nodeName_ == 'ToState': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToState') - value_ = self.gds_validate_string(value_, node, 'ToState') - self.ToState = value_ - self.ToState_nsprefix_ = child_.prefix - elif nodeName_ == 'ToZip5': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToZip5') - value_ = self.gds_validate_string(value_, node, 'ToZip5') - self.ToZip5 = value_ - self.ToZip5_nsprefix_ = child_.prefix - elif nodeName_ == 'ToZip4': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToZip4') - value_ = self.gds_validate_string(value_, node, 'ToZip4') - self.ToZip4 = value_ - self.ToZip4_nsprefix_ = child_.prefix - elif nodeName_ == 'ToPhone': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToPhone') - value_ = self.gds_validate_string(value_, node, 'ToPhone') - self.ToPhone = value_ - self.ToPhone_nsprefix_ = child_.prefix - elif nodeName_ == 'POBox': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'POBox') - value_ = self.gds_validate_string(value_, node, 'POBox') - self.POBox = value_ - self.POBox_nsprefix_ = child_.prefix - elif nodeName_ == 'ToContactPreference': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToContactPreference') - value_ = self.gds_validate_string(value_, node, 'ToContactPreference') - self.ToContactPreference = value_ - self.ToContactPreference_nsprefix_ = child_.prefix - elif nodeName_ == 'ToContactMessaging': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToContactMessaging') - value_ = self.gds_validate_string(value_, node, 'ToContactMessaging') - self.ToContactMessaging = value_ - self.ToContactMessaging_nsprefix_ = child_.prefix - elif nodeName_ == 'ToContactEmail': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToContactEmail') - value_ = self.gds_validate_string(value_, node, 'ToContactEmail') - self.ToContactEmail = value_ - self.ToContactEmail_nsprefix_ = child_.prefix - elif nodeName_ == 'AllowNonCleansedDestAddr': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'AllowNonCleansedDestAddr') - ival_ = self.gds_validate_boolean(ival_, node, 'AllowNonCleansedDestAddr') - self.AllowNonCleansedDestAddr = ival_ - self.AllowNonCleansedDestAddr_nsprefix_ = child_.prefix - elif nodeName_ == 'WeightInOunces': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'WeightInOunces') - value_ = self.gds_validate_string(value_, node, 'WeightInOunces') - self.WeightInOunces = value_ - self.WeightInOunces_nsprefix_ = child_.prefix - elif nodeName_ == 'ServiceType': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ServiceType') - value_ = self.gds_validate_string(value_, node, 'ServiceType') - self.ServiceType = value_ - self.ServiceType_nsprefix_ = child_.prefix - elif nodeName_ == 'Container': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Container') - value_ = self.gds_validate_string(value_, node, 'Container') - self.Container = value_ - self.Container_nsprefix_ = child_.prefix - elif nodeName_ == 'Width' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_decimal(sval_, node, 'Width') - fval_ = self.gds_validate_decimal(fval_, node, 'Width') - self.Width = fval_ - self.Width_nsprefix_ = child_.prefix - elif nodeName_ == 'Length' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_decimal(sval_, node, 'Length') - fval_ = self.gds_validate_decimal(fval_, node, 'Length') - self.Length = fval_ - self.Length_nsprefix_ = child_.prefix - elif nodeName_ == 'Height' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_decimal(sval_, node, 'Height') - fval_ = self.gds_validate_decimal(fval_, node, 'Height') - self.Height = fval_ - self.Height_nsprefix_ = child_.prefix - elif nodeName_ == 'Girth' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_decimal(sval_, node, 'Girth') - fval_ = self.gds_validate_decimal(fval_, node, 'Girth') - self.Girth = fval_ - self.Girth_nsprefix_ = child_.prefix - elif nodeName_ == 'Machinable': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Machinable') - value_ = self.gds_validate_string(value_, node, 'Machinable') - self.Machinable = value_ - self.Machinable_nsprefix_ = child_.prefix - elif nodeName_ == 'ProcessingCategory': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ProcessingCategory') - value_ = self.gds_validate_string(value_, node, 'ProcessingCategory') - self.ProcessingCategory = value_ - self.ProcessingCategory_nsprefix_ = child_.prefix - elif nodeName_ == 'PriceOptions': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PriceOptions') - value_ = self.gds_validate_string(value_, node, 'PriceOptions') - self.PriceOptions = value_ - self.PriceOptions_nsprefix_ = child_.prefix - elif nodeName_ == 'InsuredAmount' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_decimal(sval_, node, 'InsuredAmount') - fval_ = self.gds_validate_decimal(fval_, node, 'InsuredAmount') - self.InsuredAmount = fval_ - self.InsuredAmount_nsprefix_ = child_.prefix - elif nodeName_ == 'AddressServiceRequested': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'AddressServiceRequested') - ival_ = self.gds_validate_boolean(ival_, node, 'AddressServiceRequested') - self.AddressServiceRequested = ival_ - self.AddressServiceRequested_nsprefix_ = child_.prefix - elif nodeName_ == 'ExpressMailOptions': - obj_ = ExpressMailOptionsType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.ExpressMailOptions = obj_ - obj_.original_tagname_ = 'ExpressMailOptions' - elif nodeName_ == 'ShipDate': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ShipDate') - value_ = self.gds_validate_string(value_, node, 'ShipDate') - self.ShipDate = value_ - self.ShipDate_nsprefix_ = child_.prefix - # validate type ShipDateType - self.validate_ShipDateType(self.ShipDate) - elif nodeName_ == 'CustomerRefNo': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CustomerRefNo') - value_ = self.gds_validate_string(value_, node, 'CustomerRefNo') - self.CustomerRefNo = value_ - self.CustomerRefNo_nsprefix_ = child_.prefix - elif nodeName_ == 'CustomerRefNo2': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CustomerRefNo2') - value_ = self.gds_validate_string(value_, node, 'CustomerRefNo2') - self.CustomerRefNo2 = value_ - self.CustomerRefNo2_nsprefix_ = child_.prefix - elif nodeName_ == 'ExtraServices': - obj_ = ExtraServicesType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.ExtraServices = obj_ - obj_.original_tagname_ = 'ExtraServices' - elif nodeName_ == 'HoldForPickup': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'HoldForPickup') - value_ = self.gds_validate_string(value_, node, 'HoldForPickup') - self.HoldForPickup = value_ - self.HoldForPickup_nsprefix_ = child_.prefix - elif nodeName_ == 'OpenDistribute': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'OpenDistribute') - value_ = self.gds_validate_string(value_, node, 'OpenDistribute') - self.OpenDistribute = value_ - self.OpenDistribute_nsprefix_ = child_.prefix - elif nodeName_ == 'PermitNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PermitNumber') - value_ = self.gds_validate_string(value_, node, 'PermitNumber') - self.PermitNumber = value_ - self.PermitNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'PermitZIPCode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PermitZIPCode') - value_ = self.gds_validate_string(value_, node, 'PermitZIPCode') - self.PermitZIPCode = value_ - self.PermitZIPCode_nsprefix_ = child_.prefix - elif nodeName_ == 'PermitHolderName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PermitHolderName') - value_ = self.gds_validate_string(value_, node, 'PermitHolderName') - self.PermitHolderName = value_ - self.PermitHolderName_nsprefix_ = child_.prefix - elif nodeName_ == 'CRID': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CRID') - value_ = self.gds_validate_string(value_, node, 'CRID') - self.CRID = value_ - self.CRID_nsprefix_ = child_.prefix - elif nodeName_ == 'MID': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'MID') - value_ = self.gds_validate_string(value_, node, 'MID') - self.MID = value_ - self.MID_nsprefix_ = child_.prefix - elif nodeName_ == 'LogisticsManagerMID': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'LogisticsManagerMID') - value_ = self.gds_validate_string(value_, node, 'LogisticsManagerMID') - self.LogisticsManagerMID = value_ - self.LogisticsManagerMID_nsprefix_ = child_.prefix - elif nodeName_ == 'VendorCode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'VendorCode') - value_ = self.gds_validate_string(value_, node, 'VendorCode') - self.VendorCode = value_ - self.VendorCode_nsprefix_ = child_.prefix - elif nodeName_ == 'VendorProductVersionNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'VendorProductVersionNumber') - value_ = self.gds_validate_string(value_, node, 'VendorProductVersionNumber') - self.VendorProductVersionNumber = value_ - self.VendorProductVersionNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'SenderName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SenderName') - value_ = self.gds_validate_string(value_, node, 'SenderName') - self.SenderName = value_ - self.SenderName_nsprefix_ = child_.prefix - elif nodeName_ == 'SenderEMail': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SenderEMail') - value_ = self.gds_validate_string(value_, node, 'SenderEMail') - self.SenderEMail = value_ - self.SenderEMail_nsprefix_ = child_.prefix - elif nodeName_ == 'RecipientName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'RecipientName') - value_ = self.gds_validate_string(value_, node, 'RecipientName') - self.RecipientName = value_ - self.RecipientName_nsprefix_ = child_.prefix - elif nodeName_ == 'RecipientEMail': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'RecipientEMail') - value_ = self.gds_validate_string(value_, node, 'RecipientEMail') - self.RecipientEMail = value_ - self.RecipientEMail_nsprefix_ = child_.prefix - elif nodeName_ == 'ReceiptOption': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ReceiptOption') - value_ = self.gds_validate_string(value_, node, 'ReceiptOption') - self.ReceiptOption = value_ - self.ReceiptOption_nsprefix_ = child_.prefix - elif nodeName_ == 'ImageType': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ImageType') - value_ = self.gds_validate_string(value_, node, 'ImageType') - self.ImageType = value_ - self.ImageType_nsprefix_ = child_.prefix - elif nodeName_ == 'HoldForManifest': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'HoldForManifest') - value_ = self.gds_validate_string(value_, node, 'HoldForManifest') - self.HoldForManifest = value_ - self.HoldForManifest_nsprefix_ = child_.prefix - elif nodeName_ == 'NineDigitRoutingZip': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'NineDigitRoutingZip') - ival_ = self.gds_validate_boolean(ival_, node, 'NineDigitRoutingZip') - self.NineDigitRoutingZip = ival_ - self.NineDigitRoutingZip_nsprefix_ = child_.prefix - elif nodeName_ == 'ShipInfo': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'ShipInfo') - ival_ = self.gds_validate_boolean(ival_, node, 'ShipInfo') - self.ShipInfo = ival_ - self.ShipInfo_nsprefix_ = child_.prefix - elif nodeName_ == 'CarrierRelease': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'CarrierRelease') - ival_ = self.gds_validate_boolean(ival_, node, 'CarrierRelease') - self.CarrierRelease = ival_ - self.CarrierRelease_nsprefix_ = child_.prefix - elif nodeName_ == 'DropOffTime': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'DropOffTime') - ival_ = self.gds_validate_boolean(ival_, node, 'DropOffTime') - self.DropOffTime = ival_ - self.DropOffTime_nsprefix_ = child_.prefix - elif nodeName_ == 'ReturnCommitments': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'ReturnCommitments') - ival_ = self.gds_validate_boolean(ival_, node, 'ReturnCommitments') - self.ReturnCommitments = ival_ - self.ReturnCommitments_nsprefix_ = child_.prefix - elif nodeName_ == 'PrintCustomerRefNo': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PrintCustomerRefNo') - value_ = self.gds_validate_string(value_, node, 'PrintCustomerRefNo') - self.PrintCustomerRefNo = value_ - self.PrintCustomerRefNo_nsprefix_ = child_.prefix - elif nodeName_ == 'Content': - obj_ = ContentType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.Content = obj_ - obj_.original_tagname_ = 'Content' - elif nodeName_ == 'ActionCode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ActionCode') - value_ = self.gds_validate_string(value_, node, 'ActionCode') - self.ActionCode = value_ - self.ActionCode_nsprefix_ = child_.prefix - elif nodeName_ == 'OptOutOfSPE': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'OptOutOfSPE') - value_ = self.gds_validate_string(value_, node, 'OptOutOfSPE') - self.OptOutOfSPE = value_ - self.OptOutOfSPE_nsprefix_ = child_.prefix - elif nodeName_ == 'SortationLevel': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SortationLevel') - value_ = self.gds_validate_string(value_, node, 'SortationLevel') - self.SortationLevel = value_ - self.SortationLevel_nsprefix_ = child_.prefix - elif nodeName_ == 'DestinationEntryFacilityType': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'DestinationEntryFacilityType') - value_ = self.gds_validate_string(value_, node, 'DestinationEntryFacilityType') - self.DestinationEntryFacilityType = value_ - self.DestinationEntryFacilityType_nsprefix_ = child_.prefix - elif nodeName_ == 'ShippingContents': - obj_ = ShippingContentsType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.ShippingContents = obj_ - obj_.original_tagname_ = 'ShippingContents' - elif nodeName_ == 'CustomsContentType': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CustomsContentType') - value_ = self.gds_validate_string(value_, node, 'CustomsContentType') - self.CustomsContentType = value_ - self.CustomsContentType_nsprefix_ = child_.prefix - elif nodeName_ == 'ContentComments': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ContentComments') - value_ = self.gds_validate_string(value_, node, 'ContentComments') - self.ContentComments = value_ - self.ContentComments_nsprefix_ = child_.prefix - elif nodeName_ == 'RestrictionType': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'RestrictionType') - value_ = self.gds_validate_string(value_, node, 'RestrictionType') - self.RestrictionType = value_ - self.RestrictionType_nsprefix_ = child_.prefix - elif nodeName_ == 'RestrictionComments': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'RestrictionComments') - value_ = self.gds_validate_string(value_, node, 'RestrictionComments') - self.RestrictionComments = value_ - self.RestrictionComments_nsprefix_ = child_.prefix - elif nodeName_ == 'AESITN': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'AESITN') - value_ = self.gds_validate_string(value_, node, 'AESITN') - self.AESITN = value_ - self.AESITN_nsprefix_ = child_.prefix - elif nodeName_ == 'ImportersReference': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ImportersReference') - value_ = self.gds_validate_string(value_, node, 'ImportersReference') - self.ImportersReference = value_ - self.ImportersReference_nsprefix_ = child_.prefix - elif nodeName_ == 'ImportersContact': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ImportersContact') - value_ = self.gds_validate_string(value_, node, 'ImportersContact') - self.ImportersContact = value_ - self.ImportersContact_nsprefix_ = child_.prefix - elif nodeName_ == 'ExportersReference': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ExportersReference') - value_ = self.gds_validate_string(value_, node, 'ExportersReference') - self.ExportersReference = value_ - self.ExportersReference_nsprefix_ = child_.prefix - elif nodeName_ == 'ExportersContact': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ExportersContact') - value_ = self.gds_validate_string(value_, node, 'ExportersContact') - self.ExportersContact = value_ - self.ExportersContact_nsprefix_ = child_.prefix - elif nodeName_ == 'InvoiceNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'InvoiceNumber') - value_ = self.gds_validate_string(value_, node, 'InvoiceNumber') - self.InvoiceNumber = value_ - self.InvoiceNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'LicenseNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'LicenseNumber') - value_ = self.gds_validate_string(value_, node, 'LicenseNumber') - self.LicenseNumber = value_ - self.LicenseNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'CertificateNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CertificateNumber') - value_ = self.gds_validate_string(value_, node, 'CertificateNumber') - self.CertificateNumber = value_ - self.CertificateNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'NonDeliveryOption': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'NonDeliveryOption') - value_ = self.gds_validate_string(value_, node, 'NonDeliveryOption') - self.NonDeliveryOption = value_ - self.NonDeliveryOption_nsprefix_ = child_.prefix - elif nodeName_ == 'AltReturnAddress1': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'AltReturnAddress1') - value_ = self.gds_validate_string(value_, node, 'AltReturnAddress1') - self.AltReturnAddress1 = value_ - self.AltReturnAddress1_nsprefix_ = child_.prefix - elif nodeName_ == 'AltReturnAddress2': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'AltReturnAddress2') - value_ = self.gds_validate_string(value_, node, 'AltReturnAddress2') - self.AltReturnAddress2 = value_ - self.AltReturnAddress2_nsprefix_ = child_.prefix - elif nodeName_ == 'AltReturnAddress3': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'AltReturnAddress3') - value_ = self.gds_validate_string(value_, node, 'AltReturnAddress3') - self.AltReturnAddress3 = value_ - self.AltReturnAddress3_nsprefix_ = child_.prefix - elif nodeName_ == 'AltReturnAddress4': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'AltReturnAddress4') - value_ = self.gds_validate_string(value_, node, 'AltReturnAddress4') - self.AltReturnAddress4 = value_ - self.AltReturnAddress4_nsprefix_ = child_.prefix - elif nodeName_ == 'AltReturnAddress5': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'AltReturnAddress5') - value_ = self.gds_validate_string(value_, node, 'AltReturnAddress5') - self.AltReturnAddress5 = value_ - self.AltReturnAddress5_nsprefix_ = child_.prefix - elif nodeName_ == 'AltReturnAddress6': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'AltReturnAddress6') - value_ = self.gds_validate_string(value_, node, 'AltReturnAddress6') - self.AltReturnAddress6 = value_ - self.AltReturnAddress6_nsprefix_ = child_.prefix - elif nodeName_ == 'AltReturnCountry': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'AltReturnCountry') - value_ = self.gds_validate_string(value_, node, 'AltReturnCountry') - self.AltReturnCountry = value_ - self.AltReturnCountry_nsprefix_ = child_.prefix - elif nodeName_ == 'LabelImportType': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'LabelImportType') - value_ = self.gds_validate_string(value_, node, 'LabelImportType') - self.LabelImportType = value_ - self.LabelImportType_nsprefix_ = child_.prefix - elif nodeName_ == 'ePostageMailerReporting': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ePostageMailerReporting') - value_ = self.gds_validate_string(value_, node, 'ePostageMailerReporting') - self.ePostageMailerReporting = value_ - self.ePostageMailerReporting_nsprefix_ = child_.prefix - elif nodeName_ == 'SenderFirstName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SenderFirstName') - value_ = self.gds_validate_string(value_, node, 'SenderFirstName') - self.SenderFirstName = value_ - self.SenderFirstName_nsprefix_ = child_.prefix - elif nodeName_ == 'SenderLastName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SenderLastName') - value_ = self.gds_validate_string(value_, node, 'SenderLastName') - self.SenderLastName = value_ - self.SenderLastName_nsprefix_ = child_.prefix - elif nodeName_ == 'SenderBusinessName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SenderBusinessName') - value_ = self.gds_validate_string(value_, node, 'SenderBusinessName') - self.SenderBusinessName = value_ - self.SenderBusinessName_nsprefix_ = child_.prefix - elif nodeName_ == 'SenderAddress1': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SenderAddress1') - value_ = self.gds_validate_string(value_, node, 'SenderAddress1') - self.SenderAddress1 = value_ - self.SenderAddress1_nsprefix_ = child_.prefix - elif nodeName_ == 'SenderCity': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SenderCity') - value_ = self.gds_validate_string(value_, node, 'SenderCity') - self.SenderCity = value_ - self.SenderCity_nsprefix_ = child_.prefix - elif nodeName_ == 'SenderState': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SenderState') - value_ = self.gds_validate_string(value_, node, 'SenderState') - self.SenderState = value_ - self.SenderState_nsprefix_ = child_.prefix - elif nodeName_ == 'SenderZip5': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SenderZip5') - value_ = self.gds_validate_string(value_, node, 'SenderZip5') - self.SenderZip5 = value_ - self.SenderZip5_nsprefix_ = child_.prefix - elif nodeName_ == 'SenderPhone': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SenderPhone') - value_ = self.gds_validate_string(value_, node, 'SenderPhone') - self.SenderPhone = value_ - self.SenderPhone_nsprefix_ = child_.prefix - elif nodeName_ == 'ChargebackCode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ChargebackCode') - value_ = self.gds_validate_string(value_, node, 'ChargebackCode') - self.ChargebackCode = value_ - self.ChargebackCode_nsprefix_ = child_.prefix - elif nodeName_ == 'TrackingRetentionPeriod': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'TrackingRetentionPeriod') - value_ = self.gds_validate_string(value_, node, 'TrackingRetentionPeriod') - self.TrackingRetentionPeriod = value_ - self.TrackingRetentionPeriod_nsprefix_ = child_.prefix -# end class eVSRequest - - -class ImageParametersType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ImageParameter=None, XCoordinate=None, YCoordinate=None, LabelSequence=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.ImageParameter = ImageParameter - self.ImageParameter_nsprefix_ = None - self.XCoordinate = XCoordinate - self.XCoordinate_nsprefix_ = None - self.YCoordinate = YCoordinate - self.YCoordinate_nsprefix_ = None - self.LabelSequence = LabelSequence - self.LabelSequence_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, ImageParametersType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if ImageParametersType.subclass: - return ImageParametersType.subclass(*args_, **kwargs_) - else: - return ImageParametersType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_ImageParameter(self): - return self.ImageParameter - def set_ImageParameter(self, ImageParameter): - self.ImageParameter = ImageParameter - def get_XCoordinate(self): - return self.XCoordinate - def set_XCoordinate(self, XCoordinate): - self.XCoordinate = XCoordinate - def get_YCoordinate(self): - return self.YCoordinate - def set_YCoordinate(self, YCoordinate): - self.YCoordinate = YCoordinate - def get_LabelSequence(self): - return self.LabelSequence - def set_LabelSequence(self, LabelSequence): - self.LabelSequence = LabelSequence - def _hasContent(self): - if ( - self.ImageParameter is not None or - self.XCoordinate is not None or - self.YCoordinate is not None or - self.LabelSequence is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ImageParametersType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('ImageParametersType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'ImageParametersType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='ImageParametersType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='ImageParametersType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='ImageParametersType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ImageParametersType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.ImageParameter is not None: - namespaceprefix_ = self.ImageParameter_nsprefix_ + ':' if (UseCapturedNS_ and self.ImageParameter_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sImageParameter>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ImageParameter), input_name='ImageParameter')), namespaceprefix_ , eol_)) - if self.XCoordinate is not None: - namespaceprefix_ = self.XCoordinate_nsprefix_ + ':' if (UseCapturedNS_ and self.XCoordinate_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sXCoordinate>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.XCoordinate, input_name='XCoordinate'), namespaceprefix_ , eol_)) - if self.YCoordinate is not None: - namespaceprefix_ = self.YCoordinate_nsprefix_ + ':' if (UseCapturedNS_ and self.YCoordinate_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sYCoordinate>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.YCoordinate, input_name='YCoordinate'), namespaceprefix_ , eol_)) - if self.LabelSequence is not None: - namespaceprefix_ = self.LabelSequence_nsprefix_ + ':' if (UseCapturedNS_ and self.LabelSequence_nsprefix_) else '' - self.LabelSequence.export(outfile, level, namespaceprefix_, namespacedef_='', name_='LabelSequence', pretty_print=pretty_print) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'ImageParameter': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ImageParameter') - value_ = self.gds_validate_string(value_, node, 'ImageParameter') - self.ImageParameter = value_ - self.ImageParameter_nsprefix_ = child_.prefix - elif nodeName_ == 'XCoordinate' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'XCoordinate') - ival_ = self.gds_validate_integer(ival_, node, 'XCoordinate') - self.XCoordinate = ival_ - self.XCoordinate_nsprefix_ = child_.prefix - elif nodeName_ == 'YCoordinate' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'YCoordinate') - ival_ = self.gds_validate_integer(ival_, node, 'YCoordinate') - self.YCoordinate = ival_ - self.YCoordinate_nsprefix_ = child_.prefix - elif nodeName_ == 'LabelSequence': - obj_ = LabelSequenceType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.LabelSequence = obj_ - obj_.original_tagname_ = 'LabelSequence' -# end class ImageParametersType - - -class LabelSequenceType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, PackageNumber=None, TotalPackages=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.PackageNumber = PackageNumber - self.PackageNumber_nsprefix_ = None - self.TotalPackages = TotalPackages - self.TotalPackages_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, LabelSequenceType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if LabelSequenceType.subclass: - return LabelSequenceType.subclass(*args_, **kwargs_) - else: - return LabelSequenceType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_PackageNumber(self): - return self.PackageNumber - def set_PackageNumber(self, PackageNumber): - self.PackageNumber = PackageNumber - def get_TotalPackages(self): - return self.TotalPackages - def set_TotalPackages(self, TotalPackages): - self.TotalPackages = TotalPackages - def _hasContent(self): - if ( - self.PackageNumber is not None or - self.TotalPackages is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='LabelSequenceType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('LabelSequenceType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'LabelSequenceType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='LabelSequenceType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='LabelSequenceType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='LabelSequenceType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='LabelSequenceType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.PackageNumber is not None: - namespaceprefix_ = self.PackageNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.PackageNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPackageNumber>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.PackageNumber, input_name='PackageNumber'), namespaceprefix_ , eol_)) - if self.TotalPackages is not None: - namespaceprefix_ = self.TotalPackages_nsprefix_ + ':' if (UseCapturedNS_ and self.TotalPackages_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sTotalPackages>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.TotalPackages, input_name='TotalPackages'), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'PackageNumber' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'PackageNumber') - ival_ = self.gds_validate_integer(ival_, node, 'PackageNumber') - self.PackageNumber = ival_ - self.PackageNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'TotalPackages' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'TotalPackages') - ival_ = self.gds_validate_integer(ival_, node, 'TotalPackages') - self.TotalPackages = ival_ - self.TotalPackages_nsprefix_ = child_.prefix -# end class LabelSequenceType - - -class ExpressMailOptionsType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, DeliveryOption=None, WaiverOfSignature=None, eSOFAllowed=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.DeliveryOption = DeliveryOption - self.DeliveryOption_nsprefix_ = None - self.WaiverOfSignature = WaiverOfSignature - self.WaiverOfSignature_nsprefix_ = None - self.eSOFAllowed = eSOFAllowed - self.eSOFAllowed_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, ExpressMailOptionsType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if ExpressMailOptionsType.subclass: - return ExpressMailOptionsType.subclass(*args_, **kwargs_) - else: - return ExpressMailOptionsType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_DeliveryOption(self): - return self.DeliveryOption - def set_DeliveryOption(self, DeliveryOption): - self.DeliveryOption = DeliveryOption - def get_WaiverOfSignature(self): - return self.WaiverOfSignature - def set_WaiverOfSignature(self, WaiverOfSignature): - self.WaiverOfSignature = WaiverOfSignature - def get_eSOFAllowed(self): - return self.eSOFAllowed - def set_eSOFAllowed(self, eSOFAllowed): - self.eSOFAllowed = eSOFAllowed - def _hasContent(self): - if ( - self.DeliveryOption is not None or - self.WaiverOfSignature is not None or - self.eSOFAllowed is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ExpressMailOptionsType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('ExpressMailOptionsType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'ExpressMailOptionsType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='ExpressMailOptionsType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='ExpressMailOptionsType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='ExpressMailOptionsType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ExpressMailOptionsType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.DeliveryOption is not None: - namespaceprefix_ = self.DeliveryOption_nsprefix_ + ':' if (UseCapturedNS_ and self.DeliveryOption_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDeliveryOption>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.DeliveryOption), input_name='DeliveryOption')), namespaceprefix_ , eol_)) - if self.WaiverOfSignature is not None: - namespaceprefix_ = self.WaiverOfSignature_nsprefix_ + ':' if (UseCapturedNS_ and self.WaiverOfSignature_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sWaiverOfSignature>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.WaiverOfSignature, input_name='WaiverOfSignature'), namespaceprefix_ , eol_)) - if self.eSOFAllowed is not None: - namespaceprefix_ = self.eSOFAllowed_nsprefix_ + ':' if (UseCapturedNS_ and self.eSOFAllowed_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%seSOFAllowed>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.eSOFAllowed, input_name='eSOFAllowed'), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'DeliveryOption': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'DeliveryOption') - value_ = self.gds_validate_string(value_, node, 'DeliveryOption') - self.DeliveryOption = value_ - self.DeliveryOption_nsprefix_ = child_.prefix - elif nodeName_ == 'WaiverOfSignature': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'WaiverOfSignature') - ival_ = self.gds_validate_boolean(ival_, node, 'WaiverOfSignature') - self.WaiverOfSignature = ival_ - self.WaiverOfSignature_nsprefix_ = child_.prefix - elif nodeName_ == 'eSOFAllowed': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'eSOFAllowed') - ival_ = self.gds_validate_boolean(ival_, node, 'eSOFAllowed') - self.eSOFAllowed = ival_ - self.eSOFAllowed_nsprefix_ = child_.prefix -# end class ExpressMailOptionsType - - -class ExtraServicesType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ExtraService=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - if ExtraService is None: - self.ExtraService = [] - else: - self.ExtraService = ExtraService - self.ExtraService_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, ExtraServicesType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if ExtraServicesType.subclass: - return ExtraServicesType.subclass(*args_, **kwargs_) - else: - return ExtraServicesType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_ExtraService(self): - return self.ExtraService - def set_ExtraService(self, ExtraService): - self.ExtraService = ExtraService - def add_ExtraService(self, value): - self.ExtraService.append(value) - def insert_ExtraService_at(self, index, value): - self.ExtraService.insert(index, value) - def replace_ExtraService_at(self, index, value): - self.ExtraService[index] = value - def _hasContent(self): - if ( - self.ExtraService - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ExtraServicesType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('ExtraServicesType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'ExtraServicesType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='ExtraServicesType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='ExtraServicesType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='ExtraServicesType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ExtraServicesType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - for ExtraService_ in self.ExtraService: - namespaceprefix_ = self.ExtraService_nsprefix_ + ':' if (UseCapturedNS_ and self.ExtraService_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sExtraService>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(ExtraService_), input_name='ExtraService')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'ExtraService': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ExtraService') - value_ = self.gds_validate_string(value_, node, 'ExtraService') - self.ExtraService.append(value_) - self.ExtraService_nsprefix_ = child_.prefix -# end class ExtraServicesType - - -class ContentType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ContentType_member=None, ContentDescription=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.ContentType = ContentType_member - self.ContentType_nsprefix_ = None - self.ContentDescription = ContentDescription - self.ContentDescription_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, ContentType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if ContentType.subclass: - return ContentType.subclass(*args_, **kwargs_) - else: - return ContentType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_ContentType(self): - return self.ContentType - def set_ContentType(self, ContentType): - self.ContentType = ContentType - def get_ContentDescription(self): - return self.ContentDescription - def set_ContentDescription(self, ContentDescription): - self.ContentDescription = ContentDescription - def _hasContent(self): - if ( - self.ContentType is not None or - self.ContentDescription is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ContentType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('ContentType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'ContentType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='ContentType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='ContentType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='ContentType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ContentType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.ContentType is not None: - namespaceprefix_ = self.ContentType_nsprefix_ + ':' if (UseCapturedNS_ and self.ContentType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sContentType>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ContentType), input_name='ContentType')), namespaceprefix_ , eol_)) - if self.ContentDescription is not None: - namespaceprefix_ = self.ContentDescription_nsprefix_ + ':' if (UseCapturedNS_ and self.ContentDescription_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sContentDescription>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ContentDescription), input_name='ContentDescription')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'ContentType': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ContentType') - value_ = self.gds_validate_string(value_, node, 'ContentType') - self.ContentType = value_ - self.ContentType_nsprefix_ = child_.prefix - elif nodeName_ == 'ContentDescription': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ContentDescription') - value_ = self.gds_validate_string(value_, node, 'ContentDescription') - self.ContentDescription = value_ - self.ContentDescription_nsprefix_ = child_.prefix -# end class ContentType - - -class ShippingContentsType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ItemDetail=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - if ItemDetail is None: - self.ItemDetail = [] - else: - self.ItemDetail = ItemDetail - self.ItemDetail_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, ShippingContentsType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if ShippingContentsType.subclass: - return ShippingContentsType.subclass(*args_, **kwargs_) - else: - return ShippingContentsType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_ItemDetail(self): - return self.ItemDetail - def set_ItemDetail(self, ItemDetail): - self.ItemDetail = ItemDetail - def add_ItemDetail(self, value): - self.ItemDetail.append(value) - def insert_ItemDetail_at(self, index, value): - self.ItemDetail.insert(index, value) - def replace_ItemDetail_at(self, index, value): - self.ItemDetail[index] = value - def _hasContent(self): - if ( - self.ItemDetail - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ShippingContentsType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('ShippingContentsType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'ShippingContentsType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='ShippingContentsType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='ShippingContentsType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='ShippingContentsType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ShippingContentsType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - for ItemDetail_ in self.ItemDetail: - namespaceprefix_ = self.ItemDetail_nsprefix_ + ':' if (UseCapturedNS_ and self.ItemDetail_nsprefix_) else '' - ItemDetail_.export(outfile, level, namespaceprefix_, namespacedef_='', name_='ItemDetail', pretty_print=pretty_print) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'ItemDetail': - obj_ = ItemDetailType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.ItemDetail.append(obj_) - obj_.original_tagname_ = 'ItemDetail' -# end class ShippingContentsType - - -class ItemDetailType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, Description=None, Quantity=None, Value=None, NetPounds=None, NetOunces=None, HSTariffNumber=None, CountryOfOrigin=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.Description = Description - self.Description_nsprefix_ = None - self.Quantity = Quantity - self.Quantity_nsprefix_ = None - self.Value = Value - self.Value_nsprefix_ = None - self.NetPounds = NetPounds - self.NetPounds_nsprefix_ = None - self.NetOunces = NetOunces - self.NetOunces_nsprefix_ = None - self.HSTariffNumber = HSTariffNumber - self.HSTariffNumber_nsprefix_ = None - self.CountryOfOrigin = CountryOfOrigin - self.CountryOfOrigin_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, ItemDetailType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if ItemDetailType.subclass: - return ItemDetailType.subclass(*args_, **kwargs_) - else: - return ItemDetailType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_Description(self): - return self.Description - def set_Description(self, Description): - self.Description = Description - def get_Quantity(self): - return self.Quantity - def set_Quantity(self, Quantity): - self.Quantity = Quantity - def get_Value(self): - return self.Value - def set_Value(self, Value): - self.Value = Value - def get_NetPounds(self): - return self.NetPounds - def set_NetPounds(self, NetPounds): - self.NetPounds = NetPounds - def get_NetOunces(self): - return self.NetOunces - def set_NetOunces(self, NetOunces): - self.NetOunces = NetOunces - def get_HSTariffNumber(self): - return self.HSTariffNumber - def set_HSTariffNumber(self, HSTariffNumber): - self.HSTariffNumber = HSTariffNumber - def get_CountryOfOrigin(self): - return self.CountryOfOrigin - def set_CountryOfOrigin(self, CountryOfOrigin): - self.CountryOfOrigin = CountryOfOrigin - def _hasContent(self): - if ( - self.Description is not None or - self.Quantity is not None or - self.Value is not None or - self.NetPounds is not None or - self.NetOunces is not None or - self.HSTariffNumber is not None or - self.CountryOfOrigin is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ItemDetailType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('ItemDetailType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'ItemDetailType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='ItemDetailType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='ItemDetailType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='ItemDetailType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ItemDetailType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.Description is not None: - namespaceprefix_ = self.Description_nsprefix_ + ':' if (UseCapturedNS_ and self.Description_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDescription>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Description), input_name='Description')), namespaceprefix_ , eol_)) - if self.Quantity is not None: - namespaceprefix_ = self.Quantity_nsprefix_ + ':' if (UseCapturedNS_ and self.Quantity_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sQuantity>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.Quantity, input_name='Quantity'), namespaceprefix_ , eol_)) - if self.Value is not None: - namespaceprefix_ = self.Value_nsprefix_ + ':' if (UseCapturedNS_ and self.Value_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sValue>%s%s' % (namespaceprefix_ , self.gds_format_float(self.Value, input_name='Value'), namespaceprefix_ , eol_)) - if self.NetPounds is not None: - namespaceprefix_ = self.NetPounds_nsprefix_ + ':' if (UseCapturedNS_ and self.NetPounds_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sNetPounds>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.NetPounds), input_name='NetPounds')), namespaceprefix_ , eol_)) - if self.NetOunces is not None: - namespaceprefix_ = self.NetOunces_nsprefix_ + ':' if (UseCapturedNS_ and self.NetOunces_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sNetOunces>%s%s' % (namespaceprefix_ , self.gds_format_float(self.NetOunces, input_name='NetOunces'), namespaceprefix_ , eol_)) - if self.HSTariffNumber is not None: - namespaceprefix_ = self.HSTariffNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.HSTariffNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sHSTariffNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.HSTariffNumber), input_name='HSTariffNumber')), namespaceprefix_ , eol_)) - if self.CountryOfOrigin is not None: - namespaceprefix_ = self.CountryOfOrigin_nsprefix_ + ':' if (UseCapturedNS_ and self.CountryOfOrigin_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCountryOfOrigin>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CountryOfOrigin), input_name='CountryOfOrigin')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'Description': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Description') - value_ = self.gds_validate_string(value_, node, 'Description') - self.Description = value_ - self.Description_nsprefix_ = child_.prefix - elif nodeName_ == 'Quantity' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'Quantity') - ival_ = self.gds_validate_integer(ival_, node, 'Quantity') - self.Quantity = ival_ - self.Quantity_nsprefix_ = child_.prefix - elif nodeName_ == 'Value' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'Value') - fval_ = self.gds_validate_float(fval_, node, 'Value') - self.Value = fval_ - self.Value_nsprefix_ = child_.prefix - elif nodeName_ == 'NetPounds': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'NetPounds') - value_ = self.gds_validate_string(value_, node, 'NetPounds') - self.NetPounds = value_ - self.NetPounds_nsprefix_ = child_.prefix - elif nodeName_ == 'NetOunces' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'NetOunces') - fval_ = self.gds_validate_float(fval_, node, 'NetOunces') - self.NetOunces = fval_ - self.NetOunces_nsprefix_ = child_.prefix - elif nodeName_ == 'HSTariffNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'HSTariffNumber') - value_ = self.gds_validate_string(value_, node, 'HSTariffNumber') - self.HSTariffNumber = value_ - self.HSTariffNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'CountryOfOrigin': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CountryOfOrigin') - value_ = self.gds_validate_string(value_, node, 'CountryOfOrigin') - self.CountryOfOrigin = value_ - self.CountryOfOrigin_nsprefix_ = child_.prefix -# end class ItemDetailType - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSRequest' - rootClass = eVSRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSRequest' - rootClass = eVSRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSRequest' - rootClass = eVSRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSRequest' - rootClass = eVSRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from evs_request import *\n\n') - sys.stdout.write('import evs_request as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "ContentType", - "ExpressMailOptionsType", - "ExtraServicesType", - "ImageParametersType", - "ItemDetailType", - "LabelSequenceType", - "ShippingContentsType", - "eVSRequest" -] diff --git a/schemas/usps/karrio/schemas/usps/evs_response.py b/schemas/usps/karrio/schemas/usps/evs_response.py deleted file mode 100644 index 2fcde0bd58..0000000000 --- a/schemas/usps/karrio/schemas/usps/evs_response.py +++ /dev/null @@ -1,1968 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:14 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/evs_response.py') -# -# Command line arguments: -# ./schemas/eVSResponse.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/evs_response.py" ./schemas/eVSResponse.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class eVSResponse(GeneratedsSuper): - """LabelImage -- over 115000 suppressed - - """ - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, BarcodeNumber=None, LabelImage=None, ToName=None, ToFirm=None, ToAddress1=None, ToAddress2=None, ToCity=None, ToState=None, ToZip5=None, ToZip4=None, Postnet=None, RDC=None, Postage=None, ExtraServices=None, Zone=None, CarrierRoute=None, PermitHolderName=None, InductionType=None, LogMessage=None, Commitment=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.BarcodeNumber = BarcodeNumber - self.BarcodeNumber_nsprefix_ = None - self.LabelImage = LabelImage - self.LabelImage_nsprefix_ = None - self.ToName = ToName - self.ToName_nsprefix_ = None - self.ToFirm = ToFirm - self.ToFirm_nsprefix_ = None - self.ToAddress1 = ToAddress1 - self.ToAddress1_nsprefix_ = None - self.ToAddress2 = ToAddress2 - self.ToAddress2_nsprefix_ = None - self.ToCity = ToCity - self.ToCity_nsprefix_ = None - self.ToState = ToState - self.ToState_nsprefix_ = None - self.ToZip5 = ToZip5 - self.ToZip5_nsprefix_ = None - self.ToZip4 = ToZip4 - self.ToZip4_nsprefix_ = None - self.Postnet = Postnet - self.Postnet_nsprefix_ = None - self.RDC = RDC - self.RDC_nsprefix_ = None - self.Postage = Postage - self.Postage_nsprefix_ = None - self.ExtraServices = ExtraServices - self.ExtraServices_nsprefix_ = None - self.Zone = Zone - self.Zone_nsprefix_ = None - self.CarrierRoute = CarrierRoute - self.CarrierRoute_nsprefix_ = None - self.PermitHolderName = PermitHolderName - self.PermitHolderName_nsprefix_ = None - self.InductionType = InductionType - self.InductionType_nsprefix_ = None - self.LogMessage = LogMessage - self.LogMessage_nsprefix_ = None - self.Commitment = Commitment - self.Commitment_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, eVSResponse) - if subclass is not None: - return subclass(*args_, **kwargs_) - if eVSResponse.subclass: - return eVSResponse.subclass(*args_, **kwargs_) - else: - return eVSResponse(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_BarcodeNumber(self): - return self.BarcodeNumber - def set_BarcodeNumber(self, BarcodeNumber): - self.BarcodeNumber = BarcodeNumber - def get_LabelImage(self): - return self.LabelImage - def set_LabelImage(self, LabelImage): - self.LabelImage = LabelImage - def get_ToName(self): - return self.ToName - def set_ToName(self, ToName): - self.ToName = ToName - def get_ToFirm(self): - return self.ToFirm - def set_ToFirm(self, ToFirm): - self.ToFirm = ToFirm - def get_ToAddress1(self): - return self.ToAddress1 - def set_ToAddress1(self, ToAddress1): - self.ToAddress1 = ToAddress1 - def get_ToAddress2(self): - return self.ToAddress2 - def set_ToAddress2(self, ToAddress2): - self.ToAddress2 = ToAddress2 - def get_ToCity(self): - return self.ToCity - def set_ToCity(self, ToCity): - self.ToCity = ToCity - def get_ToState(self): - return self.ToState - def set_ToState(self, ToState): - self.ToState = ToState - def get_ToZip5(self): - return self.ToZip5 - def set_ToZip5(self, ToZip5): - self.ToZip5 = ToZip5 - def get_ToZip4(self): - return self.ToZip4 - def set_ToZip4(self, ToZip4): - self.ToZip4 = ToZip4 - def get_Postnet(self): - return self.Postnet - def set_Postnet(self, Postnet): - self.Postnet = Postnet - def get_RDC(self): - return self.RDC - def set_RDC(self, RDC): - self.RDC = RDC - def get_Postage(self): - return self.Postage - def set_Postage(self, Postage): - self.Postage = Postage - def get_ExtraServices(self): - return self.ExtraServices - def set_ExtraServices(self, ExtraServices): - self.ExtraServices = ExtraServices - def get_Zone(self): - return self.Zone - def set_Zone(self, Zone): - self.Zone = Zone - def get_CarrierRoute(self): - return self.CarrierRoute - def set_CarrierRoute(self, CarrierRoute): - self.CarrierRoute = CarrierRoute - def get_PermitHolderName(self): - return self.PermitHolderName - def set_PermitHolderName(self, PermitHolderName): - self.PermitHolderName = PermitHolderName - def get_InductionType(self): - return self.InductionType - def set_InductionType(self, InductionType): - self.InductionType = InductionType - def get_LogMessage(self): - return self.LogMessage - def set_LogMessage(self, LogMessage): - self.LogMessage = LogMessage - def get_Commitment(self): - return self.Commitment - def set_Commitment(self, Commitment): - self.Commitment = Commitment - def _hasContent(self): - if ( - self.BarcodeNumber is not None or - self.LabelImage is not None or - self.ToName is not None or - self.ToFirm is not None or - self.ToAddress1 is not None or - self.ToAddress2 is not None or - self.ToCity is not None or - self.ToState is not None or - self.ToZip5 is not None or - self.ToZip4 is not None or - self.Postnet is not None or - self.RDC is not None or - self.Postage is not None or - self.ExtraServices is not None or - self.Zone is not None or - self.CarrierRoute is not None or - self.PermitHolderName is not None or - self.InductionType is not None or - self.LogMessage is not None or - self.Commitment is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='eVSResponse', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('eVSResponse') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'eVSResponse': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='eVSResponse') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='eVSResponse', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='eVSResponse'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='eVSResponse', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.BarcodeNumber is not None: - namespaceprefix_ = self.BarcodeNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.BarcodeNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sBarcodeNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.BarcodeNumber), input_name='BarcodeNumber')), namespaceprefix_ , eol_)) - if self.LabelImage is not None: - namespaceprefix_ = self.LabelImage_nsprefix_ + ':' if (UseCapturedNS_ and self.LabelImage_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sLabelImage>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.LabelImage), input_name='LabelImage')), namespaceprefix_ , eol_)) - if self.ToName is not None: - namespaceprefix_ = self.ToName_nsprefix_ + ':' if (UseCapturedNS_ and self.ToName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToName), input_name='ToName')), namespaceprefix_ , eol_)) - if self.ToFirm is not None: - namespaceprefix_ = self.ToFirm_nsprefix_ + ':' if (UseCapturedNS_ and self.ToFirm_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToFirm>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToFirm), input_name='ToFirm')), namespaceprefix_ , eol_)) - if self.ToAddress1 is not None: - namespaceprefix_ = self.ToAddress1_nsprefix_ + ':' if (UseCapturedNS_ and self.ToAddress1_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToAddress1>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToAddress1), input_name='ToAddress1')), namespaceprefix_ , eol_)) - if self.ToAddress2 is not None: - namespaceprefix_ = self.ToAddress2_nsprefix_ + ':' if (UseCapturedNS_ and self.ToAddress2_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToAddress2>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToAddress2), input_name='ToAddress2')), namespaceprefix_ , eol_)) - if self.ToCity is not None: - namespaceprefix_ = self.ToCity_nsprefix_ + ':' if (UseCapturedNS_ and self.ToCity_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToCity), input_name='ToCity')), namespaceprefix_ , eol_)) - if self.ToState is not None: - namespaceprefix_ = self.ToState_nsprefix_ + ':' if (UseCapturedNS_ and self.ToState_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ToState), input_name='ToState')), namespaceprefix_ , eol_)) - if self.ToZip5 is not None: - namespaceprefix_ = self.ToZip5_nsprefix_ + ':' if (UseCapturedNS_ and self.ToZip5_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToZip5>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.ToZip5, input_name='ToZip5'), namespaceprefix_ , eol_)) - if self.ToZip4 is not None: - namespaceprefix_ = self.ToZip4_nsprefix_ + ':' if (UseCapturedNS_ and self.ToZip4_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sToZip4>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.ToZip4, input_name='ToZip4'), namespaceprefix_ , eol_)) - if self.Postnet is not None: - namespaceprefix_ = self.Postnet_nsprefix_ + ':' if (UseCapturedNS_ and self.Postnet_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPostnet>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.Postnet, input_name='Postnet'), namespaceprefix_ , eol_)) - if self.RDC is not None: - namespaceprefix_ = self.RDC_nsprefix_ + ':' if (UseCapturedNS_ and self.RDC_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRDC>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.RDC), input_name='RDC')), namespaceprefix_ , eol_)) - if self.Postage is not None: - namespaceprefix_ = self.Postage_nsprefix_ + ':' if (UseCapturedNS_ and self.Postage_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPostage>%s%s' % (namespaceprefix_ , self.gds_format_float(self.Postage, input_name='Postage'), namespaceprefix_ , eol_)) - if self.ExtraServices is not None: - namespaceprefix_ = self.ExtraServices_nsprefix_ + ':' if (UseCapturedNS_ and self.ExtraServices_nsprefix_) else '' - self.ExtraServices.export(outfile, level, namespaceprefix_, namespacedef_='', name_='ExtraServices', pretty_print=pretty_print) - if self.Zone is not None: - namespaceprefix_ = self.Zone_nsprefix_ + ':' if (UseCapturedNS_ and self.Zone_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sZone>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Zone), input_name='Zone')), namespaceprefix_ , eol_)) - if self.CarrierRoute is not None: - namespaceprefix_ = self.CarrierRoute_nsprefix_ + ':' if (UseCapturedNS_ and self.CarrierRoute_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCarrierRoute>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CarrierRoute), input_name='CarrierRoute')), namespaceprefix_ , eol_)) - if self.PermitHolderName is not None: - namespaceprefix_ = self.PermitHolderName_nsprefix_ + ':' if (UseCapturedNS_ and self.PermitHolderName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPermitHolderName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PermitHolderName), input_name='PermitHolderName')), namespaceprefix_ , eol_)) - if self.InductionType is not None: - namespaceprefix_ = self.InductionType_nsprefix_ + ':' if (UseCapturedNS_ and self.InductionType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sInductionType>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.InductionType), input_name='InductionType')), namespaceprefix_ , eol_)) - if self.LogMessage is not None: - namespaceprefix_ = self.LogMessage_nsprefix_ + ':' if (UseCapturedNS_ and self.LogMessage_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sLogMessage>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.LogMessage), input_name='LogMessage')), namespaceprefix_ , eol_)) - if self.Commitment is not None: - namespaceprefix_ = self.Commitment_nsprefix_ + ':' if (UseCapturedNS_ and self.Commitment_nsprefix_) else '' - self.Commitment.export(outfile, level, namespaceprefix_, namespacedef_='', name_='Commitment', pretty_print=pretty_print) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'BarcodeNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'BarcodeNumber') - value_ = self.gds_validate_string(value_, node, 'BarcodeNumber') - self.BarcodeNumber = value_ - self.BarcodeNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'LabelImage': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'LabelImage') - value_ = self.gds_validate_string(value_, node, 'LabelImage') - self.LabelImage = value_ - self.LabelImage_nsprefix_ = child_.prefix - elif nodeName_ == 'ToName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToName') - value_ = self.gds_validate_string(value_, node, 'ToName') - self.ToName = value_ - self.ToName_nsprefix_ = child_.prefix - elif nodeName_ == 'ToFirm': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToFirm') - value_ = self.gds_validate_string(value_, node, 'ToFirm') - self.ToFirm = value_ - self.ToFirm_nsprefix_ = child_.prefix - elif nodeName_ == 'ToAddress1': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToAddress1') - value_ = self.gds_validate_string(value_, node, 'ToAddress1') - self.ToAddress1 = value_ - self.ToAddress1_nsprefix_ = child_.prefix - elif nodeName_ == 'ToAddress2': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToAddress2') - value_ = self.gds_validate_string(value_, node, 'ToAddress2') - self.ToAddress2 = value_ - self.ToAddress2_nsprefix_ = child_.prefix - elif nodeName_ == 'ToCity': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToCity') - value_ = self.gds_validate_string(value_, node, 'ToCity') - self.ToCity = value_ - self.ToCity_nsprefix_ = child_.prefix - elif nodeName_ == 'ToState': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ToState') - value_ = self.gds_validate_string(value_, node, 'ToState') - self.ToState = value_ - self.ToState_nsprefix_ = child_.prefix - elif nodeName_ == 'ToZip5' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'ToZip5') - ival_ = self.gds_validate_integer(ival_, node, 'ToZip5') - self.ToZip5 = ival_ - self.ToZip5_nsprefix_ = child_.prefix - elif nodeName_ == 'ToZip4' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'ToZip4') - ival_ = self.gds_validate_integer(ival_, node, 'ToZip4') - self.ToZip4 = ival_ - self.ToZip4_nsprefix_ = child_.prefix - elif nodeName_ == 'Postnet' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'Postnet') - ival_ = self.gds_validate_integer(ival_, node, 'Postnet') - self.Postnet = ival_ - self.Postnet_nsprefix_ = child_.prefix - elif nodeName_ == 'RDC': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'RDC') - value_ = self.gds_validate_string(value_, node, 'RDC') - self.RDC = value_ - self.RDC_nsprefix_ = child_.prefix - elif nodeName_ == 'Postage' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'Postage') - fval_ = self.gds_validate_float(fval_, node, 'Postage') - self.Postage = fval_ - self.Postage_nsprefix_ = child_.prefix - elif nodeName_ == 'ExtraServices': - obj_ = ExtraServicesType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.ExtraServices = obj_ - obj_.original_tagname_ = 'ExtraServices' - elif nodeName_ == 'Zone': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Zone') - value_ = self.gds_validate_string(value_, node, 'Zone') - self.Zone = value_ - self.Zone_nsprefix_ = child_.prefix - elif nodeName_ == 'CarrierRoute': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CarrierRoute') - value_ = self.gds_validate_string(value_, node, 'CarrierRoute') - self.CarrierRoute = value_ - self.CarrierRoute_nsprefix_ = child_.prefix - elif nodeName_ == 'PermitHolderName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PermitHolderName') - value_ = self.gds_validate_string(value_, node, 'PermitHolderName') - self.PermitHolderName = value_ - self.PermitHolderName_nsprefix_ = child_.prefix - elif nodeName_ == 'InductionType': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'InductionType') - value_ = self.gds_validate_string(value_, node, 'InductionType') - self.InductionType = value_ - self.InductionType_nsprefix_ = child_.prefix - elif nodeName_ == 'LogMessage': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'LogMessage') - value_ = self.gds_validate_string(value_, node, 'LogMessage') - self.LogMessage = value_ - self.LogMessage_nsprefix_ = child_.prefix - elif nodeName_ == 'Commitment': - obj_ = CommitmentType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.Commitment = obj_ - obj_.original_tagname_ = 'Commitment' -# end class eVSResponse - - -class ExtraServicesType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ExtraService=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - if ExtraService is None: - self.ExtraService = [] - else: - self.ExtraService = ExtraService - self.ExtraService_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, ExtraServicesType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if ExtraServicesType.subclass: - return ExtraServicesType.subclass(*args_, **kwargs_) - else: - return ExtraServicesType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_ExtraService(self): - return self.ExtraService - def set_ExtraService(self, ExtraService): - self.ExtraService = ExtraService - def add_ExtraService(self, value): - self.ExtraService.append(value) - def insert_ExtraService_at(self, index, value): - self.ExtraService.insert(index, value) - def replace_ExtraService_at(self, index, value): - self.ExtraService[index] = value - def _hasContent(self): - if ( - self.ExtraService - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ExtraServicesType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('ExtraServicesType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'ExtraServicesType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='ExtraServicesType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='ExtraServicesType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='ExtraServicesType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ExtraServicesType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - for ExtraService_ in self.ExtraService: - namespaceprefix_ = self.ExtraService_nsprefix_ + ':' if (UseCapturedNS_ and self.ExtraService_nsprefix_) else '' - ExtraService_.export(outfile, level, namespaceprefix_, namespacedef_='', name_='ExtraService', pretty_print=pretty_print) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'ExtraService': - obj_ = ExtraServiceType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.ExtraService.append(obj_) - obj_.original_tagname_ = 'ExtraService' -# end class ExtraServicesType - - -class ExtraServiceType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ServiceID=None, ServiceName=None, Price=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.ServiceID = ServiceID - self.ServiceID_nsprefix_ = None - self.ServiceName = ServiceName - self.ServiceName_nsprefix_ = None - self.Price = Price - self.Price_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, ExtraServiceType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if ExtraServiceType.subclass: - return ExtraServiceType.subclass(*args_, **kwargs_) - else: - return ExtraServiceType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_ServiceID(self): - return self.ServiceID - def set_ServiceID(self, ServiceID): - self.ServiceID = ServiceID - def get_ServiceName(self): - return self.ServiceName - def set_ServiceName(self, ServiceName): - self.ServiceName = ServiceName - def get_Price(self): - return self.Price - def set_Price(self, Price): - self.Price = Price - def _hasContent(self): - if ( - self.ServiceID is not None or - self.ServiceName is not None or - self.Price is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ExtraServiceType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('ExtraServiceType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'ExtraServiceType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='ExtraServiceType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='ExtraServiceType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='ExtraServiceType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ExtraServiceType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.ServiceID is not None: - namespaceprefix_ = self.ServiceID_nsprefix_ + ':' if (UseCapturedNS_ and self.ServiceID_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sServiceID>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.ServiceID, input_name='ServiceID'), namespaceprefix_ , eol_)) - if self.ServiceName is not None: - namespaceprefix_ = self.ServiceName_nsprefix_ + ':' if (UseCapturedNS_ and self.ServiceName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sServiceName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ServiceName), input_name='ServiceName')), namespaceprefix_ , eol_)) - if self.Price is not None: - namespaceprefix_ = self.Price_nsprefix_ + ':' if (UseCapturedNS_ and self.Price_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPrice>%s%s' % (namespaceprefix_ , self.gds_format_float(self.Price, input_name='Price'), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'ServiceID' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'ServiceID') - ival_ = self.gds_validate_integer(ival_, node, 'ServiceID') - self.ServiceID = ival_ - self.ServiceID_nsprefix_ = child_.prefix - elif nodeName_ == 'ServiceName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ServiceName') - value_ = self.gds_validate_string(value_, node, 'ServiceName') - self.ServiceName = value_ - self.ServiceName_nsprefix_ = child_.prefix - elif nodeName_ == 'Price' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'Price') - fval_ = self.gds_validate_float(fval_, node, 'Price') - self.Price = fval_ - self.Price_nsprefix_ = child_.prefix -# end class ExtraServiceType - - -class CommitmentType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, CommitmentName=None, ScheduledDeliveryDate=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.CommitmentName = CommitmentName - self.CommitmentName_nsprefix_ = None - self.ScheduledDeliveryDate = ScheduledDeliveryDate - self.ScheduledDeliveryDate_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, CommitmentType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if CommitmentType.subclass: - return CommitmentType.subclass(*args_, **kwargs_) - else: - return CommitmentType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_CommitmentName(self): - return self.CommitmentName - def set_CommitmentName(self, CommitmentName): - self.CommitmentName = CommitmentName - def get_ScheduledDeliveryDate(self): - return self.ScheduledDeliveryDate - def set_ScheduledDeliveryDate(self, ScheduledDeliveryDate): - self.ScheduledDeliveryDate = ScheduledDeliveryDate - def _hasContent(self): - if ( - self.CommitmentName is not None or - self.ScheduledDeliveryDate is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='CommitmentType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('CommitmentType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'CommitmentType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='CommitmentType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='CommitmentType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='CommitmentType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='CommitmentType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.CommitmentName is not None: - namespaceprefix_ = self.CommitmentName_nsprefix_ + ':' if (UseCapturedNS_ and self.CommitmentName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCommitmentName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CommitmentName), input_name='CommitmentName')), namespaceprefix_ , eol_)) - if self.ScheduledDeliveryDate is not None: - namespaceprefix_ = self.ScheduledDeliveryDate_nsprefix_ + ':' if (UseCapturedNS_ and self.ScheduledDeliveryDate_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sScheduledDeliveryDate>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ScheduledDeliveryDate), input_name='ScheduledDeliveryDate')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'CommitmentName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CommitmentName') - value_ = self.gds_validate_string(value_, node, 'CommitmentName') - self.CommitmentName = value_ - self.CommitmentName_nsprefix_ = child_.prefix - elif nodeName_ == 'ScheduledDeliveryDate': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ScheduledDeliveryDate') - value_ = self.gds_validate_string(value_, node, 'ScheduledDeliveryDate') - self.ScheduledDeliveryDate = value_ - self.ScheduledDeliveryDate_nsprefix_ = child_.prefix -# end class CommitmentType - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSResponse' - rootClass = eVSResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSResponse' - rootClass = eVSResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSResponse' - rootClass = eVSResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSResponse' - rootClass = eVSResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from evs_response import *\n\n') - sys.stdout.write('import evs_response as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "CommitmentType", - "ExtraServiceType", - "ExtraServicesType", - "eVSResponse" -] diff --git a/schemas/usps/karrio/schemas/usps/evsi_cancel_request.py b/schemas/usps/karrio/schemas/usps/evsi_cancel_request.py deleted file mode 100644 index 3456e6e17a..0000000000 --- a/schemas/usps/karrio/schemas/usps/evsi_cancel_request.py +++ /dev/null @@ -1,1311 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:15 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/evsi_cancel_request.py') -# -# Command line arguments: -# ./schemas/eVSICancelRequest.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/evsi_cancel_request.py" ./schemas/eVSICancelRequest.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class eVSICancelRequest(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, USERID=None, BarcodeNumber=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.USERID = _cast(None, USERID) - self.USERID_nsprefix_ = None - self.BarcodeNumber = BarcodeNumber - self.BarcodeNumber_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, eVSICancelRequest) - if subclass is not None: - return subclass(*args_, **kwargs_) - if eVSICancelRequest.subclass: - return eVSICancelRequest.subclass(*args_, **kwargs_) - else: - return eVSICancelRequest(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_BarcodeNumber(self): - return self.BarcodeNumber - def set_BarcodeNumber(self, BarcodeNumber): - self.BarcodeNumber = BarcodeNumber - def get_USERID(self): - return self.USERID - def set_USERID(self, USERID): - self.USERID = USERID - def _hasContent(self): - if ( - self.BarcodeNumber is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='eVSICancelRequest', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('eVSICancelRequest') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'eVSICancelRequest': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='eVSICancelRequest') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='eVSICancelRequest', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='eVSICancelRequest'): - if self.USERID is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - outfile.write(' USERID=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.USERID), input_name='USERID')), )) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='eVSICancelRequest', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.BarcodeNumber is not None: - namespaceprefix_ = self.BarcodeNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.BarcodeNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sBarcodeNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.BarcodeNumber), input_name='BarcodeNumber')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('USERID', node) - if value is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - self.USERID = value - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'BarcodeNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'BarcodeNumber') - value_ = self.gds_validate_string(value_, node, 'BarcodeNumber') - self.BarcodeNumber = value_ - self.BarcodeNumber_nsprefix_ = child_.prefix -# end class eVSICancelRequest - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSICancelRequest' - rootClass = eVSICancelRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSICancelRequest' - rootClass = eVSICancelRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSICancelRequest' - rootClass = eVSICancelRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSICancelRequest' - rootClass = eVSICancelRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from evsi_cancel_request import *\n\n') - sys.stdout.write('import evsi_cancel_request as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "eVSICancelRequest" -] diff --git a/schemas/usps/karrio/schemas/usps/evsi_cancel_response.py b/schemas/usps/karrio/schemas/usps/evsi_cancel_response.py deleted file mode 100644 index 6b576a687d..0000000000 --- a/schemas/usps/karrio/schemas/usps/evsi_cancel_response.py +++ /dev/null @@ -1,1334 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:15 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/evsi_cancel_response.py') -# -# Command line arguments: -# ./schemas/eVSICancelResponse.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/evsi_cancel_response.py" ./schemas/eVSICancelResponse.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class eVSICancelResponse(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, BarcodeNumber=None, Status=None, Reason=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.BarcodeNumber = BarcodeNumber - self.BarcodeNumber_nsprefix_ = None - self.Status = Status - self.Status_nsprefix_ = None - self.Reason = Reason - self.Reason_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, eVSICancelResponse) - if subclass is not None: - return subclass(*args_, **kwargs_) - if eVSICancelResponse.subclass: - return eVSICancelResponse.subclass(*args_, **kwargs_) - else: - return eVSICancelResponse(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_BarcodeNumber(self): - return self.BarcodeNumber - def set_BarcodeNumber(self, BarcodeNumber): - self.BarcodeNumber = BarcodeNumber - def get_Status(self): - return self.Status - def set_Status(self, Status): - self.Status = Status - def get_Reason(self): - return self.Reason - def set_Reason(self, Reason): - self.Reason = Reason - def _hasContent(self): - if ( - self.BarcodeNumber is not None or - self.Status is not None or - self.Reason is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='eVSICancelResponse', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('eVSICancelResponse') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'eVSICancelResponse': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='eVSICancelResponse') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='eVSICancelResponse', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='eVSICancelResponse'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='eVSICancelResponse', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.BarcodeNumber is not None: - namespaceprefix_ = self.BarcodeNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.BarcodeNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sBarcodeNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.BarcodeNumber), input_name='BarcodeNumber')), namespaceprefix_ , eol_)) - if self.Status is not None: - namespaceprefix_ = self.Status_nsprefix_ + ':' if (UseCapturedNS_ and self.Status_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sStatus>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Status), input_name='Status')), namespaceprefix_ , eol_)) - if self.Reason is not None: - namespaceprefix_ = self.Reason_nsprefix_ + ':' if (UseCapturedNS_ and self.Reason_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sReason>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Reason), input_name='Reason')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'BarcodeNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'BarcodeNumber') - value_ = self.gds_validate_string(value_, node, 'BarcodeNumber') - self.BarcodeNumber = value_ - self.BarcodeNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'Status': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Status') - value_ = self.gds_validate_string(value_, node, 'Status') - self.Status = value_ - self.Status_nsprefix_ = child_.prefix - elif nodeName_ == 'Reason': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Reason') - value_ = self.gds_validate_string(value_, node, 'Reason') - self.Reason = value_ - self.Reason_nsprefix_ = child_.prefix -# end class eVSICancelResponse - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSICancelResponse' - rootClass = eVSICancelResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSICancelResponse' - rootClass = eVSICancelResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSICancelResponse' - rootClass = eVSICancelResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'eVSICancelResponse' - rootClass = eVSICancelResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from evsi_cancel_response import *\n\n') - sys.stdout.write('import evsi_cancel_response as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "eVSICancelResponse" -] diff --git a/schemas/usps/karrio/schemas/usps/express_mail_commitment_request.py b/schemas/usps/karrio/schemas/usps/express_mail_commitment_request.py deleted file mode 100644 index 7750b4cbf3..0000000000 --- a/schemas/usps/karrio/schemas/usps/express_mail_commitment_request.py +++ /dev/null @@ -1,1413 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:07 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/express_mail_commitment_request.py') -# -# Command line arguments: -# ./schemas/ExpressMailCommitmentRequest.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/express_mail_commitment_request.py" ./schemas/ExpressMailCommitmentRequest.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class ExpressMailCommitmentRequest(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, USERID=None, OriginZip=None, DestinationZip=None, Date=None, DropOffTime=None, ReturnDates=None, PMGuarantee=None, ClientType=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.USERID = _cast(None, USERID) - self.USERID_nsprefix_ = None - self.OriginZip = OriginZip - self.OriginZip_nsprefix_ = None - self.DestinationZip = DestinationZip - self.DestinationZip_nsprefix_ = None - self.Date = Date - self.Date_nsprefix_ = None - self.DropOffTime = DropOffTime - self.DropOffTime_nsprefix_ = None - self.ReturnDates = ReturnDates - self.ReturnDates_nsprefix_ = None - self.PMGuarantee = PMGuarantee - self.PMGuarantee_nsprefix_ = None - self.ClientType = ClientType - self.ClientType_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, ExpressMailCommitmentRequest) - if subclass is not None: - return subclass(*args_, **kwargs_) - if ExpressMailCommitmentRequest.subclass: - return ExpressMailCommitmentRequest.subclass(*args_, **kwargs_) - else: - return ExpressMailCommitmentRequest(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_OriginZip(self): - return self.OriginZip - def set_OriginZip(self, OriginZip): - self.OriginZip = OriginZip - def get_DestinationZip(self): - return self.DestinationZip - def set_DestinationZip(self, DestinationZip): - self.DestinationZip = DestinationZip - def get_Date(self): - return self.Date - def set_Date(self, Date): - self.Date = Date - def get_DropOffTime(self): - return self.DropOffTime - def set_DropOffTime(self, DropOffTime): - self.DropOffTime = DropOffTime - def get_ReturnDates(self): - return self.ReturnDates - def set_ReturnDates(self, ReturnDates): - self.ReturnDates = ReturnDates - def get_PMGuarantee(self): - return self.PMGuarantee - def set_PMGuarantee(self, PMGuarantee): - self.PMGuarantee = PMGuarantee - def get_ClientType(self): - return self.ClientType - def set_ClientType(self, ClientType): - self.ClientType = ClientType - def get_USERID(self): - return self.USERID - def set_USERID(self, USERID): - self.USERID = USERID - def _hasContent(self): - if ( - self.OriginZip is not None or - self.DestinationZip is not None or - self.Date is not None or - self.DropOffTime is not None or - self.ReturnDates is not None or - self.PMGuarantee is not None or - self.ClientType is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ExpressMailCommitmentRequest', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('ExpressMailCommitmentRequest') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'ExpressMailCommitmentRequest': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='ExpressMailCommitmentRequest') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='ExpressMailCommitmentRequest', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='ExpressMailCommitmentRequest'): - if self.USERID is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - outfile.write(' USERID=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.USERID), input_name='USERID')), )) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ExpressMailCommitmentRequest', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.OriginZip is not None: - namespaceprefix_ = self.OriginZip_nsprefix_ + ':' if (UseCapturedNS_ and self.OriginZip_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sOriginZip>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.OriginZip, input_name='OriginZip'), namespaceprefix_ , eol_)) - if self.DestinationZip is not None: - namespaceprefix_ = self.DestinationZip_nsprefix_ + ':' if (UseCapturedNS_ and self.DestinationZip_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDestinationZip>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.DestinationZip, input_name='DestinationZip'), namespaceprefix_ , eol_)) - if self.Date is not None: - namespaceprefix_ = self.Date_nsprefix_ + ':' if (UseCapturedNS_ and self.Date_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDate>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Date), input_name='Date')), namespaceprefix_ , eol_)) - if self.DropOffTime is not None: - namespaceprefix_ = self.DropOffTime_nsprefix_ + ':' if (UseCapturedNS_ and self.DropOffTime_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDropOffTime>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.DropOffTime), input_name='DropOffTime')), namespaceprefix_ , eol_)) - if self.ReturnDates is not None: - namespaceprefix_ = self.ReturnDates_nsprefix_ + ':' if (UseCapturedNS_ and self.ReturnDates_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sReturnDates>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ReturnDates), input_name='ReturnDates')), namespaceprefix_ , eol_)) - if self.PMGuarantee is not None: - namespaceprefix_ = self.PMGuarantee_nsprefix_ + ':' if (UseCapturedNS_ and self.PMGuarantee_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPMGuarantee>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PMGuarantee), input_name='PMGuarantee')), namespaceprefix_ , eol_)) - if self.ClientType is not None: - namespaceprefix_ = self.ClientType_nsprefix_ + ':' if (UseCapturedNS_ and self.ClientType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sClientType>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.ClientType, input_name='ClientType'), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('USERID', node) - if value is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - self.USERID = value - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'OriginZip' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'OriginZip') - ival_ = self.gds_validate_integer(ival_, node, 'OriginZip') - self.OriginZip = ival_ - self.OriginZip_nsprefix_ = child_.prefix - elif nodeName_ == 'DestinationZip' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'DestinationZip') - ival_ = self.gds_validate_integer(ival_, node, 'DestinationZip') - self.DestinationZip = ival_ - self.DestinationZip_nsprefix_ = child_.prefix - elif nodeName_ == 'Date': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Date') - value_ = self.gds_validate_string(value_, node, 'Date') - self.Date = value_ - self.Date_nsprefix_ = child_.prefix - elif nodeName_ == 'DropOffTime': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'DropOffTime') - value_ = self.gds_validate_string(value_, node, 'DropOffTime') - self.DropOffTime = value_ - self.DropOffTime_nsprefix_ = child_.prefix - elif nodeName_ == 'ReturnDates': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ReturnDates') - value_ = self.gds_validate_string(value_, node, 'ReturnDates') - self.ReturnDates = value_ - self.ReturnDates_nsprefix_ = child_.prefix - elif nodeName_ == 'PMGuarantee': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PMGuarantee') - value_ = self.gds_validate_string(value_, node, 'PMGuarantee') - self.PMGuarantee = value_ - self.PMGuarantee_nsprefix_ = child_.prefix - elif nodeName_ == 'ClientType' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'ClientType') - ival_ = self.gds_validate_integer(ival_, node, 'ClientType') - self.ClientType = ival_ - self.ClientType_nsprefix_ = child_.prefix -# end class ExpressMailCommitmentRequest - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'ExpressMailCommitmentRequest' - rootClass = ExpressMailCommitmentRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'ExpressMailCommitmentRequest' - rootClass = ExpressMailCommitmentRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'ExpressMailCommitmentRequest' - rootClass = ExpressMailCommitmentRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'ExpressMailCommitmentRequest' - rootClass = ExpressMailCommitmentRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from express_mail_commitment_request import *\n\n') - sys.stdout.write('import express_mail_commitment_request as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "ExpressMailCommitmentRequest" -] diff --git a/schemas/usps/karrio/schemas/usps/express_mail_commitment_response.py b/schemas/usps/karrio/schemas/usps/express_mail_commitment_response.py deleted file mode 100644 index b7928a6ed1..0000000000 --- a/schemas/usps/karrio/schemas/usps/express_mail_commitment_response.py +++ /dev/null @@ -1,1835 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:07 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/express_mail_commitment_response.py') -# -# Command line arguments: -# ./schemas/ExpressMailCommitmentResponse.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/express_mail_commitment_response.py" ./schemas/ExpressMailCommitmentResponse.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class ExpressMailCommitmentResponse(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, OriginZIP=None, OriginCity=None, OriginState=None, DestinationZIP=None, DestinationCity=None, DestinationState=None, Date=None, Time=None, EffectiveAcceptanceDate=None, Commitment=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.OriginZIP = OriginZIP - self.OriginZIP_nsprefix_ = None - self.OriginCity = OriginCity - self.OriginCity_nsprefix_ = None - self.OriginState = OriginState - self.OriginState_nsprefix_ = None - self.DestinationZIP = DestinationZIP - self.DestinationZIP_nsprefix_ = None - self.DestinationCity = DestinationCity - self.DestinationCity_nsprefix_ = None - self.DestinationState = DestinationState - self.DestinationState_nsprefix_ = None - self.Date = Date - self.Date_nsprefix_ = None - self.Time = Time - self.Time_nsprefix_ = None - if isinstance(EffectiveAcceptanceDate, BaseStrType_): - initvalue_ = datetime_.datetime.strptime(EffectiveAcceptanceDate, '%Y-%m-%d').date() - else: - initvalue_ = EffectiveAcceptanceDate - self.EffectiveAcceptanceDate = initvalue_ - self.EffectiveAcceptanceDate_nsprefix_ = None - if Commitment is None: - self.Commitment = [] - else: - self.Commitment = Commitment - self.Commitment_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, ExpressMailCommitmentResponse) - if subclass is not None: - return subclass(*args_, **kwargs_) - if ExpressMailCommitmentResponse.subclass: - return ExpressMailCommitmentResponse.subclass(*args_, **kwargs_) - else: - return ExpressMailCommitmentResponse(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_OriginZIP(self): - return self.OriginZIP - def set_OriginZIP(self, OriginZIP): - self.OriginZIP = OriginZIP - def get_OriginCity(self): - return self.OriginCity - def set_OriginCity(self, OriginCity): - self.OriginCity = OriginCity - def get_OriginState(self): - return self.OriginState - def set_OriginState(self, OriginState): - self.OriginState = OriginState - def get_DestinationZIP(self): - return self.DestinationZIP - def set_DestinationZIP(self, DestinationZIP): - self.DestinationZIP = DestinationZIP - def get_DestinationCity(self): - return self.DestinationCity - def set_DestinationCity(self, DestinationCity): - self.DestinationCity = DestinationCity - def get_DestinationState(self): - return self.DestinationState - def set_DestinationState(self, DestinationState): - self.DestinationState = DestinationState - def get_Date(self): - return self.Date - def set_Date(self, Date): - self.Date = Date - def get_Time(self): - return self.Time - def set_Time(self, Time): - self.Time = Time - def get_EffectiveAcceptanceDate(self): - return self.EffectiveAcceptanceDate - def set_EffectiveAcceptanceDate(self, EffectiveAcceptanceDate): - self.EffectiveAcceptanceDate = EffectiveAcceptanceDate - def get_Commitment(self): - return self.Commitment - def set_Commitment(self, Commitment): - self.Commitment = Commitment - def add_Commitment(self, value): - self.Commitment.append(value) - def insert_Commitment_at(self, index, value): - self.Commitment.insert(index, value) - def replace_Commitment_at(self, index, value): - self.Commitment[index] = value - def _hasContent(self): - if ( - self.OriginZIP is not None or - self.OriginCity is not None or - self.OriginState is not None or - self.DestinationZIP is not None or - self.DestinationCity is not None or - self.DestinationState is not None or - self.Date is not None or - self.Time is not None or - self.EffectiveAcceptanceDate is not None or - self.Commitment - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ExpressMailCommitmentResponse', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('ExpressMailCommitmentResponse') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'ExpressMailCommitmentResponse': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='ExpressMailCommitmentResponse') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='ExpressMailCommitmentResponse', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='ExpressMailCommitmentResponse'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ExpressMailCommitmentResponse', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.OriginZIP is not None: - namespaceprefix_ = self.OriginZIP_nsprefix_ + ':' if (UseCapturedNS_ and self.OriginZIP_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sOriginZIP>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.OriginZIP, input_name='OriginZIP'), namespaceprefix_ , eol_)) - if self.OriginCity is not None: - namespaceprefix_ = self.OriginCity_nsprefix_ + ':' if (UseCapturedNS_ and self.OriginCity_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sOriginCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.OriginCity), input_name='OriginCity')), namespaceprefix_ , eol_)) - if self.OriginState is not None: - namespaceprefix_ = self.OriginState_nsprefix_ + ':' if (UseCapturedNS_ and self.OriginState_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sOriginState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.OriginState), input_name='OriginState')), namespaceprefix_ , eol_)) - if self.DestinationZIP is not None: - namespaceprefix_ = self.DestinationZIP_nsprefix_ + ':' if (UseCapturedNS_ and self.DestinationZIP_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDestinationZIP>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.DestinationZIP, input_name='DestinationZIP'), namespaceprefix_ , eol_)) - if self.DestinationCity is not None: - namespaceprefix_ = self.DestinationCity_nsprefix_ + ':' if (UseCapturedNS_ and self.DestinationCity_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDestinationCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.DestinationCity), input_name='DestinationCity')), namespaceprefix_ , eol_)) - if self.DestinationState is not None: - namespaceprefix_ = self.DestinationState_nsprefix_ + ':' if (UseCapturedNS_ and self.DestinationState_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDestinationState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.DestinationState), input_name='DestinationState')), namespaceprefix_ , eol_)) - if self.Date is not None: - namespaceprefix_ = self.Date_nsprefix_ + ':' if (UseCapturedNS_ and self.Date_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDate>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Date), input_name='Date')), namespaceprefix_ , eol_)) - if self.Time is not None: - namespaceprefix_ = self.Time_nsprefix_ + ':' if (UseCapturedNS_ and self.Time_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sTime>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Time), input_name='Time')), namespaceprefix_ , eol_)) - if self.EffectiveAcceptanceDate is not None: - namespaceprefix_ = self.EffectiveAcceptanceDate_nsprefix_ + ':' if (UseCapturedNS_ and self.EffectiveAcceptanceDate_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEffectiveAcceptanceDate>%s%s' % (namespaceprefix_ , self.gds_format_date(self.EffectiveAcceptanceDate, input_name='EffectiveAcceptanceDate'), namespaceprefix_ , eol_)) - for Commitment_ in self.Commitment: - namespaceprefix_ = self.Commitment_nsprefix_ + ':' if (UseCapturedNS_ and self.Commitment_nsprefix_) else '' - Commitment_.export(outfile, level, namespaceprefix_, namespacedef_='', name_='Commitment', pretty_print=pretty_print) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'OriginZIP' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'OriginZIP') - ival_ = self.gds_validate_integer(ival_, node, 'OriginZIP') - self.OriginZIP = ival_ - self.OriginZIP_nsprefix_ = child_.prefix - elif nodeName_ == 'OriginCity': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'OriginCity') - value_ = self.gds_validate_string(value_, node, 'OriginCity') - self.OriginCity = value_ - self.OriginCity_nsprefix_ = child_.prefix - elif nodeName_ == 'OriginState': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'OriginState') - value_ = self.gds_validate_string(value_, node, 'OriginState') - self.OriginState = value_ - self.OriginState_nsprefix_ = child_.prefix - elif nodeName_ == 'DestinationZIP' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'DestinationZIP') - ival_ = self.gds_validate_integer(ival_, node, 'DestinationZIP') - self.DestinationZIP = ival_ - self.DestinationZIP_nsprefix_ = child_.prefix - elif nodeName_ == 'DestinationCity': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'DestinationCity') - value_ = self.gds_validate_string(value_, node, 'DestinationCity') - self.DestinationCity = value_ - self.DestinationCity_nsprefix_ = child_.prefix - elif nodeName_ == 'DestinationState': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'DestinationState') - value_ = self.gds_validate_string(value_, node, 'DestinationState') - self.DestinationState = value_ - self.DestinationState_nsprefix_ = child_.prefix - elif nodeName_ == 'Date': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Date') - value_ = self.gds_validate_string(value_, node, 'Date') - self.Date = value_ - self.Date_nsprefix_ = child_.prefix - elif nodeName_ == 'Time': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Time') - value_ = self.gds_validate_string(value_, node, 'Time') - self.Time = value_ - self.Time_nsprefix_ = child_.prefix - elif nodeName_ == 'EffectiveAcceptanceDate': - sval_ = child_.text - dval_ = self.gds_parse_date(sval_) - self.EffectiveAcceptanceDate = dval_ - self.EffectiveAcceptanceDate_nsprefix_ = child_.prefix - elif nodeName_ == 'Commitment': - obj_ = CommitmentType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.Commitment.append(obj_) - obj_.original_tagname_ = 'Commitment' -# end class ExpressMailCommitmentResponse - - -class CommitmentType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, CommitmentName=None, CommitmentTime=None, CommitmentSequence=None, Location=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.CommitmentName = CommitmentName - self.CommitmentName_nsprefix_ = None - self.CommitmentTime = CommitmentTime - self.CommitmentTime_nsprefix_ = None - self.CommitmentSequence = CommitmentSequence - self.CommitmentSequence_nsprefix_ = None - if Location is None: - self.Location = [] - else: - self.Location = Location - self.Location_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, CommitmentType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if CommitmentType.subclass: - return CommitmentType.subclass(*args_, **kwargs_) - else: - return CommitmentType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_CommitmentName(self): - return self.CommitmentName - def set_CommitmentName(self, CommitmentName): - self.CommitmentName = CommitmentName - def get_CommitmentTime(self): - return self.CommitmentTime - def set_CommitmentTime(self, CommitmentTime): - self.CommitmentTime = CommitmentTime - def get_CommitmentSequence(self): - return self.CommitmentSequence - def set_CommitmentSequence(self, CommitmentSequence): - self.CommitmentSequence = CommitmentSequence - def get_Location(self): - return self.Location - def set_Location(self, Location): - self.Location = Location - def add_Location(self, value): - self.Location.append(value) - def insert_Location_at(self, index, value): - self.Location.insert(index, value) - def replace_Location_at(self, index, value): - self.Location[index] = value - def _hasContent(self): - if ( - self.CommitmentName is not None or - self.CommitmentTime is not None or - self.CommitmentSequence is not None or - self.Location - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='CommitmentType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('CommitmentType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'CommitmentType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='CommitmentType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='CommitmentType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='CommitmentType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='CommitmentType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.CommitmentName is not None: - namespaceprefix_ = self.CommitmentName_nsprefix_ + ':' if (UseCapturedNS_ and self.CommitmentName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCommitmentName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CommitmentName), input_name='CommitmentName')), namespaceprefix_ , eol_)) - if self.CommitmentTime is not None: - namespaceprefix_ = self.CommitmentTime_nsprefix_ + ':' if (UseCapturedNS_ and self.CommitmentTime_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCommitmentTime>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CommitmentTime), input_name='CommitmentTime')), namespaceprefix_ , eol_)) - if self.CommitmentSequence is not None: - namespaceprefix_ = self.CommitmentSequence_nsprefix_ + ':' if (UseCapturedNS_ and self.CommitmentSequence_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCommitmentSequence>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CommitmentSequence), input_name='CommitmentSequence')), namespaceprefix_ , eol_)) - for Location_ in self.Location: - namespaceprefix_ = self.Location_nsprefix_ + ':' if (UseCapturedNS_ and self.Location_nsprefix_) else '' - Location_.export(outfile, level, namespaceprefix_, namespacedef_='', name_='Location', pretty_print=pretty_print) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'CommitmentName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CommitmentName') - value_ = self.gds_validate_string(value_, node, 'CommitmentName') - self.CommitmentName = value_ - self.CommitmentName_nsprefix_ = child_.prefix - elif nodeName_ == 'CommitmentTime': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CommitmentTime') - value_ = self.gds_validate_string(value_, node, 'CommitmentTime') - self.CommitmentTime = value_ - self.CommitmentTime_nsprefix_ = child_.prefix - elif nodeName_ == 'CommitmentSequence': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CommitmentSequence') - value_ = self.gds_validate_string(value_, node, 'CommitmentSequence') - self.CommitmentSequence = value_ - self.CommitmentSequence_nsprefix_ = child_.prefix - elif nodeName_ == 'Location': - obj_ = LocationType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.Location.append(obj_) - obj_.original_tagname_ = 'Location' -# end class CommitmentType - - -class LocationType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ScheduledDeliveryDate=None, CutOff=None, Facility=None, Street=None, City=None, State=None, Zip=None, IsGuaranteed=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - if isinstance(ScheduledDeliveryDate, BaseStrType_): - initvalue_ = datetime_.datetime.strptime(ScheduledDeliveryDate, '%Y-%m-%d').date() - else: - initvalue_ = ScheduledDeliveryDate - self.ScheduledDeliveryDate = initvalue_ - self.ScheduledDeliveryDate_nsprefix_ = None - self.CutOff = CutOff - self.CutOff_nsprefix_ = None - self.Facility = Facility - self.Facility_nsprefix_ = None - self.Street = Street - self.Street_nsprefix_ = None - self.City = City - self.City_nsprefix_ = None - self.State = State - self.State_nsprefix_ = None - self.Zip = Zip - self.Zip_nsprefix_ = None - self.IsGuaranteed = IsGuaranteed - self.IsGuaranteed_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, LocationType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if LocationType.subclass: - return LocationType.subclass(*args_, **kwargs_) - else: - return LocationType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_ScheduledDeliveryDate(self): - return self.ScheduledDeliveryDate - def set_ScheduledDeliveryDate(self, ScheduledDeliveryDate): - self.ScheduledDeliveryDate = ScheduledDeliveryDate - def get_CutOff(self): - return self.CutOff - def set_CutOff(self, CutOff): - self.CutOff = CutOff - def get_Facility(self): - return self.Facility - def set_Facility(self, Facility): - self.Facility = Facility - def get_Street(self): - return self.Street - def set_Street(self, Street): - self.Street = Street - def get_City(self): - return self.City - def set_City(self, City): - self.City = City - def get_State(self): - return self.State - def set_State(self, State): - self.State = State - def get_Zip(self): - return self.Zip - def set_Zip(self, Zip): - self.Zip = Zip - def get_IsGuaranteed(self): - return self.IsGuaranteed - def set_IsGuaranteed(self, IsGuaranteed): - self.IsGuaranteed = IsGuaranteed - def _hasContent(self): - if ( - self.ScheduledDeliveryDate is not None or - self.CutOff is not None or - self.Facility is not None or - self.Street is not None or - self.City is not None or - self.State is not None or - self.Zip is not None or - self.IsGuaranteed is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='LocationType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('LocationType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'LocationType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='LocationType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='LocationType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='LocationType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='LocationType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.ScheduledDeliveryDate is not None: - namespaceprefix_ = self.ScheduledDeliveryDate_nsprefix_ + ':' if (UseCapturedNS_ and self.ScheduledDeliveryDate_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sScheduledDeliveryDate>%s%s' % (namespaceprefix_ , self.gds_format_date(self.ScheduledDeliveryDate, input_name='ScheduledDeliveryDate'), namespaceprefix_ , eol_)) - if self.CutOff is not None: - namespaceprefix_ = self.CutOff_nsprefix_ + ':' if (UseCapturedNS_ and self.CutOff_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCutOff>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CutOff), input_name='CutOff')), namespaceprefix_ , eol_)) - if self.Facility is not None: - namespaceprefix_ = self.Facility_nsprefix_ + ':' if (UseCapturedNS_ and self.Facility_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFacility>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Facility), input_name='Facility')), namespaceprefix_ , eol_)) - if self.Street is not None: - namespaceprefix_ = self.Street_nsprefix_ + ':' if (UseCapturedNS_ and self.Street_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sStreet>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Street), input_name='Street')), namespaceprefix_ , eol_)) - if self.City is not None: - namespaceprefix_ = self.City_nsprefix_ + ':' if (UseCapturedNS_ and self.City_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.City), input_name='City')), namespaceprefix_ , eol_)) - if self.State is not None: - namespaceprefix_ = self.State_nsprefix_ + ':' if (UseCapturedNS_ and self.State_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.State), input_name='State')), namespaceprefix_ , eol_)) - if self.Zip is not None: - namespaceprefix_ = self.Zip_nsprefix_ + ':' if (UseCapturedNS_ and self.Zip_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sZip>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.Zip, input_name='Zip'), namespaceprefix_ , eol_)) - if self.IsGuaranteed is not None: - namespaceprefix_ = self.IsGuaranteed_nsprefix_ + ':' if (UseCapturedNS_ and self.IsGuaranteed_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sIsGuaranteed>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.IsGuaranteed, input_name='IsGuaranteed'), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'ScheduledDeliveryDate': - sval_ = child_.text - dval_ = self.gds_parse_date(sval_) - self.ScheduledDeliveryDate = dval_ - self.ScheduledDeliveryDate_nsprefix_ = child_.prefix - elif nodeName_ == 'CutOff': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CutOff') - value_ = self.gds_validate_string(value_, node, 'CutOff') - self.CutOff = value_ - self.CutOff_nsprefix_ = child_.prefix - elif nodeName_ == 'Facility': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Facility') - value_ = self.gds_validate_string(value_, node, 'Facility') - self.Facility = value_ - self.Facility_nsprefix_ = child_.prefix - elif nodeName_ == 'Street': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Street') - value_ = self.gds_validate_string(value_, node, 'Street') - self.Street = value_ - self.Street_nsprefix_ = child_.prefix - elif nodeName_ == 'City': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'City') - value_ = self.gds_validate_string(value_, node, 'City') - self.City = value_ - self.City_nsprefix_ = child_.prefix - elif nodeName_ == 'State': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'State') - value_ = self.gds_validate_string(value_, node, 'State') - self.State = value_ - self.State_nsprefix_ = child_.prefix - elif nodeName_ == 'Zip' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'Zip') - ival_ = self.gds_validate_integer(ival_, node, 'Zip') - self.Zip = ival_ - self.Zip_nsprefix_ = child_.prefix - elif nodeName_ == 'IsGuaranteed' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'IsGuaranteed') - ival_ = self.gds_validate_integer(ival_, node, 'IsGuaranteed') - self.IsGuaranteed = ival_ - self.IsGuaranteed_nsprefix_ = child_.prefix -# end class LocationType - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'ExpressMailCommitmentResponse' - rootClass = ExpressMailCommitmentResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'ExpressMailCommitmentResponse' - rootClass = ExpressMailCommitmentResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'ExpressMailCommitmentResponse' - rootClass = ExpressMailCommitmentResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'ExpressMailCommitmentResponse' - rootClass = ExpressMailCommitmentResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from express_mail_commitment_response import *\n\n') - sys.stdout.write('import express_mail_commitment_response as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "CommitmentType", - "ExpressMailCommitmentResponse", - "LocationType" -] diff --git a/schemas/usps/karrio/schemas/usps/first_class_mail_request.py b/schemas/usps/karrio/schemas/usps/first_class_mail_request.py deleted file mode 100644 index 7057ddd535..0000000000 --- a/schemas/usps/karrio/schemas/usps/first_class_mail_request.py +++ /dev/null @@ -1,1379 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:07 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/first_class_mail_request.py') -# -# Command line arguments: -# ./schemas/FirstClassMailRequest.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/first_class_mail_request.py" ./schemas/FirstClassMailRequest.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class FirstClassMailRequest(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, USERID=None, OriginZip=None, DestinationZip=None, DestinationType=None, PMGuarantee=None, ClientType=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.USERID = _cast(None, USERID) - self.USERID_nsprefix_ = None - self.OriginZip = OriginZip - self.OriginZip_nsprefix_ = None - self.DestinationZip = DestinationZip - self.DestinationZip_nsprefix_ = None - self.DestinationType = DestinationType - self.DestinationType_nsprefix_ = None - self.PMGuarantee = PMGuarantee - self.PMGuarantee_nsprefix_ = None - self.ClientType = ClientType - self.ClientType_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, FirstClassMailRequest) - if subclass is not None: - return subclass(*args_, **kwargs_) - if FirstClassMailRequest.subclass: - return FirstClassMailRequest.subclass(*args_, **kwargs_) - else: - return FirstClassMailRequest(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_OriginZip(self): - return self.OriginZip - def set_OriginZip(self, OriginZip): - self.OriginZip = OriginZip - def get_DestinationZip(self): - return self.DestinationZip - def set_DestinationZip(self, DestinationZip): - self.DestinationZip = DestinationZip - def get_DestinationType(self): - return self.DestinationType - def set_DestinationType(self, DestinationType): - self.DestinationType = DestinationType - def get_PMGuarantee(self): - return self.PMGuarantee - def set_PMGuarantee(self, PMGuarantee): - self.PMGuarantee = PMGuarantee - def get_ClientType(self): - return self.ClientType - def set_ClientType(self, ClientType): - self.ClientType = ClientType - def get_USERID(self): - return self.USERID - def set_USERID(self, USERID): - self.USERID = USERID - def _hasContent(self): - if ( - self.OriginZip is not None or - self.DestinationZip is not None or - self.DestinationType is not None or - self.PMGuarantee is not None or - self.ClientType is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='FirstClassMailRequest', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('FirstClassMailRequest') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'FirstClassMailRequest': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='FirstClassMailRequest') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='FirstClassMailRequest', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='FirstClassMailRequest'): - if self.USERID is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - outfile.write(' USERID=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.USERID), input_name='USERID')), )) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='FirstClassMailRequest', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.OriginZip is not None: - namespaceprefix_ = self.OriginZip_nsprefix_ + ':' if (UseCapturedNS_ and self.OriginZip_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sOriginZip>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.OriginZip, input_name='OriginZip'), namespaceprefix_ , eol_)) - if self.DestinationZip is not None: - namespaceprefix_ = self.DestinationZip_nsprefix_ + ':' if (UseCapturedNS_ and self.DestinationZip_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDestinationZip>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.DestinationZip, input_name='DestinationZip'), namespaceprefix_ , eol_)) - if self.DestinationType is not None: - namespaceprefix_ = self.DestinationType_nsprefix_ + ':' if (UseCapturedNS_ and self.DestinationType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDestinationType>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.DestinationType, input_name='DestinationType'), namespaceprefix_ , eol_)) - if self.PMGuarantee is not None: - namespaceprefix_ = self.PMGuarantee_nsprefix_ + ':' if (UseCapturedNS_ and self.PMGuarantee_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPMGuarantee>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PMGuarantee), input_name='PMGuarantee')), namespaceprefix_ , eol_)) - if self.ClientType is not None: - namespaceprefix_ = self.ClientType_nsprefix_ + ':' if (UseCapturedNS_ and self.ClientType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sClientType>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.ClientType, input_name='ClientType'), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('USERID', node) - if value is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - self.USERID = value - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'OriginZip' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'OriginZip') - ival_ = self.gds_validate_integer(ival_, node, 'OriginZip') - self.OriginZip = ival_ - self.OriginZip_nsprefix_ = child_.prefix - elif nodeName_ == 'DestinationZip' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'DestinationZip') - ival_ = self.gds_validate_integer(ival_, node, 'DestinationZip') - self.DestinationZip = ival_ - self.DestinationZip_nsprefix_ = child_.prefix - elif nodeName_ == 'DestinationType' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'DestinationType') - ival_ = self.gds_validate_integer(ival_, node, 'DestinationType') - self.DestinationType = ival_ - self.DestinationType_nsprefix_ = child_.prefix - elif nodeName_ == 'PMGuarantee': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PMGuarantee') - value_ = self.gds_validate_string(value_, node, 'PMGuarantee') - self.PMGuarantee = value_ - self.PMGuarantee_nsprefix_ = child_.prefix - elif nodeName_ == 'ClientType' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'ClientType') - ival_ = self.gds_validate_integer(ival_, node, 'ClientType') - self.ClientType = ival_ - self.ClientType_nsprefix_ = child_.prefix -# end class FirstClassMailRequest - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'FirstClassMailRequest' - rootClass = FirstClassMailRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'FirstClassMailRequest' - rootClass = FirstClassMailRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'FirstClassMailRequest' - rootClass = FirstClassMailRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'FirstClassMailRequest' - rootClass = FirstClassMailRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from first_class_mail_request import *\n\n') - sys.stdout.write('import first_class_mail_request as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "FirstClassMailRequest" -] diff --git a/schemas/usps/karrio/schemas/usps/first_class_mail_response.py b/schemas/usps/karrio/schemas/usps/first_class_mail_response.py deleted file mode 100644 index 20ae4726f5..0000000000 --- a/schemas/usps/karrio/schemas/usps/first_class_mail_response.py +++ /dev/null @@ -1,1385 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:07 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/first_class_mail_response.py') -# -# Command line arguments: -# ./schemas/FirstClassMailResponse.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/first_class_mail_response.py" ./schemas/FirstClassMailResponse.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class FirstClassMailResponse(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, OriginZip=None, DestinationZip=None, Days=None, Message=None, EffectiveAcceptanceDate=None, ScheduledDeliveryDate=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.OriginZip = OriginZip - self.OriginZip_nsprefix_ = None - self.DestinationZip = DestinationZip - self.DestinationZip_nsprefix_ = None - self.Days = Days - self.Days_nsprefix_ = None - self.Message = Message - self.Message_nsprefix_ = None - self.EffectiveAcceptanceDate = EffectiveAcceptanceDate - self.EffectiveAcceptanceDate_nsprefix_ = None - self.ScheduledDeliveryDate = ScheduledDeliveryDate - self.ScheduledDeliveryDate_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, FirstClassMailResponse) - if subclass is not None: - return subclass(*args_, **kwargs_) - if FirstClassMailResponse.subclass: - return FirstClassMailResponse.subclass(*args_, **kwargs_) - else: - return FirstClassMailResponse(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_OriginZip(self): - return self.OriginZip - def set_OriginZip(self, OriginZip): - self.OriginZip = OriginZip - def get_DestinationZip(self): - return self.DestinationZip - def set_DestinationZip(self, DestinationZip): - self.DestinationZip = DestinationZip - def get_Days(self): - return self.Days - def set_Days(self, Days): - self.Days = Days - def get_Message(self): - return self.Message - def set_Message(self, Message): - self.Message = Message - def get_EffectiveAcceptanceDate(self): - return self.EffectiveAcceptanceDate - def set_EffectiveAcceptanceDate(self, EffectiveAcceptanceDate): - self.EffectiveAcceptanceDate = EffectiveAcceptanceDate - def get_ScheduledDeliveryDate(self): - return self.ScheduledDeliveryDate - def set_ScheduledDeliveryDate(self, ScheduledDeliveryDate): - self.ScheduledDeliveryDate = ScheduledDeliveryDate - def _hasContent(self): - if ( - self.OriginZip is not None or - self.DestinationZip is not None or - self.Days is not None or - self.Message is not None or - self.EffectiveAcceptanceDate is not None or - self.ScheduledDeliveryDate is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='FirstClassMailResponse', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('FirstClassMailResponse') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'FirstClassMailResponse': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='FirstClassMailResponse') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='FirstClassMailResponse', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='FirstClassMailResponse'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='FirstClassMailResponse', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.OriginZip is not None: - namespaceprefix_ = self.OriginZip_nsprefix_ + ':' if (UseCapturedNS_ and self.OriginZip_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sOriginZip>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.OriginZip, input_name='OriginZip'), namespaceprefix_ , eol_)) - if self.DestinationZip is not None: - namespaceprefix_ = self.DestinationZip_nsprefix_ + ':' if (UseCapturedNS_ and self.DestinationZip_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDestinationZip>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.DestinationZip, input_name='DestinationZip'), namespaceprefix_ , eol_)) - if self.Days is not None: - namespaceprefix_ = self.Days_nsprefix_ + ':' if (UseCapturedNS_ and self.Days_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDays>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.Days, input_name='Days'), namespaceprefix_ , eol_)) - if self.Message is not None: - namespaceprefix_ = self.Message_nsprefix_ + ':' if (UseCapturedNS_ and self.Message_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sMessage>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Message), input_name='Message')), namespaceprefix_ , eol_)) - if self.EffectiveAcceptanceDate is not None: - namespaceprefix_ = self.EffectiveAcceptanceDate_nsprefix_ + ':' if (UseCapturedNS_ and self.EffectiveAcceptanceDate_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEffectiveAcceptanceDate>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.EffectiveAcceptanceDate), input_name='EffectiveAcceptanceDate')), namespaceprefix_ , eol_)) - if self.ScheduledDeliveryDate is not None: - namespaceprefix_ = self.ScheduledDeliveryDate_nsprefix_ + ':' if (UseCapturedNS_ and self.ScheduledDeliveryDate_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sScheduledDeliveryDate>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ScheduledDeliveryDate), input_name='ScheduledDeliveryDate')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'OriginZip' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'OriginZip') - ival_ = self.gds_validate_integer(ival_, node, 'OriginZip') - self.OriginZip = ival_ - self.OriginZip_nsprefix_ = child_.prefix - elif nodeName_ == 'DestinationZip' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'DestinationZip') - ival_ = self.gds_validate_integer(ival_, node, 'DestinationZip') - self.DestinationZip = ival_ - self.DestinationZip_nsprefix_ = child_.prefix - elif nodeName_ == 'Days' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'Days') - ival_ = self.gds_validate_integer(ival_, node, 'Days') - self.Days = ival_ - self.Days_nsprefix_ = child_.prefix - elif nodeName_ == 'Message': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Message') - value_ = self.gds_validate_string(value_, node, 'Message') - self.Message = value_ - self.Message_nsprefix_ = child_.prefix - elif nodeName_ == 'EffectiveAcceptanceDate': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'EffectiveAcceptanceDate') - value_ = self.gds_validate_string(value_, node, 'EffectiveAcceptanceDate') - self.EffectiveAcceptanceDate = value_ - self.EffectiveAcceptanceDate_nsprefix_ = child_.prefix - elif nodeName_ == 'ScheduledDeliveryDate': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ScheduledDeliveryDate') - value_ = self.gds_validate_string(value_, node, 'ScheduledDeliveryDate') - self.ScheduledDeliveryDate = value_ - self.ScheduledDeliveryDate_nsprefix_ = child_.prefix -# end class FirstClassMailResponse - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'FirstClassMailResponse' - rootClass = FirstClassMailResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'FirstClassMailResponse' - rootClass = FirstClassMailResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'FirstClassMailResponse' - rootClass = FirstClassMailResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'FirstClassMailResponse' - rootClass = FirstClassMailResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from first_class_mail_response import *\n\n') - sys.stdout.write('import first_class_mail_response as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "FirstClassMailResponse" -] diff --git a/schemas/usps/karrio/schemas/usps/hfp_facility_info_request.py b/schemas/usps/karrio/schemas/usps/hfp_facility_info_request.py deleted file mode 100644 index ea0c5ee53f..0000000000 --- a/schemas/usps/karrio/schemas/usps/hfp_facility_info_request.py +++ /dev/null @@ -1,1379 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:07 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/hfp_facility_info_request.py') -# -# Command line arguments: -# ./schemas/HFPFacilityInfoRequest.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/hfp_facility_info_request.py" ./schemas/HFPFacilityInfoRequest.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class HFPFacilityInfoRequest(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, USERID=None, PickupCity=None, PickupState=None, PickupZIP=None, PickupZIP4=None, Service=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.USERID = _cast(None, USERID) - self.USERID_nsprefix_ = None - self.PickupCity = PickupCity - self.PickupCity_nsprefix_ = None - self.PickupState = PickupState - self.PickupState_nsprefix_ = None - self.PickupZIP = PickupZIP - self.PickupZIP_nsprefix_ = None - self.PickupZIP4 = PickupZIP4 - self.PickupZIP4_nsprefix_ = None - self.Service = Service - self.Service_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, HFPFacilityInfoRequest) - if subclass is not None: - return subclass(*args_, **kwargs_) - if HFPFacilityInfoRequest.subclass: - return HFPFacilityInfoRequest.subclass(*args_, **kwargs_) - else: - return HFPFacilityInfoRequest(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_PickupCity(self): - return self.PickupCity - def set_PickupCity(self, PickupCity): - self.PickupCity = PickupCity - def get_PickupState(self): - return self.PickupState - def set_PickupState(self, PickupState): - self.PickupState = PickupState - def get_PickupZIP(self): - return self.PickupZIP - def set_PickupZIP(self, PickupZIP): - self.PickupZIP = PickupZIP - def get_PickupZIP4(self): - return self.PickupZIP4 - def set_PickupZIP4(self, PickupZIP4): - self.PickupZIP4 = PickupZIP4 - def get_Service(self): - return self.Service - def set_Service(self, Service): - self.Service = Service - def get_USERID(self): - return self.USERID - def set_USERID(self, USERID): - self.USERID = USERID - def _hasContent(self): - if ( - self.PickupCity is not None or - self.PickupState is not None or - self.PickupZIP is not None or - self.PickupZIP4 is not None or - self.Service is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='HFPFacilityInfoRequest', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('HFPFacilityInfoRequest') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'HFPFacilityInfoRequest': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='HFPFacilityInfoRequest') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='HFPFacilityInfoRequest', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='HFPFacilityInfoRequest'): - if self.USERID is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - outfile.write(' USERID=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.USERID), input_name='USERID')), )) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='HFPFacilityInfoRequest', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.PickupCity is not None: - namespaceprefix_ = self.PickupCity_nsprefix_ + ':' if (UseCapturedNS_ and self.PickupCity_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPickupCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PickupCity), input_name='PickupCity')), namespaceprefix_ , eol_)) - if self.PickupState is not None: - namespaceprefix_ = self.PickupState_nsprefix_ + ':' if (UseCapturedNS_ and self.PickupState_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPickupState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PickupState), input_name='PickupState')), namespaceprefix_ , eol_)) - if self.PickupZIP is not None: - namespaceprefix_ = self.PickupZIP_nsprefix_ + ':' if (UseCapturedNS_ and self.PickupZIP_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPickupZIP>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.PickupZIP, input_name='PickupZIP'), namespaceprefix_ , eol_)) - if self.PickupZIP4 is not None: - namespaceprefix_ = self.PickupZIP4_nsprefix_ + ':' if (UseCapturedNS_ and self.PickupZIP4_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPickupZIP4>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PickupZIP4), input_name='PickupZIP4')), namespaceprefix_ , eol_)) - if self.Service is not None: - namespaceprefix_ = self.Service_nsprefix_ + ':' if (UseCapturedNS_ and self.Service_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sService>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Service), input_name='Service')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('USERID', node) - if value is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - self.USERID = value - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'PickupCity': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PickupCity') - value_ = self.gds_validate_string(value_, node, 'PickupCity') - self.PickupCity = value_ - self.PickupCity_nsprefix_ = child_.prefix - elif nodeName_ == 'PickupState': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PickupState') - value_ = self.gds_validate_string(value_, node, 'PickupState') - self.PickupState = value_ - self.PickupState_nsprefix_ = child_.prefix - elif nodeName_ == 'PickupZIP' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'PickupZIP') - ival_ = self.gds_validate_integer(ival_, node, 'PickupZIP') - self.PickupZIP = ival_ - self.PickupZIP_nsprefix_ = child_.prefix - elif nodeName_ == 'PickupZIP4': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PickupZIP4') - value_ = self.gds_validate_string(value_, node, 'PickupZIP4') - self.PickupZIP4 = value_ - self.PickupZIP4_nsprefix_ = child_.prefix - elif nodeName_ == 'Service': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Service') - value_ = self.gds_validate_string(value_, node, 'Service') - self.Service = value_ - self.Service_nsprefix_ = child_.prefix -# end class HFPFacilityInfoRequest - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'HFPFacilityInfoRequest' - rootClass = HFPFacilityInfoRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'HFPFacilityInfoRequest' - rootClass = HFPFacilityInfoRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'HFPFacilityInfoRequest' - rootClass = HFPFacilityInfoRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'HFPFacilityInfoRequest' - rootClass = HFPFacilityInfoRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from hfp_facility_info_request import *\n\n') - sys.stdout.write('import hfp_facility_info_request as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "HFPFacilityInfoRequest" -] diff --git a/schemas/usps/karrio/schemas/usps/hfp_facility_info_response.py b/schemas/usps/karrio/schemas/usps/hfp_facility_info_response.py deleted file mode 100644 index 702a7dd3ba..0000000000 --- a/schemas/usps/karrio/schemas/usps/hfp_facility_info_response.py +++ /dev/null @@ -1,1590 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:07 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/hfp_facility_info_response.py') -# -# Command line arguments: -# ./schemas/HFPFacilityInfoResponse.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/hfp_facility_info_response.py" ./schemas/HFPFacilityInfoResponse.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class HFPFacilityInfoResponse(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, PickupCity=None, PickupState=None, PickupZIP=None, PickupZIP4=None, Facility=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.PickupCity = PickupCity - self.PickupCity_nsprefix_ = None - self.PickupState = PickupState - self.PickupState_nsprefix_ = None - self.PickupZIP = PickupZIP - self.PickupZIP_nsprefix_ = None - self.PickupZIP4 = PickupZIP4 - self.PickupZIP4_nsprefix_ = None - if Facility is None: - self.Facility = [] - else: - self.Facility = Facility - self.Facility_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, HFPFacilityInfoResponse) - if subclass is not None: - return subclass(*args_, **kwargs_) - if HFPFacilityInfoResponse.subclass: - return HFPFacilityInfoResponse.subclass(*args_, **kwargs_) - else: - return HFPFacilityInfoResponse(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_PickupCity(self): - return self.PickupCity - def set_PickupCity(self, PickupCity): - self.PickupCity = PickupCity - def get_PickupState(self): - return self.PickupState - def set_PickupState(self, PickupState): - self.PickupState = PickupState - def get_PickupZIP(self): - return self.PickupZIP - def set_PickupZIP(self, PickupZIP): - self.PickupZIP = PickupZIP - def get_PickupZIP4(self): - return self.PickupZIP4 - def set_PickupZIP4(self, PickupZIP4): - self.PickupZIP4 = PickupZIP4 - def get_Facility(self): - return self.Facility - def set_Facility(self, Facility): - self.Facility = Facility - def add_Facility(self, value): - self.Facility.append(value) - def insert_Facility_at(self, index, value): - self.Facility.insert(index, value) - def replace_Facility_at(self, index, value): - self.Facility[index] = value - def _hasContent(self): - if ( - self.PickupCity is not None or - self.PickupState is not None or - self.PickupZIP is not None or - self.PickupZIP4 is not None or - self.Facility - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='HFPFacilityInfoResponse', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('HFPFacilityInfoResponse') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'HFPFacilityInfoResponse': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='HFPFacilityInfoResponse') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='HFPFacilityInfoResponse', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='HFPFacilityInfoResponse'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='HFPFacilityInfoResponse', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.PickupCity is not None: - namespaceprefix_ = self.PickupCity_nsprefix_ + ':' if (UseCapturedNS_ and self.PickupCity_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPickupCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PickupCity), input_name='PickupCity')), namespaceprefix_ , eol_)) - if self.PickupState is not None: - namespaceprefix_ = self.PickupState_nsprefix_ + ':' if (UseCapturedNS_ and self.PickupState_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPickupState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PickupState), input_name='PickupState')), namespaceprefix_ , eol_)) - if self.PickupZIP is not None: - namespaceprefix_ = self.PickupZIP_nsprefix_ + ':' if (UseCapturedNS_ and self.PickupZIP_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPickupZIP>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.PickupZIP, input_name='PickupZIP'), namespaceprefix_ , eol_)) - if self.PickupZIP4 is not None: - namespaceprefix_ = self.PickupZIP4_nsprefix_ + ':' if (UseCapturedNS_ and self.PickupZIP4_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPickupZIP4>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PickupZIP4), input_name='PickupZIP4')), namespaceprefix_ , eol_)) - for Facility_ in self.Facility: - namespaceprefix_ = self.Facility_nsprefix_ + ':' if (UseCapturedNS_ and self.Facility_nsprefix_) else '' - Facility_.export(outfile, level, namespaceprefix_, namespacedef_='', name_='Facility', pretty_print=pretty_print) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'PickupCity': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PickupCity') - value_ = self.gds_validate_string(value_, node, 'PickupCity') - self.PickupCity = value_ - self.PickupCity_nsprefix_ = child_.prefix - elif nodeName_ == 'PickupState': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PickupState') - value_ = self.gds_validate_string(value_, node, 'PickupState') - self.PickupState = value_ - self.PickupState_nsprefix_ = child_.prefix - elif nodeName_ == 'PickupZIP' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'PickupZIP') - ival_ = self.gds_validate_integer(ival_, node, 'PickupZIP') - self.PickupZIP = ival_ - self.PickupZIP_nsprefix_ = child_.prefix - elif nodeName_ == 'PickupZIP4': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PickupZIP4') - value_ = self.gds_validate_string(value_, node, 'PickupZIP4') - self.PickupZIP4 = value_ - self.PickupZIP4_nsprefix_ = child_.prefix - elif nodeName_ == 'Facility': - obj_ = FacilityType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.Facility.append(obj_) - obj_.original_tagname_ = 'Facility' -# end class HFPFacilityInfoResponse - - -class FacilityType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, FacilityID=None, FacilityName=None, FacilityAddress=None, FacilityCity=None, FacilityState=None, FacilityZIP=None, FacilityZIP4=None, Has10amCommitment=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.FacilityID = FacilityID - self.FacilityID_nsprefix_ = None - self.FacilityName = FacilityName - self.FacilityName_nsprefix_ = None - self.FacilityAddress = FacilityAddress - self.FacilityAddress_nsprefix_ = None - self.FacilityCity = FacilityCity - self.FacilityCity_nsprefix_ = None - self.FacilityState = FacilityState - self.FacilityState_nsprefix_ = None - self.FacilityZIP = FacilityZIP - self.FacilityZIP_nsprefix_ = None - self.FacilityZIP4 = FacilityZIP4 - self.FacilityZIP4_nsprefix_ = None - self.Has10amCommitment = Has10amCommitment - self.Has10amCommitment_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, FacilityType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if FacilityType.subclass: - return FacilityType.subclass(*args_, **kwargs_) - else: - return FacilityType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_FacilityID(self): - return self.FacilityID - def set_FacilityID(self, FacilityID): - self.FacilityID = FacilityID - def get_FacilityName(self): - return self.FacilityName - def set_FacilityName(self, FacilityName): - self.FacilityName = FacilityName - def get_FacilityAddress(self): - return self.FacilityAddress - def set_FacilityAddress(self, FacilityAddress): - self.FacilityAddress = FacilityAddress - def get_FacilityCity(self): - return self.FacilityCity - def set_FacilityCity(self, FacilityCity): - self.FacilityCity = FacilityCity - def get_FacilityState(self): - return self.FacilityState - def set_FacilityState(self, FacilityState): - self.FacilityState = FacilityState - def get_FacilityZIP(self): - return self.FacilityZIP - def set_FacilityZIP(self, FacilityZIP): - self.FacilityZIP = FacilityZIP - def get_FacilityZIP4(self): - return self.FacilityZIP4 - def set_FacilityZIP4(self, FacilityZIP4): - self.FacilityZIP4 = FacilityZIP4 - def get_Has10amCommitment(self): - return self.Has10amCommitment - def set_Has10amCommitment(self, Has10amCommitment): - self.Has10amCommitment = Has10amCommitment - def _hasContent(self): - if ( - self.FacilityID is not None or - self.FacilityName is not None or - self.FacilityAddress is not None or - self.FacilityCity is not None or - self.FacilityState is not None or - self.FacilityZIP is not None or - self.FacilityZIP4 is not None or - self.Has10amCommitment is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='FacilityType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('FacilityType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'FacilityType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='FacilityType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='FacilityType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='FacilityType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='FacilityType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.FacilityID is not None: - namespaceprefix_ = self.FacilityID_nsprefix_ + ':' if (UseCapturedNS_ and self.FacilityID_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFacilityID>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.FacilityID, input_name='FacilityID'), namespaceprefix_ , eol_)) - if self.FacilityName is not None: - namespaceprefix_ = self.FacilityName_nsprefix_ + ':' if (UseCapturedNS_ and self.FacilityName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFacilityName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FacilityName), input_name='FacilityName')), namespaceprefix_ , eol_)) - if self.FacilityAddress is not None: - namespaceprefix_ = self.FacilityAddress_nsprefix_ + ':' if (UseCapturedNS_ and self.FacilityAddress_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFacilityAddress>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FacilityAddress), input_name='FacilityAddress')), namespaceprefix_ , eol_)) - if self.FacilityCity is not None: - namespaceprefix_ = self.FacilityCity_nsprefix_ + ':' if (UseCapturedNS_ and self.FacilityCity_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFacilityCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FacilityCity), input_name='FacilityCity')), namespaceprefix_ , eol_)) - if self.FacilityState is not None: - namespaceprefix_ = self.FacilityState_nsprefix_ + ':' if (UseCapturedNS_ and self.FacilityState_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFacilityState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FacilityState), input_name='FacilityState')), namespaceprefix_ , eol_)) - if self.FacilityZIP is not None: - namespaceprefix_ = self.FacilityZIP_nsprefix_ + ':' if (UseCapturedNS_ and self.FacilityZIP_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFacilityZIP>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.FacilityZIP, input_name='FacilityZIP'), namespaceprefix_ , eol_)) - if self.FacilityZIP4 is not None: - namespaceprefix_ = self.FacilityZIP4_nsprefix_ + ':' if (UseCapturedNS_ and self.FacilityZIP4_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFacilityZIP4>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.FacilityZIP4, input_name='FacilityZIP4'), namespaceprefix_ , eol_)) - if self.Has10amCommitment is not None: - namespaceprefix_ = self.Has10amCommitment_nsprefix_ + ':' if (UseCapturedNS_ and self.Has10amCommitment_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sHas10amCommitment>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Has10amCommitment), input_name='Has10amCommitment')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'FacilityID' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'FacilityID') - ival_ = self.gds_validate_integer(ival_, node, 'FacilityID') - self.FacilityID = ival_ - self.FacilityID_nsprefix_ = child_.prefix - elif nodeName_ == 'FacilityName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FacilityName') - value_ = self.gds_validate_string(value_, node, 'FacilityName') - self.FacilityName = value_ - self.FacilityName_nsprefix_ = child_.prefix - elif nodeName_ == 'FacilityAddress': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FacilityAddress') - value_ = self.gds_validate_string(value_, node, 'FacilityAddress') - self.FacilityAddress = value_ - self.FacilityAddress_nsprefix_ = child_.prefix - elif nodeName_ == 'FacilityCity': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FacilityCity') - value_ = self.gds_validate_string(value_, node, 'FacilityCity') - self.FacilityCity = value_ - self.FacilityCity_nsprefix_ = child_.prefix - elif nodeName_ == 'FacilityState': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FacilityState') - value_ = self.gds_validate_string(value_, node, 'FacilityState') - self.FacilityState = value_ - self.FacilityState_nsprefix_ = child_.prefix - elif nodeName_ == 'FacilityZIP' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'FacilityZIP') - ival_ = self.gds_validate_integer(ival_, node, 'FacilityZIP') - self.FacilityZIP = ival_ - self.FacilityZIP_nsprefix_ = child_.prefix - elif nodeName_ == 'FacilityZIP4' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'FacilityZIP4') - ival_ = self.gds_validate_integer(ival_, node, 'FacilityZIP4') - self.FacilityZIP4 = ival_ - self.FacilityZIP4_nsprefix_ = child_.prefix - elif nodeName_ == 'Has10amCommitment': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Has10amCommitment') - value_ = self.gds_validate_string(value_, node, 'Has10amCommitment') - self.Has10amCommitment = value_ - self.Has10amCommitment_nsprefix_ = child_.prefix -# end class FacilityType - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'HFPFacilityInfoResponse' - rootClass = HFPFacilityInfoResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'HFPFacilityInfoResponse' - rootClass = HFPFacilityInfoResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'HFPFacilityInfoResponse' - rootClass = HFPFacilityInfoResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'HFPFacilityInfoResponse' - rootClass = HFPFacilityInfoResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from hfp_facility_info_response import *\n\n') - sys.stdout.write('import hfp_facility_info_response as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "FacilityType", - "HFPFacilityInfoResponse" -] diff --git a/schemas/usps/karrio/schemas/usps/intl_rate_v2_request.py b/schemas/usps/karrio/schemas/usps/intl_rate_v2_request.py deleted file mode 100644 index a972884777..0000000000 --- a/schemas/usps/karrio/schemas/usps/intl_rate_v2_request.py +++ /dev/null @@ -1,2126 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:08 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/intl_rate_v2_request.py') -# -# Command line arguments: -# ./schemas/IntlRateV2Request.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/intl_rate_v2_request.py" ./schemas/IntlRateV2Request.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class IntlRateV2Request(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, USERID=None, Revision=None, Package=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.USERID = _cast(None, USERID) - self.USERID_nsprefix_ = None - self.Revision = Revision - self.Revision_nsprefix_ = None - if Package is None: - self.Package = [] - else: - self.Package = Package - self.Package_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, IntlRateV2Request) - if subclass is not None: - return subclass(*args_, **kwargs_) - if IntlRateV2Request.subclass: - return IntlRateV2Request.subclass(*args_, **kwargs_) - else: - return IntlRateV2Request(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_Revision(self): - return self.Revision - def set_Revision(self, Revision): - self.Revision = Revision - def get_Package(self): - return self.Package - def set_Package(self, Package): - self.Package = Package - def add_Package(self, value): - self.Package.append(value) - def insert_Package_at(self, index, value): - self.Package.insert(index, value) - def replace_Package_at(self, index, value): - self.Package[index] = value - def get_USERID(self): - return self.USERID - def set_USERID(self, USERID): - self.USERID = USERID - def _hasContent(self): - if ( - self.Revision is not None or - self.Package - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='IntlRateV2Request', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('IntlRateV2Request') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'IntlRateV2Request': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='IntlRateV2Request') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='IntlRateV2Request', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='IntlRateV2Request'): - if self.USERID is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - outfile.write(' USERID=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.USERID), input_name='USERID')), )) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='IntlRateV2Request', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.Revision is not None: - namespaceprefix_ = self.Revision_nsprefix_ + ':' if (UseCapturedNS_ and self.Revision_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRevision>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Revision), input_name='Revision')), namespaceprefix_ , eol_)) - for Package_ in self.Package: - namespaceprefix_ = self.Package_nsprefix_ + ':' if (UseCapturedNS_ and self.Package_nsprefix_) else '' - Package_.export(outfile, level, namespaceprefix_, namespacedef_='', name_='Package', pretty_print=pretty_print) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('USERID', node) - if value is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - self.USERID = value - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'Revision': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Revision') - value_ = self.gds_validate_string(value_, node, 'Revision') - self.Revision = value_ - self.Revision_nsprefix_ = child_.prefix - elif nodeName_ == 'Package': - obj_ = PackageType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.Package.append(obj_) - obj_.original_tagname_ = 'Package' -# end class IntlRateV2Request - - -class PackageType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ID=None, Pounds=None, Ounces=None, Machinable=True, MailType=None, GXG=None, ValueOfContents=None, Country=None, Container=None, Size=None, Width=None, Length=None, Height=None, Girth=None, OriginZip=None, CommercialFlag=None, CommercialPlusFlag=None, ExtraServices=None, AcceptanceDateTime=None, DestinationPostalCode=None, Content=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.ID = _cast(None, ID) - self.ID_nsprefix_ = None - self.Pounds = Pounds - self.validate_PoundsType(self.Pounds) - self.Pounds_nsprefix_ = None - self.Ounces = Ounces - self.validate_OuncesType(self.Ounces) - self.Ounces_nsprefix_ = None - self.Machinable = Machinable - self.Machinable_nsprefix_ = None - self.MailType = MailType - self.MailType_nsprefix_ = None - self.GXG = GXG - self.GXG_nsprefix_ = None - self.ValueOfContents = ValueOfContents - self.ValueOfContents_nsprefix_ = None - self.Country = Country - self.Country_nsprefix_ = None - self.Container = Container - self.Container_nsprefix_ = None - self.Size = Size - self.Size_nsprefix_ = None - self.Width = Width - self.Width_nsprefix_ = None - self.Length = Length - self.Length_nsprefix_ = None - self.Height = Height - self.Height_nsprefix_ = None - self.Girth = Girth - self.Girth_nsprefix_ = None - self.OriginZip = OriginZip - self.OriginZip_nsprefix_ = None - self.CommercialFlag = CommercialFlag - self.CommercialFlag_nsprefix_ = None - self.CommercialPlusFlag = CommercialPlusFlag - self.CommercialPlusFlag_nsprefix_ = None - self.ExtraServices = ExtraServices - self.ExtraServices_nsprefix_ = None - self.AcceptanceDateTime = AcceptanceDateTime - self.AcceptanceDateTime_nsprefix_ = None - self.DestinationPostalCode = DestinationPostalCode - self.DestinationPostalCode_nsprefix_ = None - self.Content = Content - self.Content_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, PackageType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if PackageType.subclass: - return PackageType.subclass(*args_, **kwargs_) - else: - return PackageType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_Pounds(self): - return self.Pounds - def set_Pounds(self, Pounds): - self.Pounds = Pounds - def get_Ounces(self): - return self.Ounces - def set_Ounces(self, Ounces): - self.Ounces = Ounces - def get_Machinable(self): - return self.Machinable - def set_Machinable(self, Machinable): - self.Machinable = Machinable - def get_MailType(self): - return self.MailType - def set_MailType(self, MailType): - self.MailType = MailType - def get_GXG(self): - return self.GXG - def set_GXG(self, GXG): - self.GXG = GXG - def get_ValueOfContents(self): - return self.ValueOfContents - def set_ValueOfContents(self, ValueOfContents): - self.ValueOfContents = ValueOfContents - def get_Country(self): - return self.Country - def set_Country(self, Country): - self.Country = Country - def get_Container(self): - return self.Container - def set_Container(self, Container): - self.Container = Container - def get_Size(self): - return self.Size - def set_Size(self, Size): - self.Size = Size - def get_Width(self): - return self.Width - def set_Width(self, Width): - self.Width = Width - def get_Length(self): - return self.Length - def set_Length(self, Length): - self.Length = Length - def get_Height(self): - return self.Height - def set_Height(self, Height): - self.Height = Height - def get_Girth(self): - return self.Girth - def set_Girth(self, Girth): - self.Girth = Girth - def get_OriginZip(self): - return self.OriginZip - def set_OriginZip(self, OriginZip): - self.OriginZip = OriginZip - def get_CommercialFlag(self): - return self.CommercialFlag - def set_CommercialFlag(self, CommercialFlag): - self.CommercialFlag = CommercialFlag - def get_CommercialPlusFlag(self): - return self.CommercialPlusFlag - def set_CommercialPlusFlag(self, CommercialPlusFlag): - self.CommercialPlusFlag = CommercialPlusFlag - def get_ExtraServices(self): - return self.ExtraServices - def set_ExtraServices(self, ExtraServices): - self.ExtraServices = ExtraServices - def get_AcceptanceDateTime(self): - return self.AcceptanceDateTime - def set_AcceptanceDateTime(self, AcceptanceDateTime): - self.AcceptanceDateTime = AcceptanceDateTime - def get_DestinationPostalCode(self): - return self.DestinationPostalCode - def set_DestinationPostalCode(self, DestinationPostalCode): - self.DestinationPostalCode = DestinationPostalCode - def get_Content(self): - return self.Content - def set_Content(self, Content): - self.Content = Content - def get_ID(self): - return self.ID - def set_ID(self, ID): - self.ID = ID - def validate_PoundsType(self, value): - result = True - # Validate type PoundsType, a restriction on xs:integer. - if value is not None and Validate_simpletypes_ and self.gds_collector_ is not None: - if not isinstance(value, int): - lineno = self.gds_get_node_lineno_() - self.gds_collector_.add_message('Value "%(value)s"%(lineno)s is not of the correct base simple type (int)' % {"value": value, "lineno": lineno, }) - return False - if value < 0: - lineno = self.gds_get_node_lineno_() - self.gds_collector_.add_message('Value "%(value)s"%(lineno)s does not match xsd minInclusive restriction on PoundsType' % {"value": value, "lineno": lineno} ) - result = False - if value > 70: - lineno = self.gds_get_node_lineno_() - self.gds_collector_.add_message('Value "%(value)s"%(lineno)s does not match xsd maxInclusive restriction on PoundsType' % {"value": value, "lineno": lineno} ) - result = False - return result - def validate_OuncesType(self, value): - result = True - # Validate type OuncesType, a restriction on xs:decimal. - if value is not None and Validate_simpletypes_ and self.gds_collector_ is not None: - if not isinstance(value, decimal_.Decimal): - lineno = self.gds_get_node_lineno_() - self.gds_collector_.add_message('Value "%(value)s"%(lineno)s is not of the correct base simple type (decimal_.Decimal)' % {"value": value, "lineno": lineno, }) - return False - if value < 0.0: - lineno = self.gds_get_node_lineno_() - self.gds_collector_.add_message('Value "%(value)s"%(lineno)s does not match xsd minInclusive restriction on OuncesType' % {"value": value, "lineno": lineno} ) - result = False - return result - def _hasContent(self): - if ( - self.Pounds is not None or - self.Ounces is not None or - not self.Machinable or - self.MailType is not None or - self.GXG is not None or - self.ValueOfContents is not None or - self.Country is not None or - self.Container is not None or - self.Size is not None or - self.Width is not None or - self.Length is not None or - self.Height is not None or - self.Girth is not None or - self.OriginZip is not None or - self.CommercialFlag is not None or - self.CommercialPlusFlag is not None or - self.ExtraServices is not None or - self.AcceptanceDateTime is not None or - self.DestinationPostalCode is not None or - self.Content is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='PackageType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('PackageType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'PackageType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='PackageType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='PackageType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='PackageType'): - if self.ID is not None and 'ID' not in already_processed: - already_processed.add('ID') - outfile.write(' ID=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.ID), input_name='ID')), )) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='PackageType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.Pounds is not None: - namespaceprefix_ = self.Pounds_nsprefix_ + ':' if (UseCapturedNS_ and self.Pounds_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPounds>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.Pounds, input_name='Pounds'), namespaceprefix_ , eol_)) - if self.Ounces is not None: - namespaceprefix_ = self.Ounces_nsprefix_ + ':' if (UseCapturedNS_ and self.Ounces_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sOunces>%s%s' % (namespaceprefix_ , self.gds_format_decimal(self.Ounces, input_name='Ounces'), namespaceprefix_ , eol_)) - if not self.Machinable: - namespaceprefix_ = self.Machinable_nsprefix_ + ':' if (UseCapturedNS_ and self.Machinable_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sMachinable>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.Machinable, input_name='Machinable'), namespaceprefix_ , eol_)) - if self.MailType is not None: - namespaceprefix_ = self.MailType_nsprefix_ + ':' if (UseCapturedNS_ and self.MailType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sMailType>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.MailType), input_name='MailType')), namespaceprefix_ , eol_)) - if self.GXG is not None: - namespaceprefix_ = self.GXG_nsprefix_ + ':' if (UseCapturedNS_ and self.GXG_nsprefix_) else '' - self.GXG.export(outfile, level, namespaceprefix_, namespacedef_='', name_='GXG', pretty_print=pretty_print) - if self.ValueOfContents is not None: - namespaceprefix_ = self.ValueOfContents_nsprefix_ + ':' if (UseCapturedNS_ and self.ValueOfContents_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sValueOfContents>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ValueOfContents), input_name='ValueOfContents')), namespaceprefix_ , eol_)) - if self.Country is not None: - namespaceprefix_ = self.Country_nsprefix_ + ':' if (UseCapturedNS_ and self.Country_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCountry>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Country), input_name='Country')), namespaceprefix_ , eol_)) - if self.Container is not None: - namespaceprefix_ = self.Container_nsprefix_ + ':' if (UseCapturedNS_ and self.Container_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sContainer>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Container), input_name='Container')), namespaceprefix_ , eol_)) - if self.Size is not None: - namespaceprefix_ = self.Size_nsprefix_ + ':' if (UseCapturedNS_ and self.Size_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSize>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Size), input_name='Size')), namespaceprefix_ , eol_)) - if self.Width is not None: - namespaceprefix_ = self.Width_nsprefix_ + ':' if (UseCapturedNS_ and self.Width_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sWidth>%s%s' % (namespaceprefix_ , self.gds_format_decimal(self.Width, input_name='Width'), namespaceprefix_ , eol_)) - if self.Length is not None: - namespaceprefix_ = self.Length_nsprefix_ + ':' if (UseCapturedNS_ and self.Length_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sLength>%s%s' % (namespaceprefix_ , self.gds_format_decimal(self.Length, input_name='Length'), namespaceprefix_ , eol_)) - if self.Height is not None: - namespaceprefix_ = self.Height_nsprefix_ + ':' if (UseCapturedNS_ and self.Height_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sHeight>%s%s' % (namespaceprefix_ , self.gds_format_decimal(self.Height, input_name='Height'), namespaceprefix_ , eol_)) - if self.Girth is not None: - namespaceprefix_ = self.Girth_nsprefix_ + ':' if (UseCapturedNS_ and self.Girth_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sGirth>%s%s' % (namespaceprefix_ , self.gds_format_decimal(self.Girth, input_name='Girth'), namespaceprefix_ , eol_)) - if self.OriginZip is not None: - namespaceprefix_ = self.OriginZip_nsprefix_ + ':' if (UseCapturedNS_ and self.OriginZip_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sOriginZip>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.OriginZip), input_name='OriginZip')), namespaceprefix_ , eol_)) - if self.CommercialFlag is not None: - namespaceprefix_ = self.CommercialFlag_nsprefix_ + ':' if (UseCapturedNS_ and self.CommercialFlag_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCommercialFlag>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CommercialFlag), input_name='CommercialFlag')), namespaceprefix_ , eol_)) - if self.CommercialPlusFlag is not None: - namespaceprefix_ = self.CommercialPlusFlag_nsprefix_ + ':' if (UseCapturedNS_ and self.CommercialPlusFlag_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCommercialPlusFlag>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CommercialPlusFlag), input_name='CommercialPlusFlag')), namespaceprefix_ , eol_)) - if self.ExtraServices is not None: - namespaceprefix_ = self.ExtraServices_nsprefix_ + ':' if (UseCapturedNS_ and self.ExtraServices_nsprefix_) else '' - self.ExtraServices.export(outfile, level, namespaceprefix_, namespacedef_='', name_='ExtraServices', pretty_print=pretty_print) - if self.AcceptanceDateTime is not None: - namespaceprefix_ = self.AcceptanceDateTime_nsprefix_ + ':' if (UseCapturedNS_ and self.AcceptanceDateTime_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAcceptanceDateTime>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.AcceptanceDateTime), input_name='AcceptanceDateTime')), namespaceprefix_ , eol_)) - if self.DestinationPostalCode is not None: - namespaceprefix_ = self.DestinationPostalCode_nsprefix_ + ':' if (UseCapturedNS_ and self.DestinationPostalCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDestinationPostalCode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.DestinationPostalCode), input_name='DestinationPostalCode')), namespaceprefix_ , eol_)) - if self.Content is not None: - namespaceprefix_ = self.Content_nsprefix_ + ':' if (UseCapturedNS_ and self.Content_nsprefix_) else '' - self.Content.export(outfile, level, namespaceprefix_, namespacedef_='', name_='Content', pretty_print=pretty_print) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('ID', node) - if value is not None and 'ID' not in already_processed: - already_processed.add('ID') - self.ID = value - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'Pounds' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'Pounds') - ival_ = self.gds_validate_integer(ival_, node, 'Pounds') - self.Pounds = ival_ - self.Pounds_nsprefix_ = child_.prefix - # validate type PoundsType - self.validate_PoundsType(self.Pounds) - elif nodeName_ == 'Ounces' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_decimal(sval_, node, 'Ounces') - fval_ = self.gds_validate_decimal(fval_, node, 'Ounces') - self.Ounces = fval_ - self.Ounces_nsprefix_ = child_.prefix - # validate type OuncesType - self.validate_OuncesType(self.Ounces) - elif nodeName_ == 'Machinable': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'Machinable') - ival_ = self.gds_validate_boolean(ival_, node, 'Machinable') - self.Machinable = ival_ - self.Machinable_nsprefix_ = child_.prefix - elif nodeName_ == 'MailType': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'MailType') - value_ = self.gds_validate_string(value_, node, 'MailType') - self.MailType = value_ - self.MailType_nsprefix_ = child_.prefix - elif nodeName_ == 'GXG': - obj_ = GXGType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.GXG = obj_ - obj_.original_tagname_ = 'GXG' - elif nodeName_ == 'ValueOfContents': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ValueOfContents') - value_ = self.gds_validate_string(value_, node, 'ValueOfContents') - self.ValueOfContents = value_ - self.ValueOfContents_nsprefix_ = child_.prefix - elif nodeName_ == 'Country': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Country') - value_ = self.gds_validate_string(value_, node, 'Country') - self.Country = value_ - self.Country_nsprefix_ = child_.prefix - elif nodeName_ == 'Container': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Container') - value_ = self.gds_validate_string(value_, node, 'Container') - self.Container = value_ - self.Container_nsprefix_ = child_.prefix - elif nodeName_ == 'Size': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Size') - value_ = self.gds_validate_string(value_, node, 'Size') - self.Size = value_ - self.Size_nsprefix_ = child_.prefix - elif nodeName_ == 'Width' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_decimal(sval_, node, 'Width') - fval_ = self.gds_validate_decimal(fval_, node, 'Width') - self.Width = fval_ - self.Width_nsprefix_ = child_.prefix - elif nodeName_ == 'Length' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_decimal(sval_, node, 'Length') - fval_ = self.gds_validate_decimal(fval_, node, 'Length') - self.Length = fval_ - self.Length_nsprefix_ = child_.prefix - elif nodeName_ == 'Height' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_decimal(sval_, node, 'Height') - fval_ = self.gds_validate_decimal(fval_, node, 'Height') - self.Height = fval_ - self.Height_nsprefix_ = child_.prefix - elif nodeName_ == 'Girth' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_decimal(sval_, node, 'Girth') - fval_ = self.gds_validate_decimal(fval_, node, 'Girth') - self.Girth = fval_ - self.Girth_nsprefix_ = child_.prefix - elif nodeName_ == 'OriginZip': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'OriginZip') - value_ = self.gds_validate_string(value_, node, 'OriginZip') - self.OriginZip = value_ - self.OriginZip_nsprefix_ = child_.prefix - elif nodeName_ == 'CommercialFlag': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CommercialFlag') - value_ = self.gds_validate_string(value_, node, 'CommercialFlag') - self.CommercialFlag = value_ - self.CommercialFlag_nsprefix_ = child_.prefix - elif nodeName_ == 'CommercialPlusFlag': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CommercialPlusFlag') - value_ = self.gds_validate_string(value_, node, 'CommercialPlusFlag') - self.CommercialPlusFlag = value_ - self.CommercialPlusFlag_nsprefix_ = child_.prefix - elif nodeName_ == 'ExtraServices': - obj_ = ExtraServicesType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.ExtraServices = obj_ - obj_.original_tagname_ = 'ExtraServices' - elif nodeName_ == 'AcceptanceDateTime': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'AcceptanceDateTime') - value_ = self.gds_validate_string(value_, node, 'AcceptanceDateTime') - self.AcceptanceDateTime = value_ - self.AcceptanceDateTime_nsprefix_ = child_.prefix - elif nodeName_ == 'DestinationPostalCode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'DestinationPostalCode') - value_ = self.gds_validate_string(value_, node, 'DestinationPostalCode') - self.DestinationPostalCode = value_ - self.DestinationPostalCode_nsprefix_ = child_.prefix - elif nodeName_ == 'Content': - obj_ = ContentType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.Content = obj_ - obj_.original_tagname_ = 'Content' -# end class PackageType - - -class GXGType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, POBoxFlag=None, GiftFlag=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.POBoxFlag = POBoxFlag - self.POBoxFlag_nsprefix_ = None - self.GiftFlag = GiftFlag - self.GiftFlag_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, GXGType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if GXGType.subclass: - return GXGType.subclass(*args_, **kwargs_) - else: - return GXGType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_POBoxFlag(self): - return self.POBoxFlag - def set_POBoxFlag(self, POBoxFlag): - self.POBoxFlag = POBoxFlag - def get_GiftFlag(self): - return self.GiftFlag - def set_GiftFlag(self, GiftFlag): - self.GiftFlag = GiftFlag - def _hasContent(self): - if ( - self.POBoxFlag is not None or - self.GiftFlag is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='GXGType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('GXGType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'GXGType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='GXGType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='GXGType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='GXGType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='GXGType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.POBoxFlag is not None: - namespaceprefix_ = self.POBoxFlag_nsprefix_ + ':' if (UseCapturedNS_ and self.POBoxFlag_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPOBoxFlag>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.POBoxFlag), input_name='POBoxFlag')), namespaceprefix_ , eol_)) - if self.GiftFlag is not None: - namespaceprefix_ = self.GiftFlag_nsprefix_ + ':' if (UseCapturedNS_ and self.GiftFlag_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sGiftFlag>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.GiftFlag), input_name='GiftFlag')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'POBoxFlag': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'POBoxFlag') - value_ = self.gds_validate_string(value_, node, 'POBoxFlag') - self.POBoxFlag = value_ - self.POBoxFlag_nsprefix_ = child_.prefix - elif nodeName_ == 'GiftFlag': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'GiftFlag') - value_ = self.gds_validate_string(value_, node, 'GiftFlag') - self.GiftFlag = value_ - self.GiftFlag_nsprefix_ = child_.prefix -# end class GXGType - - -class ExtraServicesType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ExtraService=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - if ExtraService is None: - self.ExtraService = [] - else: - self.ExtraService = ExtraService - self.ExtraService_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, ExtraServicesType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if ExtraServicesType.subclass: - return ExtraServicesType.subclass(*args_, **kwargs_) - else: - return ExtraServicesType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_ExtraService(self): - return self.ExtraService - def set_ExtraService(self, ExtraService): - self.ExtraService = ExtraService - def add_ExtraService(self, value): - self.ExtraService.append(value) - def insert_ExtraService_at(self, index, value): - self.ExtraService.insert(index, value) - def replace_ExtraService_at(self, index, value): - self.ExtraService[index] = value - def _hasContent(self): - if ( - self.ExtraService - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ExtraServicesType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('ExtraServicesType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'ExtraServicesType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='ExtraServicesType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='ExtraServicesType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='ExtraServicesType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ExtraServicesType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - for ExtraService_ in self.ExtraService: - namespaceprefix_ = self.ExtraService_nsprefix_ + ':' if (UseCapturedNS_ and self.ExtraService_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sExtraService>%s%s' % (namespaceprefix_ , self.gds_format_integer(ExtraService_, input_name='ExtraService'), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'ExtraService' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'ExtraService') - ival_ = self.gds_validate_integer(ival_, node, 'ExtraService') - self.ExtraService.append(ival_) - self.ExtraService_nsprefix_ = child_.prefix -# end class ExtraServicesType - - -class ContentType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ContentType_member=None, ContentDescription=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.ContentType = ContentType_member - self.ContentType_nsprefix_ = None - self.ContentDescription = ContentDescription - self.ContentDescription_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, ContentType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if ContentType.subclass: - return ContentType.subclass(*args_, **kwargs_) - else: - return ContentType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_ContentType(self): - return self.ContentType - def set_ContentType(self, ContentType): - self.ContentType = ContentType - def get_ContentDescription(self): - return self.ContentDescription - def set_ContentDescription(self, ContentDescription): - self.ContentDescription = ContentDescription - def _hasContent(self): - if ( - self.ContentType is not None or - self.ContentDescription is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ContentType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('ContentType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'ContentType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='ContentType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='ContentType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='ContentType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ContentType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.ContentType is not None: - namespaceprefix_ = self.ContentType_nsprefix_ + ':' if (UseCapturedNS_ and self.ContentType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sContentType>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ContentType), input_name='ContentType')), namespaceprefix_ , eol_)) - if self.ContentDescription is not None: - namespaceprefix_ = self.ContentDescription_nsprefix_ + ':' if (UseCapturedNS_ and self.ContentDescription_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sContentDescription>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ContentDescription), input_name='ContentDescription')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'ContentType': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ContentType') - value_ = self.gds_validate_string(value_, node, 'ContentType') - self.ContentType = value_ - self.ContentType_nsprefix_ = child_.prefix - elif nodeName_ == 'ContentDescription': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ContentDescription') - value_ = self.gds_validate_string(value_, node, 'ContentDescription') - self.ContentDescription = value_ - self.ContentDescription_nsprefix_ = child_.prefix -# end class ContentType - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'IntlRateV2Request' - rootClass = IntlRateV2Request - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'IntlRateV2Request' - rootClass = IntlRateV2Request - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'IntlRateV2Request' - rootClass = IntlRateV2Request - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'IntlRateV2Request' - rootClass = IntlRateV2Request - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from intl_rate_v2_request import *\n\n') - sys.stdout.write('import intl_rate_v2_request as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "ContentType", - "ExtraServicesType", - "GXGType", - "IntlRateV2Request", - "PackageType" -] diff --git a/schemas/usps/karrio/schemas/usps/intl_rate_v2_response.py b/schemas/usps/karrio/schemas/usps/intl_rate_v2_response.py deleted file mode 100644 index d91cab0f5e..0000000000 --- a/schemas/usps/karrio/schemas/usps/intl_rate_v2_response.py +++ /dev/null @@ -1,2866 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:08 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/intl_rate_v2_response.py') -# -# Command line arguments: -# ./schemas/IntlRateV2Response.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/intl_rate_v2_response.py" ./schemas/IntlRateV2Response.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class IntlRateV2Response(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, Package=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - if Package is None: - self.Package = [] - else: - self.Package = Package - self.Package_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, IntlRateV2Response) - if subclass is not None: - return subclass(*args_, **kwargs_) - if IntlRateV2Response.subclass: - return IntlRateV2Response.subclass(*args_, **kwargs_) - else: - return IntlRateV2Response(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_Package(self): - return self.Package - def set_Package(self, Package): - self.Package = Package - def add_Package(self, value): - self.Package.append(value) - def insert_Package_at(self, index, value): - self.Package.insert(index, value) - def replace_Package_at(self, index, value): - self.Package[index] = value - def _hasContent(self): - if ( - self.Package - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='IntlRateV2Response', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('IntlRateV2Response') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'IntlRateV2Response': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='IntlRateV2Response') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='IntlRateV2Response', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='IntlRateV2Response'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='IntlRateV2Response', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - for Package_ in self.Package: - namespaceprefix_ = self.Package_nsprefix_ + ':' if (UseCapturedNS_ and self.Package_nsprefix_) else '' - Package_.export(outfile, level, namespaceprefix_, namespacedef_='', name_='Package', pretty_print=pretty_print) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'Package': - obj_ = PackageType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.Package.append(obj_) - obj_.original_tagname_ = 'Package' -# end class IntlRateV2Response - - -class PackageType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ID=None, Prohibitions=None, Restrictions=None, Observations=None, CustomsForms=None, ExpressMail=None, AreasServed=None, AdditionalRestrictions=None, Content=None, Service=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.ID = _cast(None, ID) - self.ID_nsprefix_ = None - self.Prohibitions = Prohibitions - self.Prohibitions_nsprefix_ = None - self.Restrictions = Restrictions - self.Restrictions_nsprefix_ = None - self.Observations = Observations - self.Observations_nsprefix_ = None - self.CustomsForms = CustomsForms - self.CustomsForms_nsprefix_ = None - self.ExpressMail = ExpressMail - self.ExpressMail_nsprefix_ = None - self.AreasServed = AreasServed - self.AreasServed_nsprefix_ = None - self.AdditionalRestrictions = AdditionalRestrictions - self.AdditionalRestrictions_nsprefix_ = None - self.Content = Content - self.Content_nsprefix_ = None - if Service is None: - self.Service = [] - else: - self.Service = Service - self.Service_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, PackageType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if PackageType.subclass: - return PackageType.subclass(*args_, **kwargs_) - else: - return PackageType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_Prohibitions(self): - return self.Prohibitions - def set_Prohibitions(self, Prohibitions): - self.Prohibitions = Prohibitions - def get_Restrictions(self): - return self.Restrictions - def set_Restrictions(self, Restrictions): - self.Restrictions = Restrictions - def get_Observations(self): - return self.Observations - def set_Observations(self, Observations): - self.Observations = Observations - def get_CustomsForms(self): - return self.CustomsForms - def set_CustomsForms(self, CustomsForms): - self.CustomsForms = CustomsForms - def get_ExpressMail(self): - return self.ExpressMail - def set_ExpressMail(self, ExpressMail): - self.ExpressMail = ExpressMail - def get_AreasServed(self): - return self.AreasServed - def set_AreasServed(self, AreasServed): - self.AreasServed = AreasServed - def get_AdditionalRestrictions(self): - return self.AdditionalRestrictions - def set_AdditionalRestrictions(self, AdditionalRestrictions): - self.AdditionalRestrictions = AdditionalRestrictions - def get_Content(self): - return self.Content - def set_Content(self, Content): - self.Content = Content - def get_Service(self): - return self.Service - def set_Service(self, Service): - self.Service = Service - def add_Service(self, value): - self.Service.append(value) - def insert_Service_at(self, index, value): - self.Service.insert(index, value) - def replace_Service_at(self, index, value): - self.Service[index] = value - def get_ID(self): - return self.ID - def set_ID(self, ID): - self.ID = ID - def _hasContent(self): - if ( - self.Prohibitions is not None or - self.Restrictions is not None or - self.Observations is not None or - self.CustomsForms is not None or - self.ExpressMail is not None or - self.AreasServed is not None or - self.AdditionalRestrictions is not None or - self.Content is not None or - self.Service - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='PackageType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('PackageType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'PackageType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='PackageType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='PackageType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='PackageType'): - if self.ID is not None and 'ID' not in already_processed: - already_processed.add('ID') - outfile.write(' ID=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.ID), input_name='ID')), )) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='PackageType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.Prohibitions is not None: - namespaceprefix_ = self.Prohibitions_nsprefix_ + ':' if (UseCapturedNS_ and self.Prohibitions_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sProhibitions>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Prohibitions), input_name='Prohibitions')), namespaceprefix_ , eol_)) - if self.Restrictions is not None: - namespaceprefix_ = self.Restrictions_nsprefix_ + ':' if (UseCapturedNS_ and self.Restrictions_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRestrictions>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Restrictions), input_name='Restrictions')), namespaceprefix_ , eol_)) - if self.Observations is not None: - namespaceprefix_ = self.Observations_nsprefix_ + ':' if (UseCapturedNS_ and self.Observations_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sObservations>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Observations), input_name='Observations')), namespaceprefix_ , eol_)) - if self.CustomsForms is not None: - namespaceprefix_ = self.CustomsForms_nsprefix_ + ':' if (UseCapturedNS_ and self.CustomsForms_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCustomsForms>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CustomsForms), input_name='CustomsForms')), namespaceprefix_ , eol_)) - if self.ExpressMail is not None: - namespaceprefix_ = self.ExpressMail_nsprefix_ + ':' if (UseCapturedNS_ and self.ExpressMail_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sExpressMail>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ExpressMail), input_name='ExpressMail')), namespaceprefix_ , eol_)) - if self.AreasServed is not None: - namespaceprefix_ = self.AreasServed_nsprefix_ + ':' if (UseCapturedNS_ and self.AreasServed_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAreasServed>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.AreasServed), input_name='AreasServed')), namespaceprefix_ , eol_)) - if self.AdditionalRestrictions is not None: - namespaceprefix_ = self.AdditionalRestrictions_nsprefix_ + ':' if (UseCapturedNS_ and self.AdditionalRestrictions_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAdditionalRestrictions>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.AdditionalRestrictions), input_name='AdditionalRestrictions')), namespaceprefix_ , eol_)) - if self.Content is not None: - namespaceprefix_ = self.Content_nsprefix_ + ':' if (UseCapturedNS_ and self.Content_nsprefix_) else '' - self.Content.export(outfile, level, namespaceprefix_, namespacedef_='', name_='Content', pretty_print=pretty_print) - for Service_ in self.Service: - namespaceprefix_ = self.Service_nsprefix_ + ':' if (UseCapturedNS_ and self.Service_nsprefix_) else '' - Service_.export(outfile, level, namespaceprefix_, namespacedef_='', name_='Service', pretty_print=pretty_print) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('ID', node) - if value is not None and 'ID' not in already_processed: - already_processed.add('ID') - self.ID = value - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'Prohibitions': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Prohibitions') - value_ = self.gds_validate_string(value_, node, 'Prohibitions') - self.Prohibitions = value_ - self.Prohibitions_nsprefix_ = child_.prefix - elif nodeName_ == 'Restrictions': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Restrictions') - value_ = self.gds_validate_string(value_, node, 'Restrictions') - self.Restrictions = value_ - self.Restrictions_nsprefix_ = child_.prefix - elif nodeName_ == 'Observations': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Observations') - value_ = self.gds_validate_string(value_, node, 'Observations') - self.Observations = value_ - self.Observations_nsprefix_ = child_.prefix - elif nodeName_ == 'CustomsForms': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CustomsForms') - value_ = self.gds_validate_string(value_, node, 'CustomsForms') - self.CustomsForms = value_ - self.CustomsForms_nsprefix_ = child_.prefix - elif nodeName_ == 'ExpressMail': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ExpressMail') - value_ = self.gds_validate_string(value_, node, 'ExpressMail') - self.ExpressMail = value_ - self.ExpressMail_nsprefix_ = child_.prefix - elif nodeName_ == 'AreasServed': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'AreasServed') - value_ = self.gds_validate_string(value_, node, 'AreasServed') - self.AreasServed = value_ - self.AreasServed_nsprefix_ = child_.prefix - elif nodeName_ == 'AdditionalRestrictions': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'AdditionalRestrictions') - value_ = self.gds_validate_string(value_, node, 'AdditionalRestrictions') - self.AdditionalRestrictions = value_ - self.AdditionalRestrictions_nsprefix_ = child_.prefix - elif nodeName_ == 'Content': - obj_ = ContentType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.Content = obj_ - obj_.original_tagname_ = 'Content' - elif nodeName_ == 'Service': - obj_ = ServiceType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.Service.append(obj_) - obj_.original_tagname_ = 'Service' -# end class PackageType - - -class ContentType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ContentType_member=None, ContentDescription=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.ContentType = ContentType_member - self.ContentType_nsprefix_ = None - self.ContentDescription = ContentDescription - self.ContentDescription_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, ContentType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if ContentType.subclass: - return ContentType.subclass(*args_, **kwargs_) - else: - return ContentType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_ContentType(self): - return self.ContentType - def set_ContentType(self, ContentType): - self.ContentType = ContentType - def get_ContentDescription(self): - return self.ContentDescription - def set_ContentDescription(self, ContentDescription): - self.ContentDescription = ContentDescription - def _hasContent(self): - if ( - self.ContentType is not None or - self.ContentDescription is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ContentType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('ContentType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'ContentType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='ContentType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='ContentType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='ContentType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ContentType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.ContentType is not None: - namespaceprefix_ = self.ContentType_nsprefix_ + ':' if (UseCapturedNS_ and self.ContentType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sContentType>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ContentType), input_name='ContentType')), namespaceprefix_ , eol_)) - if self.ContentDescription is not None: - namespaceprefix_ = self.ContentDescription_nsprefix_ + ':' if (UseCapturedNS_ and self.ContentDescription_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sContentDescription>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ContentDescription), input_name='ContentDescription')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'ContentType': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ContentType') - value_ = self.gds_validate_string(value_, node, 'ContentType') - self.ContentType = value_ - self.ContentType_nsprefix_ = child_.prefix - elif nodeName_ == 'ContentDescription': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ContentDescription') - value_ = self.gds_validate_string(value_, node, 'ContentDescription') - self.ContentDescription = value_ - self.ContentDescription_nsprefix_ = child_.prefix -# end class ContentType - - -class ServiceType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ID=None, Pounds=None, Ounces=None, Machinable=None, MailType=None, GXG=None, Container=None, Width=None, Length=None, Height=None, Girth=None, Country=None, Postage=None, CommercialPostage=None, CommercialPlusPostage=None, ExtraServices=None, ValueOfContents=None, InsComment=None, ParcelIndemnityCoverage=None, SvcCommitments=None, SvcDescription=None, MaxDimensions=None, MaxWeight=None, GuaranteeAvailability=None, GXGLocations=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.ID = _cast(int, ID) - self.ID_nsprefix_ = None - self.Pounds = Pounds - self.Pounds_nsprefix_ = None - self.Ounces = Ounces - self.Ounces_nsprefix_ = None - self.Machinable = Machinable - self.Machinable_nsprefix_ = None - self.MailType = MailType - self.MailType_nsprefix_ = None - self.GXG = GXG - self.GXG_nsprefix_ = None - self.Container = Container - self.Container_nsprefix_ = None - self.Width = Width - self.Width_nsprefix_ = None - self.Length = Length - self.Length_nsprefix_ = None - self.Height = Height - self.Height_nsprefix_ = None - self.Girth = Girth - self.Girth_nsprefix_ = None - self.Country = Country - self.Country_nsprefix_ = None - self.Postage = Postage - self.Postage_nsprefix_ = None - self.CommercialPostage = CommercialPostage - self.CommercialPostage_nsprefix_ = None - self.CommercialPlusPostage = CommercialPlusPostage - self.CommercialPlusPostage_nsprefix_ = None - self.ExtraServices = ExtraServices - self.ExtraServices_nsprefix_ = None - self.ValueOfContents = ValueOfContents - self.ValueOfContents_nsprefix_ = None - self.InsComment = InsComment - self.InsComment_nsprefix_ = None - self.ParcelIndemnityCoverage = ParcelIndemnityCoverage - self.ParcelIndemnityCoverage_nsprefix_ = None - self.SvcCommitments = SvcCommitments - self.SvcCommitments_nsprefix_ = None - self.SvcDescription = SvcDescription - self.SvcDescription_nsprefix_ = None - self.MaxDimensions = MaxDimensions - self.MaxDimensions_nsprefix_ = None - self.MaxWeight = MaxWeight - self.MaxWeight_nsprefix_ = None - self.GuaranteeAvailability = GuaranteeAvailability - self.GuaranteeAvailability_nsprefix_ = None - self.GXGLocations = GXGLocations - self.GXGLocations_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, ServiceType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if ServiceType.subclass: - return ServiceType.subclass(*args_, **kwargs_) - else: - return ServiceType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_Pounds(self): - return self.Pounds - def set_Pounds(self, Pounds): - self.Pounds = Pounds - def get_Ounces(self): - return self.Ounces - def set_Ounces(self, Ounces): - self.Ounces = Ounces - def get_Machinable(self): - return self.Machinable - def set_Machinable(self, Machinable): - self.Machinable = Machinable - def get_MailType(self): - return self.MailType - def set_MailType(self, MailType): - self.MailType = MailType - def get_GXG(self): - return self.GXG - def set_GXG(self, GXG): - self.GXG = GXG - def get_Container(self): - return self.Container - def set_Container(self, Container): - self.Container = Container - def get_Width(self): - return self.Width - def set_Width(self, Width): - self.Width = Width - def get_Length(self): - return self.Length - def set_Length(self, Length): - self.Length = Length - def get_Height(self): - return self.Height - def set_Height(self, Height): - self.Height = Height - def get_Girth(self): - return self.Girth - def set_Girth(self, Girth): - self.Girth = Girth - def get_Country(self): - return self.Country - def set_Country(self, Country): - self.Country = Country - def get_Postage(self): - return self.Postage - def set_Postage(self, Postage): - self.Postage = Postage - def get_CommercialPostage(self): - return self.CommercialPostage - def set_CommercialPostage(self, CommercialPostage): - self.CommercialPostage = CommercialPostage - def get_CommercialPlusPostage(self): - return self.CommercialPlusPostage - def set_CommercialPlusPostage(self, CommercialPlusPostage): - self.CommercialPlusPostage = CommercialPlusPostage - def get_ExtraServices(self): - return self.ExtraServices - def set_ExtraServices(self, ExtraServices): - self.ExtraServices = ExtraServices - def get_ValueOfContents(self): - return self.ValueOfContents - def set_ValueOfContents(self, ValueOfContents): - self.ValueOfContents = ValueOfContents - def get_InsComment(self): - return self.InsComment - def set_InsComment(self, InsComment): - self.InsComment = InsComment - def get_ParcelIndemnityCoverage(self): - return self.ParcelIndemnityCoverage - def set_ParcelIndemnityCoverage(self, ParcelIndemnityCoverage): - self.ParcelIndemnityCoverage = ParcelIndemnityCoverage - def get_SvcCommitments(self): - return self.SvcCommitments - def set_SvcCommitments(self, SvcCommitments): - self.SvcCommitments = SvcCommitments - def get_SvcDescription(self): - return self.SvcDescription - def set_SvcDescription(self, SvcDescription): - self.SvcDescription = SvcDescription - def get_MaxDimensions(self): - return self.MaxDimensions - def set_MaxDimensions(self, MaxDimensions): - self.MaxDimensions = MaxDimensions - def get_MaxWeight(self): - return self.MaxWeight - def set_MaxWeight(self, MaxWeight): - self.MaxWeight = MaxWeight - def get_GuaranteeAvailability(self): - return self.GuaranteeAvailability - def set_GuaranteeAvailability(self, GuaranteeAvailability): - self.GuaranteeAvailability = GuaranteeAvailability - def get_GXGLocations(self): - return self.GXGLocations - def set_GXGLocations(self, GXGLocations): - self.GXGLocations = GXGLocations - def get_ID(self): - return self.ID - def set_ID(self, ID): - self.ID = ID - def _hasContent(self): - if ( - self.Pounds is not None or - self.Ounces is not None or - self.Machinable is not None or - self.MailType is not None or - self.GXG is not None or - self.Container is not None or - self.Width is not None or - self.Length is not None or - self.Height is not None or - self.Girth is not None or - self.Country is not None or - self.Postage is not None or - self.CommercialPostage is not None or - self.CommercialPlusPostage is not None or - self.ExtraServices is not None or - self.ValueOfContents is not None or - self.InsComment is not None or - self.ParcelIndemnityCoverage is not None or - self.SvcCommitments is not None or - self.SvcDescription is not None or - self.MaxDimensions is not None or - self.MaxWeight is not None or - self.GuaranteeAvailability is not None or - self.GXGLocations is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ServiceType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('ServiceType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'ServiceType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='ServiceType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='ServiceType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='ServiceType'): - if self.ID is not None and 'ID' not in already_processed: - already_processed.add('ID') - outfile.write(' ID="%s"' % self.gds_format_integer(self.ID, input_name='ID')) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ServiceType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.Pounds is not None: - namespaceprefix_ = self.Pounds_nsprefix_ + ':' if (UseCapturedNS_ and self.Pounds_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPounds>%s%s' % (namespaceprefix_ , self.gds_format_float(self.Pounds, input_name='Pounds'), namespaceprefix_ , eol_)) - if self.Ounces is not None: - namespaceprefix_ = self.Ounces_nsprefix_ + ':' if (UseCapturedNS_ and self.Ounces_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sOunces>%s%s' % (namespaceprefix_ , self.gds_format_float(self.Ounces, input_name='Ounces'), namespaceprefix_ , eol_)) - if self.Machinable is not None: - namespaceprefix_ = self.Machinable_nsprefix_ + ':' if (UseCapturedNS_ and self.Machinable_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sMachinable>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Machinable), input_name='Machinable')), namespaceprefix_ , eol_)) - if self.MailType is not None: - namespaceprefix_ = self.MailType_nsprefix_ + ':' if (UseCapturedNS_ and self.MailType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sMailType>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.MailType), input_name='MailType')), namespaceprefix_ , eol_)) - if self.GXG is not None: - namespaceprefix_ = self.GXG_nsprefix_ + ':' if (UseCapturedNS_ and self.GXG_nsprefix_) else '' - self.GXG.export(outfile, level, namespaceprefix_, namespacedef_='', name_='GXG', pretty_print=pretty_print) - if self.Container is not None: - namespaceprefix_ = self.Container_nsprefix_ + ':' if (UseCapturedNS_ and self.Container_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sContainer>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Container), input_name='Container')), namespaceprefix_ , eol_)) - if self.Width is not None: - namespaceprefix_ = self.Width_nsprefix_ + ':' if (UseCapturedNS_ and self.Width_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sWidth>%s%s' % (namespaceprefix_ , self.gds_format_float(self.Width, input_name='Width'), namespaceprefix_ , eol_)) - if self.Length is not None: - namespaceprefix_ = self.Length_nsprefix_ + ':' if (UseCapturedNS_ and self.Length_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sLength>%s%s' % (namespaceprefix_ , self.gds_format_float(self.Length, input_name='Length'), namespaceprefix_ , eol_)) - if self.Height is not None: - namespaceprefix_ = self.Height_nsprefix_ + ':' if (UseCapturedNS_ and self.Height_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sHeight>%s%s' % (namespaceprefix_ , self.gds_format_float(self.Height, input_name='Height'), namespaceprefix_ , eol_)) - if self.Girth is not None: - namespaceprefix_ = self.Girth_nsprefix_ + ':' if (UseCapturedNS_ and self.Girth_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sGirth>%s%s' % (namespaceprefix_ , self.gds_format_float(self.Girth, input_name='Girth'), namespaceprefix_ , eol_)) - if self.Country is not None: - namespaceprefix_ = self.Country_nsprefix_ + ':' if (UseCapturedNS_ and self.Country_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCountry>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Country), input_name='Country')), namespaceprefix_ , eol_)) - if self.Postage is not None: - namespaceprefix_ = self.Postage_nsprefix_ + ':' if (UseCapturedNS_ and self.Postage_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPostage>%s%s' % (namespaceprefix_ , self.gds_format_float(self.Postage, input_name='Postage'), namespaceprefix_ , eol_)) - if self.CommercialPostage is not None: - namespaceprefix_ = self.CommercialPostage_nsprefix_ + ':' if (UseCapturedNS_ and self.CommercialPostage_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCommercialPostage>%s%s' % (namespaceprefix_ , self.gds_format_float(self.CommercialPostage, input_name='CommercialPostage'), namespaceprefix_ , eol_)) - if self.CommercialPlusPostage is not None: - namespaceprefix_ = self.CommercialPlusPostage_nsprefix_ + ':' if (UseCapturedNS_ and self.CommercialPlusPostage_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCommercialPlusPostage>%s%s' % (namespaceprefix_ , self.gds_format_float(self.CommercialPlusPostage, input_name='CommercialPlusPostage'), namespaceprefix_ , eol_)) - if self.ExtraServices is not None: - namespaceprefix_ = self.ExtraServices_nsprefix_ + ':' if (UseCapturedNS_ and self.ExtraServices_nsprefix_) else '' - self.ExtraServices.export(outfile, level, namespaceprefix_, namespacedef_='', name_='ExtraServices', pretty_print=pretty_print) - if self.ValueOfContents is not None: - namespaceprefix_ = self.ValueOfContents_nsprefix_ + ':' if (UseCapturedNS_ and self.ValueOfContents_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sValueOfContents>%s%s' % (namespaceprefix_ , self.gds_format_float(self.ValueOfContents, input_name='ValueOfContents'), namespaceprefix_ , eol_)) - if self.InsComment is not None: - namespaceprefix_ = self.InsComment_nsprefix_ + ':' if (UseCapturedNS_ and self.InsComment_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sInsComment>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.InsComment), input_name='InsComment')), namespaceprefix_ , eol_)) - if self.ParcelIndemnityCoverage is not None: - namespaceprefix_ = self.ParcelIndemnityCoverage_nsprefix_ + ':' if (UseCapturedNS_ and self.ParcelIndemnityCoverage_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sParcelIndemnityCoverage>%s%s' % (namespaceprefix_ , self.gds_format_float(self.ParcelIndemnityCoverage, input_name='ParcelIndemnityCoverage'), namespaceprefix_ , eol_)) - if self.SvcCommitments is not None: - namespaceprefix_ = self.SvcCommitments_nsprefix_ + ':' if (UseCapturedNS_ and self.SvcCommitments_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSvcCommitments>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SvcCommitments), input_name='SvcCommitments')), namespaceprefix_ , eol_)) - if self.SvcDescription is not None: - namespaceprefix_ = self.SvcDescription_nsprefix_ + ':' if (UseCapturedNS_ and self.SvcDescription_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSvcDescription>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SvcDescription), input_name='SvcDescription')), namespaceprefix_ , eol_)) - if self.MaxDimensions is not None: - namespaceprefix_ = self.MaxDimensions_nsprefix_ + ':' if (UseCapturedNS_ and self.MaxDimensions_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sMaxDimensions>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.MaxDimensions), input_name='MaxDimensions')), namespaceprefix_ , eol_)) - if self.MaxWeight is not None: - namespaceprefix_ = self.MaxWeight_nsprefix_ + ':' if (UseCapturedNS_ and self.MaxWeight_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sMaxWeight>%s%s' % (namespaceprefix_ , self.gds_format_float(self.MaxWeight, input_name='MaxWeight'), namespaceprefix_ , eol_)) - if self.GuaranteeAvailability is not None: - namespaceprefix_ = self.GuaranteeAvailability_nsprefix_ + ':' if (UseCapturedNS_ and self.GuaranteeAvailability_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sGuaranteeAvailability>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.GuaranteeAvailability), input_name='GuaranteeAvailability')), namespaceprefix_ , eol_)) - if self.GXGLocations is not None: - namespaceprefix_ = self.GXGLocations_nsprefix_ + ':' if (UseCapturedNS_ and self.GXGLocations_nsprefix_) else '' - self.GXGLocations.export(outfile, level, namespaceprefix_, namespacedef_='', name_='GXGLocations', pretty_print=pretty_print) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('ID', node) - if value is not None and 'ID' not in already_processed: - already_processed.add('ID') - self.ID = self.gds_parse_integer(value, node, 'ID') - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'Pounds' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'Pounds') - fval_ = self.gds_validate_float(fval_, node, 'Pounds') - self.Pounds = fval_ - self.Pounds_nsprefix_ = child_.prefix - elif nodeName_ == 'Ounces' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'Ounces') - fval_ = self.gds_validate_float(fval_, node, 'Ounces') - self.Ounces = fval_ - self.Ounces_nsprefix_ = child_.prefix - elif nodeName_ == 'Machinable': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Machinable') - value_ = self.gds_validate_string(value_, node, 'Machinable') - self.Machinable = value_ - self.Machinable_nsprefix_ = child_.prefix - elif nodeName_ == 'MailType': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'MailType') - value_ = self.gds_validate_string(value_, node, 'MailType') - self.MailType = value_ - self.MailType_nsprefix_ = child_.prefix - elif nodeName_ == 'GXG': - obj_ = GXGType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.GXG = obj_ - obj_.original_tagname_ = 'GXG' - elif nodeName_ == 'Container': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Container') - value_ = self.gds_validate_string(value_, node, 'Container') - self.Container = value_ - self.Container_nsprefix_ = child_.prefix - elif nodeName_ == 'Width' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'Width') - fval_ = self.gds_validate_float(fval_, node, 'Width') - self.Width = fval_ - self.Width_nsprefix_ = child_.prefix - elif nodeName_ == 'Length' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'Length') - fval_ = self.gds_validate_float(fval_, node, 'Length') - self.Length = fval_ - self.Length_nsprefix_ = child_.prefix - elif nodeName_ == 'Height' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'Height') - fval_ = self.gds_validate_float(fval_, node, 'Height') - self.Height = fval_ - self.Height_nsprefix_ = child_.prefix - elif nodeName_ == 'Girth' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'Girth') - fval_ = self.gds_validate_float(fval_, node, 'Girth') - self.Girth = fval_ - self.Girth_nsprefix_ = child_.prefix - elif nodeName_ == 'Country': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Country') - value_ = self.gds_validate_string(value_, node, 'Country') - self.Country = value_ - self.Country_nsprefix_ = child_.prefix - elif nodeName_ == 'Postage' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'Postage') - fval_ = self.gds_validate_float(fval_, node, 'Postage') - self.Postage = fval_ - self.Postage_nsprefix_ = child_.prefix - elif nodeName_ == 'CommercialPostage' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'CommercialPostage') - fval_ = self.gds_validate_float(fval_, node, 'CommercialPostage') - self.CommercialPostage = fval_ - self.CommercialPostage_nsprefix_ = child_.prefix - elif nodeName_ == 'CommercialPlusPostage' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'CommercialPlusPostage') - fval_ = self.gds_validate_float(fval_, node, 'CommercialPlusPostage') - self.CommercialPlusPostage = fval_ - self.CommercialPlusPostage_nsprefix_ = child_.prefix - elif nodeName_ == 'ExtraServices': - obj_ = ExtraServicesType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.ExtraServices = obj_ - obj_.original_tagname_ = 'ExtraServices' - elif nodeName_ == 'ValueOfContents' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'ValueOfContents') - fval_ = self.gds_validate_float(fval_, node, 'ValueOfContents') - self.ValueOfContents = fval_ - self.ValueOfContents_nsprefix_ = child_.prefix - elif nodeName_ == 'InsComment': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'InsComment') - value_ = self.gds_validate_string(value_, node, 'InsComment') - self.InsComment = value_ - self.InsComment_nsprefix_ = child_.prefix - elif nodeName_ == 'ParcelIndemnityCoverage' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'ParcelIndemnityCoverage') - fval_ = self.gds_validate_float(fval_, node, 'ParcelIndemnityCoverage') - self.ParcelIndemnityCoverage = fval_ - self.ParcelIndemnityCoverage_nsprefix_ = child_.prefix - elif nodeName_ == 'SvcCommitments': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SvcCommitments') - value_ = self.gds_validate_string(value_, node, 'SvcCommitments') - self.SvcCommitments = value_ - self.SvcCommitments_nsprefix_ = child_.prefix - elif nodeName_ == 'SvcDescription': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SvcDescription') - value_ = self.gds_validate_string(value_, node, 'SvcDescription') - self.SvcDescription = value_ - self.SvcDescription_nsprefix_ = child_.prefix - elif nodeName_ == 'MaxDimensions': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'MaxDimensions') - value_ = self.gds_validate_string(value_, node, 'MaxDimensions') - self.MaxDimensions = value_ - self.MaxDimensions_nsprefix_ = child_.prefix - elif nodeName_ == 'MaxWeight' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'MaxWeight') - fval_ = self.gds_validate_float(fval_, node, 'MaxWeight') - self.MaxWeight = fval_ - self.MaxWeight_nsprefix_ = child_.prefix - elif nodeName_ == 'GuaranteeAvailability': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'GuaranteeAvailability') - value_ = self.gds_validate_string(value_, node, 'GuaranteeAvailability') - self.GuaranteeAvailability = value_ - self.GuaranteeAvailability_nsprefix_ = child_.prefix - elif nodeName_ == 'GXGLocations': - obj_ = GXGLocationsType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.GXGLocations = obj_ - obj_.original_tagname_ = 'GXGLocations' -# end class ServiceType - - -class GXGType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, POBoxFlag=None, GiftFlag=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.POBoxFlag = POBoxFlag - self.POBoxFlag_nsprefix_ = None - self.GiftFlag = GiftFlag - self.GiftFlag_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, GXGType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if GXGType.subclass: - return GXGType.subclass(*args_, **kwargs_) - else: - return GXGType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_POBoxFlag(self): - return self.POBoxFlag - def set_POBoxFlag(self, POBoxFlag): - self.POBoxFlag = POBoxFlag - def get_GiftFlag(self): - return self.GiftFlag - def set_GiftFlag(self, GiftFlag): - self.GiftFlag = GiftFlag - def _hasContent(self): - if ( - self.POBoxFlag is not None or - self.GiftFlag is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='GXGType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('GXGType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'GXGType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='GXGType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='GXGType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='GXGType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='GXGType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.POBoxFlag is not None: - namespaceprefix_ = self.POBoxFlag_nsprefix_ + ':' if (UseCapturedNS_ and self.POBoxFlag_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPOBoxFlag>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.POBoxFlag), input_name='POBoxFlag')), namespaceprefix_ , eol_)) - if self.GiftFlag is not None: - namespaceprefix_ = self.GiftFlag_nsprefix_ + ':' if (UseCapturedNS_ and self.GiftFlag_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sGiftFlag>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.GiftFlag), input_name='GiftFlag')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'POBoxFlag': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'POBoxFlag') - value_ = self.gds_validate_string(value_, node, 'POBoxFlag') - self.POBoxFlag = value_ - self.POBoxFlag_nsprefix_ = child_.prefix - elif nodeName_ == 'GiftFlag': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'GiftFlag') - value_ = self.gds_validate_string(value_, node, 'GiftFlag') - self.GiftFlag = value_ - self.GiftFlag_nsprefix_ = child_.prefix -# end class GXGType - - -class ExtraServicesType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ExtraService=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - if ExtraService is None: - self.ExtraService = [] - else: - self.ExtraService = ExtraService - self.ExtraService_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, ExtraServicesType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if ExtraServicesType.subclass: - return ExtraServicesType.subclass(*args_, **kwargs_) - else: - return ExtraServicesType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_ExtraService(self): - return self.ExtraService - def set_ExtraService(self, ExtraService): - self.ExtraService = ExtraService - def add_ExtraService(self, value): - self.ExtraService.append(value) - def insert_ExtraService_at(self, index, value): - self.ExtraService.insert(index, value) - def replace_ExtraService_at(self, index, value): - self.ExtraService[index] = value - def _hasContent(self): - if ( - self.ExtraService - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ExtraServicesType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('ExtraServicesType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'ExtraServicesType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='ExtraServicesType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='ExtraServicesType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='ExtraServicesType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ExtraServicesType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - for ExtraService_ in self.ExtraService: - namespaceprefix_ = self.ExtraService_nsprefix_ + ':' if (UseCapturedNS_ and self.ExtraService_nsprefix_) else '' - ExtraService_.export(outfile, level, namespaceprefix_, namespacedef_='', name_='ExtraService', pretty_print=pretty_print) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'ExtraService': - obj_ = ExtraServiceType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.ExtraService.append(obj_) - obj_.original_tagname_ = 'ExtraService' -# end class ExtraServicesType - - -class ExtraServiceType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ServiceID=None, ServiceName=None, Available=None, OnlineAvailable=None, Price=None, OnlinePrice=None, DeclaredValueRequired=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.ServiceID = ServiceID - self.ServiceID_nsprefix_ = None - self.ServiceName = ServiceName - self.ServiceName_nsprefix_ = None - self.Available = Available - self.Available_nsprefix_ = None - self.OnlineAvailable = OnlineAvailable - self.OnlineAvailable_nsprefix_ = None - self.Price = Price - self.Price_nsprefix_ = None - self.OnlinePrice = OnlinePrice - self.OnlinePrice_nsprefix_ = None - self.DeclaredValueRequired = DeclaredValueRequired - self.DeclaredValueRequired_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, ExtraServiceType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if ExtraServiceType.subclass: - return ExtraServiceType.subclass(*args_, **kwargs_) - else: - return ExtraServiceType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_ServiceID(self): - return self.ServiceID - def set_ServiceID(self, ServiceID): - self.ServiceID = ServiceID - def get_ServiceName(self): - return self.ServiceName - def set_ServiceName(self, ServiceName): - self.ServiceName = ServiceName - def get_Available(self): - return self.Available - def set_Available(self, Available): - self.Available = Available - def get_OnlineAvailable(self): - return self.OnlineAvailable - def set_OnlineAvailable(self, OnlineAvailable): - self.OnlineAvailable = OnlineAvailable - def get_Price(self): - return self.Price - def set_Price(self, Price): - self.Price = Price - def get_OnlinePrice(self): - return self.OnlinePrice - def set_OnlinePrice(self, OnlinePrice): - self.OnlinePrice = OnlinePrice - def get_DeclaredValueRequired(self): - return self.DeclaredValueRequired - def set_DeclaredValueRequired(self, DeclaredValueRequired): - self.DeclaredValueRequired = DeclaredValueRequired - def _hasContent(self): - if ( - self.ServiceID is not None or - self.ServiceName is not None or - self.Available is not None or - self.OnlineAvailable is not None or - self.Price is not None or - self.OnlinePrice is not None or - self.DeclaredValueRequired is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ExtraServiceType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('ExtraServiceType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'ExtraServiceType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='ExtraServiceType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='ExtraServiceType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='ExtraServiceType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ExtraServiceType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.ServiceID is not None: - namespaceprefix_ = self.ServiceID_nsprefix_ + ':' if (UseCapturedNS_ and self.ServiceID_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sServiceID>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ServiceID), input_name='ServiceID')), namespaceprefix_ , eol_)) - if self.ServiceName is not None: - namespaceprefix_ = self.ServiceName_nsprefix_ + ':' if (UseCapturedNS_ and self.ServiceName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sServiceName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ServiceName), input_name='ServiceName')), namespaceprefix_ , eol_)) - if self.Available is not None: - namespaceprefix_ = self.Available_nsprefix_ + ':' if (UseCapturedNS_ and self.Available_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAvailable>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Available), input_name='Available')), namespaceprefix_ , eol_)) - if self.OnlineAvailable is not None: - namespaceprefix_ = self.OnlineAvailable_nsprefix_ + ':' if (UseCapturedNS_ and self.OnlineAvailable_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sOnlineAvailable>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.OnlineAvailable), input_name='OnlineAvailable')), namespaceprefix_ , eol_)) - if self.Price is not None: - namespaceprefix_ = self.Price_nsprefix_ + ':' if (UseCapturedNS_ and self.Price_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPrice>%s%s' % (namespaceprefix_ , self.gds_format_float(self.Price, input_name='Price'), namespaceprefix_ , eol_)) - if self.OnlinePrice is not None: - namespaceprefix_ = self.OnlinePrice_nsprefix_ + ':' if (UseCapturedNS_ and self.OnlinePrice_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sOnlinePrice>%s%s' % (namespaceprefix_ , self.gds_format_float(self.OnlinePrice, input_name='OnlinePrice'), namespaceprefix_ , eol_)) - if self.DeclaredValueRequired is not None: - namespaceprefix_ = self.DeclaredValueRequired_nsprefix_ + ':' if (UseCapturedNS_ and self.DeclaredValueRequired_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDeclaredValueRequired>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.DeclaredValueRequired), input_name='DeclaredValueRequired')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'ServiceID': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ServiceID') - value_ = self.gds_validate_string(value_, node, 'ServiceID') - self.ServiceID = value_ - self.ServiceID_nsprefix_ = child_.prefix - elif nodeName_ == 'ServiceName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ServiceName') - value_ = self.gds_validate_string(value_, node, 'ServiceName') - self.ServiceName = value_ - self.ServiceName_nsprefix_ = child_.prefix - elif nodeName_ == 'Available': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Available') - value_ = self.gds_validate_string(value_, node, 'Available') - self.Available = value_ - self.Available_nsprefix_ = child_.prefix - elif nodeName_ == 'OnlineAvailable': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'OnlineAvailable') - value_ = self.gds_validate_string(value_, node, 'OnlineAvailable') - self.OnlineAvailable = value_ - self.OnlineAvailable_nsprefix_ = child_.prefix - elif nodeName_ == 'Price' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'Price') - fval_ = self.gds_validate_float(fval_, node, 'Price') - self.Price = fval_ - self.Price_nsprefix_ = child_.prefix - elif nodeName_ == 'OnlinePrice' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'OnlinePrice') - fval_ = self.gds_validate_float(fval_, node, 'OnlinePrice') - self.OnlinePrice = fval_ - self.OnlinePrice_nsprefix_ = child_.prefix - elif nodeName_ == 'DeclaredValueRequired': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'DeclaredValueRequired') - value_ = self.gds_validate_string(value_, node, 'DeclaredValueRequired') - self.DeclaredValueRequired = value_ - self.DeclaredValueRequired_nsprefix_ = child_.prefix -# end class ExtraServiceType - - -class GXGLocationsType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, PostOffice=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.PostOffice = PostOffice - self.PostOffice_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, GXGLocationsType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if GXGLocationsType.subclass: - return GXGLocationsType.subclass(*args_, **kwargs_) - else: - return GXGLocationsType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_PostOffice(self): - return self.PostOffice - def set_PostOffice(self, PostOffice): - self.PostOffice = PostOffice - def _hasContent(self): - if ( - self.PostOffice is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='GXGLocationsType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('GXGLocationsType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'GXGLocationsType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='GXGLocationsType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='GXGLocationsType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='GXGLocationsType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='GXGLocationsType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.PostOffice is not None: - namespaceprefix_ = self.PostOffice_nsprefix_ + ':' if (UseCapturedNS_ and self.PostOffice_nsprefix_) else '' - self.PostOffice.export(outfile, level, namespaceprefix_, namespacedef_='', name_='PostOffice', pretty_print=pretty_print) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'PostOffice': - obj_ = PostOfficeType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.PostOffice = obj_ - obj_.original_tagname_ = 'PostOffice' -# end class GXGLocationsType - - -class PostOfficeType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, Name=None, Address=None, City=None, State=None, ZipCode=None, RetailGXGCutOffTime=None, SaturDayCutOffTime=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.Name = Name - self.Name_nsprefix_ = None - self.Address = Address - self.Address_nsprefix_ = None - self.City = City - self.City_nsprefix_ = None - self.State = State - self.State_nsprefix_ = None - self.ZipCode = ZipCode - self.ZipCode_nsprefix_ = None - self.RetailGXGCutOffTime = RetailGXGCutOffTime - self.RetailGXGCutOffTime_nsprefix_ = None - self.SaturDayCutOffTime = SaturDayCutOffTime - self.SaturDayCutOffTime_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, PostOfficeType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if PostOfficeType.subclass: - return PostOfficeType.subclass(*args_, **kwargs_) - else: - return PostOfficeType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_Name(self): - return self.Name - def set_Name(self, Name): - self.Name = Name - def get_Address(self): - return self.Address - def set_Address(self, Address): - self.Address = Address - def get_City(self): - return self.City - def set_City(self, City): - self.City = City - def get_State(self): - return self.State - def set_State(self, State): - self.State = State - def get_ZipCode(self): - return self.ZipCode - def set_ZipCode(self, ZipCode): - self.ZipCode = ZipCode - def get_RetailGXGCutOffTime(self): - return self.RetailGXGCutOffTime - def set_RetailGXGCutOffTime(self, RetailGXGCutOffTime): - self.RetailGXGCutOffTime = RetailGXGCutOffTime - def get_SaturDayCutOffTime(self): - return self.SaturDayCutOffTime - def set_SaturDayCutOffTime(self, SaturDayCutOffTime): - self.SaturDayCutOffTime = SaturDayCutOffTime - def _hasContent(self): - if ( - self.Name is not None or - self.Address is not None or - self.City is not None or - self.State is not None or - self.ZipCode is not None or - self.RetailGXGCutOffTime is not None or - self.SaturDayCutOffTime is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='PostOfficeType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('PostOfficeType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'PostOfficeType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='PostOfficeType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='PostOfficeType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='PostOfficeType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='PostOfficeType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.Name is not None: - namespaceprefix_ = self.Name_nsprefix_ + ':' if (UseCapturedNS_ and self.Name_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Name), input_name='Name')), namespaceprefix_ , eol_)) - if self.Address is not None: - namespaceprefix_ = self.Address_nsprefix_ + ':' if (UseCapturedNS_ and self.Address_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAddress>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Address), input_name='Address')), namespaceprefix_ , eol_)) - if self.City is not None: - namespaceprefix_ = self.City_nsprefix_ + ':' if (UseCapturedNS_ and self.City_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.City), input_name='City')), namespaceprefix_ , eol_)) - if self.State is not None: - namespaceprefix_ = self.State_nsprefix_ + ':' if (UseCapturedNS_ and self.State_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.State), input_name='State')), namespaceprefix_ , eol_)) - if self.ZipCode is not None: - namespaceprefix_ = self.ZipCode_nsprefix_ + ':' if (UseCapturedNS_ and self.ZipCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sZipCode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ZipCode), input_name='ZipCode')), namespaceprefix_ , eol_)) - if self.RetailGXGCutOffTime is not None: - namespaceprefix_ = self.RetailGXGCutOffTime_nsprefix_ + ':' if (UseCapturedNS_ and self.RetailGXGCutOffTime_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRetailGXGCutOffTime>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.RetailGXGCutOffTime), input_name='RetailGXGCutOffTime')), namespaceprefix_ , eol_)) - if self.SaturDayCutOffTime is not None: - namespaceprefix_ = self.SaturDayCutOffTime_nsprefix_ + ':' if (UseCapturedNS_ and self.SaturDayCutOffTime_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSaturDayCutOffTime>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SaturDayCutOffTime), input_name='SaturDayCutOffTime')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'Name': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Name') - value_ = self.gds_validate_string(value_, node, 'Name') - self.Name = value_ - self.Name_nsprefix_ = child_.prefix - elif nodeName_ == 'Address': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Address') - value_ = self.gds_validate_string(value_, node, 'Address') - self.Address = value_ - self.Address_nsprefix_ = child_.prefix - elif nodeName_ == 'City': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'City') - value_ = self.gds_validate_string(value_, node, 'City') - self.City = value_ - self.City_nsprefix_ = child_.prefix - elif nodeName_ == 'State': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'State') - value_ = self.gds_validate_string(value_, node, 'State') - self.State = value_ - self.State_nsprefix_ = child_.prefix - elif nodeName_ == 'ZipCode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ZipCode') - value_ = self.gds_validate_string(value_, node, 'ZipCode') - self.ZipCode = value_ - self.ZipCode_nsprefix_ = child_.prefix - elif nodeName_ == 'RetailGXGCutOffTime': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'RetailGXGCutOffTime') - value_ = self.gds_validate_string(value_, node, 'RetailGXGCutOffTime') - self.RetailGXGCutOffTime = value_ - self.RetailGXGCutOffTime_nsprefix_ = child_.prefix - elif nodeName_ == 'SaturDayCutOffTime': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SaturDayCutOffTime') - value_ = self.gds_validate_string(value_, node, 'SaturDayCutOffTime') - self.SaturDayCutOffTime = value_ - self.SaturDayCutOffTime_nsprefix_ = child_.prefix -# end class PostOfficeType - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'IntlRateV2Response' - rootClass = IntlRateV2Response - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'IntlRateV2Response' - rootClass = IntlRateV2Response - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'IntlRateV2Response' - rootClass = IntlRateV2Response - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'IntlRateV2Response' - rootClass = IntlRateV2Response - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from intl_rate_v2_response import *\n\n') - sys.stdout.write('import intl_rate_v2_response as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "ContentType", - "ExtraServiceType", - "ExtraServicesType", - "GXGLocationsType", - "GXGType", - "IntlRateV2Response", - "PackageType", - "PostOfficeType", - "ServiceType" -] diff --git a/schemas/usps/karrio/schemas/usps/mrsv4_0_request.py b/schemas/usps/karrio/schemas/usps/mrsv4_0_request.py deleted file mode 100644 index a2c98c51cc..0000000000 --- a/schemas/usps/karrio/schemas/usps/mrsv4_0_request.py +++ /dev/null @@ -1,1804 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:08 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/mrsv4_0_request.py') -# -# Command line arguments: -# ./schemas/MRSV4.0Request.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/mrsv4_0_request.py" ./schemas/MRSV4.0Request.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class MRSV4_0Request(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, USERID=None, Option=None, CustomerName=None, CustomerAddress1=None, CustomerAddress2=None, CustomerCity=None, CustomerState=None, CustomerZip5=None, CustomerZip4=None, RetailerName=None, RetailerAddress=None, PermitNumber=None, PermitIssuingPOCity=None, PermitIssuingPOState=None, PermitIssuingPOZip5=None, PDUFirmName=None, PDUPOBox=None, PDUCity=None, PDUState=None, PDUZip5=None, PDUZip4=None, ServiceType=None, DeliveryConfirmation=None, InsuranceValue=None, MailingAckPackageID=None, WeightInPounds=None, WeightInOunces=None, RMA=None, RMAPICFlag=None, ImageType=None, RMABarcode=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.USERID = _cast(None, USERID) - self.USERID_nsprefix_ = None - self.Option = Option - self.Option_nsprefix_ = None - self.CustomerName = CustomerName - self.CustomerName_nsprefix_ = None - self.CustomerAddress1 = CustomerAddress1 - self.CustomerAddress1_nsprefix_ = None - self.CustomerAddress2 = CustomerAddress2 - self.CustomerAddress2_nsprefix_ = None - self.CustomerCity = CustomerCity - self.CustomerCity_nsprefix_ = None - self.CustomerState = CustomerState - self.CustomerState_nsprefix_ = None - self.CustomerZip5 = CustomerZip5 - self.CustomerZip5_nsprefix_ = None - self.CustomerZip4 = CustomerZip4 - self.CustomerZip4_nsprefix_ = None - self.RetailerName = RetailerName - self.RetailerName_nsprefix_ = None - self.RetailerAddress = RetailerAddress - self.RetailerAddress_nsprefix_ = None - self.PermitNumber = PermitNumber - self.PermitNumber_nsprefix_ = None - self.PermitIssuingPOCity = PermitIssuingPOCity - self.PermitIssuingPOCity_nsprefix_ = None - self.PermitIssuingPOState = PermitIssuingPOState - self.PermitIssuingPOState_nsprefix_ = None - self.PermitIssuingPOZip5 = PermitIssuingPOZip5 - self.PermitIssuingPOZip5_nsprefix_ = None - self.PDUFirmName = PDUFirmName - self.PDUFirmName_nsprefix_ = None - self.PDUPOBox = PDUPOBox - self.PDUPOBox_nsprefix_ = None - self.PDUCity = PDUCity - self.PDUCity_nsprefix_ = None - self.PDUState = PDUState - self.PDUState_nsprefix_ = None - self.PDUZip5 = PDUZip5 - self.PDUZip5_nsprefix_ = None - self.PDUZip4 = PDUZip4 - self.PDUZip4_nsprefix_ = None - self.ServiceType = ServiceType - self.ServiceType_nsprefix_ = None - self.DeliveryConfirmation = DeliveryConfirmation - self.DeliveryConfirmation_nsprefix_ = None - self.InsuranceValue = InsuranceValue - self.InsuranceValue_nsprefix_ = None - self.MailingAckPackageID = MailingAckPackageID - self.MailingAckPackageID_nsprefix_ = None - self.WeightInPounds = WeightInPounds - self.WeightInPounds_nsprefix_ = None - self.WeightInOunces = WeightInOunces - self.WeightInOunces_nsprefix_ = None - self.RMA = RMA - self.RMA_nsprefix_ = None - self.RMAPICFlag = RMAPICFlag - self.RMAPICFlag_nsprefix_ = None - self.ImageType = ImageType - self.ImageType_nsprefix_ = None - self.RMABarcode = RMABarcode - self.RMABarcode_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, MRSV4_0Request) - if subclass is not None: - return subclass(*args_, **kwargs_) - if MRSV4_0Request.subclass: - return MRSV4_0Request.subclass(*args_, **kwargs_) - else: - return MRSV4_0Request(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_Option(self): - return self.Option - def set_Option(self, Option): - self.Option = Option - def get_CustomerName(self): - return self.CustomerName - def set_CustomerName(self, CustomerName): - self.CustomerName = CustomerName - def get_CustomerAddress1(self): - return self.CustomerAddress1 - def set_CustomerAddress1(self, CustomerAddress1): - self.CustomerAddress1 = CustomerAddress1 - def get_CustomerAddress2(self): - return self.CustomerAddress2 - def set_CustomerAddress2(self, CustomerAddress2): - self.CustomerAddress2 = CustomerAddress2 - def get_CustomerCity(self): - return self.CustomerCity - def set_CustomerCity(self, CustomerCity): - self.CustomerCity = CustomerCity - def get_CustomerState(self): - return self.CustomerState - def set_CustomerState(self, CustomerState): - self.CustomerState = CustomerState - def get_CustomerZip5(self): - return self.CustomerZip5 - def set_CustomerZip5(self, CustomerZip5): - self.CustomerZip5 = CustomerZip5 - def get_CustomerZip4(self): - return self.CustomerZip4 - def set_CustomerZip4(self, CustomerZip4): - self.CustomerZip4 = CustomerZip4 - def get_RetailerName(self): - return self.RetailerName - def set_RetailerName(self, RetailerName): - self.RetailerName = RetailerName - def get_RetailerAddress(self): - return self.RetailerAddress - def set_RetailerAddress(self, RetailerAddress): - self.RetailerAddress = RetailerAddress - def get_PermitNumber(self): - return self.PermitNumber - def set_PermitNumber(self, PermitNumber): - self.PermitNumber = PermitNumber - def get_PermitIssuingPOCity(self): - return self.PermitIssuingPOCity - def set_PermitIssuingPOCity(self, PermitIssuingPOCity): - self.PermitIssuingPOCity = PermitIssuingPOCity - def get_PermitIssuingPOState(self): - return self.PermitIssuingPOState - def set_PermitIssuingPOState(self, PermitIssuingPOState): - self.PermitIssuingPOState = PermitIssuingPOState - def get_PermitIssuingPOZip5(self): - return self.PermitIssuingPOZip5 - def set_PermitIssuingPOZip5(self, PermitIssuingPOZip5): - self.PermitIssuingPOZip5 = PermitIssuingPOZip5 - def get_PDUFirmName(self): - return self.PDUFirmName - def set_PDUFirmName(self, PDUFirmName): - self.PDUFirmName = PDUFirmName - def get_PDUPOBox(self): - return self.PDUPOBox - def set_PDUPOBox(self, PDUPOBox): - self.PDUPOBox = PDUPOBox - def get_PDUCity(self): - return self.PDUCity - def set_PDUCity(self, PDUCity): - self.PDUCity = PDUCity - def get_PDUState(self): - return self.PDUState - def set_PDUState(self, PDUState): - self.PDUState = PDUState - def get_PDUZip5(self): - return self.PDUZip5 - def set_PDUZip5(self, PDUZip5): - self.PDUZip5 = PDUZip5 - def get_PDUZip4(self): - return self.PDUZip4 - def set_PDUZip4(self, PDUZip4): - self.PDUZip4 = PDUZip4 - def get_ServiceType(self): - return self.ServiceType - def set_ServiceType(self, ServiceType): - self.ServiceType = ServiceType - def get_DeliveryConfirmation(self): - return self.DeliveryConfirmation - def set_DeliveryConfirmation(self, DeliveryConfirmation): - self.DeliveryConfirmation = DeliveryConfirmation - def get_InsuranceValue(self): - return self.InsuranceValue - def set_InsuranceValue(self, InsuranceValue): - self.InsuranceValue = InsuranceValue - def get_MailingAckPackageID(self): - return self.MailingAckPackageID - def set_MailingAckPackageID(self, MailingAckPackageID): - self.MailingAckPackageID = MailingAckPackageID - def get_WeightInPounds(self): - return self.WeightInPounds - def set_WeightInPounds(self, WeightInPounds): - self.WeightInPounds = WeightInPounds - def get_WeightInOunces(self): - return self.WeightInOunces - def set_WeightInOunces(self, WeightInOunces): - self.WeightInOunces = WeightInOunces - def get_RMA(self): - return self.RMA - def set_RMA(self, RMA): - self.RMA = RMA - def get_RMAPICFlag(self): - return self.RMAPICFlag - def set_RMAPICFlag(self, RMAPICFlag): - self.RMAPICFlag = RMAPICFlag - def get_ImageType(self): - return self.ImageType - def set_ImageType(self, ImageType): - self.ImageType = ImageType - def get_RMABarcode(self): - return self.RMABarcode - def set_RMABarcode(self, RMABarcode): - self.RMABarcode = RMABarcode - def get_USERID(self): - return self.USERID - def set_USERID(self, USERID): - self.USERID = USERID - def _hasContent(self): - if ( - self.Option is not None or - self.CustomerName is not None or - self.CustomerAddress1 is not None or - self.CustomerAddress2 is not None or - self.CustomerCity is not None or - self.CustomerState is not None or - self.CustomerZip5 is not None or - self.CustomerZip4 is not None or - self.RetailerName is not None or - self.RetailerAddress is not None or - self.PermitNumber is not None or - self.PermitIssuingPOCity is not None or - self.PermitIssuingPOState is not None or - self.PermitIssuingPOZip5 is not None or - self.PDUFirmName is not None or - self.PDUPOBox is not None or - self.PDUCity is not None or - self.PDUState is not None or - self.PDUZip5 is not None or - self.PDUZip4 is not None or - self.ServiceType is not None or - self.DeliveryConfirmation is not None or - self.InsuranceValue is not None or - self.MailingAckPackageID is not None or - self.WeightInPounds is not None or - self.WeightInOunces is not None or - self.RMA is not None or - self.RMAPICFlag is not None or - self.ImageType is not None or - self.RMABarcode is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='MRSV4.0Request', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('MRSV4.0Request') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'MRSV4.0Request': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='MRSV4.0Request') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='MRSV4.0Request', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='MRSV4.0Request'): - if self.USERID is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - outfile.write(' USERID=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.USERID), input_name='USERID')), )) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='MRSV4.0Request', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.Option is not None: - namespaceprefix_ = self.Option_nsprefix_ + ':' if (UseCapturedNS_ and self.Option_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sOption>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Option), input_name='Option')), namespaceprefix_ , eol_)) - if self.CustomerName is not None: - namespaceprefix_ = self.CustomerName_nsprefix_ + ':' if (UseCapturedNS_ and self.CustomerName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCustomerName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CustomerName), input_name='CustomerName')), namespaceprefix_ , eol_)) - if self.CustomerAddress1 is not None: - namespaceprefix_ = self.CustomerAddress1_nsprefix_ + ':' if (UseCapturedNS_ and self.CustomerAddress1_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCustomerAddress1>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CustomerAddress1), input_name='CustomerAddress1')), namespaceprefix_ , eol_)) - if self.CustomerAddress2 is not None: - namespaceprefix_ = self.CustomerAddress2_nsprefix_ + ':' if (UseCapturedNS_ and self.CustomerAddress2_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCustomerAddress2>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CustomerAddress2), input_name='CustomerAddress2')), namespaceprefix_ , eol_)) - if self.CustomerCity is not None: - namespaceprefix_ = self.CustomerCity_nsprefix_ + ':' if (UseCapturedNS_ and self.CustomerCity_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCustomerCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CustomerCity), input_name='CustomerCity')), namespaceprefix_ , eol_)) - if self.CustomerState is not None: - namespaceprefix_ = self.CustomerState_nsprefix_ + ':' if (UseCapturedNS_ and self.CustomerState_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCustomerState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CustomerState), input_name='CustomerState')), namespaceprefix_ , eol_)) - if self.CustomerZip5 is not None: - namespaceprefix_ = self.CustomerZip5_nsprefix_ + ':' if (UseCapturedNS_ and self.CustomerZip5_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCustomerZip5>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.CustomerZip5, input_name='CustomerZip5'), namespaceprefix_ , eol_)) - if self.CustomerZip4 is not None: - namespaceprefix_ = self.CustomerZip4_nsprefix_ + ':' if (UseCapturedNS_ and self.CustomerZip4_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCustomerZip4>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CustomerZip4), input_name='CustomerZip4')), namespaceprefix_ , eol_)) - if self.RetailerName is not None: - namespaceprefix_ = self.RetailerName_nsprefix_ + ':' if (UseCapturedNS_ and self.RetailerName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRetailerName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.RetailerName), input_name='RetailerName')), namespaceprefix_ , eol_)) - if self.RetailerAddress is not None: - namespaceprefix_ = self.RetailerAddress_nsprefix_ + ':' if (UseCapturedNS_ and self.RetailerAddress_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRetailerAddress>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.RetailerAddress), input_name='RetailerAddress')), namespaceprefix_ , eol_)) - if self.PermitNumber is not None: - namespaceprefix_ = self.PermitNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.PermitNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPermitNumber>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.PermitNumber, input_name='PermitNumber'), namespaceprefix_ , eol_)) - if self.PermitIssuingPOCity is not None: - namespaceprefix_ = self.PermitIssuingPOCity_nsprefix_ + ':' if (UseCapturedNS_ and self.PermitIssuingPOCity_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPermitIssuingPOCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PermitIssuingPOCity), input_name='PermitIssuingPOCity')), namespaceprefix_ , eol_)) - if self.PermitIssuingPOState is not None: - namespaceprefix_ = self.PermitIssuingPOState_nsprefix_ + ':' if (UseCapturedNS_ and self.PermitIssuingPOState_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPermitIssuingPOState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PermitIssuingPOState), input_name='PermitIssuingPOState')), namespaceprefix_ , eol_)) - if self.PermitIssuingPOZip5 is not None: - namespaceprefix_ = self.PermitIssuingPOZip5_nsprefix_ + ':' if (UseCapturedNS_ and self.PermitIssuingPOZip5_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPermitIssuingPOZip5>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.PermitIssuingPOZip5, input_name='PermitIssuingPOZip5'), namespaceprefix_ , eol_)) - if self.PDUFirmName is not None: - namespaceprefix_ = self.PDUFirmName_nsprefix_ + ':' if (UseCapturedNS_ and self.PDUFirmName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPDUFirmName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PDUFirmName), input_name='PDUFirmName')), namespaceprefix_ , eol_)) - if self.PDUPOBox is not None: - namespaceprefix_ = self.PDUPOBox_nsprefix_ + ':' if (UseCapturedNS_ and self.PDUPOBox_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPDUPOBox>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PDUPOBox), input_name='PDUPOBox')), namespaceprefix_ , eol_)) - if self.PDUCity is not None: - namespaceprefix_ = self.PDUCity_nsprefix_ + ':' if (UseCapturedNS_ and self.PDUCity_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPDUCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PDUCity), input_name='PDUCity')), namespaceprefix_ , eol_)) - if self.PDUState is not None: - namespaceprefix_ = self.PDUState_nsprefix_ + ':' if (UseCapturedNS_ and self.PDUState_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPDUState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PDUState), input_name='PDUState')), namespaceprefix_ , eol_)) - if self.PDUZip5 is not None: - namespaceprefix_ = self.PDUZip5_nsprefix_ + ':' if (UseCapturedNS_ and self.PDUZip5_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPDUZip5>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.PDUZip5, input_name='PDUZip5'), namespaceprefix_ , eol_)) - if self.PDUZip4 is not None: - namespaceprefix_ = self.PDUZip4_nsprefix_ + ':' if (UseCapturedNS_ and self.PDUZip4_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPDUZip4>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.PDUZip4, input_name='PDUZip4'), namespaceprefix_ , eol_)) - if self.ServiceType is not None: - namespaceprefix_ = self.ServiceType_nsprefix_ + ':' if (UseCapturedNS_ and self.ServiceType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sServiceType>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ServiceType), input_name='ServiceType')), namespaceprefix_ , eol_)) - if self.DeliveryConfirmation is not None: - namespaceprefix_ = self.DeliveryConfirmation_nsprefix_ + ':' if (UseCapturedNS_ and self.DeliveryConfirmation_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDeliveryConfirmation>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.DeliveryConfirmation), input_name='DeliveryConfirmation')), namespaceprefix_ , eol_)) - if self.InsuranceValue is not None: - namespaceprefix_ = self.InsuranceValue_nsprefix_ + ':' if (UseCapturedNS_ and self.InsuranceValue_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sInsuranceValue>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.InsuranceValue), input_name='InsuranceValue')), namespaceprefix_ , eol_)) - if self.MailingAckPackageID is not None: - namespaceprefix_ = self.MailingAckPackageID_nsprefix_ + ':' if (UseCapturedNS_ and self.MailingAckPackageID_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sMailingAckPackageID>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.MailingAckPackageID), input_name='MailingAckPackageID')), namespaceprefix_ , eol_)) - if self.WeightInPounds is not None: - namespaceprefix_ = self.WeightInPounds_nsprefix_ + ':' if (UseCapturedNS_ and self.WeightInPounds_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sWeightInPounds>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.WeightInPounds, input_name='WeightInPounds'), namespaceprefix_ , eol_)) - if self.WeightInOunces is not None: - namespaceprefix_ = self.WeightInOunces_nsprefix_ + ':' if (UseCapturedNS_ and self.WeightInOunces_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sWeightInOunces>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.WeightInOunces, input_name='WeightInOunces'), namespaceprefix_ , eol_)) - if self.RMA is not None: - namespaceprefix_ = self.RMA_nsprefix_ + ':' if (UseCapturedNS_ and self.RMA_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRMA>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.RMA), input_name='RMA')), namespaceprefix_ , eol_)) - if self.RMAPICFlag is not None: - namespaceprefix_ = self.RMAPICFlag_nsprefix_ + ':' if (UseCapturedNS_ and self.RMAPICFlag_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRMAPICFlag>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.RMAPICFlag), input_name='RMAPICFlag')), namespaceprefix_ , eol_)) - if self.ImageType is not None: - namespaceprefix_ = self.ImageType_nsprefix_ + ':' if (UseCapturedNS_ and self.ImageType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sImageType>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ImageType), input_name='ImageType')), namespaceprefix_ , eol_)) - if self.RMABarcode is not None: - namespaceprefix_ = self.RMABarcode_nsprefix_ + ':' if (UseCapturedNS_ and self.RMABarcode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRMABarcode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.RMABarcode), input_name='RMABarcode')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('USERID', node) - if value is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - self.USERID = value - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'Option': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Option') - value_ = self.gds_validate_string(value_, node, 'Option') - self.Option = value_ - self.Option_nsprefix_ = child_.prefix - elif nodeName_ == 'CustomerName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CustomerName') - value_ = self.gds_validate_string(value_, node, 'CustomerName') - self.CustomerName = value_ - self.CustomerName_nsprefix_ = child_.prefix - elif nodeName_ == 'CustomerAddress1': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CustomerAddress1') - value_ = self.gds_validate_string(value_, node, 'CustomerAddress1') - self.CustomerAddress1 = value_ - self.CustomerAddress1_nsprefix_ = child_.prefix - elif nodeName_ == 'CustomerAddress2': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CustomerAddress2') - value_ = self.gds_validate_string(value_, node, 'CustomerAddress2') - self.CustomerAddress2 = value_ - self.CustomerAddress2_nsprefix_ = child_.prefix - elif nodeName_ == 'CustomerCity': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CustomerCity') - value_ = self.gds_validate_string(value_, node, 'CustomerCity') - self.CustomerCity = value_ - self.CustomerCity_nsprefix_ = child_.prefix - elif nodeName_ == 'CustomerState': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CustomerState') - value_ = self.gds_validate_string(value_, node, 'CustomerState') - self.CustomerState = value_ - self.CustomerState_nsprefix_ = child_.prefix - elif nodeName_ == 'CustomerZip5' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'CustomerZip5') - ival_ = self.gds_validate_integer(ival_, node, 'CustomerZip5') - self.CustomerZip5 = ival_ - self.CustomerZip5_nsprefix_ = child_.prefix - elif nodeName_ == 'CustomerZip4': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CustomerZip4') - value_ = self.gds_validate_string(value_, node, 'CustomerZip4') - self.CustomerZip4 = value_ - self.CustomerZip4_nsprefix_ = child_.prefix - elif nodeName_ == 'RetailerName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'RetailerName') - value_ = self.gds_validate_string(value_, node, 'RetailerName') - self.RetailerName = value_ - self.RetailerName_nsprefix_ = child_.prefix - elif nodeName_ == 'RetailerAddress': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'RetailerAddress') - value_ = self.gds_validate_string(value_, node, 'RetailerAddress') - self.RetailerAddress = value_ - self.RetailerAddress_nsprefix_ = child_.prefix - elif nodeName_ == 'PermitNumber' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'PermitNumber') - ival_ = self.gds_validate_integer(ival_, node, 'PermitNumber') - self.PermitNumber = ival_ - self.PermitNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'PermitIssuingPOCity': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PermitIssuingPOCity') - value_ = self.gds_validate_string(value_, node, 'PermitIssuingPOCity') - self.PermitIssuingPOCity = value_ - self.PermitIssuingPOCity_nsprefix_ = child_.prefix - elif nodeName_ == 'PermitIssuingPOState': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PermitIssuingPOState') - value_ = self.gds_validate_string(value_, node, 'PermitIssuingPOState') - self.PermitIssuingPOState = value_ - self.PermitIssuingPOState_nsprefix_ = child_.prefix - elif nodeName_ == 'PermitIssuingPOZip5' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'PermitIssuingPOZip5') - ival_ = self.gds_validate_integer(ival_, node, 'PermitIssuingPOZip5') - self.PermitIssuingPOZip5 = ival_ - self.PermitIssuingPOZip5_nsprefix_ = child_.prefix - elif nodeName_ == 'PDUFirmName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PDUFirmName') - value_ = self.gds_validate_string(value_, node, 'PDUFirmName') - self.PDUFirmName = value_ - self.PDUFirmName_nsprefix_ = child_.prefix - elif nodeName_ == 'PDUPOBox': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PDUPOBox') - value_ = self.gds_validate_string(value_, node, 'PDUPOBox') - self.PDUPOBox = value_ - self.PDUPOBox_nsprefix_ = child_.prefix - elif nodeName_ == 'PDUCity': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PDUCity') - value_ = self.gds_validate_string(value_, node, 'PDUCity') - self.PDUCity = value_ - self.PDUCity_nsprefix_ = child_.prefix - elif nodeName_ == 'PDUState': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PDUState') - value_ = self.gds_validate_string(value_, node, 'PDUState') - self.PDUState = value_ - self.PDUState_nsprefix_ = child_.prefix - elif nodeName_ == 'PDUZip5' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'PDUZip5') - ival_ = self.gds_validate_integer(ival_, node, 'PDUZip5') - self.PDUZip5 = ival_ - self.PDUZip5_nsprefix_ = child_.prefix - elif nodeName_ == 'PDUZip4' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'PDUZip4') - ival_ = self.gds_validate_integer(ival_, node, 'PDUZip4') - self.PDUZip4 = ival_ - self.PDUZip4_nsprefix_ = child_.prefix - elif nodeName_ == 'ServiceType': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ServiceType') - value_ = self.gds_validate_string(value_, node, 'ServiceType') - self.ServiceType = value_ - self.ServiceType_nsprefix_ = child_.prefix - elif nodeName_ == 'DeliveryConfirmation': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'DeliveryConfirmation') - value_ = self.gds_validate_string(value_, node, 'DeliveryConfirmation') - self.DeliveryConfirmation = value_ - self.DeliveryConfirmation_nsprefix_ = child_.prefix - elif nodeName_ == 'InsuranceValue': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'InsuranceValue') - value_ = self.gds_validate_string(value_, node, 'InsuranceValue') - self.InsuranceValue = value_ - self.InsuranceValue_nsprefix_ = child_.prefix - elif nodeName_ == 'MailingAckPackageID': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'MailingAckPackageID') - value_ = self.gds_validate_string(value_, node, 'MailingAckPackageID') - self.MailingAckPackageID = value_ - self.MailingAckPackageID_nsprefix_ = child_.prefix - elif nodeName_ == 'WeightInPounds' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'WeightInPounds') - ival_ = self.gds_validate_integer(ival_, node, 'WeightInPounds') - self.WeightInPounds = ival_ - self.WeightInPounds_nsprefix_ = child_.prefix - elif nodeName_ == 'WeightInOunces' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'WeightInOunces') - ival_ = self.gds_validate_integer(ival_, node, 'WeightInOunces') - self.WeightInOunces = ival_ - self.WeightInOunces_nsprefix_ = child_.prefix - elif nodeName_ == 'RMA': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'RMA') - value_ = self.gds_validate_string(value_, node, 'RMA') - self.RMA = value_ - self.RMA_nsprefix_ = child_.prefix - elif nodeName_ == 'RMAPICFlag': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'RMAPICFlag') - value_ = self.gds_validate_string(value_, node, 'RMAPICFlag') - self.RMAPICFlag = value_ - self.RMAPICFlag_nsprefix_ = child_.prefix - elif nodeName_ == 'ImageType': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ImageType') - value_ = self.gds_validate_string(value_, node, 'ImageType') - self.ImageType = value_ - self.ImageType_nsprefix_ = child_.prefix - elif nodeName_ == 'RMABarcode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'RMABarcode') - value_ = self.gds_validate_string(value_, node, 'RMABarcode') - self.RMABarcode = value_ - self.RMABarcode_nsprefix_ = child_.prefix -# end class MRSV4_0Request - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'MRSV4_0Request' - rootClass = MRSV4_0Request - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'MRSV4_0Request' - rootClass = MRSV4_0Request - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'MRSV4_0Request' - rootClass = MRSV4_0Request - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'MRSV4_0Request' - rootClass = MRSV4_0Request - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from mrsv4_0_request import *\n\n') - sys.stdout.write('import mrsv4_0_request as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "MRSV4_0Request" -] diff --git a/schemas/usps/karrio/schemas/usps/priority_mail_request.py b/schemas/usps/karrio/schemas/usps/priority_mail_request.py deleted file mode 100644 index 7ca3c6731b..0000000000 --- a/schemas/usps/karrio/schemas/usps/priority_mail_request.py +++ /dev/null @@ -1,1379 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:10 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/priority_mail_request.py') -# -# Command line arguments: -# ./schemas/PriorityMailRequest.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/priority_mail_request.py" ./schemas/PriorityMailRequest.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class PriorityMailRequest(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, USERID=None, OriginZip=None, DestinationZip=None, DestinationType=None, PMGuarantee=None, ClientType=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.USERID = _cast(None, USERID) - self.USERID_nsprefix_ = None - self.OriginZip = OriginZip - self.OriginZip_nsprefix_ = None - self.DestinationZip = DestinationZip - self.DestinationZip_nsprefix_ = None - self.DestinationType = DestinationType - self.DestinationType_nsprefix_ = None - self.PMGuarantee = PMGuarantee - self.PMGuarantee_nsprefix_ = None - self.ClientType = ClientType - self.ClientType_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, PriorityMailRequest) - if subclass is not None: - return subclass(*args_, **kwargs_) - if PriorityMailRequest.subclass: - return PriorityMailRequest.subclass(*args_, **kwargs_) - else: - return PriorityMailRequest(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_OriginZip(self): - return self.OriginZip - def set_OriginZip(self, OriginZip): - self.OriginZip = OriginZip - def get_DestinationZip(self): - return self.DestinationZip - def set_DestinationZip(self, DestinationZip): - self.DestinationZip = DestinationZip - def get_DestinationType(self): - return self.DestinationType - def set_DestinationType(self, DestinationType): - self.DestinationType = DestinationType - def get_PMGuarantee(self): - return self.PMGuarantee - def set_PMGuarantee(self, PMGuarantee): - self.PMGuarantee = PMGuarantee - def get_ClientType(self): - return self.ClientType - def set_ClientType(self, ClientType): - self.ClientType = ClientType - def get_USERID(self): - return self.USERID - def set_USERID(self, USERID): - self.USERID = USERID - def _hasContent(self): - if ( - self.OriginZip is not None or - self.DestinationZip is not None or - self.DestinationType is not None or - self.PMGuarantee is not None or - self.ClientType is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='PriorityMailRequest', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('PriorityMailRequest') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'PriorityMailRequest': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='PriorityMailRequest') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='PriorityMailRequest', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='PriorityMailRequest'): - if self.USERID is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - outfile.write(' USERID=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.USERID), input_name='USERID')), )) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='PriorityMailRequest', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.OriginZip is not None: - namespaceprefix_ = self.OriginZip_nsprefix_ + ':' if (UseCapturedNS_ and self.OriginZip_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sOriginZip>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.OriginZip, input_name='OriginZip'), namespaceprefix_ , eol_)) - if self.DestinationZip is not None: - namespaceprefix_ = self.DestinationZip_nsprefix_ + ':' if (UseCapturedNS_ and self.DestinationZip_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDestinationZip>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.DestinationZip, input_name='DestinationZip'), namespaceprefix_ , eol_)) - if self.DestinationType is not None: - namespaceprefix_ = self.DestinationType_nsprefix_ + ':' if (UseCapturedNS_ and self.DestinationType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDestinationType>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.DestinationType, input_name='DestinationType'), namespaceprefix_ , eol_)) - if self.PMGuarantee is not None: - namespaceprefix_ = self.PMGuarantee_nsprefix_ + ':' if (UseCapturedNS_ and self.PMGuarantee_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPMGuarantee>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PMGuarantee), input_name='PMGuarantee')), namespaceprefix_ , eol_)) - if self.ClientType is not None: - namespaceprefix_ = self.ClientType_nsprefix_ + ':' if (UseCapturedNS_ and self.ClientType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sClientType>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.ClientType, input_name='ClientType'), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('USERID', node) - if value is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - self.USERID = value - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'OriginZip' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'OriginZip') - ival_ = self.gds_validate_integer(ival_, node, 'OriginZip') - self.OriginZip = ival_ - self.OriginZip_nsprefix_ = child_.prefix - elif nodeName_ == 'DestinationZip' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'DestinationZip') - ival_ = self.gds_validate_integer(ival_, node, 'DestinationZip') - self.DestinationZip = ival_ - self.DestinationZip_nsprefix_ = child_.prefix - elif nodeName_ == 'DestinationType' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'DestinationType') - ival_ = self.gds_validate_integer(ival_, node, 'DestinationType') - self.DestinationType = ival_ - self.DestinationType_nsprefix_ = child_.prefix - elif nodeName_ == 'PMGuarantee': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PMGuarantee') - value_ = self.gds_validate_string(value_, node, 'PMGuarantee') - self.PMGuarantee = value_ - self.PMGuarantee_nsprefix_ = child_.prefix - elif nodeName_ == 'ClientType' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'ClientType') - ival_ = self.gds_validate_integer(ival_, node, 'ClientType') - self.ClientType = ival_ - self.ClientType_nsprefix_ = child_.prefix -# end class PriorityMailRequest - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'PriorityMailRequest' - rootClass = PriorityMailRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'PriorityMailRequest' - rootClass = PriorityMailRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'PriorityMailRequest' - rootClass = PriorityMailRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'PriorityMailRequest' - rootClass = PriorityMailRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from priority_mail_request import *\n\n') - sys.stdout.write('import priority_mail_request as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "PriorityMailRequest" -] diff --git a/schemas/usps/karrio/schemas/usps/priority_mail_response.py b/schemas/usps/karrio/schemas/usps/priority_mail_response.py deleted file mode 100644 index 62d57bff67..0000000000 --- a/schemas/usps/karrio/schemas/usps/priority_mail_response.py +++ /dev/null @@ -1,1385 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:10 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/priority_mail_response.py') -# -# Command line arguments: -# ./schemas/PriorityMailResponse.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/priority_mail_response.py" ./schemas/PriorityMailResponse.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class PriorityMailResponse(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, OriginZip=None, DestinationZip=None, Days=None, Message=None, EffectiveAcceptanceDate=None, ScheduledDeliveryDate=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.OriginZip = OriginZip - self.OriginZip_nsprefix_ = None - self.DestinationZip = DestinationZip - self.DestinationZip_nsprefix_ = None - self.Days = Days - self.Days_nsprefix_ = None - self.Message = Message - self.Message_nsprefix_ = None - self.EffectiveAcceptanceDate = EffectiveAcceptanceDate - self.EffectiveAcceptanceDate_nsprefix_ = None - self.ScheduledDeliveryDate = ScheduledDeliveryDate - self.ScheduledDeliveryDate_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, PriorityMailResponse) - if subclass is not None: - return subclass(*args_, **kwargs_) - if PriorityMailResponse.subclass: - return PriorityMailResponse.subclass(*args_, **kwargs_) - else: - return PriorityMailResponse(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_OriginZip(self): - return self.OriginZip - def set_OriginZip(self, OriginZip): - self.OriginZip = OriginZip - def get_DestinationZip(self): - return self.DestinationZip - def set_DestinationZip(self, DestinationZip): - self.DestinationZip = DestinationZip - def get_Days(self): - return self.Days - def set_Days(self, Days): - self.Days = Days - def get_Message(self): - return self.Message - def set_Message(self, Message): - self.Message = Message - def get_EffectiveAcceptanceDate(self): - return self.EffectiveAcceptanceDate - def set_EffectiveAcceptanceDate(self, EffectiveAcceptanceDate): - self.EffectiveAcceptanceDate = EffectiveAcceptanceDate - def get_ScheduledDeliveryDate(self): - return self.ScheduledDeliveryDate - def set_ScheduledDeliveryDate(self, ScheduledDeliveryDate): - self.ScheduledDeliveryDate = ScheduledDeliveryDate - def _hasContent(self): - if ( - self.OriginZip is not None or - self.DestinationZip is not None or - self.Days is not None or - self.Message is not None or - self.EffectiveAcceptanceDate is not None or - self.ScheduledDeliveryDate is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='PriorityMailResponse', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('PriorityMailResponse') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'PriorityMailResponse': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='PriorityMailResponse') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='PriorityMailResponse', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='PriorityMailResponse'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='PriorityMailResponse', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.OriginZip is not None: - namespaceprefix_ = self.OriginZip_nsprefix_ + ':' if (UseCapturedNS_ and self.OriginZip_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sOriginZip>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.OriginZip, input_name='OriginZip'), namespaceprefix_ , eol_)) - if self.DestinationZip is not None: - namespaceprefix_ = self.DestinationZip_nsprefix_ + ':' if (UseCapturedNS_ and self.DestinationZip_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDestinationZip>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.DestinationZip, input_name='DestinationZip'), namespaceprefix_ , eol_)) - if self.Days is not None: - namespaceprefix_ = self.Days_nsprefix_ + ':' if (UseCapturedNS_ and self.Days_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDays>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.Days, input_name='Days'), namespaceprefix_ , eol_)) - if self.Message is not None: - namespaceprefix_ = self.Message_nsprefix_ + ':' if (UseCapturedNS_ and self.Message_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sMessage>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Message), input_name='Message')), namespaceprefix_ , eol_)) - if self.EffectiveAcceptanceDate is not None: - namespaceprefix_ = self.EffectiveAcceptanceDate_nsprefix_ + ':' if (UseCapturedNS_ and self.EffectiveAcceptanceDate_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEffectiveAcceptanceDate>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.EffectiveAcceptanceDate), input_name='EffectiveAcceptanceDate')), namespaceprefix_ , eol_)) - if self.ScheduledDeliveryDate is not None: - namespaceprefix_ = self.ScheduledDeliveryDate_nsprefix_ + ':' if (UseCapturedNS_ and self.ScheduledDeliveryDate_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sScheduledDeliveryDate>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ScheduledDeliveryDate), input_name='ScheduledDeliveryDate')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'OriginZip' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'OriginZip') - ival_ = self.gds_validate_integer(ival_, node, 'OriginZip') - self.OriginZip = ival_ - self.OriginZip_nsprefix_ = child_.prefix - elif nodeName_ == 'DestinationZip' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'DestinationZip') - ival_ = self.gds_validate_integer(ival_, node, 'DestinationZip') - self.DestinationZip = ival_ - self.DestinationZip_nsprefix_ = child_.prefix - elif nodeName_ == 'Days' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'Days') - ival_ = self.gds_validate_integer(ival_, node, 'Days') - self.Days = ival_ - self.Days_nsprefix_ = child_.prefix - elif nodeName_ == 'Message': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Message') - value_ = self.gds_validate_string(value_, node, 'Message') - self.Message = value_ - self.Message_nsprefix_ = child_.prefix - elif nodeName_ == 'EffectiveAcceptanceDate': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'EffectiveAcceptanceDate') - value_ = self.gds_validate_string(value_, node, 'EffectiveAcceptanceDate') - self.EffectiveAcceptanceDate = value_ - self.EffectiveAcceptanceDate_nsprefix_ = child_.prefix - elif nodeName_ == 'ScheduledDeliveryDate': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ScheduledDeliveryDate') - value_ = self.gds_validate_string(value_, node, 'ScheduledDeliveryDate') - self.ScheduledDeliveryDate = value_ - self.ScheduledDeliveryDate_nsprefix_ = child_.prefix -# end class PriorityMailResponse - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'PriorityMailResponse' - rootClass = PriorityMailResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'PriorityMailResponse' - rootClass = PriorityMailResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'PriorityMailResponse' - rootClass = PriorityMailResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'PriorityMailResponse' - rootClass = PriorityMailResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from priority_mail_response import *\n\n') - sys.stdout.write('import priority_mail_response as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "PriorityMailResponse" -] diff --git a/schemas/usps/karrio/schemas/usps/pts_email_request.py b/schemas/usps/karrio/schemas/usps/pts_email_request.py deleted file mode 100644 index 2677667d2b..0000000000 --- a/schemas/usps/karrio/schemas/usps/pts_email_request.py +++ /dev/null @@ -1,1473 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:09 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/pts_email_request.py') -# -# Command line arguments: -# ./schemas/PTSEmailRequest.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/pts_email_request.py" ./schemas/PTSEmailRequest.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class PTSEmailRequest(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, USERID=None, TrackId=None, ClientIp=None, MpSuffix=None, MpDate=None, RequestType=None, FirstName=None, LastName=None, Email1=None, Email2=None, Email3=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.USERID = _cast(None, USERID) - self.USERID_nsprefix_ = None - self.TrackId = TrackId - self.TrackId_nsprefix_ = None - self.ClientIp = ClientIp - self.ClientIp_nsprefix_ = None - self.MpSuffix = MpSuffix - self.MpSuffix_nsprefix_ = None - self.MpDate = MpDate - self.MpDate_nsprefix_ = None - if RequestType is None: - self.RequestType = [] - else: - self.RequestType = RequestType - self.RequestType_nsprefix_ = None - self.FirstName = FirstName - self.FirstName_nsprefix_ = None - self.LastName = LastName - self.LastName_nsprefix_ = None - self.Email1 = Email1 - self.Email1_nsprefix_ = None - self.Email2 = Email2 - self.Email2_nsprefix_ = None - self.Email3 = Email3 - self.Email3_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, PTSEmailRequest) - if subclass is not None: - return subclass(*args_, **kwargs_) - if PTSEmailRequest.subclass: - return PTSEmailRequest.subclass(*args_, **kwargs_) - else: - return PTSEmailRequest(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_TrackId(self): - return self.TrackId - def set_TrackId(self, TrackId): - self.TrackId = TrackId - def get_ClientIp(self): - return self.ClientIp - def set_ClientIp(self, ClientIp): - self.ClientIp = ClientIp - def get_MpSuffix(self): - return self.MpSuffix - def set_MpSuffix(self, MpSuffix): - self.MpSuffix = MpSuffix - def get_MpDate(self): - return self.MpDate - def set_MpDate(self, MpDate): - self.MpDate = MpDate - def get_RequestType(self): - return self.RequestType - def set_RequestType(self, RequestType): - self.RequestType = RequestType - def add_RequestType(self, value): - self.RequestType.append(value) - def insert_RequestType_at(self, index, value): - self.RequestType.insert(index, value) - def replace_RequestType_at(self, index, value): - self.RequestType[index] = value - def get_FirstName(self): - return self.FirstName - def set_FirstName(self, FirstName): - self.FirstName = FirstName - def get_LastName(self): - return self.LastName - def set_LastName(self, LastName): - self.LastName = LastName - def get_Email1(self): - return self.Email1 - def set_Email1(self, Email1): - self.Email1 = Email1 - def get_Email2(self): - return self.Email2 - def set_Email2(self, Email2): - self.Email2 = Email2 - def get_Email3(self): - return self.Email3 - def set_Email3(self, Email3): - self.Email3 = Email3 - def get_USERID(self): - return self.USERID - def set_USERID(self, USERID): - self.USERID = USERID - def _hasContent(self): - if ( - self.TrackId is not None or - self.ClientIp is not None or - self.MpSuffix is not None or - self.MpDate is not None or - self.RequestType or - self.FirstName is not None or - self.LastName is not None or - self.Email1 is not None or - self.Email2 is not None or - self.Email3 is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='PTSEmailRequest', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('PTSEmailRequest') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'PTSEmailRequest': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='PTSEmailRequest') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='PTSEmailRequest', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='PTSEmailRequest'): - if self.USERID is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - outfile.write(' USERID=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.USERID), input_name='USERID')), )) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='PTSEmailRequest', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.TrackId is not None: - namespaceprefix_ = self.TrackId_nsprefix_ + ':' if (UseCapturedNS_ and self.TrackId_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sTrackId>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.TrackId), input_name='TrackId')), namespaceprefix_ , eol_)) - if self.ClientIp is not None: - namespaceprefix_ = self.ClientIp_nsprefix_ + ':' if (UseCapturedNS_ and self.ClientIp_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sClientIp>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ClientIp), input_name='ClientIp')), namespaceprefix_ , eol_)) - if self.MpSuffix is not None: - namespaceprefix_ = self.MpSuffix_nsprefix_ + ':' if (UseCapturedNS_ and self.MpSuffix_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sMpSuffix>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.MpSuffix, input_name='MpSuffix'), namespaceprefix_ , eol_)) - if self.MpDate is not None: - namespaceprefix_ = self.MpDate_nsprefix_ + ':' if (UseCapturedNS_ and self.MpDate_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sMpDate>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.MpDate), input_name='MpDate')), namespaceprefix_ , eol_)) - for RequestType_ in self.RequestType: - namespaceprefix_ = self.RequestType_nsprefix_ + ':' if (UseCapturedNS_ and self.RequestType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRequestType>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(RequestType_), input_name='RequestType')), namespaceprefix_ , eol_)) - if self.FirstName is not None: - namespaceprefix_ = self.FirstName_nsprefix_ + ':' if (UseCapturedNS_ and self.FirstName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFirstName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FirstName), input_name='FirstName')), namespaceprefix_ , eol_)) - if self.LastName is not None: - namespaceprefix_ = self.LastName_nsprefix_ + ':' if (UseCapturedNS_ and self.LastName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sLastName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.LastName), input_name='LastName')), namespaceprefix_ , eol_)) - if self.Email1 is not None: - namespaceprefix_ = self.Email1_nsprefix_ + ':' if (UseCapturedNS_ and self.Email1_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEmail1>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Email1), input_name='Email1')), namespaceprefix_ , eol_)) - if self.Email2 is not None: - namespaceprefix_ = self.Email2_nsprefix_ + ':' if (UseCapturedNS_ and self.Email2_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEmail2>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Email2), input_name='Email2')), namespaceprefix_ , eol_)) - if self.Email3 is not None: - namespaceprefix_ = self.Email3_nsprefix_ + ':' if (UseCapturedNS_ and self.Email3_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEmail3>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Email3), input_name='Email3')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('USERID', node) - if value is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - self.USERID = value - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'TrackId': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'TrackId') - value_ = self.gds_validate_string(value_, node, 'TrackId') - self.TrackId = value_ - self.TrackId_nsprefix_ = child_.prefix - elif nodeName_ == 'ClientIp': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ClientIp') - value_ = self.gds_validate_string(value_, node, 'ClientIp') - self.ClientIp = value_ - self.ClientIp_nsprefix_ = child_.prefix - elif nodeName_ == 'MpSuffix' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'MpSuffix') - ival_ = self.gds_validate_integer(ival_, node, 'MpSuffix') - self.MpSuffix = ival_ - self.MpSuffix_nsprefix_ = child_.prefix - elif nodeName_ == 'MpDate': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'MpDate') - value_ = self.gds_validate_string(value_, node, 'MpDate') - self.MpDate = value_ - self.MpDate_nsprefix_ = child_.prefix - elif nodeName_ == 'RequestType': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'RequestType') - value_ = self.gds_validate_string(value_, node, 'RequestType') - self.RequestType.append(value_) - self.RequestType_nsprefix_ = child_.prefix - elif nodeName_ == 'FirstName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FirstName') - value_ = self.gds_validate_string(value_, node, 'FirstName') - self.FirstName = value_ - self.FirstName_nsprefix_ = child_.prefix - elif nodeName_ == 'LastName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'LastName') - value_ = self.gds_validate_string(value_, node, 'LastName') - self.LastName = value_ - self.LastName_nsprefix_ = child_.prefix - elif nodeName_ == 'Email1': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Email1') - value_ = self.gds_validate_string(value_, node, 'Email1') - self.Email1 = value_ - self.Email1_nsprefix_ = child_.prefix - elif nodeName_ == 'Email2': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Email2') - value_ = self.gds_validate_string(value_, node, 'Email2') - self.Email2 = value_ - self.Email2_nsprefix_ = child_.prefix - elif nodeName_ == 'Email3': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Email3') - value_ = self.gds_validate_string(value_, node, 'Email3') - self.Email3 = value_ - self.Email3_nsprefix_ = child_.prefix -# end class PTSEmailRequest - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'PTSEmailRequest' - rootClass = PTSEmailRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'PTSEmailRequest' - rootClass = PTSEmailRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'PTSEmailRequest' - rootClass = PTSEmailRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'PTSEmailRequest' - rootClass = PTSEmailRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from pts_email_request import *\n\n') - sys.stdout.write('import pts_email_request as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "PTSEmailRequest" -] diff --git a/schemas/usps/karrio/schemas/usps/pts_emailresult.py b/schemas/usps/karrio/schemas/usps/pts_emailresult.py deleted file mode 100644 index 0fb248e2ed..0000000000 --- a/schemas/usps/karrio/schemas/usps/pts_emailresult.py +++ /dev/null @@ -1,1317 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:08 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/pts_emailresult.py') -# -# Command line arguments: -# ./schemas/PTSEmailResult.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/pts_emailresult.py" ./schemas/PTSEmailResult.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class PTSEMAILRESULT(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ResultText=None, ReturnCode=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.ResultText = ResultText - self.ResultText_nsprefix_ = None - self.ReturnCode = ReturnCode - self.ReturnCode_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, PTSEMAILRESULT) - if subclass is not None: - return subclass(*args_, **kwargs_) - if PTSEMAILRESULT.subclass: - return PTSEMAILRESULT.subclass(*args_, **kwargs_) - else: - return PTSEMAILRESULT(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_ResultText(self): - return self.ResultText - def set_ResultText(self, ResultText): - self.ResultText = ResultText - def get_ReturnCode(self): - return self.ReturnCode - def set_ReturnCode(self, ReturnCode): - self.ReturnCode = ReturnCode - def _hasContent(self): - if ( - self.ResultText is not None or - self.ReturnCode is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='PTSEMAILRESULT', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('PTSEMAILRESULT') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'PTSEMAILRESULT': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='PTSEMAILRESULT') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='PTSEMAILRESULT', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='PTSEMAILRESULT'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='PTSEMAILRESULT', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.ResultText is not None: - namespaceprefix_ = self.ResultText_nsprefix_ + ':' if (UseCapturedNS_ and self.ResultText_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sResultText>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ResultText), input_name='ResultText')), namespaceprefix_ , eol_)) - if self.ReturnCode is not None: - namespaceprefix_ = self.ReturnCode_nsprefix_ + ':' if (UseCapturedNS_ and self.ReturnCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sReturnCode>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.ReturnCode, input_name='ReturnCode'), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'ResultText': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ResultText') - value_ = self.gds_validate_string(value_, node, 'ResultText') - self.ResultText = value_ - self.ResultText_nsprefix_ = child_.prefix - elif nodeName_ == 'ReturnCode' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'ReturnCode') - ival_ = self.gds_validate_integer(ival_, node, 'ReturnCode') - self.ReturnCode = ival_ - self.ReturnCode_nsprefix_ = child_.prefix -# end class PTSEMAILRESULT - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'PTSEMAILRESULT' - rootClass = PTSEMAILRESULT - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'PTSEMAILRESULT' - rootClass = PTSEMAILRESULT - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'PTSEMAILRESULT' - rootClass = PTSEMAILRESULT - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'PTSEMAILRESULT' - rootClass = PTSEMAILRESULT - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from pts_emailresult import *\n\n') - sys.stdout.write('import pts_emailresult as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "PTSEMAILRESULT" -] diff --git a/schemas/usps/karrio/schemas/usps/ptspod_request.py b/schemas/usps/karrio/schemas/usps/ptspod_request.py deleted file mode 100644 index 7f6a987653..0000000000 --- a/schemas/usps/karrio/schemas/usps/ptspod_request.py +++ /dev/null @@ -1,1617 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:09 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/ptspod_request.py') -# -# Command line arguments: -# ./schemas/PTSPodRequest.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/ptspod_request.py" ./schemas/PTSPodRequest.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class PTSPodRequest(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, USERID=None, TrackId=None, ClientIp=None, MpSuffix=None, MpDate=None, RequestType=None, FirstName=None, LastName=None, Email1=None, Email2=None, Email3=None, FaxNumber=None, AddressLine1=None, AddressLine2=None, City=None, State=None, Zip=None, VerifyAddress=None, TableCode=None, CustRegID=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.USERID = _cast(None, USERID) - self.USERID_nsprefix_ = None - self.TrackId = TrackId - self.TrackId_nsprefix_ = None - self.ClientIp = ClientIp - self.ClientIp_nsprefix_ = None - self.MpSuffix = MpSuffix - self.MpSuffix_nsprefix_ = None - self.MpDate = MpDate - self.MpDate_nsprefix_ = None - self.RequestType = RequestType - self.RequestType_nsprefix_ = None - self.FirstName = FirstName - self.FirstName_nsprefix_ = None - self.LastName = LastName - self.LastName_nsprefix_ = None - self.Email1 = Email1 - self.Email1_nsprefix_ = None - self.Email2 = Email2 - self.Email2_nsprefix_ = None - self.Email3 = Email3 - self.Email3_nsprefix_ = None - self.FaxNumber = FaxNumber - self.FaxNumber_nsprefix_ = None - self.AddressLine1 = AddressLine1 - self.AddressLine1_nsprefix_ = None - self.AddressLine2 = AddressLine2 - self.AddressLine2_nsprefix_ = None - self.City = City - self.City_nsprefix_ = None - self.State = State - self.State_nsprefix_ = None - self.Zip = Zip - self.Zip_nsprefix_ = None - self.VerifyAddress = VerifyAddress - self.VerifyAddress_nsprefix_ = None - self.TableCode = TableCode - self.TableCode_nsprefix_ = None - self.CustRegID = CustRegID - self.CustRegID_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, PTSPodRequest) - if subclass is not None: - return subclass(*args_, **kwargs_) - if PTSPodRequest.subclass: - return PTSPodRequest.subclass(*args_, **kwargs_) - else: - return PTSPodRequest(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_TrackId(self): - return self.TrackId - def set_TrackId(self, TrackId): - self.TrackId = TrackId - def get_ClientIp(self): - return self.ClientIp - def set_ClientIp(self, ClientIp): - self.ClientIp = ClientIp - def get_MpSuffix(self): - return self.MpSuffix - def set_MpSuffix(self, MpSuffix): - self.MpSuffix = MpSuffix - def get_MpDate(self): - return self.MpDate - def set_MpDate(self, MpDate): - self.MpDate = MpDate - def get_RequestType(self): - return self.RequestType - def set_RequestType(self, RequestType): - self.RequestType = RequestType - def get_FirstName(self): - return self.FirstName - def set_FirstName(self, FirstName): - self.FirstName = FirstName - def get_LastName(self): - return self.LastName - def set_LastName(self, LastName): - self.LastName = LastName - def get_Email1(self): - return self.Email1 - def set_Email1(self, Email1): - self.Email1 = Email1 - def get_Email2(self): - return self.Email2 - def set_Email2(self, Email2): - self.Email2 = Email2 - def get_Email3(self): - return self.Email3 - def set_Email3(self, Email3): - self.Email3 = Email3 - def get_FaxNumber(self): - return self.FaxNumber - def set_FaxNumber(self, FaxNumber): - self.FaxNumber = FaxNumber - def get_AddressLine1(self): - return self.AddressLine1 - def set_AddressLine1(self, AddressLine1): - self.AddressLine1 = AddressLine1 - def get_AddressLine2(self): - return self.AddressLine2 - def set_AddressLine2(self, AddressLine2): - self.AddressLine2 = AddressLine2 - def get_City(self): - return self.City - def set_City(self, City): - self.City = City - def get_State(self): - return self.State - def set_State(self, State): - self.State = State - def get_Zip(self): - return self.Zip - def set_Zip(self, Zip): - self.Zip = Zip - def get_VerifyAddress(self): - return self.VerifyAddress - def set_VerifyAddress(self, VerifyAddress): - self.VerifyAddress = VerifyAddress - def get_TableCode(self): - return self.TableCode - def set_TableCode(self, TableCode): - self.TableCode = TableCode - def get_CustRegID(self): - return self.CustRegID - def set_CustRegID(self, CustRegID): - self.CustRegID = CustRegID - def get_USERID(self): - return self.USERID - def set_USERID(self, USERID): - self.USERID = USERID - def _hasContent(self): - if ( - self.TrackId is not None or - self.ClientIp is not None or - self.MpSuffix is not None or - self.MpDate is not None or - self.RequestType is not None or - self.FirstName is not None or - self.LastName is not None or - self.Email1 is not None or - self.Email2 is not None or - self.Email3 is not None or - self.FaxNumber is not None or - self.AddressLine1 is not None or - self.AddressLine2 is not None or - self.City is not None or - self.State is not None or - self.Zip is not None or - self.VerifyAddress is not None or - self.TableCode is not None or - self.CustRegID is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='PTSPodRequest', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('PTSPodRequest') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'PTSPodRequest': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='PTSPodRequest') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='PTSPodRequest', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='PTSPodRequest'): - if self.USERID is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - outfile.write(' USERID=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.USERID), input_name='USERID')), )) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='PTSPodRequest', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.TrackId is not None: - namespaceprefix_ = self.TrackId_nsprefix_ + ':' if (UseCapturedNS_ and self.TrackId_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sTrackId>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.TrackId), input_name='TrackId')), namespaceprefix_ , eol_)) - if self.ClientIp is not None: - namespaceprefix_ = self.ClientIp_nsprefix_ + ':' if (UseCapturedNS_ and self.ClientIp_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sClientIp>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ClientIp), input_name='ClientIp')), namespaceprefix_ , eol_)) - if self.MpSuffix is not None: - namespaceprefix_ = self.MpSuffix_nsprefix_ + ':' if (UseCapturedNS_ and self.MpSuffix_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sMpSuffix>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.MpSuffix, input_name='MpSuffix'), namespaceprefix_ , eol_)) - if self.MpDate is not None: - namespaceprefix_ = self.MpDate_nsprefix_ + ':' if (UseCapturedNS_ and self.MpDate_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sMpDate>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.MpDate), input_name='MpDate')), namespaceprefix_ , eol_)) - if self.RequestType is not None: - namespaceprefix_ = self.RequestType_nsprefix_ + ':' if (UseCapturedNS_ and self.RequestType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRequestType>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.RequestType), input_name='RequestType')), namespaceprefix_ , eol_)) - if self.FirstName is not None: - namespaceprefix_ = self.FirstName_nsprefix_ + ':' if (UseCapturedNS_ and self.FirstName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFirstName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FirstName), input_name='FirstName')), namespaceprefix_ , eol_)) - if self.LastName is not None: - namespaceprefix_ = self.LastName_nsprefix_ + ':' if (UseCapturedNS_ and self.LastName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sLastName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.LastName), input_name='LastName')), namespaceprefix_ , eol_)) - if self.Email1 is not None: - namespaceprefix_ = self.Email1_nsprefix_ + ':' if (UseCapturedNS_ and self.Email1_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEmail1>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Email1), input_name='Email1')), namespaceprefix_ , eol_)) - if self.Email2 is not None: - namespaceprefix_ = self.Email2_nsprefix_ + ':' if (UseCapturedNS_ and self.Email2_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEmail2>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Email2), input_name='Email2')), namespaceprefix_ , eol_)) - if self.Email3 is not None: - namespaceprefix_ = self.Email3_nsprefix_ + ':' if (UseCapturedNS_ and self.Email3_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEmail3>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Email3), input_name='Email3')), namespaceprefix_ , eol_)) - if self.FaxNumber is not None: - namespaceprefix_ = self.FaxNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.FaxNumber_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFaxNumber>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FaxNumber), input_name='FaxNumber')), namespaceprefix_ , eol_)) - if self.AddressLine1 is not None: - namespaceprefix_ = self.AddressLine1_nsprefix_ + ':' if (UseCapturedNS_ and self.AddressLine1_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAddressLine1>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.AddressLine1), input_name='AddressLine1')), namespaceprefix_ , eol_)) - if self.AddressLine2 is not None: - namespaceprefix_ = self.AddressLine2_nsprefix_ + ':' if (UseCapturedNS_ and self.AddressLine2_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAddressLine2>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.AddressLine2), input_name='AddressLine2')), namespaceprefix_ , eol_)) - if self.City is not None: - namespaceprefix_ = self.City_nsprefix_ + ':' if (UseCapturedNS_ and self.City_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.City), input_name='City')), namespaceprefix_ , eol_)) - if self.State is not None: - namespaceprefix_ = self.State_nsprefix_ + ':' if (UseCapturedNS_ and self.State_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.State), input_name='State')), namespaceprefix_ , eol_)) - if self.Zip is not None: - namespaceprefix_ = self.Zip_nsprefix_ + ':' if (UseCapturedNS_ and self.Zip_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sZip>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Zip), input_name='Zip')), namespaceprefix_ , eol_)) - if self.VerifyAddress is not None: - namespaceprefix_ = self.VerifyAddress_nsprefix_ + ':' if (UseCapturedNS_ and self.VerifyAddress_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sVerifyAddress>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.VerifyAddress, input_name='VerifyAddress'), namespaceprefix_ , eol_)) - if self.TableCode is not None: - namespaceprefix_ = self.TableCode_nsprefix_ + ':' if (UseCapturedNS_ and self.TableCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sTableCode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.TableCode), input_name='TableCode')), namespaceprefix_ , eol_)) - if self.CustRegID is not None: - namespaceprefix_ = self.CustRegID_nsprefix_ + ':' if (UseCapturedNS_ and self.CustRegID_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCustRegID>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.CustRegID, input_name='CustRegID'), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('USERID', node) - if value is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - self.USERID = value - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'TrackId': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'TrackId') - value_ = self.gds_validate_string(value_, node, 'TrackId') - self.TrackId = value_ - self.TrackId_nsprefix_ = child_.prefix - elif nodeName_ == 'ClientIp': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ClientIp') - value_ = self.gds_validate_string(value_, node, 'ClientIp') - self.ClientIp = value_ - self.ClientIp_nsprefix_ = child_.prefix - elif nodeName_ == 'MpSuffix' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'MpSuffix') - ival_ = self.gds_validate_integer(ival_, node, 'MpSuffix') - self.MpSuffix = ival_ - self.MpSuffix_nsprefix_ = child_.prefix - elif nodeName_ == 'MpDate': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'MpDate') - value_ = self.gds_validate_string(value_, node, 'MpDate') - self.MpDate = value_ - self.MpDate_nsprefix_ = child_.prefix - elif nodeName_ == 'RequestType': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'RequestType') - value_ = self.gds_validate_string(value_, node, 'RequestType') - self.RequestType = value_ - self.RequestType_nsprefix_ = child_.prefix - elif nodeName_ == 'FirstName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FirstName') - value_ = self.gds_validate_string(value_, node, 'FirstName') - self.FirstName = value_ - self.FirstName_nsprefix_ = child_.prefix - elif nodeName_ == 'LastName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'LastName') - value_ = self.gds_validate_string(value_, node, 'LastName') - self.LastName = value_ - self.LastName_nsprefix_ = child_.prefix - elif nodeName_ == 'Email1': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Email1') - value_ = self.gds_validate_string(value_, node, 'Email1') - self.Email1 = value_ - self.Email1_nsprefix_ = child_.prefix - elif nodeName_ == 'Email2': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Email2') - value_ = self.gds_validate_string(value_, node, 'Email2') - self.Email2 = value_ - self.Email2_nsprefix_ = child_.prefix - elif nodeName_ == 'Email3': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Email3') - value_ = self.gds_validate_string(value_, node, 'Email3') - self.Email3 = value_ - self.Email3_nsprefix_ = child_.prefix - elif nodeName_ == 'FaxNumber': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FaxNumber') - value_ = self.gds_validate_string(value_, node, 'FaxNumber') - self.FaxNumber = value_ - self.FaxNumber_nsprefix_ = child_.prefix - elif nodeName_ == 'AddressLine1': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'AddressLine1') - value_ = self.gds_validate_string(value_, node, 'AddressLine1') - self.AddressLine1 = value_ - self.AddressLine1_nsprefix_ = child_.prefix - elif nodeName_ == 'AddressLine2': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'AddressLine2') - value_ = self.gds_validate_string(value_, node, 'AddressLine2') - self.AddressLine2 = value_ - self.AddressLine2_nsprefix_ = child_.prefix - elif nodeName_ == 'City': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'City') - value_ = self.gds_validate_string(value_, node, 'City') - self.City = value_ - self.City_nsprefix_ = child_.prefix - elif nodeName_ == 'State': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'State') - value_ = self.gds_validate_string(value_, node, 'State') - self.State = value_ - self.State_nsprefix_ = child_.prefix - elif nodeName_ == 'Zip': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Zip') - value_ = self.gds_validate_string(value_, node, 'Zip') - self.Zip = value_ - self.Zip_nsprefix_ = child_.prefix - elif nodeName_ == 'VerifyAddress': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'VerifyAddress') - ival_ = self.gds_validate_boolean(ival_, node, 'VerifyAddress') - self.VerifyAddress = ival_ - self.VerifyAddress_nsprefix_ = child_.prefix - elif nodeName_ == 'TableCode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'TableCode') - value_ = self.gds_validate_string(value_, node, 'TableCode') - self.TableCode = value_ - self.TableCode_nsprefix_ = child_.prefix - elif nodeName_ == 'CustRegID' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'CustRegID') - ival_ = self.gds_validate_integer(ival_, node, 'CustRegID') - self.CustRegID = ival_ - self.CustRegID_nsprefix_ = child_.prefix -# end class PTSPodRequest - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'PTSPodRequest' - rootClass = PTSPodRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'PTSPodRequest' - rootClass = PTSPodRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'PTSPodRequest' - rootClass = PTSPodRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'PTSPodRequest' - rootClass = PTSPodRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from ptspod_request import *\n\n') - sys.stdout.write('import ptspod_request as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "PTSPodRequest" -] diff --git a/schemas/usps/karrio/schemas/usps/ptspod_result.py b/schemas/usps/karrio/schemas/usps/ptspod_result.py deleted file mode 100644 index 56f6e70dd0..0000000000 --- a/schemas/usps/karrio/schemas/usps/ptspod_result.py +++ /dev/null @@ -1,1317 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:09 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/ptspod_result.py') -# -# Command line arguments: -# ./schemas/PTSPODResult.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/ptspod_result.py" ./schemas/PTSPODResult.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class PTSPODRESULT(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ResultText=None, ReturnCode=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.ResultText = ResultText - self.ResultText_nsprefix_ = None - self.ReturnCode = ReturnCode - self.ReturnCode_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, PTSPODRESULT) - if subclass is not None: - return subclass(*args_, **kwargs_) - if PTSPODRESULT.subclass: - return PTSPODRESULT.subclass(*args_, **kwargs_) - else: - return PTSPODRESULT(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_ResultText(self): - return self.ResultText - def set_ResultText(self, ResultText): - self.ResultText = ResultText - def get_ReturnCode(self): - return self.ReturnCode - def set_ReturnCode(self, ReturnCode): - self.ReturnCode = ReturnCode - def _hasContent(self): - if ( - self.ResultText is not None or - self.ReturnCode is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='PTSPODRESULT', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('PTSPODRESULT') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'PTSPODRESULT': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='PTSPODRESULT') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='PTSPODRESULT', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='PTSPODRESULT'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='PTSPODRESULT', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.ResultText is not None: - namespaceprefix_ = self.ResultText_nsprefix_ + ':' if (UseCapturedNS_ and self.ResultText_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sResultText>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ResultText), input_name='ResultText')), namespaceprefix_ , eol_)) - if self.ReturnCode is not None: - namespaceprefix_ = self.ReturnCode_nsprefix_ + ':' if (UseCapturedNS_ and self.ReturnCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sReturnCode>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.ReturnCode, input_name='ReturnCode'), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'ResultText': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ResultText') - value_ = self.gds_validate_string(value_, node, 'ResultText') - self.ResultText = value_ - self.ResultText_nsprefix_ = child_.prefix - elif nodeName_ == 'ReturnCode' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'ReturnCode') - ival_ = self.gds_validate_integer(ival_, node, 'ReturnCode') - self.ReturnCode = ival_ - self.ReturnCode_nsprefix_ = child_.prefix -# end class PTSPODRESULT - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'PTSPODRESULT' - rootClass = PTSPODRESULT - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'PTSPODRESULT' - rootClass = PTSPODRESULT - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'PTSPODRESULT' - rootClass = PTSPODRESULT - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'PTSPODRESULT' - rootClass = PTSPODRESULT - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from ptspod_result import *\n\n') - sys.stdout.write('import ptspod_result as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "PTSPODRESULT" -] diff --git a/schemas/usps/karrio/schemas/usps/ptsrre_request.py b/schemas/usps/karrio/schemas/usps/ptsrre_request.py deleted file mode 100644 index 903f8de5c6..0000000000 --- a/schemas/usps/karrio/schemas/usps/ptsrre_request.py +++ /dev/null @@ -1,1481 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:10 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/ptsrre_request.py') -# -# Command line arguments: -# ./schemas/PTSRreRequest.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/ptsrre_request.py" ./schemas/PTSRreRequest.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class PTSRreRequest(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, USERID=None, TrackId=None, ClientIp=None, MpSuffix=None, MpDate=None, FirstName=None, LastName=None, Email1=None, Email2=None, Email3=None, TableCode=None, CustRegID=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.USERID = _cast(None, USERID) - self.USERID_nsprefix_ = None - self.TrackId = TrackId - self.TrackId_nsprefix_ = None - self.ClientIp = ClientIp - self.ClientIp_nsprefix_ = None - self.MpSuffix = MpSuffix - self.MpSuffix_nsprefix_ = None - self.MpDate = MpDate - self.MpDate_nsprefix_ = None - self.FirstName = FirstName - self.FirstName_nsprefix_ = None - self.LastName = LastName - self.LastName_nsprefix_ = None - self.Email1 = Email1 - self.Email1_nsprefix_ = None - self.Email2 = Email2 - self.Email2_nsprefix_ = None - self.Email3 = Email3 - self.Email3_nsprefix_ = None - self.TableCode = TableCode - self.TableCode_nsprefix_ = None - self.CustRegID = CustRegID - self.CustRegID_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, PTSRreRequest) - if subclass is not None: - return subclass(*args_, **kwargs_) - if PTSRreRequest.subclass: - return PTSRreRequest.subclass(*args_, **kwargs_) - else: - return PTSRreRequest(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_TrackId(self): - return self.TrackId - def set_TrackId(self, TrackId): - self.TrackId = TrackId - def get_ClientIp(self): - return self.ClientIp - def set_ClientIp(self, ClientIp): - self.ClientIp = ClientIp - def get_MpSuffix(self): - return self.MpSuffix - def set_MpSuffix(self, MpSuffix): - self.MpSuffix = MpSuffix - def get_MpDate(self): - return self.MpDate - def set_MpDate(self, MpDate): - self.MpDate = MpDate - def get_FirstName(self): - return self.FirstName - def set_FirstName(self, FirstName): - self.FirstName = FirstName - def get_LastName(self): - return self.LastName - def set_LastName(self, LastName): - self.LastName = LastName - def get_Email1(self): - return self.Email1 - def set_Email1(self, Email1): - self.Email1 = Email1 - def get_Email2(self): - return self.Email2 - def set_Email2(self, Email2): - self.Email2 = Email2 - def get_Email3(self): - return self.Email3 - def set_Email3(self, Email3): - self.Email3 = Email3 - def get_TableCode(self): - return self.TableCode - def set_TableCode(self, TableCode): - self.TableCode = TableCode - def get_CustRegID(self): - return self.CustRegID - def set_CustRegID(self, CustRegID): - self.CustRegID = CustRegID - def get_USERID(self): - return self.USERID - def set_USERID(self, USERID): - self.USERID = USERID - def _hasContent(self): - if ( - self.TrackId is not None or - self.ClientIp is not None or - self.MpSuffix is not None or - self.MpDate is not None or - self.FirstName is not None or - self.LastName is not None or - self.Email1 is not None or - self.Email2 is not None or - self.Email3 is not None or - self.TableCode is not None or - self.CustRegID is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='PTSRreRequest', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('PTSRreRequest') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'PTSRreRequest': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='PTSRreRequest') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='PTSRreRequest', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='PTSRreRequest'): - if self.USERID is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - outfile.write(' USERID=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.USERID), input_name='USERID')), )) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='PTSRreRequest', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.TrackId is not None: - namespaceprefix_ = self.TrackId_nsprefix_ + ':' if (UseCapturedNS_ and self.TrackId_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sTrackId>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.TrackId), input_name='TrackId')), namespaceprefix_ , eol_)) - if self.ClientIp is not None: - namespaceprefix_ = self.ClientIp_nsprefix_ + ':' if (UseCapturedNS_ and self.ClientIp_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sClientIp>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ClientIp), input_name='ClientIp')), namespaceprefix_ , eol_)) - if self.MpSuffix is not None: - namespaceprefix_ = self.MpSuffix_nsprefix_ + ':' if (UseCapturedNS_ and self.MpSuffix_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sMpSuffix>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.MpSuffix, input_name='MpSuffix'), namespaceprefix_ , eol_)) - if self.MpDate is not None: - namespaceprefix_ = self.MpDate_nsprefix_ + ':' if (UseCapturedNS_ and self.MpDate_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sMpDate>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.MpDate), input_name='MpDate')), namespaceprefix_ , eol_)) - if self.FirstName is not None: - namespaceprefix_ = self.FirstName_nsprefix_ + ':' if (UseCapturedNS_ and self.FirstName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFirstName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FirstName), input_name='FirstName')), namespaceprefix_ , eol_)) - if self.LastName is not None: - namespaceprefix_ = self.LastName_nsprefix_ + ':' if (UseCapturedNS_ and self.LastName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sLastName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.LastName), input_name='LastName')), namespaceprefix_ , eol_)) - if self.Email1 is not None: - namespaceprefix_ = self.Email1_nsprefix_ + ':' if (UseCapturedNS_ and self.Email1_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEmail1>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Email1), input_name='Email1')), namespaceprefix_ , eol_)) - if self.Email2 is not None: - namespaceprefix_ = self.Email2_nsprefix_ + ':' if (UseCapturedNS_ and self.Email2_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEmail2>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Email2), input_name='Email2')), namespaceprefix_ , eol_)) - if self.Email3 is not None: - namespaceprefix_ = self.Email3_nsprefix_ + ':' if (UseCapturedNS_ and self.Email3_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEmail3>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Email3), input_name='Email3')), namespaceprefix_ , eol_)) - if self.TableCode is not None: - namespaceprefix_ = self.TableCode_nsprefix_ + ':' if (UseCapturedNS_ and self.TableCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sTableCode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.TableCode), input_name='TableCode')), namespaceprefix_ , eol_)) - if self.CustRegID is not None: - namespaceprefix_ = self.CustRegID_nsprefix_ + ':' if (UseCapturedNS_ and self.CustRegID_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCustRegID>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.CustRegID, input_name='CustRegID'), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('USERID', node) - if value is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - self.USERID = value - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'TrackId': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'TrackId') - value_ = self.gds_validate_string(value_, node, 'TrackId') - self.TrackId = value_ - self.TrackId_nsprefix_ = child_.prefix - elif nodeName_ == 'ClientIp': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ClientIp') - value_ = self.gds_validate_string(value_, node, 'ClientIp') - self.ClientIp = value_ - self.ClientIp_nsprefix_ = child_.prefix - elif nodeName_ == 'MpSuffix' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'MpSuffix') - ival_ = self.gds_validate_integer(ival_, node, 'MpSuffix') - self.MpSuffix = ival_ - self.MpSuffix_nsprefix_ = child_.prefix - elif nodeName_ == 'MpDate': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'MpDate') - value_ = self.gds_validate_string(value_, node, 'MpDate') - self.MpDate = value_ - self.MpDate_nsprefix_ = child_.prefix - elif nodeName_ == 'FirstName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FirstName') - value_ = self.gds_validate_string(value_, node, 'FirstName') - self.FirstName = value_ - self.FirstName_nsprefix_ = child_.prefix - elif nodeName_ == 'LastName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'LastName') - value_ = self.gds_validate_string(value_, node, 'LastName') - self.LastName = value_ - self.LastName_nsprefix_ = child_.prefix - elif nodeName_ == 'Email1': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Email1') - value_ = self.gds_validate_string(value_, node, 'Email1') - self.Email1 = value_ - self.Email1_nsprefix_ = child_.prefix - elif nodeName_ == 'Email2': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Email2') - value_ = self.gds_validate_string(value_, node, 'Email2') - self.Email2 = value_ - self.Email2_nsprefix_ = child_.prefix - elif nodeName_ == 'Email3': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Email3') - value_ = self.gds_validate_string(value_, node, 'Email3') - self.Email3 = value_ - self.Email3_nsprefix_ = child_.prefix - elif nodeName_ == 'TableCode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'TableCode') - value_ = self.gds_validate_string(value_, node, 'TableCode') - self.TableCode = value_ - self.TableCode_nsprefix_ = child_.prefix - elif nodeName_ == 'CustRegID' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'CustRegID') - ival_ = self.gds_validate_integer(ival_, node, 'CustRegID') - self.CustRegID = ival_ - self.CustRegID_nsprefix_ = child_.prefix -# end class PTSRreRequest - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'PTSRreRequest' - rootClass = PTSRreRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'PTSRreRequest' - rootClass = PTSRreRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'PTSRreRequest' - rootClass = PTSRreRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'PTSRreRequest' - rootClass = PTSRreRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from ptsrre_request import *\n\n') - sys.stdout.write('import ptsrre_request as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "PTSRreRequest" -] diff --git a/schemas/usps/karrio/schemas/usps/ptsrre_result.py b/schemas/usps/karrio/schemas/usps/ptsrre_result.py deleted file mode 100644 index 08d4ecc12b..0000000000 --- a/schemas/usps/karrio/schemas/usps/ptsrre_result.py +++ /dev/null @@ -1,1317 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:10 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/ptsrre_result.py') -# -# Command line arguments: -# ./schemas/PTSRREResult.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/ptsrre_result.py" ./schemas/PTSRREResult.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class PTSRRERESULT(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ResultText=None, ReturnCode=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.ResultText = ResultText - self.ResultText_nsprefix_ = None - self.ReturnCode = ReturnCode - self.ReturnCode_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, PTSRRERESULT) - if subclass is not None: - return subclass(*args_, **kwargs_) - if PTSRRERESULT.subclass: - return PTSRRERESULT.subclass(*args_, **kwargs_) - else: - return PTSRRERESULT(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_ResultText(self): - return self.ResultText - def set_ResultText(self, ResultText): - self.ResultText = ResultText - def get_ReturnCode(self): - return self.ReturnCode - def set_ReturnCode(self, ReturnCode): - self.ReturnCode = ReturnCode - def _hasContent(self): - if ( - self.ResultText is not None or - self.ReturnCode is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='PTSRRERESULT', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('PTSRRERESULT') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'PTSRRERESULT': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='PTSRRERESULT') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='PTSRRERESULT', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='PTSRRERESULT'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='PTSRRERESULT', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.ResultText is not None: - namespaceprefix_ = self.ResultText_nsprefix_ + ':' if (UseCapturedNS_ and self.ResultText_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sResultText>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ResultText), input_name='ResultText')), namespaceprefix_ , eol_)) - if self.ReturnCode is not None: - namespaceprefix_ = self.ReturnCode_nsprefix_ + ':' if (UseCapturedNS_ and self.ReturnCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sReturnCode>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.ReturnCode, input_name='ReturnCode'), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'ResultText': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ResultText') - value_ = self.gds_validate_string(value_, node, 'ResultText') - self.ResultText = value_ - self.ResultText_nsprefix_ = child_.prefix - elif nodeName_ == 'ReturnCode' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'ReturnCode') - ival_ = self.gds_validate_integer(ival_, node, 'ReturnCode') - self.ReturnCode = ival_ - self.ReturnCode_nsprefix_ = child_.prefix -# end class PTSRRERESULT - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'PTSRRERESULT' - rootClass = PTSRRERESULT - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'PTSRRERESULT' - rootClass = PTSRRERESULT - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'PTSRRERESULT' - rootClass = PTSRRERESULT - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'PTSRRERESULT' - rootClass = PTSRRERESULT - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from ptsrre_result import *\n\n') - sys.stdout.write('import ptsrre_result as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "PTSRRERESULT" -] diff --git a/schemas/usps/karrio/schemas/usps/ptstpod_request.py b/schemas/usps/karrio/schemas/usps/ptstpod_request.py deleted file mode 100644 index 2b33ce9132..0000000000 --- a/schemas/usps/karrio/schemas/usps/ptstpod_request.py +++ /dev/null @@ -1,1498 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:10 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/ptstpod_request.py') -# -# Command line arguments: -# ./schemas/PTSTPodRequest.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/ptstpod_request.py" ./schemas/PTSTPodRequest.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class PTSTPodRequest(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, USERID=None, TrackId=None, ClientIp=None, MpSuffix=None, MpDate=None, RequestType=None, FirstName=None, LastName=None, Email1=None, Email2=None, Email3=None, TableCode=None, CustRegID=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.USERID = _cast(None, USERID) - self.USERID_nsprefix_ = None - self.TrackId = TrackId - self.TrackId_nsprefix_ = None - self.ClientIp = ClientIp - self.ClientIp_nsprefix_ = None - self.MpSuffix = MpSuffix - self.MpSuffix_nsprefix_ = None - self.MpDate = MpDate - self.MpDate_nsprefix_ = None - self.RequestType = RequestType - self.RequestType_nsprefix_ = None - self.FirstName = FirstName - self.FirstName_nsprefix_ = None - self.LastName = LastName - self.LastName_nsprefix_ = None - self.Email1 = Email1 - self.Email1_nsprefix_ = None - self.Email2 = Email2 - self.Email2_nsprefix_ = None - self.Email3 = Email3 - self.Email3_nsprefix_ = None - self.TableCode = TableCode - self.TableCode_nsprefix_ = None - self.CustRegID = CustRegID - self.CustRegID_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, PTSTPodRequest) - if subclass is not None: - return subclass(*args_, **kwargs_) - if PTSTPodRequest.subclass: - return PTSTPodRequest.subclass(*args_, **kwargs_) - else: - return PTSTPodRequest(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_TrackId(self): - return self.TrackId - def set_TrackId(self, TrackId): - self.TrackId = TrackId - def get_ClientIp(self): - return self.ClientIp - def set_ClientIp(self, ClientIp): - self.ClientIp = ClientIp - def get_MpSuffix(self): - return self.MpSuffix - def set_MpSuffix(self, MpSuffix): - self.MpSuffix = MpSuffix - def get_MpDate(self): - return self.MpDate - def set_MpDate(self, MpDate): - self.MpDate = MpDate - def get_RequestType(self): - return self.RequestType - def set_RequestType(self, RequestType): - self.RequestType = RequestType - def get_FirstName(self): - return self.FirstName - def set_FirstName(self, FirstName): - self.FirstName = FirstName - def get_LastName(self): - return self.LastName - def set_LastName(self, LastName): - self.LastName = LastName - def get_Email1(self): - return self.Email1 - def set_Email1(self, Email1): - self.Email1 = Email1 - def get_Email2(self): - return self.Email2 - def set_Email2(self, Email2): - self.Email2 = Email2 - def get_Email3(self): - return self.Email3 - def set_Email3(self, Email3): - self.Email3 = Email3 - def get_TableCode(self): - return self.TableCode - def set_TableCode(self, TableCode): - self.TableCode = TableCode - def get_CustRegID(self): - return self.CustRegID - def set_CustRegID(self, CustRegID): - self.CustRegID = CustRegID - def get_USERID(self): - return self.USERID - def set_USERID(self, USERID): - self.USERID = USERID - def _hasContent(self): - if ( - self.TrackId is not None or - self.ClientIp is not None or - self.MpSuffix is not None or - self.MpDate is not None or - self.RequestType is not None or - self.FirstName is not None or - self.LastName is not None or - self.Email1 is not None or - self.Email2 is not None or - self.Email3 is not None or - self.TableCode is not None or - self.CustRegID is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='PTSTPodRequest', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('PTSTPodRequest') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'PTSTPodRequest': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='PTSTPodRequest') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='PTSTPodRequest', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='PTSTPodRequest'): - if self.USERID is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - outfile.write(' USERID=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.USERID), input_name='USERID')), )) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='PTSTPodRequest', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.TrackId is not None: - namespaceprefix_ = self.TrackId_nsprefix_ + ':' if (UseCapturedNS_ and self.TrackId_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sTrackId>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.TrackId), input_name='TrackId')), namespaceprefix_ , eol_)) - if self.ClientIp is not None: - namespaceprefix_ = self.ClientIp_nsprefix_ + ':' if (UseCapturedNS_ and self.ClientIp_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sClientIp>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ClientIp), input_name='ClientIp')), namespaceprefix_ , eol_)) - if self.MpSuffix is not None: - namespaceprefix_ = self.MpSuffix_nsprefix_ + ':' if (UseCapturedNS_ and self.MpSuffix_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sMpSuffix>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.MpSuffix, input_name='MpSuffix'), namespaceprefix_ , eol_)) - if self.MpDate is not None: - namespaceprefix_ = self.MpDate_nsprefix_ + ':' if (UseCapturedNS_ and self.MpDate_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sMpDate>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.MpDate), input_name='MpDate')), namespaceprefix_ , eol_)) - if self.RequestType is not None: - namespaceprefix_ = self.RequestType_nsprefix_ + ':' if (UseCapturedNS_ and self.RequestType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRequestType>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.RequestType), input_name='RequestType')), namespaceprefix_ , eol_)) - if self.FirstName is not None: - namespaceprefix_ = self.FirstName_nsprefix_ + ':' if (UseCapturedNS_ and self.FirstName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFirstName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FirstName), input_name='FirstName')), namespaceprefix_ , eol_)) - if self.LastName is not None: - namespaceprefix_ = self.LastName_nsprefix_ + ':' if (UseCapturedNS_ and self.LastName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sLastName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.LastName), input_name='LastName')), namespaceprefix_ , eol_)) - if self.Email1 is not None: - namespaceprefix_ = self.Email1_nsprefix_ + ':' if (UseCapturedNS_ and self.Email1_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEmail1>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Email1), input_name='Email1')), namespaceprefix_ , eol_)) - if self.Email2 is not None: - namespaceprefix_ = self.Email2_nsprefix_ + ':' if (UseCapturedNS_ and self.Email2_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEmail2>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Email2), input_name='Email2')), namespaceprefix_ , eol_)) - if self.Email3 is not None: - namespaceprefix_ = self.Email3_nsprefix_ + ':' if (UseCapturedNS_ and self.Email3_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEmail3>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Email3), input_name='Email3')), namespaceprefix_ , eol_)) - if self.TableCode is not None: - namespaceprefix_ = self.TableCode_nsprefix_ + ':' if (UseCapturedNS_ and self.TableCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sTableCode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.TableCode), input_name='TableCode')), namespaceprefix_ , eol_)) - if self.CustRegID is not None: - namespaceprefix_ = self.CustRegID_nsprefix_ + ':' if (UseCapturedNS_ and self.CustRegID_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCustRegID>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.CustRegID, input_name='CustRegID'), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('USERID', node) - if value is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - self.USERID = value - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'TrackId': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'TrackId') - value_ = self.gds_validate_string(value_, node, 'TrackId') - self.TrackId = value_ - self.TrackId_nsprefix_ = child_.prefix - elif nodeName_ == 'ClientIp': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ClientIp') - value_ = self.gds_validate_string(value_, node, 'ClientIp') - self.ClientIp = value_ - self.ClientIp_nsprefix_ = child_.prefix - elif nodeName_ == 'MpSuffix' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'MpSuffix') - ival_ = self.gds_validate_integer(ival_, node, 'MpSuffix') - self.MpSuffix = ival_ - self.MpSuffix_nsprefix_ = child_.prefix - elif nodeName_ == 'MpDate': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'MpDate') - value_ = self.gds_validate_string(value_, node, 'MpDate') - self.MpDate = value_ - self.MpDate_nsprefix_ = child_.prefix - elif nodeName_ == 'RequestType': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'RequestType') - value_ = self.gds_validate_string(value_, node, 'RequestType') - self.RequestType = value_ - self.RequestType_nsprefix_ = child_.prefix - elif nodeName_ == 'FirstName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FirstName') - value_ = self.gds_validate_string(value_, node, 'FirstName') - self.FirstName = value_ - self.FirstName_nsprefix_ = child_.prefix - elif nodeName_ == 'LastName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'LastName') - value_ = self.gds_validate_string(value_, node, 'LastName') - self.LastName = value_ - self.LastName_nsprefix_ = child_.prefix - elif nodeName_ == 'Email1': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Email1') - value_ = self.gds_validate_string(value_, node, 'Email1') - self.Email1 = value_ - self.Email1_nsprefix_ = child_.prefix - elif nodeName_ == 'Email2': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Email2') - value_ = self.gds_validate_string(value_, node, 'Email2') - self.Email2 = value_ - self.Email2_nsprefix_ = child_.prefix - elif nodeName_ == 'Email3': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Email3') - value_ = self.gds_validate_string(value_, node, 'Email3') - self.Email3 = value_ - self.Email3_nsprefix_ = child_.prefix - elif nodeName_ == 'TableCode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'TableCode') - value_ = self.gds_validate_string(value_, node, 'TableCode') - self.TableCode = value_ - self.TableCode_nsprefix_ = child_.prefix - elif nodeName_ == 'CustRegID' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'CustRegID') - ival_ = self.gds_validate_integer(ival_, node, 'CustRegID') - self.CustRegID = ival_ - self.CustRegID_nsprefix_ = child_.prefix -# end class PTSTPodRequest - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'PTSTPodRequest' - rootClass = PTSTPodRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'PTSTPodRequest' - rootClass = PTSTPodRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'PTSTPodRequest' - rootClass = PTSTPodRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'PTSTPodRequest' - rootClass = PTSTPodRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from ptstpod_request import *\n\n') - sys.stdout.write('import ptstpod_request as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "PTSTPodRequest" -] diff --git a/schemas/usps/karrio/schemas/usps/ptstpod_result.py b/schemas/usps/karrio/schemas/usps/ptstpod_result.py deleted file mode 100644 index 1bd6ab3c32..0000000000 --- a/schemas/usps/karrio/schemas/usps/ptstpod_result.py +++ /dev/null @@ -1,1317 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:10 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/ptstpod_result.py') -# -# Command line arguments: -# ./schemas/PTSTPODResult.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/ptstpod_result.py" ./schemas/PTSTPODResult.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class PTSTPODRESULT(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ResultText=None, ReturnCode=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.ResultText = ResultText - self.ResultText_nsprefix_ = None - self.ReturnCode = ReturnCode - self.ReturnCode_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, PTSTPODRESULT) - if subclass is not None: - return subclass(*args_, **kwargs_) - if PTSTPODRESULT.subclass: - return PTSTPODRESULT.subclass(*args_, **kwargs_) - else: - return PTSTPODRESULT(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_ResultText(self): - return self.ResultText - def set_ResultText(self, ResultText): - self.ResultText = ResultText - def get_ReturnCode(self): - return self.ReturnCode - def set_ReturnCode(self, ReturnCode): - self.ReturnCode = ReturnCode - def _hasContent(self): - if ( - self.ResultText is not None or - self.ReturnCode is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='PTSTPODRESULT', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('PTSTPODRESULT') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'PTSTPODRESULT': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='PTSTPODRESULT') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='PTSTPODRESULT', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='PTSTPODRESULT'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='PTSTPODRESULT', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.ResultText is not None: - namespaceprefix_ = self.ResultText_nsprefix_ + ':' if (UseCapturedNS_ and self.ResultText_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sResultText>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ResultText), input_name='ResultText')), namespaceprefix_ , eol_)) - if self.ReturnCode is not None: - namespaceprefix_ = self.ReturnCode_nsprefix_ + ':' if (UseCapturedNS_ and self.ReturnCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sReturnCode>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.ReturnCode, input_name='ReturnCode'), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'ResultText': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ResultText') - value_ = self.gds_validate_string(value_, node, 'ResultText') - self.ResultText = value_ - self.ResultText_nsprefix_ = child_.prefix - elif nodeName_ == 'ReturnCode' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'ReturnCode') - ival_ = self.gds_validate_integer(ival_, node, 'ReturnCode') - self.ReturnCode = ival_ - self.ReturnCode_nsprefix_ = child_.prefix -# end class PTSTPODRESULT - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'PTSTPODRESULT' - rootClass = PTSTPODRESULT - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'PTSTPODRESULT' - rootClass = PTSTPODRESULT - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'PTSTPODRESULT' - rootClass = PTSTPODRESULT - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'PTSTPODRESULT' - rootClass = PTSTPODRESULT - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from ptstpod_result import *\n\n') - sys.stdout.write('import ptstpod_result as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "PTSTPODRESULT" -] diff --git a/schemas/usps/karrio/schemas/usps/rate_v4_request.py b/schemas/usps/karrio/schemas/usps/rate_v4_request.py deleted file mode 100644 index b8b188e31a..0000000000 --- a/schemas/usps/karrio/schemas/usps/rate_v4_request.py +++ /dev/null @@ -1,2195 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:11 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/rate_v4_request.py') -# -# Command line arguments: -# ./schemas/RateV4Request.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/rate_v4_request.py" ./schemas/RateV4Request.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class RateV4Request(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, USERID=None, Revision=None, Package=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.USERID = _cast(None, USERID) - self.USERID_nsprefix_ = None - self.Revision = Revision - self.Revision_nsprefix_ = None - if Package is None: - self.Package = [] - else: - self.Package = Package - self.Package_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, RateV4Request) - if subclass is not None: - return subclass(*args_, **kwargs_) - if RateV4Request.subclass: - return RateV4Request.subclass(*args_, **kwargs_) - else: - return RateV4Request(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_Revision(self): - return self.Revision - def set_Revision(self, Revision): - self.Revision = Revision - def get_Package(self): - return self.Package - def set_Package(self, Package): - self.Package = Package - def add_Package(self, value): - self.Package.append(value) - def insert_Package_at(self, index, value): - self.Package.insert(index, value) - def replace_Package_at(self, index, value): - self.Package[index] = value - def get_USERID(self): - return self.USERID - def set_USERID(self, USERID): - self.USERID = USERID - def _hasContent(self): - if ( - self.Revision is not None or - self.Package - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='RateV4Request', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('RateV4Request') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'RateV4Request': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='RateV4Request') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='RateV4Request', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='RateV4Request'): - if self.USERID is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - outfile.write(' USERID=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.USERID), input_name='USERID')), )) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='RateV4Request', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.Revision is not None: - namespaceprefix_ = self.Revision_nsprefix_ + ':' if (UseCapturedNS_ and self.Revision_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRevision>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Revision), input_name='Revision')), namespaceprefix_ , eol_)) - for Package_ in self.Package: - namespaceprefix_ = self.Package_nsprefix_ + ':' if (UseCapturedNS_ and self.Package_nsprefix_) else '' - Package_.export(outfile, level, namespaceprefix_, namespacedef_='', name_='Package', pretty_print=pretty_print) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('USERID', node) - if value is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - self.USERID = value - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'Revision': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Revision') - value_ = self.gds_validate_string(value_, node, 'Revision') - self.Revision = value_ - self.Revision_nsprefix_ = child_.prefix - elif nodeName_ == 'Package': - obj_ = PackageType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.Package.append(obj_) - obj_.original_tagname_ = 'Package' -# end class RateV4Request - - -class PackageType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ID=None, Service=None, FirstClassMailType=None, ZipOrigination=None, ZipDestination=None, Pounds=None, Ounces=None, Container=None, Size=None, Width=None, Length=None, Height=None, Girth=None, Value=None, AmountToCollect=None, SpecialServices=None, Content=None, GroundOnly=None, SortBy=None, Machinable=None, ReturnLocations=None, ReturnServiceInfo=None, DropOffTime=None, ShipDate=None, ReturnDimensionalWeight=None, TrackingRetentionPeriod=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.ID = _cast(None, ID) - self.ID_nsprefix_ = None - self.Service = Service - self.Service_nsprefix_ = None - self.FirstClassMailType = FirstClassMailType - self.FirstClassMailType_nsprefix_ = None - self.ZipOrigination = ZipOrigination - self.ZipOrigination_nsprefix_ = None - self.ZipDestination = ZipDestination - self.ZipDestination_nsprefix_ = None - self.Pounds = Pounds - self.validate_PoundsType(self.Pounds) - self.Pounds_nsprefix_ = None - self.Ounces = Ounces - self.validate_OuncesType(self.Ounces) - self.Ounces_nsprefix_ = None - self.Container = Container - self.Container_nsprefix_ = None - self.Size = Size - self.Size_nsprefix_ = None - self.Width = Width - self.Width_nsprefix_ = None - self.Length = Length - self.Length_nsprefix_ = None - self.Height = Height - self.Height_nsprefix_ = None - self.Girth = Girth - self.Girth_nsprefix_ = None - self.Value = Value - self.Value_nsprefix_ = None - self.AmountToCollect = AmountToCollect - self.AmountToCollect_nsprefix_ = None - self.SpecialServices = SpecialServices - self.SpecialServices_nsprefix_ = None - self.Content = Content - self.Content_nsprefix_ = None - self.GroundOnly = GroundOnly - self.GroundOnly_nsprefix_ = None - self.SortBy = SortBy - self.SortBy_nsprefix_ = None - self.Machinable = Machinable - self.Machinable_nsprefix_ = None - self.ReturnLocations = ReturnLocations - self.ReturnLocations_nsprefix_ = None - self.ReturnServiceInfo = ReturnServiceInfo - self.ReturnServiceInfo_nsprefix_ = None - self.DropOffTime = DropOffTime - self.DropOffTime_nsprefix_ = None - self.ShipDate = ShipDate - self.ShipDate_nsprefix_ = None - self.ReturnDimensionalWeight = ReturnDimensionalWeight - self.ReturnDimensionalWeight_nsprefix_ = None - self.TrackingRetentionPeriod = TrackingRetentionPeriod - self.TrackingRetentionPeriod_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, PackageType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if PackageType.subclass: - return PackageType.subclass(*args_, **kwargs_) - else: - return PackageType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_Service(self): - return self.Service - def set_Service(self, Service): - self.Service = Service - def get_FirstClassMailType(self): - return self.FirstClassMailType - def set_FirstClassMailType(self, FirstClassMailType): - self.FirstClassMailType = FirstClassMailType - def get_ZipOrigination(self): - return self.ZipOrigination - def set_ZipOrigination(self, ZipOrigination): - self.ZipOrigination = ZipOrigination - def get_ZipDestination(self): - return self.ZipDestination - def set_ZipDestination(self, ZipDestination): - self.ZipDestination = ZipDestination - def get_Pounds(self): - return self.Pounds - def set_Pounds(self, Pounds): - self.Pounds = Pounds - def get_Ounces(self): - return self.Ounces - def set_Ounces(self, Ounces): - self.Ounces = Ounces - def get_Container(self): - return self.Container - def set_Container(self, Container): - self.Container = Container - def get_Size(self): - return self.Size - def set_Size(self, Size): - self.Size = Size - def get_Width(self): - return self.Width - def set_Width(self, Width): - self.Width = Width - def get_Length(self): - return self.Length - def set_Length(self, Length): - self.Length = Length - def get_Height(self): - return self.Height - def set_Height(self, Height): - self.Height = Height - def get_Girth(self): - return self.Girth - def set_Girth(self, Girth): - self.Girth = Girth - def get_Value(self): - return self.Value - def set_Value(self, Value): - self.Value = Value - def get_AmountToCollect(self): - return self.AmountToCollect - def set_AmountToCollect(self, AmountToCollect): - self.AmountToCollect = AmountToCollect - def get_SpecialServices(self): - return self.SpecialServices - def set_SpecialServices(self, SpecialServices): - self.SpecialServices = SpecialServices - def get_Content(self): - return self.Content - def set_Content(self, Content): - self.Content = Content - def get_GroundOnly(self): - return self.GroundOnly - def set_GroundOnly(self, GroundOnly): - self.GroundOnly = GroundOnly - def get_SortBy(self): - return self.SortBy - def set_SortBy(self, SortBy): - self.SortBy = SortBy - def get_Machinable(self): - return self.Machinable - def set_Machinable(self, Machinable): - self.Machinable = Machinable - def get_ReturnLocations(self): - return self.ReturnLocations - def set_ReturnLocations(self, ReturnLocations): - self.ReturnLocations = ReturnLocations - def get_ReturnServiceInfo(self): - return self.ReturnServiceInfo - def set_ReturnServiceInfo(self, ReturnServiceInfo): - self.ReturnServiceInfo = ReturnServiceInfo - def get_DropOffTime(self): - return self.DropOffTime - def set_DropOffTime(self, DropOffTime): - self.DropOffTime = DropOffTime - def get_ShipDate(self): - return self.ShipDate - def set_ShipDate(self, ShipDate): - self.ShipDate = ShipDate - def get_ReturnDimensionalWeight(self): - return self.ReturnDimensionalWeight - def set_ReturnDimensionalWeight(self, ReturnDimensionalWeight): - self.ReturnDimensionalWeight = ReturnDimensionalWeight - def get_TrackingRetentionPeriod(self): - return self.TrackingRetentionPeriod - def set_TrackingRetentionPeriod(self, TrackingRetentionPeriod): - self.TrackingRetentionPeriod = TrackingRetentionPeriod - def get_ID(self): - return self.ID - def set_ID(self, ID): - self.ID = ID - def validate_PoundsType(self, value): - result = True - # Validate type PoundsType, a restriction on xs:integer. - if value is not None and Validate_simpletypes_ and self.gds_collector_ is not None: - if not isinstance(value, int): - lineno = self.gds_get_node_lineno_() - self.gds_collector_.add_message('Value "%(value)s"%(lineno)s is not of the correct base simple type (int)' % {"value": value, "lineno": lineno, }) - return False - if value < 0: - lineno = self.gds_get_node_lineno_() - self.gds_collector_.add_message('Value "%(value)s"%(lineno)s does not match xsd minInclusive restriction on PoundsType' % {"value": value, "lineno": lineno} ) - result = False - if value > 70: - lineno = self.gds_get_node_lineno_() - self.gds_collector_.add_message('Value "%(value)s"%(lineno)s does not match xsd maxInclusive restriction on PoundsType' % {"value": value, "lineno": lineno} ) - result = False - return result - def validate_OuncesType(self, value): - result = True - # Validate type OuncesType, a restriction on xs:decimal. - if value is not None and Validate_simpletypes_ and self.gds_collector_ is not None: - if not isinstance(value, decimal_.Decimal): - lineno = self.gds_get_node_lineno_() - self.gds_collector_.add_message('Value "%(value)s"%(lineno)s is not of the correct base simple type (decimal_.Decimal)' % {"value": value, "lineno": lineno, }) - return False - if value < 0.0: - lineno = self.gds_get_node_lineno_() - self.gds_collector_.add_message('Value "%(value)s"%(lineno)s does not match xsd minInclusive restriction on OuncesType' % {"value": value, "lineno": lineno} ) - result = False - if value > 1120.0: - lineno = self.gds_get_node_lineno_() - self.gds_collector_.add_message('Value "%(value)s"%(lineno)s does not match xsd maxInclusive restriction on OuncesType' % {"value": value, "lineno": lineno} ) - result = False - return result - def _hasContent(self): - if ( - self.Service is not None or - self.FirstClassMailType is not None or - self.ZipOrigination is not None or - self.ZipDestination is not None or - self.Pounds is not None or - self.Ounces is not None or - self.Container is not None or - self.Size is not None or - self.Width is not None or - self.Length is not None or - self.Height is not None or - self.Girth is not None or - self.Value is not None or - self.AmountToCollect is not None or - self.SpecialServices is not None or - self.Content is not None or - self.GroundOnly is not None or - self.SortBy is not None or - self.Machinable is not None or - self.ReturnLocations is not None or - self.ReturnServiceInfo is not None or - self.DropOffTime is not None or - self.ShipDate is not None or - self.ReturnDimensionalWeight is not None or - self.TrackingRetentionPeriod is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='PackageType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('PackageType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'PackageType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='PackageType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='PackageType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='PackageType'): - if self.ID is not None and 'ID' not in already_processed: - already_processed.add('ID') - outfile.write(' ID=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.ID), input_name='ID')), )) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='PackageType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.Service is not None: - namespaceprefix_ = self.Service_nsprefix_ + ':' if (UseCapturedNS_ and self.Service_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sService>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Service), input_name='Service')), namespaceprefix_ , eol_)) - if self.FirstClassMailType is not None: - namespaceprefix_ = self.FirstClassMailType_nsprefix_ + ':' if (UseCapturedNS_ and self.FirstClassMailType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFirstClassMailType>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FirstClassMailType), input_name='FirstClassMailType')), namespaceprefix_ , eol_)) - if self.ZipOrigination is not None: - namespaceprefix_ = self.ZipOrigination_nsprefix_ + ':' if (UseCapturedNS_ and self.ZipOrigination_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sZipOrigination>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ZipOrigination), input_name='ZipOrigination')), namespaceprefix_ , eol_)) - if self.ZipDestination is not None: - namespaceprefix_ = self.ZipDestination_nsprefix_ + ':' if (UseCapturedNS_ and self.ZipDestination_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sZipDestination>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ZipDestination), input_name='ZipDestination')), namespaceprefix_ , eol_)) - if self.Pounds is not None: - namespaceprefix_ = self.Pounds_nsprefix_ + ':' if (UseCapturedNS_ and self.Pounds_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPounds>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.Pounds, input_name='Pounds'), namespaceprefix_ , eol_)) - if self.Ounces is not None: - namespaceprefix_ = self.Ounces_nsprefix_ + ':' if (UseCapturedNS_ and self.Ounces_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sOunces>%s%s' % (namespaceprefix_ , self.gds_format_decimal(self.Ounces, input_name='Ounces'), namespaceprefix_ , eol_)) - if self.Container is not None: - namespaceprefix_ = self.Container_nsprefix_ + ':' if (UseCapturedNS_ and self.Container_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sContainer>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Container), input_name='Container')), namespaceprefix_ , eol_)) - if self.Size is not None: - namespaceprefix_ = self.Size_nsprefix_ + ':' if (UseCapturedNS_ and self.Size_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSize>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Size), input_name='Size')), namespaceprefix_ , eol_)) - if self.Width is not None: - namespaceprefix_ = self.Width_nsprefix_ + ':' if (UseCapturedNS_ and self.Width_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sWidth>%s%s' % (namespaceprefix_ , self.gds_format_decimal(self.Width, input_name='Width'), namespaceprefix_ , eol_)) - if self.Length is not None: - namespaceprefix_ = self.Length_nsprefix_ + ':' if (UseCapturedNS_ and self.Length_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sLength>%s%s' % (namespaceprefix_ , self.gds_format_decimal(self.Length, input_name='Length'), namespaceprefix_ , eol_)) - if self.Height is not None: - namespaceprefix_ = self.Height_nsprefix_ + ':' if (UseCapturedNS_ and self.Height_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sHeight>%s%s' % (namespaceprefix_ , self.gds_format_decimal(self.Height, input_name='Height'), namespaceprefix_ , eol_)) - if self.Girth is not None: - namespaceprefix_ = self.Girth_nsprefix_ + ':' if (UseCapturedNS_ and self.Girth_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sGirth>%s%s' % (namespaceprefix_ , self.gds_format_decimal(self.Girth, input_name='Girth'), namespaceprefix_ , eol_)) - if self.Value is not None: - namespaceprefix_ = self.Value_nsprefix_ + ':' if (UseCapturedNS_ and self.Value_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sValue>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Value), input_name='Value')), namespaceprefix_ , eol_)) - if self.AmountToCollect is not None: - namespaceprefix_ = self.AmountToCollect_nsprefix_ + ':' if (UseCapturedNS_ and self.AmountToCollect_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAmountToCollect>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.AmountToCollect), input_name='AmountToCollect')), namespaceprefix_ , eol_)) - if self.SpecialServices is not None: - namespaceprefix_ = self.SpecialServices_nsprefix_ + ':' if (UseCapturedNS_ and self.SpecialServices_nsprefix_) else '' - self.SpecialServices.export(outfile, level, namespaceprefix_, namespacedef_='', name_='SpecialServices', pretty_print=pretty_print) - if self.Content is not None: - namespaceprefix_ = self.Content_nsprefix_ + ':' if (UseCapturedNS_ and self.Content_nsprefix_) else '' - self.Content.export(outfile, level, namespaceprefix_, namespacedef_='', name_='Content', pretty_print=pretty_print) - if self.GroundOnly is not None: - namespaceprefix_ = self.GroundOnly_nsprefix_ + ':' if (UseCapturedNS_ and self.GroundOnly_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sGroundOnly>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.GroundOnly, input_name='GroundOnly'), namespaceprefix_ , eol_)) - if self.SortBy is not None: - namespaceprefix_ = self.SortBy_nsprefix_ + ':' if (UseCapturedNS_ and self.SortBy_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSortBy>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SortBy), input_name='SortBy')), namespaceprefix_ , eol_)) - if self.Machinable is not None: - namespaceprefix_ = self.Machinable_nsprefix_ + ':' if (UseCapturedNS_ and self.Machinable_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sMachinable>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.Machinable, input_name='Machinable'), namespaceprefix_ , eol_)) - if self.ReturnLocations is not None: - namespaceprefix_ = self.ReturnLocations_nsprefix_ + ':' if (UseCapturedNS_ and self.ReturnLocations_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sReturnLocations>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.ReturnLocations, input_name='ReturnLocations'), namespaceprefix_ , eol_)) - if self.ReturnServiceInfo is not None: - namespaceprefix_ = self.ReturnServiceInfo_nsprefix_ + ':' if (UseCapturedNS_ and self.ReturnServiceInfo_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sReturnServiceInfo>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.ReturnServiceInfo, input_name='ReturnServiceInfo'), namespaceprefix_ , eol_)) - if self.DropOffTime is not None: - namespaceprefix_ = self.DropOffTime_nsprefix_ + ':' if (UseCapturedNS_ and self.DropOffTime_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDropOffTime>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.DropOffTime), input_name='DropOffTime')), namespaceprefix_ , eol_)) - if self.ShipDate is not None: - namespaceprefix_ = self.ShipDate_nsprefix_ + ':' if (UseCapturedNS_ and self.ShipDate_nsprefix_) else '' - self.ShipDate.export(outfile, level, namespaceprefix_, namespacedef_='', name_='ShipDate', pretty_print=pretty_print) - if self.ReturnDimensionalWeight is not None: - namespaceprefix_ = self.ReturnDimensionalWeight_nsprefix_ + ':' if (UseCapturedNS_ and self.ReturnDimensionalWeight_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sReturnDimensionalWeight>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ReturnDimensionalWeight), input_name='ReturnDimensionalWeight')), namespaceprefix_ , eol_)) - if self.TrackingRetentionPeriod is not None: - namespaceprefix_ = self.TrackingRetentionPeriod_nsprefix_ + ':' if (UseCapturedNS_ and self.TrackingRetentionPeriod_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sTrackingRetentionPeriod>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.TrackingRetentionPeriod), input_name='TrackingRetentionPeriod')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('ID', node) - if value is not None and 'ID' not in already_processed: - already_processed.add('ID') - self.ID = value - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'Service': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Service') - value_ = self.gds_validate_string(value_, node, 'Service') - self.Service = value_ - self.Service_nsprefix_ = child_.prefix - elif nodeName_ == 'FirstClassMailType': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FirstClassMailType') - value_ = self.gds_validate_string(value_, node, 'FirstClassMailType') - self.FirstClassMailType = value_ - self.FirstClassMailType_nsprefix_ = child_.prefix - elif nodeName_ == 'ZipOrigination': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ZipOrigination') - value_ = self.gds_validate_string(value_, node, 'ZipOrigination') - self.ZipOrigination = value_ - self.ZipOrigination_nsprefix_ = child_.prefix - elif nodeName_ == 'ZipDestination': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ZipDestination') - value_ = self.gds_validate_string(value_, node, 'ZipDestination') - self.ZipDestination = value_ - self.ZipDestination_nsprefix_ = child_.prefix - elif nodeName_ == 'Pounds' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'Pounds') - ival_ = self.gds_validate_integer(ival_, node, 'Pounds') - self.Pounds = ival_ - self.Pounds_nsprefix_ = child_.prefix - # validate type PoundsType - self.validate_PoundsType(self.Pounds) - elif nodeName_ == 'Ounces' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_decimal(sval_, node, 'Ounces') - fval_ = self.gds_validate_decimal(fval_, node, 'Ounces') - self.Ounces = fval_ - self.Ounces_nsprefix_ = child_.prefix - # validate type OuncesType - self.validate_OuncesType(self.Ounces) - elif nodeName_ == 'Container': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Container') - value_ = self.gds_validate_string(value_, node, 'Container') - self.Container = value_ - self.Container_nsprefix_ = child_.prefix - elif nodeName_ == 'Size': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Size') - value_ = self.gds_validate_string(value_, node, 'Size') - self.Size = value_ - self.Size_nsprefix_ = child_.prefix - elif nodeName_ == 'Width' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_decimal(sval_, node, 'Width') - fval_ = self.gds_validate_decimal(fval_, node, 'Width') - self.Width = fval_ - self.Width_nsprefix_ = child_.prefix - elif nodeName_ == 'Length' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_decimal(sval_, node, 'Length') - fval_ = self.gds_validate_decimal(fval_, node, 'Length') - self.Length = fval_ - self.Length_nsprefix_ = child_.prefix - elif nodeName_ == 'Height' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_decimal(sval_, node, 'Height') - fval_ = self.gds_validate_decimal(fval_, node, 'Height') - self.Height = fval_ - self.Height_nsprefix_ = child_.prefix - elif nodeName_ == 'Girth' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_decimal(sval_, node, 'Girth') - fval_ = self.gds_validate_decimal(fval_, node, 'Girth') - self.Girth = fval_ - self.Girth_nsprefix_ = child_.prefix - elif nodeName_ == 'Value': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Value') - value_ = self.gds_validate_string(value_, node, 'Value') - self.Value = value_ - self.Value_nsprefix_ = child_.prefix - elif nodeName_ == 'AmountToCollect': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'AmountToCollect') - value_ = self.gds_validate_string(value_, node, 'AmountToCollect') - self.AmountToCollect = value_ - self.AmountToCollect_nsprefix_ = child_.prefix - elif nodeName_ == 'SpecialServices': - obj_ = SpecialServicesType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.SpecialServices = obj_ - obj_.original_tagname_ = 'SpecialServices' - elif nodeName_ == 'Content': - obj_ = ContentType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.Content = obj_ - obj_.original_tagname_ = 'Content' - elif nodeName_ == 'GroundOnly': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'GroundOnly') - ival_ = self.gds_validate_boolean(ival_, node, 'GroundOnly') - self.GroundOnly = ival_ - self.GroundOnly_nsprefix_ = child_.prefix - elif nodeName_ == 'SortBy': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SortBy') - value_ = self.gds_validate_string(value_, node, 'SortBy') - self.SortBy = value_ - self.SortBy_nsprefix_ = child_.prefix - elif nodeName_ == 'Machinable': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'Machinable') - ival_ = self.gds_validate_boolean(ival_, node, 'Machinable') - self.Machinable = ival_ - self.Machinable_nsprefix_ = child_.prefix - elif nodeName_ == 'ReturnLocations': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'ReturnLocations') - ival_ = self.gds_validate_boolean(ival_, node, 'ReturnLocations') - self.ReturnLocations = ival_ - self.ReturnLocations_nsprefix_ = child_.prefix - elif nodeName_ == 'ReturnServiceInfo': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'ReturnServiceInfo') - ival_ = self.gds_validate_boolean(ival_, node, 'ReturnServiceInfo') - self.ReturnServiceInfo = ival_ - self.ReturnServiceInfo_nsprefix_ = child_.prefix - elif nodeName_ == 'DropOffTime': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'DropOffTime') - value_ = self.gds_validate_string(value_, node, 'DropOffTime') - self.DropOffTime = value_ - self.DropOffTime_nsprefix_ = child_.prefix - elif nodeName_ == 'ShipDate': - obj_ = ShipDateType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.ShipDate = obj_ - obj_.original_tagname_ = 'ShipDate' - elif nodeName_ == 'ReturnDimensionalWeight': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ReturnDimensionalWeight') - value_ = self.gds_validate_string(value_, node, 'ReturnDimensionalWeight') - self.ReturnDimensionalWeight = value_ - self.ReturnDimensionalWeight_nsprefix_ = child_.prefix - elif nodeName_ == 'TrackingRetentionPeriod': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'TrackingRetentionPeriod') - value_ = self.gds_validate_string(value_, node, 'TrackingRetentionPeriod') - self.TrackingRetentionPeriod = value_ - self.TrackingRetentionPeriod_nsprefix_ = child_.prefix -# end class PackageType - - -class SpecialServicesType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, SpecialService=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - if SpecialService is None: - self.SpecialService = [] - else: - self.SpecialService = SpecialService - self.SpecialService_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, SpecialServicesType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if SpecialServicesType.subclass: - return SpecialServicesType.subclass(*args_, **kwargs_) - else: - return SpecialServicesType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_SpecialService(self): - return self.SpecialService - def set_SpecialService(self, SpecialService): - self.SpecialService = SpecialService - def add_SpecialService(self, value): - self.SpecialService.append(value) - def insert_SpecialService_at(self, index, value): - self.SpecialService.insert(index, value) - def replace_SpecialService_at(self, index, value): - self.SpecialService[index] = value - def _hasContent(self): - if ( - self.SpecialService - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='SpecialServicesType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('SpecialServicesType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'SpecialServicesType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='SpecialServicesType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='SpecialServicesType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='SpecialServicesType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='SpecialServicesType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - for SpecialService_ in self.SpecialService: - namespaceprefix_ = self.SpecialService_nsprefix_ + ':' if (UseCapturedNS_ and self.SpecialService_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSpecialService>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(SpecialService_), input_name='SpecialService')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'SpecialService': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SpecialService') - value_ = self.gds_validate_string(value_, node, 'SpecialService') - self.SpecialService.append(value_) - self.SpecialService_nsprefix_ = child_.prefix -# end class SpecialServicesType - - -class ContentType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ContentType_member=None, ContentDescription=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.ContentType = ContentType_member - self.ContentType_nsprefix_ = None - self.ContentDescription = ContentDescription - self.ContentDescription_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, ContentType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if ContentType.subclass: - return ContentType.subclass(*args_, **kwargs_) - else: - return ContentType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_ContentType(self): - return self.ContentType - def set_ContentType(self, ContentType): - self.ContentType = ContentType - def get_ContentDescription(self): - return self.ContentDescription - def set_ContentDescription(self, ContentDescription): - self.ContentDescription = ContentDescription - def _hasContent(self): - if ( - self.ContentType is not None or - self.ContentDescription is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ContentType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('ContentType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'ContentType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='ContentType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='ContentType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='ContentType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ContentType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.ContentType is not None: - namespaceprefix_ = self.ContentType_nsprefix_ + ':' if (UseCapturedNS_ and self.ContentType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sContentType>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ContentType), input_name='ContentType')), namespaceprefix_ , eol_)) - if self.ContentDescription is not None: - namespaceprefix_ = self.ContentDescription_nsprefix_ + ':' if (UseCapturedNS_ and self.ContentDescription_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sContentDescription>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ContentDescription), input_name='ContentDescription')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'ContentType': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ContentType') - value_ = self.gds_validate_string(value_, node, 'ContentType') - self.ContentType = value_ - self.ContentType_nsprefix_ = child_.prefix - elif nodeName_ == 'ContentDescription': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ContentDescription') - value_ = self.gds_validate_string(value_, node, 'ContentDescription') - self.ContentDescription = value_ - self.ContentDescription_nsprefix_ = child_.prefix -# end class ContentType - - -class ShipDateType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, Option=None, valueOf_=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.Option = _cast(None, Option) - self.Option_nsprefix_ = None - self.valueOf_ = valueOf_ - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, ShipDateType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if ShipDateType.subclass: - return ShipDateType.subclass(*args_, **kwargs_) - else: - return ShipDateType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_Option(self): - return self.Option - def set_Option(self, Option): - self.Option = Option - def get_valueOf_(self): return self.valueOf_ - def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_ - def _hasContent(self): - if ( - (1 if type(self.valueOf_) in [int,float] else self.valueOf_) - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ShipDateType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('ShipDateType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'ShipDateType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='ShipDateType') - if self._hasContent(): - outfile.write('>') - outfile.write(self.convert_unicode(self.valueOf_)) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='ShipDateType', pretty_print=pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='ShipDateType'): - if self.Option is not None and 'Option' not in already_processed: - already_processed.add('Option') - outfile.write(' Option=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.Option), input_name='Option')), )) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ShipDateType', fromsubclass_=False, pretty_print=True): - pass - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - self.valueOf_ = get_all_text_(node) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('Option', node) - if value is not None and 'Option' not in already_processed: - already_processed.add('Option') - self.Option = value - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - pass -# end class ShipDateType - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'RateV4Request' - rootClass = RateV4Request - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'RateV4Request' - rootClass = RateV4Request - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'RateV4Request' - rootClass = RateV4Request - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'RateV4Request' - rootClass = RateV4Request - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from rate_v4_request import *\n\n') - sys.stdout.write('import rate_v4_request as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "ContentType", - "PackageType", - "RateV4Request", - "ShipDateType", - "SpecialServicesType" -] diff --git a/schemas/usps/karrio/schemas/usps/rate_v4_response.py b/schemas/usps/karrio/schemas/usps/rate_v4_response.py deleted file mode 100644 index 8694d13c65..0000000000 --- a/schemas/usps/karrio/schemas/usps/rate_v4_response.py +++ /dev/null @@ -1,2720 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:11 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/rate_v4_response.py') -# -# Command line arguments: -# ./schemas/RateV4Response.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/rate_v4_response.py" ./schemas/RateV4Response.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class RateV4Response(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, Package=None, valueOf_=None, mixedclass_=None, content_=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - if Package is None: - self.Package = [] - else: - self.Package = Package - self.Package_nsprefix_ = None - self.valueOf_ = valueOf_ - if mixedclass_ is None: - self.mixedclass_ = MixedContainer - else: - self.mixedclass_ = mixedclass_ - if content_ is None: - self.content_ = [] - else: - self.content_ = content_ - self.valueOf_ = valueOf_ - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, RateV4Response) - if subclass is not None: - return subclass(*args_, **kwargs_) - if RateV4Response.subclass: - return RateV4Response.subclass(*args_, **kwargs_) - else: - return RateV4Response(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_Package(self): - return self.Package - def set_Package(self, Package): - self.Package = Package - def add_Package(self, value): - self.Package.append(value) - def insert_Package_at(self, index, value): - self.Package.insert(index, value) - def replace_Package_at(self, index, value): - self.Package[index] = value - def get_valueOf_(self): return self.valueOf_ - def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_ - def _hasContent(self): - if ( - self.Package or - (1 if type(self.valueOf_) in [int,float] else self.valueOf_) or - self.content_ - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='RateV4Response', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('RateV4Response') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'RateV4Response': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='RateV4Response') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='RateV4Response', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='RateV4Response'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='RateV4Response', fromsubclass_=False, pretty_print=True): - if not fromsubclass_: - for item_ in self.content_: - item_.export(outfile, level, item_.name, namespaceprefix_, pretty_print=pretty_print) - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - for Package_ in self.Package: - namespaceprefix_ = self.Package_nsprefix_ + ':' if (UseCapturedNS_ and self.Package_nsprefix_) else '' - Package_.export(outfile, level, namespaceprefix_, namespacedef_='', name_='Package', pretty_print=pretty_print) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - self.valueOf_ = get_all_text_(node) - if node.text is not None: - obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', node.text) - self.content_.append(obj_) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'Package': - obj_ = PackageType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'Package', obj_) - self.content_.append(obj_) - if hasattr(self, 'add_Package'): - self.add_Package(obj_.value) - elif hasattr(self, 'set_Package'): - self.set_Package(obj_.value) - if not fromsubclass_ and child_.tail is not None: - obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.tail) - self.content_.append(obj_) -# end class RateV4Response - - -class PackageType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ID=None, Error=None, ZipOrigination=None, ZipDestination=None, Pounds=None, Ounces=None, FirstClassMailType=None, Container=None, Size=None, Width=None, Length=None, Height=None, Girth=None, Machinable=None, Zone=None, Postage=None, Restriction=None, valueOf_=None, mixedclass_=None, content_=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.ID = _cast(None, ID) - self.ID_nsprefix_ = None - self.Error = Error - self.Error_nsprefix_ = None - self.ZipOrigination = ZipOrigination - self.ZipOrigination_nsprefix_ = None - self.ZipDestination = ZipDestination - self.ZipDestination_nsprefix_ = None - self.Pounds = Pounds - self.Pounds_nsprefix_ = None - self.Ounces = Ounces - self.Ounces_nsprefix_ = None - self.FirstClassMailType = FirstClassMailType - self.FirstClassMailType_nsprefix_ = None - self.Container = Container - self.Container_nsprefix_ = None - self.Size = Size - self.Size_nsprefix_ = None - self.Width = Width - self.Width_nsprefix_ = None - self.Length = Length - self.Length_nsprefix_ = None - self.Height = Height - self.Height_nsprefix_ = None - self.Girth = Girth - self.Girth_nsprefix_ = None - self.Machinable = Machinable - self.Machinable_nsprefix_ = None - self.Zone = Zone - self.Zone_nsprefix_ = None - if Postage is None: - self.Postage = [] - else: - self.Postage = Postage - self.Postage_nsprefix_ = None - self.Restriction = Restriction - self.Restriction_nsprefix_ = None - self.valueOf_ = valueOf_ - if mixedclass_ is None: - self.mixedclass_ = MixedContainer - else: - self.mixedclass_ = mixedclass_ - if content_ is None: - self.content_ = [] - else: - self.content_ = content_ - self.valueOf_ = valueOf_ - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, PackageType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if PackageType.subclass: - return PackageType.subclass(*args_, **kwargs_) - else: - return PackageType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_Error(self): - return self.Error - def set_Error(self, Error): - self.Error = Error - def get_ZipOrigination(self): - return self.ZipOrigination - def set_ZipOrigination(self, ZipOrigination): - self.ZipOrigination = ZipOrigination - def get_ZipDestination(self): - return self.ZipDestination - def set_ZipDestination(self, ZipDestination): - self.ZipDestination = ZipDestination - def get_Pounds(self): - return self.Pounds - def set_Pounds(self, Pounds): - self.Pounds = Pounds - def get_Ounces(self): - return self.Ounces - def set_Ounces(self, Ounces): - self.Ounces = Ounces - def get_FirstClassMailType(self): - return self.FirstClassMailType - def set_FirstClassMailType(self, FirstClassMailType): - self.FirstClassMailType = FirstClassMailType - def get_Container(self): - return self.Container - def set_Container(self, Container): - self.Container = Container - def get_Size(self): - return self.Size - def set_Size(self, Size): - self.Size = Size - def get_Width(self): - return self.Width - def set_Width(self, Width): - self.Width = Width - def get_Length(self): - return self.Length - def set_Length(self, Length): - self.Length = Length - def get_Height(self): - return self.Height - def set_Height(self, Height): - self.Height = Height - def get_Girth(self): - return self.Girth - def set_Girth(self, Girth): - self.Girth = Girth - def get_Machinable(self): - return self.Machinable - def set_Machinable(self, Machinable): - self.Machinable = Machinable - def get_Zone(self): - return self.Zone - def set_Zone(self, Zone): - self.Zone = Zone - def get_Postage(self): - return self.Postage - def set_Postage(self, Postage): - self.Postage = Postage - def add_Postage(self, value): - self.Postage.append(value) - def insert_Postage_at(self, index, value): - self.Postage.insert(index, value) - def replace_Postage_at(self, index, value): - self.Postage[index] = value - def get_Restriction(self): - return self.Restriction - def set_Restriction(self, Restriction): - self.Restriction = Restriction - def get_ID(self): - return self.ID - def set_ID(self, ID): - self.ID = ID - def get_valueOf_(self): return self.valueOf_ - def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_ - def _hasContent(self): - if ( - self.Error is not None or - self.ZipOrigination is not None or - self.ZipDestination is not None or - self.Pounds is not None or - self.Ounces is not None or - self.FirstClassMailType is not None or - self.Container is not None or - self.Size is not None or - self.Width is not None or - self.Length is not None or - self.Height is not None or - self.Girth is not None or - self.Machinable is not None or - self.Zone is not None or - self.Postage or - self.Restriction is not None or - (1 if type(self.valueOf_) in [int,float] else self.valueOf_) or - self.content_ - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='PackageType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('PackageType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'PackageType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='PackageType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='PackageType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='PackageType'): - if self.ID is not None and 'ID' not in already_processed: - already_processed.add('ID') - outfile.write(' ID=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.ID), input_name='ID')), )) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='PackageType', fromsubclass_=False, pretty_print=True): - if not fromsubclass_: - for item_ in self.content_: - item_.export(outfile, level, item_.name, namespaceprefix_, pretty_print=pretty_print) - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.Error is not None: - namespaceprefix_ = self.Error_nsprefix_ + ':' if (UseCapturedNS_ and self.Error_nsprefix_) else '' - self.Error.export(outfile, level, namespaceprefix_, namespacedef_='', name_='Error', pretty_print=pretty_print) - if self.ZipOrigination is not None: - namespaceprefix_ = self.ZipOrigination_nsprefix_ + ':' if (UseCapturedNS_ and self.ZipOrigination_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sZipOrigination>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ZipOrigination), input_name='ZipOrigination')), namespaceprefix_ , eol_)) - if self.ZipDestination is not None: - namespaceprefix_ = self.ZipDestination_nsprefix_ + ':' if (UseCapturedNS_ and self.ZipDestination_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sZipDestination>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ZipDestination), input_name='ZipDestination')), namespaceprefix_ , eol_)) - if self.Pounds is not None: - namespaceprefix_ = self.Pounds_nsprefix_ + ':' if (UseCapturedNS_ and self.Pounds_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPounds>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.Pounds, input_name='Pounds'), namespaceprefix_ , eol_)) - if self.Ounces is not None: - namespaceprefix_ = self.Ounces_nsprefix_ + ':' if (UseCapturedNS_ and self.Ounces_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sOunces>%s%s' % (namespaceprefix_ , self.gds_format_decimal(self.Ounces, input_name='Ounces'), namespaceprefix_ , eol_)) - if self.FirstClassMailType is not None: - namespaceprefix_ = self.FirstClassMailType_nsprefix_ + ':' if (UseCapturedNS_ and self.FirstClassMailType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFirstClassMailType>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FirstClassMailType), input_name='FirstClassMailType')), namespaceprefix_ , eol_)) - if self.Container is not None: - namespaceprefix_ = self.Container_nsprefix_ + ':' if (UseCapturedNS_ and self.Container_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sContainer>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Container), input_name='Container')), namespaceprefix_ , eol_)) - if self.Size is not None: - namespaceprefix_ = self.Size_nsprefix_ + ':' if (UseCapturedNS_ and self.Size_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSize>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Size), input_name='Size')), namespaceprefix_ , eol_)) - if self.Width is not None: - namespaceprefix_ = self.Width_nsprefix_ + ':' if (UseCapturedNS_ and self.Width_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sWidth>%s%s' % (namespaceprefix_ , self.gds_format_decimal(self.Width, input_name='Width'), namespaceprefix_ , eol_)) - if self.Length is not None: - namespaceprefix_ = self.Length_nsprefix_ + ':' if (UseCapturedNS_ and self.Length_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sLength>%s%s' % (namespaceprefix_ , self.gds_format_decimal(self.Length, input_name='Length'), namespaceprefix_ , eol_)) - if self.Height is not None: - namespaceprefix_ = self.Height_nsprefix_ + ':' if (UseCapturedNS_ and self.Height_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sHeight>%s%s' % (namespaceprefix_ , self.gds_format_decimal(self.Height, input_name='Height'), namespaceprefix_ , eol_)) - if self.Girth is not None: - namespaceprefix_ = self.Girth_nsprefix_ + ':' if (UseCapturedNS_ and self.Girth_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sGirth>%s%s' % (namespaceprefix_ , self.gds_format_decimal(self.Girth, input_name='Girth'), namespaceprefix_ , eol_)) - if self.Machinable is not None: - namespaceprefix_ = self.Machinable_nsprefix_ + ':' if (UseCapturedNS_ and self.Machinable_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sMachinable>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Machinable), input_name='Machinable')), namespaceprefix_ , eol_)) - if self.Zone is not None: - namespaceprefix_ = self.Zone_nsprefix_ + ':' if (UseCapturedNS_ and self.Zone_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sZone>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.Zone, input_name='Zone'), namespaceprefix_ , eol_)) - for Postage_ in self.Postage: - namespaceprefix_ = self.Postage_nsprefix_ + ':' if (UseCapturedNS_ and self.Postage_nsprefix_) else '' - Postage_.export(outfile, level, namespaceprefix_, namespacedef_='', name_='Postage', pretty_print=pretty_print) - if self.Restriction is not None: - namespaceprefix_ = self.Restriction_nsprefix_ + ':' if (UseCapturedNS_ and self.Restriction_nsprefix_) else '' - self.Restriction.export(outfile, level, namespaceprefix_, namespacedef_='', name_='Restriction', pretty_print=pretty_print) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - self.valueOf_ = get_all_text_(node) - if node.text is not None: - obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', node.text) - self.content_.append(obj_) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('ID', node) - if value is not None and 'ID' not in already_processed: - already_processed.add('ID') - self.ID = value - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'Error': - obj_ = ErrorType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'Error', obj_) - self.content_.append(obj_) - if hasattr(self, 'add_Error'): - self.add_Error(obj_.value) - elif hasattr(self, 'set_Error'): - self.set_Error(obj_.value) - elif nodeName_ == 'ZipOrigination' and child_.text is not None: - valuestr_ = child_.text - valuestr_ = self.gds_parse_string(valuestr_, node, 'ZipOrigination') - valuestr_ = self.gds_validate_string(valuestr_, node, 'ZipOrigination') - obj_ = self.mixedclass_(MixedContainer.CategorySimple, - MixedContainer.TypeString, 'ZipOrigination', valuestr_) - self.content_.append(obj_) - self.ZipOrigination_nsprefix_ = child_.prefix - elif nodeName_ == 'ZipDestination' and child_.text is not None: - valuestr_ = child_.text - valuestr_ = self.gds_parse_string(valuestr_, node, 'ZipDestination') - valuestr_ = self.gds_validate_string(valuestr_, node, 'ZipDestination') - obj_ = self.mixedclass_(MixedContainer.CategorySimple, - MixedContainer.TypeString, 'ZipDestination', valuestr_) - self.content_.append(obj_) - self.ZipDestination_nsprefix_ = child_.prefix - elif nodeName_ == 'Pounds' and child_.text is not None: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'Pounds') - ival_ = self.gds_validate_integer(ival_, node, 'Pounds') - obj_ = self.mixedclass_(MixedContainer.CategorySimple, - MixedContainer.TypeInteger, 'Pounds', ival_) - self.content_.append(obj_) - self.Pounds_nsprefix_ = child_.prefix - elif nodeName_ == 'Ounces' and child_.text is not None: - sval_ = child_.text - fval_ = self.gds_parse_decimal(sval_, node, 'Ounces') - fval_ = self.gds_validate_decimal(fval_, node, 'Ounces') - obj_ = self.mixedclass_(MixedContainer.CategorySimple, - MixedContainer.TypeFloat, 'Ounces', fval_) - self.content_.append(obj_) - self.Ounces_nsprefix_ = child_.prefix - elif nodeName_ == 'FirstClassMailType' and child_.text is not None: - valuestr_ = child_.text - valuestr_ = self.gds_parse_string(valuestr_, node, 'FirstClassMailType') - valuestr_ = self.gds_validate_string(valuestr_, node, 'FirstClassMailType') - obj_ = self.mixedclass_(MixedContainer.CategorySimple, - MixedContainer.TypeString, 'FirstClassMailType', valuestr_) - self.content_.append(obj_) - self.FirstClassMailType_nsprefix_ = child_.prefix - elif nodeName_ == 'Container' and child_.text is not None: - valuestr_ = child_.text - valuestr_ = self.gds_parse_string(valuestr_, node, 'Container') - valuestr_ = self.gds_validate_string(valuestr_, node, 'Container') - obj_ = self.mixedclass_(MixedContainer.CategorySimple, - MixedContainer.TypeString, 'Container', valuestr_) - self.content_.append(obj_) - self.Container_nsprefix_ = child_.prefix - elif nodeName_ == 'Size' and child_.text is not None: - valuestr_ = child_.text - valuestr_ = self.gds_parse_string(valuestr_, node, 'Size') - valuestr_ = self.gds_validate_string(valuestr_, node, 'Size') - obj_ = self.mixedclass_(MixedContainer.CategorySimple, - MixedContainer.TypeString, 'Size', valuestr_) - self.content_.append(obj_) - self.Size_nsprefix_ = child_.prefix - elif nodeName_ == 'Width' and child_.text is not None: - sval_ = child_.text - fval_ = self.gds_parse_decimal(sval_, node, 'Width') - fval_ = self.gds_validate_decimal(fval_, node, 'Width') - obj_ = self.mixedclass_(MixedContainer.CategorySimple, - MixedContainer.TypeFloat, 'Width', fval_) - self.content_.append(obj_) - self.Width_nsprefix_ = child_.prefix - elif nodeName_ == 'Length' and child_.text is not None: - sval_ = child_.text - fval_ = self.gds_parse_decimal(sval_, node, 'Length') - fval_ = self.gds_validate_decimal(fval_, node, 'Length') - obj_ = self.mixedclass_(MixedContainer.CategorySimple, - MixedContainer.TypeFloat, 'Length', fval_) - self.content_.append(obj_) - self.Length_nsprefix_ = child_.prefix - elif nodeName_ == 'Height' and child_.text is not None: - sval_ = child_.text - fval_ = self.gds_parse_decimal(sval_, node, 'Height') - fval_ = self.gds_validate_decimal(fval_, node, 'Height') - obj_ = self.mixedclass_(MixedContainer.CategorySimple, - MixedContainer.TypeFloat, 'Height', fval_) - self.content_.append(obj_) - self.Height_nsprefix_ = child_.prefix - elif nodeName_ == 'Girth' and child_.text is not None: - sval_ = child_.text - fval_ = self.gds_parse_decimal(sval_, node, 'Girth') - fval_ = self.gds_validate_decimal(fval_, node, 'Girth') - obj_ = self.mixedclass_(MixedContainer.CategorySimple, - MixedContainer.TypeFloat, 'Girth', fval_) - self.content_.append(obj_) - self.Girth_nsprefix_ = child_.prefix - elif nodeName_ == 'Machinable' and child_.text is not None: - valuestr_ = child_.text - valuestr_ = self.gds_parse_string(valuestr_, node, 'Machinable') - valuestr_ = self.gds_validate_string(valuestr_, node, 'Machinable') - obj_ = self.mixedclass_(MixedContainer.CategorySimple, - MixedContainer.TypeString, 'Machinable', valuestr_) - self.content_.append(obj_) - self.Machinable_nsprefix_ = child_.prefix - elif nodeName_ == 'Zone' and child_.text is not None: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'Zone') - ival_ = self.gds_validate_integer(ival_, node, 'Zone') - obj_ = self.mixedclass_(MixedContainer.CategorySimple, - MixedContainer.TypeInteger, 'Zone', ival_) - self.content_.append(obj_) - self.Zone_nsprefix_ = child_.prefix - elif nodeName_ == 'Postage': - obj_ = PostageType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'Postage', obj_) - self.content_.append(obj_) - if hasattr(self, 'add_Postage'): - self.add_Postage(obj_.value) - elif hasattr(self, 'set_Postage'): - self.set_Postage(obj_.value) - elif nodeName_ == 'Restriction': - obj_ = RestrictionType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'Restriction', obj_) - self.content_.append(obj_) - if hasattr(self, 'add_Restriction'): - self.add_Restriction(obj_.value) - elif hasattr(self, 'set_Restriction'): - self.set_Restriction(obj_.value) - if not fromsubclass_ and child_.tail is not None: - obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.tail) - self.content_.append(obj_) -# end class PackageType - - -class ErrorType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, Number=None, Source=None, Description=None, HelpFile=None, HelpContext=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.Number = Number - self.Number_nsprefix_ = None - self.Source = Source - self.Source_nsprefix_ = None - self.Description = Description - self.Description_nsprefix_ = None - self.HelpFile = HelpFile - self.HelpFile_nsprefix_ = None - self.HelpContext = HelpContext - self.HelpContext_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, ErrorType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if ErrorType.subclass: - return ErrorType.subclass(*args_, **kwargs_) - else: - return ErrorType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_Number(self): - return self.Number - def set_Number(self, Number): - self.Number = Number - def get_Source(self): - return self.Source - def set_Source(self, Source): - self.Source = Source - def get_Description(self): - return self.Description - def set_Description(self, Description): - self.Description = Description - def get_HelpFile(self): - return self.HelpFile - def set_HelpFile(self, HelpFile): - self.HelpFile = HelpFile - def get_HelpContext(self): - return self.HelpContext - def set_HelpContext(self, HelpContext): - self.HelpContext = HelpContext - def _hasContent(self): - if ( - self.Number is not None or - self.Source is not None or - self.Description is not None or - self.HelpFile is not None or - self.HelpContext is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ErrorType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('ErrorType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'ErrorType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='ErrorType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='ErrorType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='ErrorType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ErrorType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.Number is not None: - namespaceprefix_ = self.Number_nsprefix_ + ':' if (UseCapturedNS_ and self.Number_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sNumber>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.Number, input_name='Number'), namespaceprefix_ , eol_)) - if self.Source is not None: - namespaceprefix_ = self.Source_nsprefix_ + ':' if (UseCapturedNS_ and self.Source_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSource>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Source), input_name='Source')), namespaceprefix_ , eol_)) - if self.Description is not None: - namespaceprefix_ = self.Description_nsprefix_ + ':' if (UseCapturedNS_ and self.Description_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDescription>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Description), input_name='Description')), namespaceprefix_ , eol_)) - if self.HelpFile is not None: - namespaceprefix_ = self.HelpFile_nsprefix_ + ':' if (UseCapturedNS_ and self.HelpFile_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sHelpFile>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.HelpFile), input_name='HelpFile')), namespaceprefix_ , eol_)) - if self.HelpContext is not None: - namespaceprefix_ = self.HelpContext_nsprefix_ + ':' if (UseCapturedNS_ and self.HelpContext_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sHelpContext>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.HelpContext, input_name='HelpContext'), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'Number' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'Number') - ival_ = self.gds_validate_integer(ival_, node, 'Number') - self.Number = ival_ - self.Number_nsprefix_ = child_.prefix - elif nodeName_ == 'Source': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Source') - value_ = self.gds_validate_string(value_, node, 'Source') - self.Source = value_ - self.Source_nsprefix_ = child_.prefix - elif nodeName_ == 'Description': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Description') - value_ = self.gds_validate_string(value_, node, 'Description') - self.Description = value_ - self.Description_nsprefix_ = child_.prefix - elif nodeName_ == 'HelpFile': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'HelpFile') - value_ = self.gds_validate_string(value_, node, 'HelpFile') - self.HelpFile = value_ - self.HelpFile_nsprefix_ = child_.prefix - elif nodeName_ == 'HelpContext' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'HelpContext') - ival_ = self.gds_validate_integer(ival_, node, 'HelpContext') - self.HelpContext = ival_ - self.HelpContext_nsprefix_ = child_.prefix -# end class ErrorType - - -class PostageType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, CLASSID=None, MailService=None, Rate=None, CommercialRate=None, CommercialPlusRate=None, CommitmentDate=None, CommitmentName=None, MaxDimensions=None, ServiceInformation=None, SpecialServices=None, Zone=None, valueOf_=None, mixedclass_=None, content_=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.CLASSID = _cast(int, CLASSID) - self.CLASSID_nsprefix_ = None - self.MailService = MailService - self.MailService_nsprefix_ = None - self.Rate = Rate - self.Rate_nsprefix_ = None - self.CommercialRate = CommercialRate - self.CommercialRate_nsprefix_ = None - self.CommercialPlusRate = CommercialPlusRate - self.CommercialPlusRate_nsprefix_ = None - self.CommitmentDate = CommitmentDate - self.CommitmentDate_nsprefix_ = None - self.CommitmentName = CommitmentName - self.CommitmentName_nsprefix_ = None - self.MaxDimensions = MaxDimensions - self.MaxDimensions_nsprefix_ = None - self.ServiceInformation = ServiceInformation - self.ServiceInformation_nsprefix_ = None - self.SpecialServices = SpecialServices - self.SpecialServices_nsprefix_ = None - self.Zone = Zone - self.Zone_nsprefix_ = None - self.valueOf_ = valueOf_ - if mixedclass_ is None: - self.mixedclass_ = MixedContainer - else: - self.mixedclass_ = mixedclass_ - if content_ is None: - self.content_ = [] - else: - self.content_ = content_ - self.valueOf_ = valueOf_ - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, PostageType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if PostageType.subclass: - return PostageType.subclass(*args_, **kwargs_) - else: - return PostageType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_MailService(self): - return self.MailService - def set_MailService(self, MailService): - self.MailService = MailService - def get_Rate(self): - return self.Rate - def set_Rate(self, Rate): - self.Rate = Rate - def get_CommercialRate(self): - return self.CommercialRate - def set_CommercialRate(self, CommercialRate): - self.CommercialRate = CommercialRate - def get_CommercialPlusRate(self): - return self.CommercialPlusRate - def set_CommercialPlusRate(self, CommercialPlusRate): - self.CommercialPlusRate = CommercialPlusRate - def get_CommitmentDate(self): - return self.CommitmentDate - def set_CommitmentDate(self, CommitmentDate): - self.CommitmentDate = CommitmentDate - def get_CommitmentName(self): - return self.CommitmentName - def set_CommitmentName(self, CommitmentName): - self.CommitmentName = CommitmentName - def get_MaxDimensions(self): - return self.MaxDimensions - def set_MaxDimensions(self, MaxDimensions): - self.MaxDimensions = MaxDimensions - def get_ServiceInformation(self): - return self.ServiceInformation - def set_ServiceInformation(self, ServiceInformation): - self.ServiceInformation = ServiceInformation - def get_SpecialServices(self): - return self.SpecialServices - def set_SpecialServices(self, SpecialServices): - self.SpecialServices = SpecialServices - def get_Zone(self): - return self.Zone - def set_Zone(self, Zone): - self.Zone = Zone - def get_CLASSID(self): - return self.CLASSID - def set_CLASSID(self, CLASSID): - self.CLASSID = CLASSID - def get_valueOf_(self): return self.valueOf_ - def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_ - def _hasContent(self): - if ( - self.MailService is not None or - self.Rate is not None or - self.CommercialRate is not None or - self.CommercialPlusRate is not None or - self.CommitmentDate is not None or - self.CommitmentName is not None or - self.MaxDimensions is not None or - self.ServiceInformation is not None or - self.SpecialServices is not None or - self.Zone is not None or - (1 if type(self.valueOf_) in [int,float] else self.valueOf_) or - self.content_ - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='PostageType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('PostageType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'PostageType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='PostageType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='PostageType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='PostageType'): - if self.CLASSID is not None and 'CLASSID' not in already_processed: - already_processed.add('CLASSID') - outfile.write(' CLASSID="%s"' % self.gds_format_integer(self.CLASSID, input_name='CLASSID')) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='PostageType', fromsubclass_=False, pretty_print=True): - if not fromsubclass_: - for item_ in self.content_: - item_.export(outfile, level, item_.name, namespaceprefix_, pretty_print=pretty_print) - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.MailService is not None: - namespaceprefix_ = self.MailService_nsprefix_ + ':' if (UseCapturedNS_ and self.MailService_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sMailService>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.MailService), input_name='MailService')), namespaceprefix_ , eol_)) - if self.Rate is not None: - namespaceprefix_ = self.Rate_nsprefix_ + ':' if (UseCapturedNS_ and self.Rate_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRate>%s%s' % (namespaceprefix_ , self.gds_format_float(self.Rate, input_name='Rate'), namespaceprefix_ , eol_)) - if self.CommercialRate is not None: - namespaceprefix_ = self.CommercialRate_nsprefix_ + ':' if (UseCapturedNS_ and self.CommercialRate_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCommercialRate>%s%s' % (namespaceprefix_ , self.gds_format_float(self.CommercialRate, input_name='CommercialRate'), namespaceprefix_ , eol_)) - if self.CommercialPlusRate is not None: - namespaceprefix_ = self.CommercialPlusRate_nsprefix_ + ':' if (UseCapturedNS_ and self.CommercialPlusRate_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCommercialPlusRate>%s%s' % (namespaceprefix_ , self.gds_format_float(self.CommercialPlusRate, input_name='CommercialPlusRate'), namespaceprefix_ , eol_)) - if self.CommitmentDate is not None: - namespaceprefix_ = self.CommitmentDate_nsprefix_ + ':' if (UseCapturedNS_ and self.CommitmentDate_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCommitmentDate>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CommitmentDate), input_name='CommitmentDate')), namespaceprefix_ , eol_)) - if self.CommitmentName is not None: - namespaceprefix_ = self.CommitmentName_nsprefix_ + ':' if (UseCapturedNS_ and self.CommitmentName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCommitmentName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CommitmentName), input_name='CommitmentName')), namespaceprefix_ , eol_)) - if self.MaxDimensions is not None: - namespaceprefix_ = self.MaxDimensions_nsprefix_ + ':' if (UseCapturedNS_ and self.MaxDimensions_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sMaxDimensions>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.MaxDimensions), input_name='MaxDimensions')), namespaceprefix_ , eol_)) - if self.ServiceInformation is not None: - namespaceprefix_ = self.ServiceInformation_nsprefix_ + ':' if (UseCapturedNS_ and self.ServiceInformation_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sServiceInformation>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ServiceInformation), input_name='ServiceInformation')), namespaceprefix_ , eol_)) - if self.SpecialServices is not None: - namespaceprefix_ = self.SpecialServices_nsprefix_ + ':' if (UseCapturedNS_ and self.SpecialServices_nsprefix_) else '' - self.SpecialServices.export(outfile, level, namespaceprefix_, namespacedef_='', name_='SpecialServices', pretty_print=pretty_print) - if self.Zone is not None: - namespaceprefix_ = self.Zone_nsprefix_ + ':' if (UseCapturedNS_ and self.Zone_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sZone>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Zone), input_name='Zone')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - self.valueOf_ = get_all_text_(node) - if node.text is not None: - obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', node.text) - self.content_.append(obj_) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('CLASSID', node) - if value is not None and 'CLASSID' not in already_processed: - already_processed.add('CLASSID') - self.CLASSID = self.gds_parse_integer(value, node, 'CLASSID') - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'MailService' and child_.text is not None: - valuestr_ = child_.text - valuestr_ = self.gds_parse_string(valuestr_, node, 'MailService') - valuestr_ = self.gds_validate_string(valuestr_, node, 'MailService') - obj_ = self.mixedclass_(MixedContainer.CategorySimple, - MixedContainer.TypeString, 'MailService', valuestr_) - self.content_.append(obj_) - self.MailService_nsprefix_ = child_.prefix - elif nodeName_ == 'Rate' and child_.text is not None: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'Rate') - fval_ = self.gds_validate_float(fval_, node, 'Rate') - obj_ = self.mixedclass_(MixedContainer.CategorySimple, - MixedContainer.TypeFloat, 'Rate', fval_) - self.content_.append(obj_) - self.Rate_nsprefix_ = child_.prefix - elif nodeName_ == 'CommercialRate' and child_.text is not None: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'CommercialRate') - fval_ = self.gds_validate_float(fval_, node, 'CommercialRate') - obj_ = self.mixedclass_(MixedContainer.CategorySimple, - MixedContainer.TypeFloat, 'CommercialRate', fval_) - self.content_.append(obj_) - self.CommercialRate_nsprefix_ = child_.prefix - elif nodeName_ == 'CommercialPlusRate' and child_.text is not None: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'CommercialPlusRate') - fval_ = self.gds_validate_float(fval_, node, 'CommercialPlusRate') - obj_ = self.mixedclass_(MixedContainer.CategorySimple, - MixedContainer.TypeFloat, 'CommercialPlusRate', fval_) - self.content_.append(obj_) - self.CommercialPlusRate_nsprefix_ = child_.prefix - elif nodeName_ == 'CommitmentDate' and child_.text is not None: - valuestr_ = child_.text - valuestr_ = self.gds_parse_string(valuestr_, node, 'CommitmentDate') - valuestr_ = self.gds_validate_string(valuestr_, node, 'CommitmentDate') - obj_ = self.mixedclass_(MixedContainer.CategorySimple, - MixedContainer.TypeString, 'CommitmentDate', valuestr_) - self.content_.append(obj_) - self.CommitmentDate_nsprefix_ = child_.prefix - elif nodeName_ == 'CommitmentName' and child_.text is not None: - valuestr_ = child_.text - valuestr_ = self.gds_parse_string(valuestr_, node, 'CommitmentName') - valuestr_ = self.gds_validate_string(valuestr_, node, 'CommitmentName') - obj_ = self.mixedclass_(MixedContainer.CategorySimple, - MixedContainer.TypeString, 'CommitmentName', valuestr_) - self.content_.append(obj_) - self.CommitmentName_nsprefix_ = child_.prefix - elif nodeName_ == 'MaxDimensions' and child_.text is not None: - valuestr_ = child_.text - valuestr_ = self.gds_parse_string(valuestr_, node, 'MaxDimensions') - valuestr_ = self.gds_validate_string(valuestr_, node, 'MaxDimensions') - obj_ = self.mixedclass_(MixedContainer.CategorySimple, - MixedContainer.TypeString, 'MaxDimensions', valuestr_) - self.content_.append(obj_) - self.MaxDimensions_nsprefix_ = child_.prefix - elif nodeName_ == 'ServiceInformation' and child_.text is not None: - valuestr_ = child_.text - valuestr_ = self.gds_parse_string(valuestr_, node, 'ServiceInformation') - valuestr_ = self.gds_validate_string(valuestr_, node, 'ServiceInformation') - obj_ = self.mixedclass_(MixedContainer.CategorySimple, - MixedContainer.TypeString, 'ServiceInformation', valuestr_) - self.content_.append(obj_) - self.ServiceInformation_nsprefix_ = child_.prefix - elif nodeName_ == 'SpecialServices': - obj_ = SpecialServicesType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'SpecialServices', obj_) - self.content_.append(obj_) - if hasattr(self, 'add_SpecialServices'): - self.add_SpecialServices(obj_.value) - elif hasattr(self, 'set_SpecialServices'): - self.set_SpecialServices(obj_.value) - elif nodeName_ == 'Zone' and child_.text is not None: - valuestr_ = child_.text - valuestr_ = self.gds_parse_string(valuestr_, node, 'Zone') - valuestr_ = self.gds_validate_string(valuestr_, node, 'Zone') - obj_ = self.mixedclass_(MixedContainer.CategorySimple, - MixedContainer.TypeString, 'Zone', valuestr_) - self.content_.append(obj_) - self.Zone_nsprefix_ = child_.prefix - if not fromsubclass_ and child_.tail is not None: - obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.tail) - self.content_.append(obj_) -# end class PostageType - - -class SpecialServicesType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, SpecialService=None, valueOf_=None, mixedclass_=None, content_=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - if SpecialService is None: - self.SpecialService = [] - else: - self.SpecialService = SpecialService - self.SpecialService_nsprefix_ = None - self.valueOf_ = valueOf_ - if mixedclass_ is None: - self.mixedclass_ = MixedContainer - else: - self.mixedclass_ = mixedclass_ - if content_ is None: - self.content_ = [] - else: - self.content_ = content_ - self.valueOf_ = valueOf_ - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, SpecialServicesType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if SpecialServicesType.subclass: - return SpecialServicesType.subclass(*args_, **kwargs_) - else: - return SpecialServicesType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_SpecialService(self): - return self.SpecialService - def set_SpecialService(self, SpecialService): - self.SpecialService = SpecialService - def add_SpecialService(self, value): - self.SpecialService.append(value) - def insert_SpecialService_at(self, index, value): - self.SpecialService.insert(index, value) - def replace_SpecialService_at(self, index, value): - self.SpecialService[index] = value - def get_valueOf_(self): return self.valueOf_ - def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_ - def _hasContent(self): - if ( - self.SpecialService or - (1 if type(self.valueOf_) in [int,float] else self.valueOf_) or - self.content_ - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='SpecialServicesType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('SpecialServicesType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'SpecialServicesType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='SpecialServicesType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='SpecialServicesType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='SpecialServicesType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='SpecialServicesType', fromsubclass_=False, pretty_print=True): - if not fromsubclass_: - for item_ in self.content_: - item_.export(outfile, level, item_.name, namespaceprefix_, pretty_print=pretty_print) - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - for SpecialService_ in self.SpecialService: - namespaceprefix_ = self.SpecialService_nsprefix_ + ':' if (UseCapturedNS_ and self.SpecialService_nsprefix_) else '' - SpecialService_.export(outfile, level, namespaceprefix_, namespacedef_='', name_='SpecialService', pretty_print=pretty_print) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - self.valueOf_ = get_all_text_(node) - if node.text is not None: - obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', node.text) - self.content_.append(obj_) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'SpecialService': - obj_ = SpecialServiceType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - obj_ = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'SpecialService', obj_) - self.content_.append(obj_) - if hasattr(self, 'add_SpecialService'): - self.add_SpecialService(obj_.value) - elif hasattr(self, 'set_SpecialService'): - self.set_SpecialService(obj_.value) - if not fromsubclass_ and child_.tail is not None: - obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.tail) - self.content_.append(obj_) -# end class SpecialServicesType - - -class SpecialServiceType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ServiceID=None, ServiceName=None, Available=None, AvailableOnline=None, AvailableCPP=None, Price=None, PriceOnline=None, PriceCPP=None, DeclaredValueRequired=None, DueSenderRequired=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.ServiceID = ServiceID - self.ServiceID_nsprefix_ = None - self.ServiceName = ServiceName - self.ServiceName_nsprefix_ = None - self.Available = Available - self.Available_nsprefix_ = None - self.AvailableOnline = AvailableOnline - self.AvailableOnline_nsprefix_ = None - self.AvailableCPP = AvailableCPP - self.AvailableCPP_nsprefix_ = None - self.Price = Price - self.Price_nsprefix_ = None - self.PriceOnline = PriceOnline - self.PriceOnline_nsprefix_ = None - self.PriceCPP = PriceCPP - self.PriceCPP_nsprefix_ = None - self.DeclaredValueRequired = DeclaredValueRequired - self.DeclaredValueRequired_nsprefix_ = None - self.DueSenderRequired = DueSenderRequired - self.DueSenderRequired_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, SpecialServiceType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if SpecialServiceType.subclass: - return SpecialServiceType.subclass(*args_, **kwargs_) - else: - return SpecialServiceType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_ServiceID(self): - return self.ServiceID - def set_ServiceID(self, ServiceID): - self.ServiceID = ServiceID - def get_ServiceName(self): - return self.ServiceName - def set_ServiceName(self, ServiceName): - self.ServiceName = ServiceName - def get_Available(self): - return self.Available - def set_Available(self, Available): - self.Available = Available - def get_AvailableOnline(self): - return self.AvailableOnline - def set_AvailableOnline(self, AvailableOnline): - self.AvailableOnline = AvailableOnline - def get_AvailableCPP(self): - return self.AvailableCPP - def set_AvailableCPP(self, AvailableCPP): - self.AvailableCPP = AvailableCPP - def get_Price(self): - return self.Price - def set_Price(self, Price): - self.Price = Price - def get_PriceOnline(self): - return self.PriceOnline - def set_PriceOnline(self, PriceOnline): - self.PriceOnline = PriceOnline - def get_PriceCPP(self): - return self.PriceCPP - def set_PriceCPP(self, PriceCPP): - self.PriceCPP = PriceCPP - def get_DeclaredValueRequired(self): - return self.DeclaredValueRequired - def set_DeclaredValueRequired(self, DeclaredValueRequired): - self.DeclaredValueRequired = DeclaredValueRequired - def get_DueSenderRequired(self): - return self.DueSenderRequired - def set_DueSenderRequired(self, DueSenderRequired): - self.DueSenderRequired = DueSenderRequired - def _hasContent(self): - if ( - self.ServiceID is not None or - self.ServiceName is not None or - self.Available is not None or - self.AvailableOnline is not None or - self.AvailableCPP is not None or - self.Price is not None or - self.PriceOnline is not None or - self.PriceCPP is not None or - self.DeclaredValueRequired is not None or - self.DueSenderRequired is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='SpecialServiceType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('SpecialServiceType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'SpecialServiceType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='SpecialServiceType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='SpecialServiceType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='SpecialServiceType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='SpecialServiceType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.ServiceID is not None: - namespaceprefix_ = self.ServiceID_nsprefix_ + ':' if (UseCapturedNS_ and self.ServiceID_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sServiceID>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.ServiceID, input_name='ServiceID'), namespaceprefix_ , eol_)) - if self.ServiceName is not None: - namespaceprefix_ = self.ServiceName_nsprefix_ + ':' if (UseCapturedNS_ and self.ServiceName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sServiceName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ServiceName), input_name='ServiceName')), namespaceprefix_ , eol_)) - if self.Available is not None: - namespaceprefix_ = self.Available_nsprefix_ + ':' if (UseCapturedNS_ and self.Available_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAvailable>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.Available, input_name='Available'), namespaceprefix_ , eol_)) - if self.AvailableOnline is not None: - namespaceprefix_ = self.AvailableOnline_nsprefix_ + ':' if (UseCapturedNS_ and self.AvailableOnline_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAvailableOnline>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.AvailableOnline, input_name='AvailableOnline'), namespaceprefix_ , eol_)) - if self.AvailableCPP is not None: - namespaceprefix_ = self.AvailableCPP_nsprefix_ + ':' if (UseCapturedNS_ and self.AvailableCPP_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAvailableCPP>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.AvailableCPP, input_name='AvailableCPP'), namespaceprefix_ , eol_)) - if self.Price is not None: - namespaceprefix_ = self.Price_nsprefix_ + ':' if (UseCapturedNS_ and self.Price_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPrice>%s%s' % (namespaceprefix_ , self.gds_format_float(self.Price, input_name='Price'), namespaceprefix_ , eol_)) - if self.PriceOnline is not None: - namespaceprefix_ = self.PriceOnline_nsprefix_ + ':' if (UseCapturedNS_ and self.PriceOnline_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPriceOnline>%s%s' % (namespaceprefix_ , self.gds_format_float(self.PriceOnline, input_name='PriceOnline'), namespaceprefix_ , eol_)) - if self.PriceCPP is not None: - namespaceprefix_ = self.PriceCPP_nsprefix_ + ':' if (UseCapturedNS_ and self.PriceCPP_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPriceCPP>%s%s' % (namespaceprefix_ , self.gds_format_float(self.PriceCPP, input_name='PriceCPP'), namespaceprefix_ , eol_)) - if self.DeclaredValueRequired is not None: - namespaceprefix_ = self.DeclaredValueRequired_nsprefix_ + ':' if (UseCapturedNS_ and self.DeclaredValueRequired_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDeclaredValueRequired>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.DeclaredValueRequired, input_name='DeclaredValueRequired'), namespaceprefix_ , eol_)) - if self.DueSenderRequired is not None: - namespaceprefix_ = self.DueSenderRequired_nsprefix_ + ':' if (UseCapturedNS_ and self.DueSenderRequired_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDueSenderRequired>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.DueSenderRequired, input_name='DueSenderRequired'), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'ServiceID' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'ServiceID') - ival_ = self.gds_validate_integer(ival_, node, 'ServiceID') - self.ServiceID = ival_ - self.ServiceID_nsprefix_ = child_.prefix - elif nodeName_ == 'ServiceName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ServiceName') - value_ = self.gds_validate_string(value_, node, 'ServiceName') - self.ServiceName = value_ - self.ServiceName_nsprefix_ = child_.prefix - elif nodeName_ == 'Available': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'Available') - ival_ = self.gds_validate_boolean(ival_, node, 'Available') - self.Available = ival_ - self.Available_nsprefix_ = child_.prefix - elif nodeName_ == 'AvailableOnline': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'AvailableOnline') - ival_ = self.gds_validate_boolean(ival_, node, 'AvailableOnline') - self.AvailableOnline = ival_ - self.AvailableOnline_nsprefix_ = child_.prefix - elif nodeName_ == 'AvailableCPP': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'AvailableCPP') - ival_ = self.gds_validate_boolean(ival_, node, 'AvailableCPP') - self.AvailableCPP = ival_ - self.AvailableCPP_nsprefix_ = child_.prefix - elif nodeName_ == 'Price' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'Price') - fval_ = self.gds_validate_float(fval_, node, 'Price') - self.Price = fval_ - self.Price_nsprefix_ = child_.prefix - elif nodeName_ == 'PriceOnline' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'PriceOnline') - fval_ = self.gds_validate_float(fval_, node, 'PriceOnline') - self.PriceOnline = fval_ - self.PriceOnline_nsprefix_ = child_.prefix - elif nodeName_ == 'PriceCPP' and child_.text: - sval_ = child_.text - fval_ = self.gds_parse_float(sval_, node, 'PriceCPP') - fval_ = self.gds_validate_float(fval_, node, 'PriceCPP') - self.PriceCPP = fval_ - self.PriceCPP_nsprefix_ = child_.prefix - elif nodeName_ == 'DeclaredValueRequired': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'DeclaredValueRequired') - ival_ = self.gds_validate_boolean(ival_, node, 'DeclaredValueRequired') - self.DeclaredValueRequired = ival_ - self.DeclaredValueRequired_nsprefix_ = child_.prefix - elif nodeName_ == 'DueSenderRequired': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'DueSenderRequired') - ival_ = self.gds_validate_boolean(ival_, node, 'DueSenderRequired') - self.DueSenderRequired = ival_ - self.DueSenderRequired_nsprefix_ = child_.prefix -# end class SpecialServiceType - - -class RestrictionType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, Restrictions=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.Restrictions = Restrictions - self.Restrictions_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, RestrictionType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if RestrictionType.subclass: - return RestrictionType.subclass(*args_, **kwargs_) - else: - return RestrictionType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_Restrictions(self): - return self.Restrictions - def set_Restrictions(self, Restrictions): - self.Restrictions = Restrictions - def _hasContent(self): - if ( - self.Restrictions is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='RestrictionType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('RestrictionType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'RestrictionType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='RestrictionType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='RestrictionType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='RestrictionType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='RestrictionType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.Restrictions is not None: - namespaceprefix_ = self.Restrictions_nsprefix_ + ':' if (UseCapturedNS_ and self.Restrictions_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRestrictions>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Restrictions), input_name='Restrictions')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'Restrictions': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Restrictions') - value_ = self.gds_validate_string(value_, node, 'Restrictions') - self.Restrictions = value_ - self.Restrictions_nsprefix_ = child_.prefix -# end class RestrictionType - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'RateV4Response' - rootClass = RateV4Response - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'RateV4Response' - rootClass = RateV4Response - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'RateV4Response' - rootClass = RateV4Response - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'RateV4Response' - rootClass = RateV4Response - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from rate_v4_response import *\n\n') - sys.stdout.write('import rate_v4_response as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "ErrorType", - "PackageType", - "PostageType", - "RateV4Response", - "RestrictionType", - "SpecialServiceType", - "SpecialServicesType" -] diff --git a/schemas/usps/karrio/schemas/usps/scan_request.py b/schemas/usps/karrio/schemas/usps/scan_request.py deleted file mode 100644 index f989cb9b9b..0000000000 --- a/schemas/usps/karrio/schemas/usps/scan_request.py +++ /dev/null @@ -1,1831 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:11 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/scan_request.py') -# -# Command line arguments: -# ./schemas/SCANRequest.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/scan_request.py" ./schemas/SCANRequest.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class SCANRequest(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, USERID=None, Option=None, FromName=None, FromFirm=None, FromAddress1=None, FromAddress2=None, FromCity=None, FromState=None, FromZip5=None, FromZip4=None, Shipment=None, MailDate=None, MailTime=None, EntryFacility=None, ImageType=None, CustomerRefNo=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.USERID = _cast(None, USERID) - self.USERID_nsprefix_ = None - self.Option = Option - self.Option_nsprefix_ = None - self.FromName = FromName - self.FromName_nsprefix_ = None - self.FromFirm = FromFirm - self.FromFirm_nsprefix_ = None - self.FromAddress1 = FromAddress1 - self.FromAddress1_nsprefix_ = None - self.FromAddress2 = FromAddress2 - self.FromAddress2_nsprefix_ = None - self.FromCity = FromCity - self.FromCity_nsprefix_ = None - self.FromState = FromState - self.FromState_nsprefix_ = None - self.FromZip5 = FromZip5 - self.FromZip5_nsprefix_ = None - self.FromZip4 = FromZip4 - self.FromZip4_nsprefix_ = None - self.Shipment = Shipment - self.Shipment_nsprefix_ = None - self.MailDate = MailDate - self.MailDate_nsprefix_ = None - self.MailTime = MailTime - self.MailTime_nsprefix_ = None - self.EntryFacility = EntryFacility - self.EntryFacility_nsprefix_ = None - self.ImageType = ImageType - self.ImageType_nsprefix_ = None - self.CustomerRefNo = CustomerRefNo - self.CustomerRefNo_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, SCANRequest) - if subclass is not None: - return subclass(*args_, **kwargs_) - if SCANRequest.subclass: - return SCANRequest.subclass(*args_, **kwargs_) - else: - return SCANRequest(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_Option(self): - return self.Option - def set_Option(self, Option): - self.Option = Option - def get_FromName(self): - return self.FromName - def set_FromName(self, FromName): - self.FromName = FromName - def get_FromFirm(self): - return self.FromFirm - def set_FromFirm(self, FromFirm): - self.FromFirm = FromFirm - def get_FromAddress1(self): - return self.FromAddress1 - def set_FromAddress1(self, FromAddress1): - self.FromAddress1 = FromAddress1 - def get_FromAddress2(self): - return self.FromAddress2 - def set_FromAddress2(self, FromAddress2): - self.FromAddress2 = FromAddress2 - def get_FromCity(self): - return self.FromCity - def set_FromCity(self, FromCity): - self.FromCity = FromCity - def get_FromState(self): - return self.FromState - def set_FromState(self, FromState): - self.FromState = FromState - def get_FromZip5(self): - return self.FromZip5 - def set_FromZip5(self, FromZip5): - self.FromZip5 = FromZip5 - def get_FromZip4(self): - return self.FromZip4 - def set_FromZip4(self, FromZip4): - self.FromZip4 = FromZip4 - def get_Shipment(self): - return self.Shipment - def set_Shipment(self, Shipment): - self.Shipment = Shipment - def get_MailDate(self): - return self.MailDate - def set_MailDate(self, MailDate): - self.MailDate = MailDate - def get_MailTime(self): - return self.MailTime - def set_MailTime(self, MailTime): - self.MailTime = MailTime - def get_EntryFacility(self): - return self.EntryFacility - def set_EntryFacility(self, EntryFacility): - self.EntryFacility = EntryFacility - def get_ImageType(self): - return self.ImageType - def set_ImageType(self, ImageType): - self.ImageType = ImageType - def get_CustomerRefNo(self): - return self.CustomerRefNo - def set_CustomerRefNo(self, CustomerRefNo): - self.CustomerRefNo = CustomerRefNo - def get_USERID(self): - return self.USERID - def set_USERID(self, USERID): - self.USERID = USERID - def _hasContent(self): - if ( - self.Option is not None or - self.FromName is not None or - self.FromFirm is not None or - self.FromAddress1 is not None or - self.FromAddress2 is not None or - self.FromCity is not None or - self.FromState is not None or - self.FromZip5 is not None or - self.FromZip4 is not None or - self.Shipment is not None or - self.MailDate is not None or - self.MailTime is not None or - self.EntryFacility is not None or - self.ImageType is not None or - self.CustomerRefNo is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='SCANRequest', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('SCANRequest') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'SCANRequest': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='SCANRequest') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='SCANRequest', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='SCANRequest'): - if self.USERID is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - outfile.write(' USERID=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.USERID), input_name='USERID')), )) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='SCANRequest', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.Option is not None: - namespaceprefix_ = self.Option_nsprefix_ + ':' if (UseCapturedNS_ and self.Option_nsprefix_) else '' - self.Option.export(outfile, level, namespaceprefix_, namespacedef_='', name_='Option', pretty_print=pretty_print) - if self.FromName is not None: - namespaceprefix_ = self.FromName_nsprefix_ + ':' if (UseCapturedNS_ and self.FromName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromName), input_name='FromName')), namespaceprefix_ , eol_)) - if self.FromFirm is not None: - namespaceprefix_ = self.FromFirm_nsprefix_ + ':' if (UseCapturedNS_ and self.FromFirm_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromFirm>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromFirm), input_name='FromFirm')), namespaceprefix_ , eol_)) - if self.FromAddress1 is not None: - namespaceprefix_ = self.FromAddress1_nsprefix_ + ':' if (UseCapturedNS_ and self.FromAddress1_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromAddress1>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromAddress1), input_name='FromAddress1')), namespaceprefix_ , eol_)) - if self.FromAddress2 is not None: - namespaceprefix_ = self.FromAddress2_nsprefix_ + ':' if (UseCapturedNS_ and self.FromAddress2_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromAddress2>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromAddress2), input_name='FromAddress2')), namespaceprefix_ , eol_)) - if self.FromCity is not None: - namespaceprefix_ = self.FromCity_nsprefix_ + ':' if (UseCapturedNS_ and self.FromCity_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromCity), input_name='FromCity')), namespaceprefix_ , eol_)) - if self.FromState is not None: - namespaceprefix_ = self.FromState_nsprefix_ + ':' if (UseCapturedNS_ and self.FromState_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FromState), input_name='FromState')), namespaceprefix_ , eol_)) - if self.FromZip5 is not None: - namespaceprefix_ = self.FromZip5_nsprefix_ + ':' if (UseCapturedNS_ and self.FromZip5_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromZip5>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.FromZip5, input_name='FromZip5'), namespaceprefix_ , eol_)) - if self.FromZip4 is not None: - namespaceprefix_ = self.FromZip4_nsprefix_ + ':' if (UseCapturedNS_ and self.FromZip4_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFromZip4>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.FromZip4, input_name='FromZip4'), namespaceprefix_ , eol_)) - if self.Shipment is not None: - namespaceprefix_ = self.Shipment_nsprefix_ + ':' if (UseCapturedNS_ and self.Shipment_nsprefix_) else '' - self.Shipment.export(outfile, level, namespaceprefix_, namespacedef_='', name_='Shipment', pretty_print=pretty_print) - if self.MailDate is not None: - namespaceprefix_ = self.MailDate_nsprefix_ + ':' if (UseCapturedNS_ and self.MailDate_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sMailDate>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.MailDate, input_name='MailDate'), namespaceprefix_ , eol_)) - if self.MailTime is not None: - namespaceprefix_ = self.MailTime_nsprefix_ + ':' if (UseCapturedNS_ and self.MailTime_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sMailTime>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.MailTime, input_name='MailTime'), namespaceprefix_ , eol_)) - if self.EntryFacility is not None: - namespaceprefix_ = self.EntryFacility_nsprefix_ + ':' if (UseCapturedNS_ and self.EntryFacility_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEntryFacility>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.EntryFacility, input_name='EntryFacility'), namespaceprefix_ , eol_)) - if self.ImageType is not None: - namespaceprefix_ = self.ImageType_nsprefix_ + ':' if (UseCapturedNS_ and self.ImageType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sImageType>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ImageType), input_name='ImageType')), namespaceprefix_ , eol_)) - if self.CustomerRefNo is not None: - namespaceprefix_ = self.CustomerRefNo_nsprefix_ + ':' if (UseCapturedNS_ and self.CustomerRefNo_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCustomerRefNo>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CustomerRefNo), input_name='CustomerRefNo')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('USERID', node) - if value is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - self.USERID = value - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'Option': - obj_ = OptionType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.Option = obj_ - obj_.original_tagname_ = 'Option' - elif nodeName_ == 'FromName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromName') - value_ = self.gds_validate_string(value_, node, 'FromName') - self.FromName = value_ - self.FromName_nsprefix_ = child_.prefix - elif nodeName_ == 'FromFirm': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromFirm') - value_ = self.gds_validate_string(value_, node, 'FromFirm') - self.FromFirm = value_ - self.FromFirm_nsprefix_ = child_.prefix - elif nodeName_ == 'FromAddress1': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromAddress1') - value_ = self.gds_validate_string(value_, node, 'FromAddress1') - self.FromAddress1 = value_ - self.FromAddress1_nsprefix_ = child_.prefix - elif nodeName_ == 'FromAddress2': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromAddress2') - value_ = self.gds_validate_string(value_, node, 'FromAddress2') - self.FromAddress2 = value_ - self.FromAddress2_nsprefix_ = child_.prefix - elif nodeName_ == 'FromCity': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromCity') - value_ = self.gds_validate_string(value_, node, 'FromCity') - self.FromCity = value_ - self.FromCity_nsprefix_ = child_.prefix - elif nodeName_ == 'FromState': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FromState') - value_ = self.gds_validate_string(value_, node, 'FromState') - self.FromState = value_ - self.FromState_nsprefix_ = child_.prefix - elif nodeName_ == 'FromZip5' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'FromZip5') - ival_ = self.gds_validate_integer(ival_, node, 'FromZip5') - self.FromZip5 = ival_ - self.FromZip5_nsprefix_ = child_.prefix - elif nodeName_ == 'FromZip4' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'FromZip4') - ival_ = self.gds_validate_integer(ival_, node, 'FromZip4') - self.FromZip4 = ival_ - self.FromZip4_nsprefix_ = child_.prefix - elif nodeName_ == 'Shipment': - obj_ = ShipmentType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.Shipment = obj_ - obj_.original_tagname_ = 'Shipment' - elif nodeName_ == 'MailDate' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'MailDate') - ival_ = self.gds_validate_integer(ival_, node, 'MailDate') - self.MailDate = ival_ - self.MailDate_nsprefix_ = child_.prefix - elif nodeName_ == 'MailTime' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'MailTime') - ival_ = self.gds_validate_integer(ival_, node, 'MailTime') - self.MailTime = ival_ - self.MailTime_nsprefix_ = child_.prefix - elif nodeName_ == 'EntryFacility' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'EntryFacility') - ival_ = self.gds_validate_integer(ival_, node, 'EntryFacility') - self.EntryFacility = ival_ - self.EntryFacility_nsprefix_ = child_.prefix - elif nodeName_ == 'ImageType': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ImageType') - value_ = self.gds_validate_string(value_, node, 'ImageType') - self.ImageType = value_ - self.ImageType_nsprefix_ = child_.prefix - elif nodeName_ == 'CustomerRefNo': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CustomerRefNo') - value_ = self.gds_validate_string(value_, node, 'CustomerRefNo') - self.CustomerRefNo = value_ - self.CustomerRefNo_nsprefix_ = child_.prefix -# end class SCANRequest - - -class OptionType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, Form=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.Form = Form - self.Form_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, OptionType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if OptionType.subclass: - return OptionType.subclass(*args_, **kwargs_) - else: - return OptionType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_Form(self): - return self.Form - def set_Form(self, Form): - self.Form = Form - def _hasContent(self): - if ( - self.Form is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='OptionType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('OptionType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'OptionType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='OptionType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='OptionType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='OptionType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='OptionType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.Form is not None: - namespaceprefix_ = self.Form_nsprefix_ + ':' if (UseCapturedNS_ and self.Form_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sForm>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.Form, input_name='Form'), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'Form' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'Form') - ival_ = self.gds_validate_integer(ival_, node, 'Form') - self.Form = ival_ - self.Form_nsprefix_ = child_.prefix -# end class OptionType - - -class ShipmentType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, PackageDetail=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.PackageDetail = PackageDetail - self.PackageDetail_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, ShipmentType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if ShipmentType.subclass: - return ShipmentType.subclass(*args_, **kwargs_) - else: - return ShipmentType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_PackageDetail(self): - return self.PackageDetail - def set_PackageDetail(self, PackageDetail): - self.PackageDetail = PackageDetail - def _hasContent(self): - if ( - self.PackageDetail is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ShipmentType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('ShipmentType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'ShipmentType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='ShipmentType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='ShipmentType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='ShipmentType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ShipmentType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.PackageDetail is not None: - namespaceprefix_ = self.PackageDetail_nsprefix_ + ':' if (UseCapturedNS_ and self.PackageDetail_nsprefix_) else '' - self.PackageDetail.export(outfile, level, namespaceprefix_, namespacedef_='', name_='PackageDetail', pretty_print=pretty_print) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'PackageDetail': - obj_ = PackageDetailType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.PackageDetail = obj_ - obj_.original_tagname_ = 'PackageDetail' -# end class ShipmentType - - -class PackageDetailType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, PkgBarcode=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.PkgBarcode = PkgBarcode - self.PkgBarcode_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, PackageDetailType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if PackageDetailType.subclass: - return PackageDetailType.subclass(*args_, **kwargs_) - else: - return PackageDetailType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_PkgBarcode(self): - return self.PkgBarcode - def set_PkgBarcode(self, PkgBarcode): - self.PkgBarcode = PkgBarcode - def _hasContent(self): - if ( - self.PkgBarcode is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='PackageDetailType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('PackageDetailType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'PackageDetailType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='PackageDetailType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='PackageDetailType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='PackageDetailType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='PackageDetailType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.PkgBarcode is not None: - namespaceprefix_ = self.PkgBarcode_nsprefix_ + ':' if (UseCapturedNS_ and self.PkgBarcode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPkgBarcode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PkgBarcode), input_name='PkgBarcode')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'PkgBarcode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PkgBarcode') - value_ = self.gds_validate_string(value_, node, 'PkgBarcode') - self.PkgBarcode = value_ - self.PkgBarcode_nsprefix_ = child_.prefix -# end class PackageDetailType - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'SCANRequest' - rootClass = SCANRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'SCANRequest' - rootClass = SCANRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'SCANRequest' - rootClass = SCANRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'SCANRequest' - rootClass = SCANRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from scan_request import *\n\n') - sys.stdout.write('import scan_request as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "OptionType", - "PackageDetailType", - "SCANRequest", - "ShipmentType" -] diff --git a/schemas/usps/karrio/schemas/usps/scan_response.py b/schemas/usps/karrio/schemas/usps/scan_response.py deleted file mode 100644 index ea2249c904..0000000000 --- a/schemas/usps/karrio/schemas/usps/scan_response.py +++ /dev/null @@ -1,1531 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:11 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/scan_response.py') -# -# Command line arguments: -# ./schemas/SCANResponse.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/scan_response.py" ./schemas/SCANResponse.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class SCANResponse(GeneratedsSuper): - """SCANFormImage -- 65255 skipped - - """ - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, SCANFormNumber=None, SCANFormImage=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.SCANFormNumber = SCANFormNumber - self.SCANFormNumber_nsprefix_ = None - self.SCANFormImage = SCANFormImage - self.SCANFormImage_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, SCANResponse) - if subclass is not None: - return subclass(*args_, **kwargs_) - if SCANResponse.subclass: - return SCANResponse.subclass(*args_, **kwargs_) - else: - return SCANResponse(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_SCANFormNumber(self): - return self.SCANFormNumber - def set_SCANFormNumber(self, SCANFormNumber): - self.SCANFormNumber = SCANFormNumber - def get_SCANFormImage(self): - return self.SCANFormImage - def set_SCANFormImage(self, SCANFormImage): - self.SCANFormImage = SCANFormImage - def _hasContent(self): - if ( - self.SCANFormNumber is not None or - self.SCANFormImage is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='SCANResponse', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('SCANResponse') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'SCANResponse': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='SCANResponse') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='SCANResponse', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='SCANResponse'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='SCANResponse', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.SCANFormNumber is not None: - namespaceprefix_ = self.SCANFormNumber_nsprefix_ + ':' if (UseCapturedNS_ and self.SCANFormNumber_nsprefix_) else '' - self.SCANFormNumber.export(outfile, level, namespaceprefix_, namespacedef_='', name_='SCANFormNumber', pretty_print=pretty_print) - if self.SCANFormImage is not None: - namespaceprefix_ = self.SCANFormImage_nsprefix_ + ':' if (UseCapturedNS_ and self.SCANFormImage_nsprefix_) else '' - self.SCANFormImage.export(outfile, level, namespaceprefix_, namespacedef_='', name_='SCANFormImage', pretty_print=pretty_print) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'SCANFormNumber': - obj_ = SCANFormNumberType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.SCANFormNumber = obj_ - obj_.original_tagname_ = 'SCANFormNumber' - elif nodeName_ == 'SCANFormImage': - obj_ = SCANFormImageType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.SCANFormImage = obj_ - obj_.original_tagname_ = 'SCANFormImage' -# end class SCANResponse - - -class SCANFormNumberType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ShipDate=None, EntryZipCode=None, valueOf_=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.ShipDate = _cast(None, ShipDate) - self.ShipDate_nsprefix_ = None - self.EntryZipCode = _cast(int, EntryZipCode) - self.EntryZipCode_nsprefix_ = None - self.valueOf_ = valueOf_ - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, SCANFormNumberType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if SCANFormNumberType.subclass: - return SCANFormNumberType.subclass(*args_, **kwargs_) - else: - return SCANFormNumberType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_ShipDate(self): - return self.ShipDate - def set_ShipDate(self, ShipDate): - self.ShipDate = ShipDate - def get_EntryZipCode(self): - return self.EntryZipCode - def set_EntryZipCode(self, EntryZipCode): - self.EntryZipCode = EntryZipCode - def get_valueOf_(self): return self.valueOf_ - def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_ - def _hasContent(self): - if ( - (1 if type(self.valueOf_) in [int,float] else self.valueOf_) - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='SCANFormNumberType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('SCANFormNumberType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'SCANFormNumberType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='SCANFormNumberType') - if self._hasContent(): - outfile.write('>') - outfile.write(self.convert_unicode(self.valueOf_)) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='SCANFormNumberType', pretty_print=pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='SCANFormNumberType'): - if self.ShipDate is not None and 'ShipDate' not in already_processed: - already_processed.add('ShipDate') - outfile.write(' ShipDate=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.ShipDate), input_name='ShipDate')), )) - if self.EntryZipCode is not None and 'EntryZipCode' not in already_processed: - already_processed.add('EntryZipCode') - outfile.write(' EntryZipCode="%s"' % self.gds_format_integer(self.EntryZipCode, input_name='EntryZipCode')) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='SCANFormNumberType', fromsubclass_=False, pretty_print=True): - pass - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - self.valueOf_ = get_all_text_(node) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('ShipDate', node) - if value is not None and 'ShipDate' not in already_processed: - already_processed.add('ShipDate') - self.ShipDate = value - value = find_attr_value_('EntryZipCode', node) - if value is not None and 'EntryZipCode' not in already_processed: - already_processed.add('EntryZipCode') - self.EntryZipCode = self.gds_parse_integer(value, node, 'EntryZipCode') - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - pass -# end class SCANFormNumberType - - -class SCANFormImageType(GeneratedsSuper): - """SCANFormImageType -- 65255 skipped - - """ - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ShipDate=None, EntryZipCode=None, valueOf_=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.ShipDate = _cast(None, ShipDate) - self.ShipDate_nsprefix_ = None - self.EntryZipCode = _cast(int, EntryZipCode) - self.EntryZipCode_nsprefix_ = None - self.valueOf_ = valueOf_ - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, SCANFormImageType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if SCANFormImageType.subclass: - return SCANFormImageType.subclass(*args_, **kwargs_) - else: - return SCANFormImageType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_ShipDate(self): - return self.ShipDate - def set_ShipDate(self, ShipDate): - self.ShipDate = ShipDate - def get_EntryZipCode(self): - return self.EntryZipCode - def set_EntryZipCode(self, EntryZipCode): - self.EntryZipCode = EntryZipCode - def get_valueOf_(self): return self.valueOf_ - def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_ - def _hasContent(self): - if ( - (1 if type(self.valueOf_) in [int,float] else self.valueOf_) - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='SCANFormImageType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('SCANFormImageType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'SCANFormImageType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='SCANFormImageType') - if self._hasContent(): - outfile.write('>') - outfile.write(self.convert_unicode(self.valueOf_)) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='SCANFormImageType', pretty_print=pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='SCANFormImageType'): - if self.ShipDate is not None and 'ShipDate' not in already_processed: - already_processed.add('ShipDate') - outfile.write(' ShipDate=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.ShipDate), input_name='ShipDate')), )) - if self.EntryZipCode is not None and 'EntryZipCode' not in already_processed: - already_processed.add('EntryZipCode') - outfile.write(' EntryZipCode="%s"' % self.gds_format_integer(self.EntryZipCode, input_name='EntryZipCode')) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='SCANFormImageType', fromsubclass_=False, pretty_print=True): - pass - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - self.valueOf_ = get_all_text_(node) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('ShipDate', node) - if value is not None and 'ShipDate' not in already_processed: - already_processed.add('ShipDate') - self.ShipDate = value - value = find_attr_value_('EntryZipCode', node) - if value is not None and 'EntryZipCode' not in already_processed: - already_processed.add('EntryZipCode') - self.EntryZipCode = self.gds_parse_integer(value, node, 'EntryZipCode') - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - pass -# end class SCANFormImageType - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'SCANResponse' - rootClass = SCANResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'SCANResponse' - rootClass = SCANResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'SCANResponse' - rootClass = SCANResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'SCANResponse' - rootClass = SCANResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from scan_response import *\n\n') - sys.stdout.write('import scan_response as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "SCANFormImageType", - "SCANFormNumberType", - "SCANResponse" -] diff --git a/schemas/usps/karrio/schemas/usps/sdc_get_locations_request.py b/schemas/usps/karrio/schemas/usps/sdc_get_locations_request.py deleted file mode 100644 index bd5074ad4e..0000000000 --- a/schemas/usps/karrio/schemas/usps/sdc_get_locations_request.py +++ /dev/null @@ -1,1413 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:12 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/sdc_get_locations_request.py') -# -# Command line arguments: -# ./schemas/SDCGetLocationsRequest.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/sdc_get_locations_request.py" ./schemas/SDCGetLocationsRequest.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class SDCGetLocationsRequest(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, USERID=None, MailClass=None, OriginZIP=None, DestinationZIP=None, AcceptDate=None, AcceptTime=None, NonExpeditedDetail=None, ClientType=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.USERID = _cast(None, USERID) - self.USERID_nsprefix_ = None - self.MailClass = MailClass - self.MailClass_nsprefix_ = None - self.OriginZIP = OriginZIP - self.OriginZIP_nsprefix_ = None - self.DestinationZIP = DestinationZIP - self.DestinationZIP_nsprefix_ = None - self.AcceptDate = AcceptDate - self.AcceptDate_nsprefix_ = None - self.AcceptTime = AcceptTime - self.AcceptTime_nsprefix_ = None - self.NonExpeditedDetail = NonExpeditedDetail - self.NonExpeditedDetail_nsprefix_ = None - self.ClientType = ClientType - self.ClientType_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, SDCGetLocationsRequest) - if subclass is not None: - return subclass(*args_, **kwargs_) - if SDCGetLocationsRequest.subclass: - return SDCGetLocationsRequest.subclass(*args_, **kwargs_) - else: - return SDCGetLocationsRequest(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_MailClass(self): - return self.MailClass - def set_MailClass(self, MailClass): - self.MailClass = MailClass - def get_OriginZIP(self): - return self.OriginZIP - def set_OriginZIP(self, OriginZIP): - self.OriginZIP = OriginZIP - def get_DestinationZIP(self): - return self.DestinationZIP - def set_DestinationZIP(self, DestinationZIP): - self.DestinationZIP = DestinationZIP - def get_AcceptDate(self): - return self.AcceptDate - def set_AcceptDate(self, AcceptDate): - self.AcceptDate = AcceptDate - def get_AcceptTime(self): - return self.AcceptTime - def set_AcceptTime(self, AcceptTime): - self.AcceptTime = AcceptTime - def get_NonExpeditedDetail(self): - return self.NonExpeditedDetail - def set_NonExpeditedDetail(self, NonExpeditedDetail): - self.NonExpeditedDetail = NonExpeditedDetail - def get_ClientType(self): - return self.ClientType - def set_ClientType(self, ClientType): - self.ClientType = ClientType - def get_USERID(self): - return self.USERID - def set_USERID(self, USERID): - self.USERID = USERID - def _hasContent(self): - if ( - self.MailClass is not None or - self.OriginZIP is not None or - self.DestinationZIP is not None or - self.AcceptDate is not None or - self.AcceptTime is not None or - self.NonExpeditedDetail is not None or - self.ClientType is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='SDCGetLocationsRequest', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('SDCGetLocationsRequest') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'SDCGetLocationsRequest': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='SDCGetLocationsRequest') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='SDCGetLocationsRequest', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='SDCGetLocationsRequest'): - if self.USERID is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - outfile.write(' USERID=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.USERID), input_name='USERID')), )) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='SDCGetLocationsRequest', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.MailClass is not None: - namespaceprefix_ = self.MailClass_nsprefix_ + ':' if (UseCapturedNS_ and self.MailClass_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sMailClass>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.MailClass, input_name='MailClass'), namespaceprefix_ , eol_)) - if self.OriginZIP is not None: - namespaceprefix_ = self.OriginZIP_nsprefix_ + ':' if (UseCapturedNS_ and self.OriginZIP_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sOriginZIP>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.OriginZIP, input_name='OriginZIP'), namespaceprefix_ , eol_)) - if self.DestinationZIP is not None: - namespaceprefix_ = self.DestinationZIP_nsprefix_ + ':' if (UseCapturedNS_ and self.DestinationZIP_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDestinationZIP>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.DestinationZIP, input_name='DestinationZIP'), namespaceprefix_ , eol_)) - if self.AcceptDate is not None: - namespaceprefix_ = self.AcceptDate_nsprefix_ + ':' if (UseCapturedNS_ and self.AcceptDate_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAcceptDate>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.AcceptDate), input_name='AcceptDate')), namespaceprefix_ , eol_)) - if self.AcceptTime is not None: - namespaceprefix_ = self.AcceptTime_nsprefix_ + ':' if (UseCapturedNS_ and self.AcceptTime_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAcceptTime>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.AcceptTime, input_name='AcceptTime'), namespaceprefix_ , eol_)) - if self.NonExpeditedDetail is not None: - namespaceprefix_ = self.NonExpeditedDetail_nsprefix_ + ':' if (UseCapturedNS_ and self.NonExpeditedDetail_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sNonExpeditedDetail>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.NonExpeditedDetail), input_name='NonExpeditedDetail')), namespaceprefix_ , eol_)) - if self.ClientType is not None: - namespaceprefix_ = self.ClientType_nsprefix_ + ':' if (UseCapturedNS_ and self.ClientType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sClientType>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.ClientType, input_name='ClientType'), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('USERID', node) - if value is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - self.USERID = value - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'MailClass' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'MailClass') - ival_ = self.gds_validate_integer(ival_, node, 'MailClass') - self.MailClass = ival_ - self.MailClass_nsprefix_ = child_.prefix - elif nodeName_ == 'OriginZIP' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'OriginZIP') - ival_ = self.gds_validate_integer(ival_, node, 'OriginZIP') - self.OriginZIP = ival_ - self.OriginZIP_nsprefix_ = child_.prefix - elif nodeName_ == 'DestinationZIP' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'DestinationZIP') - ival_ = self.gds_validate_integer(ival_, node, 'DestinationZIP') - self.DestinationZIP = ival_ - self.DestinationZIP_nsprefix_ = child_.prefix - elif nodeName_ == 'AcceptDate': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'AcceptDate') - value_ = self.gds_validate_string(value_, node, 'AcceptDate') - self.AcceptDate = value_ - self.AcceptDate_nsprefix_ = child_.prefix - elif nodeName_ == 'AcceptTime' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'AcceptTime') - ival_ = self.gds_validate_integer(ival_, node, 'AcceptTime') - self.AcceptTime = ival_ - self.AcceptTime_nsprefix_ = child_.prefix - elif nodeName_ == 'NonExpeditedDetail': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'NonExpeditedDetail') - value_ = self.gds_validate_string(value_, node, 'NonExpeditedDetail') - self.NonExpeditedDetail = value_ - self.NonExpeditedDetail_nsprefix_ = child_.prefix - elif nodeName_ == 'ClientType' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'ClientType') - ival_ = self.gds_validate_integer(ival_, node, 'ClientType') - self.ClientType = ival_ - self.ClientType_nsprefix_ = child_.prefix -# end class SDCGetLocationsRequest - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'SDCGetLocationsRequest' - rootClass = SDCGetLocationsRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'SDCGetLocationsRequest' - rootClass = SDCGetLocationsRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'SDCGetLocationsRequest' - rootClass = SDCGetLocationsRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'SDCGetLocationsRequest' - rootClass = SDCGetLocationsRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from sdc_get_locations_request import *\n\n') - sys.stdout.write('import sdc_get_locations_request as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "SDCGetLocationsRequest" -] diff --git a/schemas/usps/karrio/schemas/usps/sdc_get_locations_response.py b/schemas/usps/karrio/schemas/usps/sdc_get_locations_response.py deleted file mode 100644 index 109a81db45..0000000000 --- a/schemas/usps/karrio/schemas/usps/sdc_get_locations_response.py +++ /dev/null @@ -1,3206 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:12 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/sdc_get_locations_response.py') -# -# Command line arguments: -# ./schemas/SDCGetLocationsResponse.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/sdc_get_locations_response.py" ./schemas/SDCGetLocationsResponse.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class SDCGetLocationsResponse(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, Release=None, MailClass=None, OriginZIP=None, OriginCity=None, OriginState=None, DestZIP=None, DestCity=None, DestState=None, AcceptDate=None, AcceptTime=None, Expedited=None, NonExpedited=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.Release = Release - self.Release_nsprefix_ = None - self.MailClass = MailClass - self.MailClass_nsprefix_ = None - self.OriginZIP = OriginZIP - self.OriginZIP_nsprefix_ = None - self.OriginCity = OriginCity - self.OriginCity_nsprefix_ = None - self.OriginState = OriginState - self.OriginState_nsprefix_ = None - self.DestZIP = DestZIP - self.DestZIP_nsprefix_ = None - self.DestCity = DestCity - self.DestCity_nsprefix_ = None - self.DestState = DestState - self.DestState_nsprefix_ = None - if isinstance(AcceptDate, BaseStrType_): - initvalue_ = datetime_.datetime.strptime(AcceptDate, '%Y-%m-%d').date() - else: - initvalue_ = AcceptDate - self.AcceptDate = initvalue_ - self.AcceptDate_nsprefix_ = None - self.AcceptTime = AcceptTime - self.AcceptTime_nsprefix_ = None - self.Expedited = Expedited - self.Expedited_nsprefix_ = None - if NonExpedited is None: - self.NonExpedited = [] - else: - self.NonExpedited = NonExpedited - self.NonExpedited_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, SDCGetLocationsResponse) - if subclass is not None: - return subclass(*args_, **kwargs_) - if SDCGetLocationsResponse.subclass: - return SDCGetLocationsResponse.subclass(*args_, **kwargs_) - else: - return SDCGetLocationsResponse(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_Release(self): - return self.Release - def set_Release(self, Release): - self.Release = Release - def get_MailClass(self): - return self.MailClass - def set_MailClass(self, MailClass): - self.MailClass = MailClass - def get_OriginZIP(self): - return self.OriginZIP - def set_OriginZIP(self, OriginZIP): - self.OriginZIP = OriginZIP - def get_OriginCity(self): - return self.OriginCity - def set_OriginCity(self, OriginCity): - self.OriginCity = OriginCity - def get_OriginState(self): - return self.OriginState - def set_OriginState(self, OriginState): - self.OriginState = OriginState - def get_DestZIP(self): - return self.DestZIP - def set_DestZIP(self, DestZIP): - self.DestZIP = DestZIP - def get_DestCity(self): - return self.DestCity - def set_DestCity(self, DestCity): - self.DestCity = DestCity - def get_DestState(self): - return self.DestState - def set_DestState(self, DestState): - self.DestState = DestState - def get_AcceptDate(self): - return self.AcceptDate - def set_AcceptDate(self, AcceptDate): - self.AcceptDate = AcceptDate - def get_AcceptTime(self): - return self.AcceptTime - def set_AcceptTime(self, AcceptTime): - self.AcceptTime = AcceptTime - def get_Expedited(self): - return self.Expedited - def set_Expedited(self, Expedited): - self.Expedited = Expedited - def get_NonExpedited(self): - return self.NonExpedited - def set_NonExpedited(self, NonExpedited): - self.NonExpedited = NonExpedited - def add_NonExpedited(self, value): - self.NonExpedited.append(value) - def insert_NonExpedited_at(self, index, value): - self.NonExpedited.insert(index, value) - def replace_NonExpedited_at(self, index, value): - self.NonExpedited[index] = value - def _hasContent(self): - if ( - self.Release is not None or - self.MailClass is not None or - self.OriginZIP is not None or - self.OriginCity is not None or - self.OriginState is not None or - self.DestZIP is not None or - self.DestCity is not None or - self.DestState is not None or - self.AcceptDate is not None or - self.AcceptTime is not None or - self.Expedited is not None or - self.NonExpedited - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='SDCGetLocationsResponse', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('SDCGetLocationsResponse') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'SDCGetLocationsResponse': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='SDCGetLocationsResponse') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='SDCGetLocationsResponse', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='SDCGetLocationsResponse'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='SDCGetLocationsResponse', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.Release is not None: - namespaceprefix_ = self.Release_nsprefix_ + ':' if (UseCapturedNS_ and self.Release_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRelease>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.Release, input_name='Release'), namespaceprefix_ , eol_)) - if self.MailClass is not None: - namespaceprefix_ = self.MailClass_nsprefix_ + ':' if (UseCapturedNS_ and self.MailClass_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sMailClass>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.MailClass, input_name='MailClass'), namespaceprefix_ , eol_)) - if self.OriginZIP is not None: - namespaceprefix_ = self.OriginZIP_nsprefix_ + ':' if (UseCapturedNS_ and self.OriginZIP_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sOriginZIP>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.OriginZIP, input_name='OriginZIP'), namespaceprefix_ , eol_)) - if self.OriginCity is not None: - namespaceprefix_ = self.OriginCity_nsprefix_ + ':' if (UseCapturedNS_ and self.OriginCity_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sOriginCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.OriginCity), input_name='OriginCity')), namespaceprefix_ , eol_)) - if self.OriginState is not None: - namespaceprefix_ = self.OriginState_nsprefix_ + ':' if (UseCapturedNS_ and self.OriginState_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sOriginState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.OriginState), input_name='OriginState')), namespaceprefix_ , eol_)) - if self.DestZIP is not None: - namespaceprefix_ = self.DestZIP_nsprefix_ + ':' if (UseCapturedNS_ and self.DestZIP_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDestZIP>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.DestZIP, input_name='DestZIP'), namespaceprefix_ , eol_)) - if self.DestCity is not None: - namespaceprefix_ = self.DestCity_nsprefix_ + ':' if (UseCapturedNS_ and self.DestCity_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDestCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.DestCity), input_name='DestCity')), namespaceprefix_ , eol_)) - if self.DestState is not None: - namespaceprefix_ = self.DestState_nsprefix_ + ':' if (UseCapturedNS_ and self.DestState_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDestState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.DestState), input_name='DestState')), namespaceprefix_ , eol_)) - if self.AcceptDate is not None: - namespaceprefix_ = self.AcceptDate_nsprefix_ + ':' if (UseCapturedNS_ and self.AcceptDate_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAcceptDate>%s%s' % (namespaceprefix_ , self.gds_format_date(self.AcceptDate, input_name='AcceptDate'), namespaceprefix_ , eol_)) - if self.AcceptTime is not None: - namespaceprefix_ = self.AcceptTime_nsprefix_ + ':' if (UseCapturedNS_ and self.AcceptTime_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAcceptTime>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.AcceptTime, input_name='AcceptTime'), namespaceprefix_ , eol_)) - if self.Expedited is not None: - namespaceprefix_ = self.Expedited_nsprefix_ + ':' if (UseCapturedNS_ and self.Expedited_nsprefix_) else '' - self.Expedited.export(outfile, level, namespaceprefix_, namespacedef_='', name_='Expedited', pretty_print=pretty_print) - for NonExpedited_ in self.NonExpedited: - namespaceprefix_ = self.NonExpedited_nsprefix_ + ':' if (UseCapturedNS_ and self.NonExpedited_nsprefix_) else '' - NonExpedited_.export(outfile, level, namespaceprefix_, namespacedef_='', name_='NonExpedited', pretty_print=pretty_print) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'Release' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'Release') - ival_ = self.gds_validate_integer(ival_, node, 'Release') - self.Release = ival_ - self.Release_nsprefix_ = child_.prefix - elif nodeName_ == 'MailClass' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'MailClass') - ival_ = self.gds_validate_integer(ival_, node, 'MailClass') - self.MailClass = ival_ - self.MailClass_nsprefix_ = child_.prefix - elif nodeName_ == 'OriginZIP' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'OriginZIP') - ival_ = self.gds_validate_integer(ival_, node, 'OriginZIP') - self.OriginZIP = ival_ - self.OriginZIP_nsprefix_ = child_.prefix - elif nodeName_ == 'OriginCity': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'OriginCity') - value_ = self.gds_validate_string(value_, node, 'OriginCity') - self.OriginCity = value_ - self.OriginCity_nsprefix_ = child_.prefix - elif nodeName_ == 'OriginState': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'OriginState') - value_ = self.gds_validate_string(value_, node, 'OriginState') - self.OriginState = value_ - self.OriginState_nsprefix_ = child_.prefix - elif nodeName_ == 'DestZIP' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'DestZIP') - ival_ = self.gds_validate_integer(ival_, node, 'DestZIP') - self.DestZIP = ival_ - self.DestZIP_nsprefix_ = child_.prefix - elif nodeName_ == 'DestCity': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'DestCity') - value_ = self.gds_validate_string(value_, node, 'DestCity') - self.DestCity = value_ - self.DestCity_nsprefix_ = child_.prefix - elif nodeName_ == 'DestState': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'DestState') - value_ = self.gds_validate_string(value_, node, 'DestState') - self.DestState = value_ - self.DestState_nsprefix_ = child_.prefix - elif nodeName_ == 'AcceptDate': - sval_ = child_.text - dval_ = self.gds_parse_date(sval_) - self.AcceptDate = dval_ - self.AcceptDate_nsprefix_ = child_.prefix - elif nodeName_ == 'AcceptTime' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'AcceptTime') - ival_ = self.gds_validate_integer(ival_, node, 'AcceptTime') - self.AcceptTime = ival_ - self.AcceptTime_nsprefix_ = child_.prefix - elif nodeName_ == 'Expedited': - obj_ = ExpeditedType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.Expedited = obj_ - obj_.original_tagname_ = 'Expedited' - elif nodeName_ == 'NonExpedited': - obj_ = NonExpeditedType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.NonExpedited.append(obj_) - obj_.original_tagname_ = 'NonExpedited' -# end class SDCGetLocationsResponse - - -class ExpeditedType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, EAD=None, Commitment=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - if isinstance(EAD, BaseStrType_): - initvalue_ = datetime_.datetime.strptime(EAD, '%Y-%m-%d').date() - else: - initvalue_ = EAD - self.EAD = initvalue_ - self.EAD_nsprefix_ = None - if Commitment is None: - self.Commitment = [] - else: - self.Commitment = Commitment - self.Commitment_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, ExpeditedType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if ExpeditedType.subclass: - return ExpeditedType.subclass(*args_, **kwargs_) - else: - return ExpeditedType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_EAD(self): - return self.EAD - def set_EAD(self, EAD): - self.EAD = EAD - def get_Commitment(self): - return self.Commitment - def set_Commitment(self, Commitment): - self.Commitment = Commitment - def add_Commitment(self, value): - self.Commitment.append(value) - def insert_Commitment_at(self, index, value): - self.Commitment.insert(index, value) - def replace_Commitment_at(self, index, value): - self.Commitment[index] = value - def _hasContent(self): - if ( - self.EAD is not None or - self.Commitment - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ExpeditedType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('ExpeditedType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'ExpeditedType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='ExpeditedType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='ExpeditedType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='ExpeditedType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ExpeditedType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.EAD is not None: - namespaceprefix_ = self.EAD_nsprefix_ + ':' if (UseCapturedNS_ and self.EAD_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEAD>%s%s' % (namespaceprefix_ , self.gds_format_date(self.EAD, input_name='EAD'), namespaceprefix_ , eol_)) - for Commitment_ in self.Commitment: - namespaceprefix_ = self.Commitment_nsprefix_ + ':' if (UseCapturedNS_ and self.Commitment_nsprefix_) else '' - Commitment_.export(outfile, level, namespaceprefix_, namespacedef_='', name_='Commitment', pretty_print=pretty_print) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'EAD': - sval_ = child_.text - dval_ = self.gds_parse_date(sval_) - self.EAD = dval_ - self.EAD_nsprefix_ = child_.prefix - elif nodeName_ == 'Commitment': - obj_ = CommitmentType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.Commitment.append(obj_) - obj_.original_tagname_ = 'Commitment' -# end class ExpeditedType - - -class CommitmentType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, MailClass=None, CommitmentName=None, CommitmentTime=None, CommitmentSeq=None, Location=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.MailClass = MailClass - self.MailClass_nsprefix_ = None - self.CommitmentName = CommitmentName - self.CommitmentName_nsprefix_ = None - self.CommitmentTime = CommitmentTime - self.CommitmentTime_nsprefix_ = None - self.CommitmentSeq = CommitmentSeq - self.CommitmentSeq_nsprefix_ = None - if Location is None: - self.Location = [] - else: - self.Location = Location - self.Location_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, CommitmentType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if CommitmentType.subclass: - return CommitmentType.subclass(*args_, **kwargs_) - else: - return CommitmentType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_MailClass(self): - return self.MailClass - def set_MailClass(self, MailClass): - self.MailClass = MailClass - def get_CommitmentName(self): - return self.CommitmentName - def set_CommitmentName(self, CommitmentName): - self.CommitmentName = CommitmentName - def get_CommitmentTime(self): - return self.CommitmentTime - def set_CommitmentTime(self, CommitmentTime): - self.CommitmentTime = CommitmentTime - def get_CommitmentSeq(self): - return self.CommitmentSeq - def set_CommitmentSeq(self, CommitmentSeq): - self.CommitmentSeq = CommitmentSeq - def get_Location(self): - return self.Location - def set_Location(self, Location): - self.Location = Location - def add_Location(self, value): - self.Location.append(value) - def insert_Location_at(self, index, value): - self.Location.insert(index, value) - def replace_Location_at(self, index, value): - self.Location[index] = value - def _hasContent(self): - if ( - self.MailClass is not None or - self.CommitmentName is not None or - self.CommitmentTime is not None or - self.CommitmentSeq is not None or - self.Location - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='CommitmentType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('CommitmentType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'CommitmentType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='CommitmentType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='CommitmentType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='CommitmentType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='CommitmentType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.MailClass is not None: - namespaceprefix_ = self.MailClass_nsprefix_ + ':' if (UseCapturedNS_ and self.MailClass_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sMailClass>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.MailClass, input_name='MailClass'), namespaceprefix_ , eol_)) - if self.CommitmentName is not None: - namespaceprefix_ = self.CommitmentName_nsprefix_ + ':' if (UseCapturedNS_ and self.CommitmentName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCommitmentName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CommitmentName), input_name='CommitmentName')), namespaceprefix_ , eol_)) - if self.CommitmentTime is not None: - namespaceprefix_ = self.CommitmentTime_nsprefix_ + ':' if (UseCapturedNS_ and self.CommitmentTime_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCommitmentTime>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.CommitmentTime, input_name='CommitmentTime'), namespaceprefix_ , eol_)) - if self.CommitmentSeq is not None: - namespaceprefix_ = self.CommitmentSeq_nsprefix_ + ':' if (UseCapturedNS_ and self.CommitmentSeq_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCommitmentSeq>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.CommitmentSeq), input_name='CommitmentSeq')), namespaceprefix_ , eol_)) - for Location_ in self.Location: - namespaceprefix_ = self.Location_nsprefix_ + ':' if (UseCapturedNS_ and self.Location_nsprefix_) else '' - Location_.export(outfile, level, namespaceprefix_, namespacedef_='', name_='Location', pretty_print=pretty_print) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'MailClass' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'MailClass') - ival_ = self.gds_validate_integer(ival_, node, 'MailClass') - self.MailClass = ival_ - self.MailClass_nsprefix_ = child_.prefix - elif nodeName_ == 'CommitmentName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CommitmentName') - value_ = self.gds_validate_string(value_, node, 'CommitmentName') - self.CommitmentName = value_ - self.CommitmentName_nsprefix_ = child_.prefix - elif nodeName_ == 'CommitmentTime' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'CommitmentTime') - ival_ = self.gds_validate_integer(ival_, node, 'CommitmentTime') - self.CommitmentTime = ival_ - self.CommitmentTime_nsprefix_ = child_.prefix - elif nodeName_ == 'CommitmentSeq': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'CommitmentSeq') - value_ = self.gds_validate_string(value_, node, 'CommitmentSeq') - self.CommitmentSeq = value_ - self.CommitmentSeq_nsprefix_ = child_.prefix - elif nodeName_ == 'Location': - obj_ = LocationType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.Location.append(obj_) - obj_.original_tagname_ = 'Location' -# end class CommitmentType - - -class LocationType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, SDD=None, COT=None, FacType=None, Street=None, City=None, State=None, ZIP=None, IsGuaranteed=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - if isinstance(SDD, BaseStrType_): - initvalue_ = datetime_.datetime.strptime(SDD, '%Y-%m-%d').date() - else: - initvalue_ = SDD - self.SDD = initvalue_ - self.SDD_nsprefix_ = None - self.COT = COT - self.COT_nsprefix_ = None - self.FacType = FacType - self.FacType_nsprefix_ = None - self.Street = Street - self.Street_nsprefix_ = None - self.City = City - self.City_nsprefix_ = None - self.State = State - self.State_nsprefix_ = None - self.ZIP = ZIP - self.ZIP_nsprefix_ = None - self.IsGuaranteed = IsGuaranteed - self.IsGuaranteed_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, LocationType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if LocationType.subclass: - return LocationType.subclass(*args_, **kwargs_) - else: - return LocationType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_SDD(self): - return self.SDD - def set_SDD(self, SDD): - self.SDD = SDD - def get_COT(self): - return self.COT - def set_COT(self, COT): - self.COT = COT - def get_FacType(self): - return self.FacType - def set_FacType(self, FacType): - self.FacType = FacType - def get_Street(self): - return self.Street - def set_Street(self, Street): - self.Street = Street - def get_City(self): - return self.City - def set_City(self, City): - self.City = City - def get_State(self): - return self.State - def set_State(self, State): - self.State = State - def get_ZIP(self): - return self.ZIP - def set_ZIP(self, ZIP): - self.ZIP = ZIP - def get_IsGuaranteed(self): - return self.IsGuaranteed - def set_IsGuaranteed(self, IsGuaranteed): - self.IsGuaranteed = IsGuaranteed - def _hasContent(self): - if ( - self.SDD is not None or - self.COT is not None or - self.FacType is not None or - self.Street is not None or - self.City is not None or - self.State is not None or - self.ZIP is not None or - self.IsGuaranteed is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='LocationType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('LocationType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'LocationType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='LocationType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='LocationType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='LocationType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='LocationType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.SDD is not None: - namespaceprefix_ = self.SDD_nsprefix_ + ':' if (UseCapturedNS_ and self.SDD_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSDD>%s%s' % (namespaceprefix_ , self.gds_format_date(self.SDD, input_name='SDD'), namespaceprefix_ , eol_)) - if self.COT is not None: - namespaceprefix_ = self.COT_nsprefix_ + ':' if (UseCapturedNS_ and self.COT_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCOT>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.COT, input_name='COT'), namespaceprefix_ , eol_)) - if self.FacType is not None: - namespaceprefix_ = self.FacType_nsprefix_ + ':' if (UseCapturedNS_ and self.FacType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFacType>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FacType), input_name='FacType')), namespaceprefix_ , eol_)) - if self.Street is not None: - namespaceprefix_ = self.Street_nsprefix_ + ':' if (UseCapturedNS_ and self.Street_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sStreet>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Street), input_name='Street')), namespaceprefix_ , eol_)) - if self.City is not None: - namespaceprefix_ = self.City_nsprefix_ + ':' if (UseCapturedNS_ and self.City_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.City), input_name='City')), namespaceprefix_ , eol_)) - if self.State is not None: - namespaceprefix_ = self.State_nsprefix_ + ':' if (UseCapturedNS_ and self.State_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.State), input_name='State')), namespaceprefix_ , eol_)) - if self.ZIP is not None: - namespaceprefix_ = self.ZIP_nsprefix_ + ':' if (UseCapturedNS_ and self.ZIP_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sZIP>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.ZIP, input_name='ZIP'), namespaceprefix_ , eol_)) - if self.IsGuaranteed is not None: - namespaceprefix_ = self.IsGuaranteed_nsprefix_ + ':' if (UseCapturedNS_ and self.IsGuaranteed_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sIsGuaranteed>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.IsGuaranteed, input_name='IsGuaranteed'), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'SDD': - sval_ = child_.text - dval_ = self.gds_parse_date(sval_) - self.SDD = dval_ - self.SDD_nsprefix_ = child_.prefix - elif nodeName_ == 'COT' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'COT') - ival_ = self.gds_validate_integer(ival_, node, 'COT') - self.COT = ival_ - self.COT_nsprefix_ = child_.prefix - elif nodeName_ == 'FacType': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FacType') - value_ = self.gds_validate_string(value_, node, 'FacType') - self.FacType = value_ - self.FacType_nsprefix_ = child_.prefix - elif nodeName_ == 'Street': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Street') - value_ = self.gds_validate_string(value_, node, 'Street') - self.Street = value_ - self.Street_nsprefix_ = child_.prefix - elif nodeName_ == 'City': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'City') - value_ = self.gds_validate_string(value_, node, 'City') - self.City = value_ - self.City_nsprefix_ = child_.prefix - elif nodeName_ == 'State': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'State') - value_ = self.gds_validate_string(value_, node, 'State') - self.State = value_ - self.State_nsprefix_ = child_.prefix - elif nodeName_ == 'ZIP' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'ZIP') - ival_ = self.gds_validate_integer(ival_, node, 'ZIP') - self.ZIP = ival_ - self.ZIP_nsprefix_ = child_.prefix - elif nodeName_ == 'IsGuaranteed' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'IsGuaranteed') - ival_ = self.gds_validate_integer(ival_, node, 'IsGuaranteed') - self.IsGuaranteed = ival_ - self.IsGuaranteed_nsprefix_ = child_.prefix -# end class LocationType - - -class NonExpeditedType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, MailClass=None, NonExpeditedDestType=None, EAD=None, COT=None, SvcStdMsg=None, SvcStdDays=None, TotDaysDeliver=None, SchedDlvryDate=None, NonDlvryDays=None, NonExpeditedExceptions=None, HFPU=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.MailClass = MailClass - self.MailClass_nsprefix_ = None - self.NonExpeditedDestType = NonExpeditedDestType - self.NonExpeditedDestType_nsprefix_ = None - if isinstance(EAD, BaseStrType_): - initvalue_ = datetime_.datetime.strptime(EAD, '%Y-%m-%d').date() - else: - initvalue_ = EAD - self.EAD = initvalue_ - self.EAD_nsprefix_ = None - self.COT = COT - self.COT_nsprefix_ = None - self.SvcStdMsg = SvcStdMsg - self.SvcStdMsg_nsprefix_ = None - self.SvcStdDays = SvcStdDays - self.SvcStdDays_nsprefix_ = None - self.TotDaysDeliver = TotDaysDeliver - self.TotDaysDeliver_nsprefix_ = None - if isinstance(SchedDlvryDate, BaseStrType_): - initvalue_ = datetime_.datetime.strptime(SchedDlvryDate, '%Y-%m-%d').date() - else: - initvalue_ = SchedDlvryDate - self.SchedDlvryDate = initvalue_ - self.SchedDlvryDate_nsprefix_ = None - self.NonDlvryDays = NonDlvryDays - self.NonDlvryDays_nsprefix_ = None - self.NonExpeditedExceptions = NonExpeditedExceptions - self.NonExpeditedExceptions_nsprefix_ = None - self.HFPU = HFPU - self.HFPU_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, NonExpeditedType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if NonExpeditedType.subclass: - return NonExpeditedType.subclass(*args_, **kwargs_) - else: - return NonExpeditedType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_MailClass(self): - return self.MailClass - def set_MailClass(self, MailClass): - self.MailClass = MailClass - def get_NonExpeditedDestType(self): - return self.NonExpeditedDestType - def set_NonExpeditedDestType(self, NonExpeditedDestType): - self.NonExpeditedDestType = NonExpeditedDestType - def get_EAD(self): - return self.EAD - def set_EAD(self, EAD): - self.EAD = EAD - def get_COT(self): - return self.COT - def set_COT(self, COT): - self.COT = COT - def get_SvcStdMsg(self): - return self.SvcStdMsg - def set_SvcStdMsg(self, SvcStdMsg): - self.SvcStdMsg = SvcStdMsg - def get_SvcStdDays(self): - return self.SvcStdDays - def set_SvcStdDays(self, SvcStdDays): - self.SvcStdDays = SvcStdDays - def get_TotDaysDeliver(self): - return self.TotDaysDeliver - def set_TotDaysDeliver(self, TotDaysDeliver): - self.TotDaysDeliver = TotDaysDeliver - def get_SchedDlvryDate(self): - return self.SchedDlvryDate - def set_SchedDlvryDate(self, SchedDlvryDate): - self.SchedDlvryDate = SchedDlvryDate - def get_NonDlvryDays(self): - return self.NonDlvryDays - def set_NonDlvryDays(self, NonDlvryDays): - self.NonDlvryDays = NonDlvryDays - def get_NonExpeditedExceptions(self): - return self.NonExpeditedExceptions - def set_NonExpeditedExceptions(self, NonExpeditedExceptions): - self.NonExpeditedExceptions = NonExpeditedExceptions - def get_HFPU(self): - return self.HFPU - def set_HFPU(self, HFPU): - self.HFPU = HFPU - def _hasContent(self): - if ( - self.MailClass is not None or - self.NonExpeditedDestType is not None or - self.EAD is not None or - self.COT is not None or - self.SvcStdMsg is not None or - self.SvcStdDays is not None or - self.TotDaysDeliver is not None or - self.SchedDlvryDate is not None or - self.NonDlvryDays is not None or - self.NonExpeditedExceptions is not None or - self.HFPU is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='NonExpeditedType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('NonExpeditedType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'NonExpeditedType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='NonExpeditedType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='NonExpeditedType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='NonExpeditedType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='NonExpeditedType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.MailClass is not None: - namespaceprefix_ = self.MailClass_nsprefix_ + ':' if (UseCapturedNS_ and self.MailClass_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sMailClass>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.MailClass, input_name='MailClass'), namespaceprefix_ , eol_)) - if self.NonExpeditedDestType is not None: - namespaceprefix_ = self.NonExpeditedDestType_nsprefix_ + ':' if (UseCapturedNS_ and self.NonExpeditedDestType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sNonExpeditedDestType>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.NonExpeditedDestType, input_name='NonExpeditedDestType'), namespaceprefix_ , eol_)) - if self.EAD is not None: - namespaceprefix_ = self.EAD_nsprefix_ + ':' if (UseCapturedNS_ and self.EAD_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEAD>%s%s' % (namespaceprefix_ , self.gds_format_date(self.EAD, input_name='EAD'), namespaceprefix_ , eol_)) - if self.COT is not None: - namespaceprefix_ = self.COT_nsprefix_ + ':' if (UseCapturedNS_ and self.COT_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCOT>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.COT, input_name='COT'), namespaceprefix_ , eol_)) - if self.SvcStdMsg is not None: - namespaceprefix_ = self.SvcStdMsg_nsprefix_ + ':' if (UseCapturedNS_ and self.SvcStdMsg_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSvcStdMsg>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SvcStdMsg), input_name='SvcStdMsg')), namespaceprefix_ , eol_)) - if self.SvcStdDays is not None: - namespaceprefix_ = self.SvcStdDays_nsprefix_ + ':' if (UseCapturedNS_ and self.SvcStdDays_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSvcStdDays>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.SvcStdDays, input_name='SvcStdDays'), namespaceprefix_ , eol_)) - if self.TotDaysDeliver is not None: - namespaceprefix_ = self.TotDaysDeliver_nsprefix_ + ':' if (UseCapturedNS_ and self.TotDaysDeliver_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sTotDaysDeliver>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.TotDaysDeliver, input_name='TotDaysDeliver'), namespaceprefix_ , eol_)) - if self.SchedDlvryDate is not None: - namespaceprefix_ = self.SchedDlvryDate_nsprefix_ + ':' if (UseCapturedNS_ and self.SchedDlvryDate_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSchedDlvryDate>%s%s' % (namespaceprefix_ , self.gds_format_date(self.SchedDlvryDate, input_name='SchedDlvryDate'), namespaceprefix_ , eol_)) - if self.NonDlvryDays is not None: - namespaceprefix_ = self.NonDlvryDays_nsprefix_ + ':' if (UseCapturedNS_ and self.NonDlvryDays_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sNonDlvryDays>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.NonDlvryDays, input_name='NonDlvryDays'), namespaceprefix_ , eol_)) - if self.NonExpeditedExceptions is not None: - namespaceprefix_ = self.NonExpeditedExceptions_nsprefix_ + ':' if (UseCapturedNS_ and self.NonExpeditedExceptions_nsprefix_) else '' - self.NonExpeditedExceptions.export(outfile, level, namespaceprefix_, namespacedef_='', name_='NonExpeditedExceptions', pretty_print=pretty_print) - if self.HFPU is not None: - namespaceprefix_ = self.HFPU_nsprefix_ + ':' if (UseCapturedNS_ and self.HFPU_nsprefix_) else '' - self.HFPU.export(outfile, level, namespaceprefix_, namespacedef_='', name_='HFPU', pretty_print=pretty_print) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'MailClass' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'MailClass') - ival_ = self.gds_validate_integer(ival_, node, 'MailClass') - self.MailClass = ival_ - self.MailClass_nsprefix_ = child_.prefix - elif nodeName_ == 'NonExpeditedDestType' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'NonExpeditedDestType') - ival_ = self.gds_validate_integer(ival_, node, 'NonExpeditedDestType') - self.NonExpeditedDestType = ival_ - self.NonExpeditedDestType_nsprefix_ = child_.prefix - elif nodeName_ == 'EAD': - sval_ = child_.text - dval_ = self.gds_parse_date(sval_) - self.EAD = dval_ - self.EAD_nsprefix_ = child_.prefix - elif nodeName_ == 'COT' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'COT') - ival_ = self.gds_validate_integer(ival_, node, 'COT') - self.COT = ival_ - self.COT_nsprefix_ = child_.prefix - elif nodeName_ == 'SvcStdMsg': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SvcStdMsg') - value_ = self.gds_validate_string(value_, node, 'SvcStdMsg') - self.SvcStdMsg = value_ - self.SvcStdMsg_nsprefix_ = child_.prefix - elif nodeName_ == 'SvcStdDays' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'SvcStdDays') - ival_ = self.gds_validate_integer(ival_, node, 'SvcStdDays') - self.SvcStdDays = ival_ - self.SvcStdDays_nsprefix_ = child_.prefix - elif nodeName_ == 'TotDaysDeliver' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'TotDaysDeliver') - ival_ = self.gds_validate_integer(ival_, node, 'TotDaysDeliver') - self.TotDaysDeliver = ival_ - self.TotDaysDeliver_nsprefix_ = child_.prefix - elif nodeName_ == 'SchedDlvryDate': - sval_ = child_.text - dval_ = self.gds_parse_date(sval_) - self.SchedDlvryDate = dval_ - self.SchedDlvryDate_nsprefix_ = child_.prefix - elif nodeName_ == 'NonDlvryDays' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'NonDlvryDays') - ival_ = self.gds_validate_integer(ival_, node, 'NonDlvryDays') - self.NonDlvryDays = ival_ - self.NonDlvryDays_nsprefix_ = child_.prefix - elif nodeName_ == 'NonExpeditedExceptions': - obj_ = NonExpeditedExceptionsType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.NonExpeditedExceptions = obj_ - obj_.original_tagname_ = 'NonExpeditedExceptions' - elif nodeName_ == 'HFPU': - obj_ = HFPUType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.HFPU = obj_ - obj_.original_tagname_ = 'HFPU' -# end class NonExpeditedType - - -class NonExpeditedExceptionsType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, SunHol=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.SunHol = SunHol - self.SunHol_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, NonExpeditedExceptionsType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if NonExpeditedExceptionsType.subclass: - return NonExpeditedExceptionsType.subclass(*args_, **kwargs_) - else: - return NonExpeditedExceptionsType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_SunHol(self): - return self.SunHol - def set_SunHol(self, SunHol): - self.SunHol = SunHol - def _hasContent(self): - if ( - self.SunHol is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='NonExpeditedExceptionsType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('NonExpeditedExceptionsType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'NonExpeditedExceptionsType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='NonExpeditedExceptionsType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='NonExpeditedExceptionsType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='NonExpeditedExceptionsType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='NonExpeditedExceptionsType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.SunHol is not None: - namespaceprefix_ = self.SunHol_nsprefix_ + ':' if (UseCapturedNS_ and self.SunHol_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSunHol>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.SunHol, input_name='SunHol'), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'SunHol' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'SunHol') - ival_ = self.gds_validate_integer(ival_, node, 'SunHol') - self.SunHol = ival_ - self.SunHol_nsprefix_ = child_.prefix -# end class NonExpeditedExceptionsType - - -class HFPUType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, EAD=None, COT=None, ServiceStandard=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - if isinstance(EAD, BaseStrType_): - initvalue_ = datetime_.datetime.strptime(EAD, '%Y-%m-%d').date() - else: - initvalue_ = EAD - self.EAD = initvalue_ - self.EAD_nsprefix_ = None - self.COT = COT - self.COT_nsprefix_ = None - self.ServiceStandard = ServiceStandard - self.ServiceStandard_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, HFPUType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if HFPUType.subclass: - return HFPUType.subclass(*args_, **kwargs_) - else: - return HFPUType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_EAD(self): - return self.EAD - def set_EAD(self, EAD): - self.EAD = EAD - def get_COT(self): - return self.COT - def set_COT(self, COT): - self.COT = COT - def get_ServiceStandard(self): - return self.ServiceStandard - def set_ServiceStandard(self, ServiceStandard): - self.ServiceStandard = ServiceStandard - def _hasContent(self): - if ( - self.EAD is not None or - self.COT is not None or - self.ServiceStandard is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='HFPUType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('HFPUType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'HFPUType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='HFPUType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='HFPUType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='HFPUType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='HFPUType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.EAD is not None: - namespaceprefix_ = self.EAD_nsprefix_ + ':' if (UseCapturedNS_ and self.EAD_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEAD>%s%s' % (namespaceprefix_ , self.gds_format_date(self.EAD, input_name='EAD'), namespaceprefix_ , eol_)) - if self.COT is not None: - namespaceprefix_ = self.COT_nsprefix_ + ':' if (UseCapturedNS_ and self.COT_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCOT>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.COT, input_name='COT'), namespaceprefix_ , eol_)) - if self.ServiceStandard is not None: - namespaceprefix_ = self.ServiceStandard_nsprefix_ + ':' if (UseCapturedNS_ and self.ServiceStandard_nsprefix_) else '' - self.ServiceStandard.export(outfile, level, namespaceprefix_, namespacedef_='', name_='ServiceStandard', pretty_print=pretty_print) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'EAD': - sval_ = child_.text - dval_ = self.gds_parse_date(sval_) - self.EAD = dval_ - self.EAD_nsprefix_ = child_.prefix - elif nodeName_ == 'COT' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'COT') - ival_ = self.gds_validate_integer(ival_, node, 'COT') - self.COT = ival_ - self.COT_nsprefix_ = child_.prefix - elif nodeName_ == 'ServiceStandard': - obj_ = ServiceStandardType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.ServiceStandard = obj_ - obj_.original_tagname_ = 'ServiceStandard' -# end class HFPUType - - -class ServiceStandardType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, SvcStdMsg=None, SvcStdDays=None, Location=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.SvcStdMsg = SvcStdMsg - self.SvcStdMsg_nsprefix_ = None - self.SvcStdDays = SvcStdDays - self.SvcStdDays_nsprefix_ = None - self.Location = Location - self.Location_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, ServiceStandardType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if ServiceStandardType.subclass: - return ServiceStandardType.subclass(*args_, **kwargs_) - else: - return ServiceStandardType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_SvcStdMsg(self): - return self.SvcStdMsg - def set_SvcStdMsg(self, SvcStdMsg): - self.SvcStdMsg = SvcStdMsg - def get_SvcStdDays(self): - return self.SvcStdDays - def set_SvcStdDays(self, SvcStdDays): - self.SvcStdDays = SvcStdDays - def get_Location(self): - return self.Location - def set_Location(self, Location): - self.Location = Location - def _hasContent(self): - if ( - self.SvcStdMsg is not None or - self.SvcStdDays is not None or - self.Location is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ServiceStandardType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('ServiceStandardType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'ServiceStandardType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='ServiceStandardType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='ServiceStandardType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='ServiceStandardType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ServiceStandardType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.SvcStdMsg is not None: - namespaceprefix_ = self.SvcStdMsg_nsprefix_ + ':' if (UseCapturedNS_ and self.SvcStdMsg_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSvcStdMsg>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SvcStdMsg), input_name='SvcStdMsg')), namespaceprefix_ , eol_)) - if self.SvcStdDays is not None: - namespaceprefix_ = self.SvcStdDays_nsprefix_ + ':' if (UseCapturedNS_ and self.SvcStdDays_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSvcStdDays>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.SvcStdDays, input_name='SvcStdDays'), namespaceprefix_ , eol_)) - if self.Location is not None: - namespaceprefix_ = self.Location_nsprefix_ + ':' if (UseCapturedNS_ and self.Location_nsprefix_) else '' - self.Location.export(outfile, level, namespaceprefix_, namespacedef_='', name_='Location', pretty_print=pretty_print) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'SvcStdMsg': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SvcStdMsg') - value_ = self.gds_validate_string(value_, node, 'SvcStdMsg') - self.SvcStdMsg = value_ - self.SvcStdMsg_nsprefix_ = child_.prefix - elif nodeName_ == 'SvcStdDays' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'SvcStdDays') - ival_ = self.gds_validate_integer(ival_, node, 'SvcStdDays') - self.SvcStdDays = ival_ - self.SvcStdDays_nsprefix_ = child_.prefix - elif nodeName_ == 'Location': - obj_ = LocationType1.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.Location = obj_ - obj_.original_tagname_ = 'Location' -# end class ServiceStandardType - - -class LocationType1(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, TotDaysDeliver=None, SchedDlvryDate=None, NonDlvryDays=None, RAUName=None, Street=None, ZIP=None, CloseTimes=None, NonExpeditedExceptions=None, City=None, State=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.TotDaysDeliver = TotDaysDeliver - self.TotDaysDeliver_nsprefix_ = None - if isinstance(SchedDlvryDate, BaseStrType_): - initvalue_ = datetime_.datetime.strptime(SchedDlvryDate, '%Y-%m-%d').date() - else: - initvalue_ = SchedDlvryDate - self.SchedDlvryDate = initvalue_ - self.SchedDlvryDate_nsprefix_ = None - self.NonDlvryDays = NonDlvryDays - self.NonDlvryDays_nsprefix_ = None - self.RAUName = RAUName - self.RAUName_nsprefix_ = None - self.Street = Street - self.Street_nsprefix_ = None - self.ZIP = ZIP - self.ZIP_nsprefix_ = None - self.CloseTimes = CloseTimes - self.CloseTimes_nsprefix_ = None - self.NonExpeditedExceptions = NonExpeditedExceptions - self.NonExpeditedExceptions_nsprefix_ = None - self.City = City - self.City_nsprefix_ = None - self.State = State - self.State_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, LocationType1) - if subclass is not None: - return subclass(*args_, **kwargs_) - if LocationType1.subclass: - return LocationType1.subclass(*args_, **kwargs_) - else: - return LocationType1(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_TotDaysDeliver(self): - return self.TotDaysDeliver - def set_TotDaysDeliver(self, TotDaysDeliver): - self.TotDaysDeliver = TotDaysDeliver - def get_SchedDlvryDate(self): - return self.SchedDlvryDate - def set_SchedDlvryDate(self, SchedDlvryDate): - self.SchedDlvryDate = SchedDlvryDate - def get_NonDlvryDays(self): - return self.NonDlvryDays - def set_NonDlvryDays(self, NonDlvryDays): - self.NonDlvryDays = NonDlvryDays - def get_RAUName(self): - return self.RAUName - def set_RAUName(self, RAUName): - self.RAUName = RAUName - def get_Street(self): - return self.Street - def set_Street(self, Street): - self.Street = Street - def get_ZIP(self): - return self.ZIP - def set_ZIP(self, ZIP): - self.ZIP = ZIP - def get_CloseTimes(self): - return self.CloseTimes - def set_CloseTimes(self, CloseTimes): - self.CloseTimes = CloseTimes - def get_NonExpeditedExceptions(self): - return self.NonExpeditedExceptions - def set_NonExpeditedExceptions(self, NonExpeditedExceptions): - self.NonExpeditedExceptions = NonExpeditedExceptions - def get_City(self): - return self.City - def set_City(self, City): - self.City = City - def get_State(self): - return self.State - def set_State(self, State): - self.State = State - def _hasContent(self): - if ( - self.TotDaysDeliver is not None or - self.SchedDlvryDate is not None or - self.NonDlvryDays is not None or - self.RAUName is not None or - self.Street is not None or - self.ZIP is not None or - self.CloseTimes is not None or - self.NonExpeditedExceptions is not None or - self.City is not None or - self.State is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='LocationType1', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('LocationType1') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'LocationType1': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='LocationType1') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='LocationType1', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='LocationType1'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='LocationType1', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.TotDaysDeliver is not None: - namespaceprefix_ = self.TotDaysDeliver_nsprefix_ + ':' if (UseCapturedNS_ and self.TotDaysDeliver_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sTotDaysDeliver>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.TotDaysDeliver, input_name='TotDaysDeliver'), namespaceprefix_ , eol_)) - if self.SchedDlvryDate is not None: - namespaceprefix_ = self.SchedDlvryDate_nsprefix_ + ':' if (UseCapturedNS_ and self.SchedDlvryDate_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSchedDlvryDate>%s%s' % (namespaceprefix_ , self.gds_format_date(self.SchedDlvryDate, input_name='SchedDlvryDate'), namespaceprefix_ , eol_)) - if self.NonDlvryDays is not None: - namespaceprefix_ = self.NonDlvryDays_nsprefix_ + ':' if (UseCapturedNS_ and self.NonDlvryDays_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sNonDlvryDays>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.NonDlvryDays, input_name='NonDlvryDays'), namespaceprefix_ , eol_)) - if self.RAUName is not None: - namespaceprefix_ = self.RAUName_nsprefix_ + ':' if (UseCapturedNS_ and self.RAUName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRAUName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.RAUName), input_name='RAUName')), namespaceprefix_ , eol_)) - if self.Street is not None: - namespaceprefix_ = self.Street_nsprefix_ + ':' if (UseCapturedNS_ and self.Street_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sStreet>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Street), input_name='Street')), namespaceprefix_ , eol_)) - if self.ZIP is not None: - namespaceprefix_ = self.ZIP_nsprefix_ + ':' if (UseCapturedNS_ and self.ZIP_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sZIP>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.ZIP, input_name='ZIP'), namespaceprefix_ , eol_)) - if self.CloseTimes is not None: - namespaceprefix_ = self.CloseTimes_nsprefix_ + ':' if (UseCapturedNS_ and self.CloseTimes_nsprefix_) else '' - self.CloseTimes.export(outfile, level, namespaceprefix_, namespacedef_='', name_='CloseTimes', pretty_print=pretty_print) - if self.NonExpeditedExceptions is not None: - namespaceprefix_ = self.NonExpeditedExceptions_nsprefix_ + ':' if (UseCapturedNS_ and self.NonExpeditedExceptions_nsprefix_) else '' - self.NonExpeditedExceptions.export(outfile, level, namespaceprefix_, namespacedef_='', name_='NonExpeditedExceptions', pretty_print=pretty_print) - if self.City is not None: - namespaceprefix_ = self.City_nsprefix_ + ':' if (UseCapturedNS_ and self.City_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.City), input_name='City')), namespaceprefix_ , eol_)) - if self.State is not None: - namespaceprefix_ = self.State_nsprefix_ + ':' if (UseCapturedNS_ and self.State_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.State), input_name='State')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'TotDaysDeliver' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'TotDaysDeliver') - ival_ = self.gds_validate_integer(ival_, node, 'TotDaysDeliver') - self.TotDaysDeliver = ival_ - self.TotDaysDeliver_nsprefix_ = child_.prefix - elif nodeName_ == 'SchedDlvryDate': - sval_ = child_.text - dval_ = self.gds_parse_date(sval_) - self.SchedDlvryDate = dval_ - self.SchedDlvryDate_nsprefix_ = child_.prefix - elif nodeName_ == 'NonDlvryDays' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'NonDlvryDays') - ival_ = self.gds_validate_integer(ival_, node, 'NonDlvryDays') - self.NonDlvryDays = ival_ - self.NonDlvryDays_nsprefix_ = child_.prefix - elif nodeName_ == 'RAUName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'RAUName') - value_ = self.gds_validate_string(value_, node, 'RAUName') - self.RAUName = value_ - self.RAUName_nsprefix_ = child_.prefix - elif nodeName_ == 'Street': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Street') - value_ = self.gds_validate_string(value_, node, 'Street') - self.Street = value_ - self.Street_nsprefix_ = child_.prefix - elif nodeName_ == 'ZIP' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'ZIP') - ival_ = self.gds_validate_integer(ival_, node, 'ZIP') - self.ZIP = ival_ - self.ZIP_nsprefix_ = child_.prefix - elif nodeName_ == 'CloseTimes': - obj_ = CloseTimesType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.CloseTimes = obj_ - obj_.original_tagname_ = 'CloseTimes' - elif nodeName_ == 'NonExpeditedExceptions': - obj_ = NonExpeditedExceptionsType2.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.NonExpeditedExceptions = obj_ - obj_.original_tagname_ = 'NonExpeditedExceptions' - elif nodeName_ == 'City': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'City') - value_ = self.gds_validate_string(value_, node, 'City') - self.City = value_ - self.City_nsprefix_ = child_.prefix - elif nodeName_ == 'State': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'State') - value_ = self.gds_validate_string(value_, node, 'State') - self.State = value_ - self.State_nsprefix_ = child_.prefix -# end class LocationType1 - - -class CloseTimesType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, M=None, Tu=None, W=None, Th=None, F=None, Sa=None, Su=None, H=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.M = M - self.M_nsprefix_ = None - self.Tu = Tu - self.Tu_nsprefix_ = None - self.W = W - self.W_nsprefix_ = None - self.Th = Th - self.Th_nsprefix_ = None - self.F = F - self.F_nsprefix_ = None - self.Sa = Sa - self.Sa_nsprefix_ = None - self.Su = Su - self.Su_nsprefix_ = None - self.H = H - self.H_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, CloseTimesType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if CloseTimesType.subclass: - return CloseTimesType.subclass(*args_, **kwargs_) - else: - return CloseTimesType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_M(self): - return self.M - def set_M(self, M): - self.M = M - def get_Tu(self): - return self.Tu - def set_Tu(self, Tu): - self.Tu = Tu - def get_W(self): - return self.W - def set_W(self, W): - self.W = W - def get_Th(self): - return self.Th - def set_Th(self, Th): - self.Th = Th - def get_F(self): - return self.F - def set_F(self, F): - self.F = F - def get_Sa(self): - return self.Sa - def set_Sa(self, Sa): - self.Sa = Sa - def get_Su(self): - return self.Su - def set_Su(self, Su): - self.Su = Su - def get_H(self): - return self.H - def set_H(self, H): - self.H = H - def _hasContent(self): - if ( - self.M is not None or - self.Tu is not None or - self.W is not None or - self.Th is not None or - self.F is not None or - self.Sa is not None or - self.Su is not None or - self.H is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='CloseTimesType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('CloseTimesType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'CloseTimesType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='CloseTimesType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='CloseTimesType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='CloseTimesType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='CloseTimesType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.M is not None: - namespaceprefix_ = self.M_nsprefix_ + ':' if (UseCapturedNS_ and self.M_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sM>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.M, input_name='M'), namespaceprefix_ , eol_)) - if self.Tu is not None: - namespaceprefix_ = self.Tu_nsprefix_ + ':' if (UseCapturedNS_ and self.Tu_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sTu>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.Tu, input_name='Tu'), namespaceprefix_ , eol_)) - if self.W is not None: - namespaceprefix_ = self.W_nsprefix_ + ':' if (UseCapturedNS_ and self.W_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sW>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.W, input_name='W'), namespaceprefix_ , eol_)) - if self.Th is not None: - namespaceprefix_ = self.Th_nsprefix_ + ':' if (UseCapturedNS_ and self.Th_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sTh>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.Th, input_name='Th'), namespaceprefix_ , eol_)) - if self.F is not None: - namespaceprefix_ = self.F_nsprefix_ + ':' if (UseCapturedNS_ and self.F_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sF>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.F, input_name='F'), namespaceprefix_ , eol_)) - if self.Sa is not None: - namespaceprefix_ = self.Sa_nsprefix_ + ':' if (UseCapturedNS_ and self.Sa_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSa>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.Sa, input_name='Sa'), namespaceprefix_ , eol_)) - if self.Su is not None: - namespaceprefix_ = self.Su_nsprefix_ + ':' if (UseCapturedNS_ and self.Su_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSu>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.Su, input_name='Su'), namespaceprefix_ , eol_)) - if self.H is not None: - namespaceprefix_ = self.H_nsprefix_ + ':' if (UseCapturedNS_ and self.H_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sH>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.H, input_name='H'), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'M' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'M') - ival_ = self.gds_validate_integer(ival_, node, 'M') - self.M = ival_ - self.M_nsprefix_ = child_.prefix - elif nodeName_ == 'Tu' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'Tu') - ival_ = self.gds_validate_integer(ival_, node, 'Tu') - self.Tu = ival_ - self.Tu_nsprefix_ = child_.prefix - elif nodeName_ == 'W' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'W') - ival_ = self.gds_validate_integer(ival_, node, 'W') - self.W = ival_ - self.W_nsprefix_ = child_.prefix - elif nodeName_ == 'Th' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'Th') - ival_ = self.gds_validate_integer(ival_, node, 'Th') - self.Th = ival_ - self.Th_nsprefix_ = child_.prefix - elif nodeName_ == 'F' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'F') - ival_ = self.gds_validate_integer(ival_, node, 'F') - self.F = ival_ - self.F_nsprefix_ = child_.prefix - elif nodeName_ == 'Sa' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'Sa') - ival_ = self.gds_validate_integer(ival_, node, 'Sa') - self.Sa = ival_ - self.Sa_nsprefix_ = child_.prefix - elif nodeName_ == 'Su' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'Su') - ival_ = self.gds_validate_integer(ival_, node, 'Su') - self.Su = ival_ - self.Su_nsprefix_ = child_.prefix - elif nodeName_ == 'H' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'H') - ival_ = self.gds_validate_integer(ival_, node, 'H') - self.H = ival_ - self.H_nsprefix_ = child_.prefix -# end class CloseTimesType - - -class NonExpeditedExceptionsType2(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, SunHol=None, Closed=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.SunHol = SunHol - self.SunHol_nsprefix_ = None - self.Closed = Closed - self.Closed_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, NonExpeditedExceptionsType2) - if subclass is not None: - return subclass(*args_, **kwargs_) - if NonExpeditedExceptionsType2.subclass: - return NonExpeditedExceptionsType2.subclass(*args_, **kwargs_) - else: - return NonExpeditedExceptionsType2(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_SunHol(self): - return self.SunHol - def set_SunHol(self, SunHol): - self.SunHol = SunHol - def get_Closed(self): - return self.Closed - def set_Closed(self, Closed): - self.Closed = Closed - def _hasContent(self): - if ( - self.SunHol is not None or - self.Closed is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='NonExpeditedExceptionsType2', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('NonExpeditedExceptionsType2') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'NonExpeditedExceptionsType2': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='NonExpeditedExceptionsType2') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='NonExpeditedExceptionsType2', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='NonExpeditedExceptionsType2'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='NonExpeditedExceptionsType2', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.SunHol is not None: - namespaceprefix_ = self.SunHol_nsprefix_ + ':' if (UseCapturedNS_ and self.SunHol_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSunHol>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.SunHol, input_name='SunHol'), namespaceprefix_ , eol_)) - if self.Closed is not None: - namespaceprefix_ = self.Closed_nsprefix_ + ':' if (UseCapturedNS_ and self.Closed_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sClosed>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.Closed, input_name='Closed'), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'SunHol' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'SunHol') - ival_ = self.gds_validate_integer(ival_, node, 'SunHol') - self.SunHol = ival_ - self.SunHol_nsprefix_ = child_.prefix - elif nodeName_ == 'Closed' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'Closed') - ival_ = self.gds_validate_integer(ival_, node, 'Closed') - self.Closed = ival_ - self.Closed_nsprefix_ = child_.prefix -# end class NonExpeditedExceptionsType2 - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'SDCGetLocationsResponse' - rootClass = SDCGetLocationsResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'SDCGetLocationsResponse' - rootClass = SDCGetLocationsResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'SDCGetLocationsResponse' - rootClass = SDCGetLocationsResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'SDCGetLocationsResponse' - rootClass = SDCGetLocationsResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from sdc_get_locations_response import *\n\n') - sys.stdout.write('import sdc_get_locations_response as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "CloseTimesType", - "CommitmentType", - "ExpeditedType", - "HFPUType", - "LocationType", - "LocationType1", - "NonExpeditedExceptionsType", - "NonExpeditedExceptionsType2", - "NonExpeditedType", - "SDCGetLocationsResponse", - "ServiceStandardType" -] diff --git a/schemas/usps/karrio/schemas/usps/standard_b_request.py b/schemas/usps/karrio/schemas/usps/standard_b_request.py deleted file mode 100644 index 4660946b04..0000000000 --- a/schemas/usps/karrio/schemas/usps/standard_b_request.py +++ /dev/null @@ -1,1362 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:12 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/standard_b_request.py') -# -# Command line arguments: -# ./schemas/StandardBRequest.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/standard_b_request.py" ./schemas/StandardBRequest.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class StandardBRequest(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, USERID=None, OriginZip=None, DestinationZip=None, DestinationType=None, ClientType=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.USERID = _cast(None, USERID) - self.USERID_nsprefix_ = None - self.OriginZip = OriginZip - self.OriginZip_nsprefix_ = None - self.DestinationZip = DestinationZip - self.DestinationZip_nsprefix_ = None - self.DestinationType = DestinationType - self.DestinationType_nsprefix_ = None - self.ClientType = ClientType - self.ClientType_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, StandardBRequest) - if subclass is not None: - return subclass(*args_, **kwargs_) - if StandardBRequest.subclass: - return StandardBRequest.subclass(*args_, **kwargs_) - else: - return StandardBRequest(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_OriginZip(self): - return self.OriginZip - def set_OriginZip(self, OriginZip): - self.OriginZip = OriginZip - def get_DestinationZip(self): - return self.DestinationZip - def set_DestinationZip(self, DestinationZip): - self.DestinationZip = DestinationZip - def get_DestinationType(self): - return self.DestinationType - def set_DestinationType(self, DestinationType): - self.DestinationType = DestinationType - def get_ClientType(self): - return self.ClientType - def set_ClientType(self, ClientType): - self.ClientType = ClientType - def get_USERID(self): - return self.USERID - def set_USERID(self, USERID): - self.USERID = USERID - def _hasContent(self): - if ( - self.OriginZip is not None or - self.DestinationZip is not None or - self.DestinationType is not None or - self.ClientType is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='StandardBRequest', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('StandardBRequest') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'StandardBRequest': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='StandardBRequest') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='StandardBRequest', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='StandardBRequest'): - if self.USERID is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - outfile.write(' USERID=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.USERID), input_name='USERID')), )) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='StandardBRequest', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.OriginZip is not None: - namespaceprefix_ = self.OriginZip_nsprefix_ + ':' if (UseCapturedNS_ and self.OriginZip_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sOriginZip>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.OriginZip, input_name='OriginZip'), namespaceprefix_ , eol_)) - if self.DestinationZip is not None: - namespaceprefix_ = self.DestinationZip_nsprefix_ + ':' if (UseCapturedNS_ and self.DestinationZip_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDestinationZip>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.DestinationZip, input_name='DestinationZip'), namespaceprefix_ , eol_)) - if self.DestinationType is not None: - namespaceprefix_ = self.DestinationType_nsprefix_ + ':' if (UseCapturedNS_ and self.DestinationType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDestinationType>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.DestinationType, input_name='DestinationType'), namespaceprefix_ , eol_)) - if self.ClientType is not None: - namespaceprefix_ = self.ClientType_nsprefix_ + ':' if (UseCapturedNS_ and self.ClientType_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sClientType>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.ClientType, input_name='ClientType'), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('USERID', node) - if value is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - self.USERID = value - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'OriginZip' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'OriginZip') - ival_ = self.gds_validate_integer(ival_, node, 'OriginZip') - self.OriginZip = ival_ - self.OriginZip_nsprefix_ = child_.prefix - elif nodeName_ == 'DestinationZip' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'DestinationZip') - ival_ = self.gds_validate_integer(ival_, node, 'DestinationZip') - self.DestinationZip = ival_ - self.DestinationZip_nsprefix_ = child_.prefix - elif nodeName_ == 'DestinationType' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'DestinationType') - ival_ = self.gds_validate_integer(ival_, node, 'DestinationType') - self.DestinationType = ival_ - self.DestinationType_nsprefix_ = child_.prefix - elif nodeName_ == 'ClientType' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'ClientType') - ival_ = self.gds_validate_integer(ival_, node, 'ClientType') - self.ClientType = ival_ - self.ClientType_nsprefix_ = child_.prefix -# end class StandardBRequest - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'StandardBRequest' - rootClass = StandardBRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'StandardBRequest' - rootClass = StandardBRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'StandardBRequest' - rootClass = StandardBRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'StandardBRequest' - rootClass = StandardBRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from standard_b_request import *\n\n') - sys.stdout.write('import standard_b_request as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "StandardBRequest" -] diff --git a/schemas/usps/karrio/schemas/usps/standard_b_response.py b/schemas/usps/karrio/schemas/usps/standard_b_response.py deleted file mode 100644 index 5b59ebec6f..0000000000 --- a/schemas/usps/karrio/schemas/usps/standard_b_response.py +++ /dev/null @@ -1,1385 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:12 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/standard_b_response.py') -# -# Command line arguments: -# ./schemas/StandardBResponse.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/standard_b_response.py" ./schemas/StandardBResponse.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class StandardBResponse(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, OriginZip=None, DestinationZip=None, Days=None, Message=None, EffectiveAcceptanceDate=None, ScheduledDeliveryDate=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.OriginZip = OriginZip - self.OriginZip_nsprefix_ = None - self.DestinationZip = DestinationZip - self.DestinationZip_nsprefix_ = None - self.Days = Days - self.Days_nsprefix_ = None - self.Message = Message - self.Message_nsprefix_ = None - self.EffectiveAcceptanceDate = EffectiveAcceptanceDate - self.EffectiveAcceptanceDate_nsprefix_ = None - self.ScheduledDeliveryDate = ScheduledDeliveryDate - self.ScheduledDeliveryDate_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, StandardBResponse) - if subclass is not None: - return subclass(*args_, **kwargs_) - if StandardBResponse.subclass: - return StandardBResponse.subclass(*args_, **kwargs_) - else: - return StandardBResponse(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_OriginZip(self): - return self.OriginZip - def set_OriginZip(self, OriginZip): - self.OriginZip = OriginZip - def get_DestinationZip(self): - return self.DestinationZip - def set_DestinationZip(self, DestinationZip): - self.DestinationZip = DestinationZip - def get_Days(self): - return self.Days - def set_Days(self, Days): - self.Days = Days - def get_Message(self): - return self.Message - def set_Message(self, Message): - self.Message = Message - def get_EffectiveAcceptanceDate(self): - return self.EffectiveAcceptanceDate - def set_EffectiveAcceptanceDate(self, EffectiveAcceptanceDate): - self.EffectiveAcceptanceDate = EffectiveAcceptanceDate - def get_ScheduledDeliveryDate(self): - return self.ScheduledDeliveryDate - def set_ScheduledDeliveryDate(self, ScheduledDeliveryDate): - self.ScheduledDeliveryDate = ScheduledDeliveryDate - def _hasContent(self): - if ( - self.OriginZip is not None or - self.DestinationZip is not None or - self.Days is not None or - self.Message is not None or - self.EffectiveAcceptanceDate is not None or - self.ScheduledDeliveryDate is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='StandardBResponse', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('StandardBResponse') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'StandardBResponse': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='StandardBResponse') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='StandardBResponse', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='StandardBResponse'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='StandardBResponse', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.OriginZip is not None: - namespaceprefix_ = self.OriginZip_nsprefix_ + ':' if (UseCapturedNS_ and self.OriginZip_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sOriginZip>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.OriginZip, input_name='OriginZip'), namespaceprefix_ , eol_)) - if self.DestinationZip is not None: - namespaceprefix_ = self.DestinationZip_nsprefix_ + ':' if (UseCapturedNS_ and self.DestinationZip_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDestinationZip>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.DestinationZip, input_name='DestinationZip'), namespaceprefix_ , eol_)) - if self.Days is not None: - namespaceprefix_ = self.Days_nsprefix_ + ':' if (UseCapturedNS_ and self.Days_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDays>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.Days, input_name='Days'), namespaceprefix_ , eol_)) - if self.Message is not None: - namespaceprefix_ = self.Message_nsprefix_ + ':' if (UseCapturedNS_ and self.Message_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sMessage>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Message), input_name='Message')), namespaceprefix_ , eol_)) - if self.EffectiveAcceptanceDate is not None: - namespaceprefix_ = self.EffectiveAcceptanceDate_nsprefix_ + ':' if (UseCapturedNS_ and self.EffectiveAcceptanceDate_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEffectiveAcceptanceDate>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.EffectiveAcceptanceDate), input_name='EffectiveAcceptanceDate')), namespaceprefix_ , eol_)) - if self.ScheduledDeliveryDate is not None: - namespaceprefix_ = self.ScheduledDeliveryDate_nsprefix_ + ':' if (UseCapturedNS_ and self.ScheduledDeliveryDate_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sScheduledDeliveryDate>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ScheduledDeliveryDate), input_name='ScheduledDeliveryDate')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'OriginZip' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'OriginZip') - ival_ = self.gds_validate_integer(ival_, node, 'OriginZip') - self.OriginZip = ival_ - self.OriginZip_nsprefix_ = child_.prefix - elif nodeName_ == 'DestinationZip' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'DestinationZip') - ival_ = self.gds_validate_integer(ival_, node, 'DestinationZip') - self.DestinationZip = ival_ - self.DestinationZip_nsprefix_ = child_.prefix - elif nodeName_ == 'Days' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'Days') - ival_ = self.gds_validate_integer(ival_, node, 'Days') - self.Days = ival_ - self.Days_nsprefix_ = child_.prefix - elif nodeName_ == 'Message': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Message') - value_ = self.gds_validate_string(value_, node, 'Message') - self.Message = value_ - self.Message_nsprefix_ = child_.prefix - elif nodeName_ == 'EffectiveAcceptanceDate': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'EffectiveAcceptanceDate') - value_ = self.gds_validate_string(value_, node, 'EffectiveAcceptanceDate') - self.EffectiveAcceptanceDate = value_ - self.EffectiveAcceptanceDate_nsprefix_ = child_.prefix - elif nodeName_ == 'ScheduledDeliveryDate': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ScheduledDeliveryDate') - value_ = self.gds_validate_string(value_, node, 'ScheduledDeliveryDate') - self.ScheduledDeliveryDate = value_ - self.ScheduledDeliveryDate_nsprefix_ = child_.prefix -# end class StandardBResponse - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'StandardBResponse' - rootClass = StandardBResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'StandardBResponse' - rootClass = StandardBResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'StandardBResponse' - rootClass = StandardBResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'StandardBResponse' - rootClass = StandardBResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from standard_b_response import *\n\n') - sys.stdout.write('import standard_b_response as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "StandardBResponse" -] diff --git a/schemas/usps/karrio/schemas/usps/track_field_request.py b/schemas/usps/karrio/schemas/usps/track_field_request.py deleted file mode 100644 index 87bb6ced86..0000000000 --- a/schemas/usps/karrio/schemas/usps/track_field_request.py +++ /dev/null @@ -1,1496 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:12 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/track_field_request.py') -# -# Command line arguments: -# ./schemas/TrackFieldRequest.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/track_field_request.py" ./schemas/TrackFieldRequest.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class TrackFieldRequest(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, USERID=None, Revision=None, ClientIp=None, SourceId=None, TrackID=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.USERID = _cast(None, USERID) - self.USERID_nsprefix_ = None - self.Revision = Revision - self.Revision_nsprefix_ = None - self.ClientIp = ClientIp - self.ClientIp_nsprefix_ = None - self.SourceId = SourceId - self.SourceId_nsprefix_ = None - if TrackID is None: - self.TrackID = [] - else: - self.TrackID = TrackID - self.TrackID_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, TrackFieldRequest) - if subclass is not None: - return subclass(*args_, **kwargs_) - if TrackFieldRequest.subclass: - return TrackFieldRequest.subclass(*args_, **kwargs_) - else: - return TrackFieldRequest(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_Revision(self): - return self.Revision - def set_Revision(self, Revision): - self.Revision = Revision - def get_ClientIp(self): - return self.ClientIp - def set_ClientIp(self, ClientIp): - self.ClientIp = ClientIp - def get_SourceId(self): - return self.SourceId - def set_SourceId(self, SourceId): - self.SourceId = SourceId - def get_TrackID(self): - return self.TrackID - def set_TrackID(self, TrackID): - self.TrackID = TrackID - def add_TrackID(self, value): - self.TrackID.append(value) - def insert_TrackID_at(self, index, value): - self.TrackID.insert(index, value) - def replace_TrackID_at(self, index, value): - self.TrackID[index] = value - def get_USERID(self): - return self.USERID - def set_USERID(self, USERID): - self.USERID = USERID - def _hasContent(self): - if ( - self.Revision is not None or - self.ClientIp is not None or - self.SourceId is not None or - self.TrackID - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='TrackFieldRequest', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('TrackFieldRequest') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'TrackFieldRequest': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='TrackFieldRequest') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='TrackFieldRequest', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='TrackFieldRequest'): - if self.USERID is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - outfile.write(' USERID=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.USERID), input_name='USERID')), )) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='TrackFieldRequest', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.Revision is not None: - namespaceprefix_ = self.Revision_nsprefix_ + ':' if (UseCapturedNS_ and self.Revision_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRevision>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Revision), input_name='Revision')), namespaceprefix_ , eol_)) - if self.ClientIp is not None: - namespaceprefix_ = self.ClientIp_nsprefix_ + ':' if (UseCapturedNS_ and self.ClientIp_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sClientIp>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ClientIp), input_name='ClientIp')), namespaceprefix_ , eol_)) - if self.SourceId is not None: - namespaceprefix_ = self.SourceId_nsprefix_ + ':' if (UseCapturedNS_ and self.SourceId_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sSourceId>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.SourceId), input_name='SourceId')), namespaceprefix_ , eol_)) - for TrackID_ in self.TrackID: - namespaceprefix_ = self.TrackID_nsprefix_ + ':' if (UseCapturedNS_ and self.TrackID_nsprefix_) else '' - TrackID_.export(outfile, level, namespaceprefix_, namespacedef_='', name_='TrackID', pretty_print=pretty_print) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('USERID', node) - if value is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - self.USERID = value - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'Revision': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Revision') - value_ = self.gds_validate_string(value_, node, 'Revision') - self.Revision = value_ - self.Revision_nsprefix_ = child_.prefix - elif nodeName_ == 'ClientIp': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ClientIp') - value_ = self.gds_validate_string(value_, node, 'ClientIp') - self.ClientIp = value_ - self.ClientIp_nsprefix_ = child_.prefix - elif nodeName_ == 'SourceId': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'SourceId') - value_ = self.gds_validate_string(value_, node, 'SourceId') - self.SourceId = value_ - self.SourceId_nsprefix_ = child_.prefix - elif nodeName_ == 'TrackID': - obj_ = TrackIDType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.TrackID.append(obj_) - obj_.original_tagname_ = 'TrackID' -# end class TrackFieldRequest - - -class TrackIDType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ID=None, DestinationZipCode=None, MailingDate=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.ID = _cast(None, ID) - self.ID_nsprefix_ = None - self.DestinationZipCode = DestinationZipCode - self.DestinationZipCode_nsprefix_ = None - if isinstance(MailingDate, BaseStrType_): - initvalue_ = datetime_.datetime.strptime(MailingDate, '%Y-%m-%d').date() - else: - initvalue_ = MailingDate - self.MailingDate = initvalue_ - self.MailingDate_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, TrackIDType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if TrackIDType.subclass: - return TrackIDType.subclass(*args_, **kwargs_) - else: - return TrackIDType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_DestinationZipCode(self): - return self.DestinationZipCode - def set_DestinationZipCode(self, DestinationZipCode): - self.DestinationZipCode = DestinationZipCode - def get_MailingDate(self): - return self.MailingDate - def set_MailingDate(self, MailingDate): - self.MailingDate = MailingDate - def get_ID(self): - return self.ID - def set_ID(self, ID): - self.ID = ID - def _hasContent(self): - if ( - self.DestinationZipCode is not None or - self.MailingDate is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='TrackIDType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('TrackIDType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'TrackIDType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='TrackIDType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='TrackIDType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='TrackIDType'): - if self.ID is not None and 'ID' not in already_processed: - already_processed.add('ID') - outfile.write(' ID=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.ID), input_name='ID')), )) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='TrackIDType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.DestinationZipCode is not None: - namespaceprefix_ = self.DestinationZipCode_nsprefix_ + ':' if (UseCapturedNS_ and self.DestinationZipCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDestinationZipCode>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.DestinationZipCode, input_name='DestinationZipCode'), namespaceprefix_ , eol_)) - if self.MailingDate is not None: - namespaceprefix_ = self.MailingDate_nsprefix_ + ':' if (UseCapturedNS_ and self.MailingDate_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sMailingDate>%s%s' % (namespaceprefix_ , self.gds_format_date(self.MailingDate, input_name='MailingDate'), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('ID', node) - if value is not None and 'ID' not in already_processed: - already_processed.add('ID') - self.ID = value - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'DestinationZipCode' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'DestinationZipCode') - ival_ = self.gds_validate_integer(ival_, node, 'DestinationZipCode') - self.DestinationZipCode = ival_ - self.DestinationZipCode_nsprefix_ = child_.prefix - elif nodeName_ == 'MailingDate': - sval_ = child_.text - dval_ = self.gds_parse_date(sval_) - self.MailingDate = dval_ - self.MailingDate_nsprefix_ = child_.prefix -# end class TrackIDType - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'TrackFieldRequest' - rootClass = TrackFieldRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'TrackFieldRequest' - rootClass = TrackFieldRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'TrackFieldRequest' - rootClass = TrackFieldRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'TrackFieldRequest' - rootClass = TrackFieldRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from track_field_request import *\n\n') - sys.stdout.write('import track_field_request as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "TrackFieldRequest", - "TrackIDType" -] diff --git a/schemas/usps/karrio/schemas/usps/track_request.py b/schemas/usps/karrio/schemas/usps/track_request.py deleted file mode 100644 index 113d4a97ff..0000000000 --- a/schemas/usps/karrio/schemas/usps/track_request.py +++ /dev/null @@ -1,1411 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:12 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/track_request.py') -# -# Command line arguments: -# ./schemas/TrackRequest.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/track_request.py" ./schemas/TrackRequest.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class TrackRequest(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, USERID=None, TrackID=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.USERID = _cast(None, USERID) - self.USERID_nsprefix_ = None - if TrackID is None: - self.TrackID = [] - else: - self.TrackID = TrackID - self.TrackID_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, TrackRequest) - if subclass is not None: - return subclass(*args_, **kwargs_) - if TrackRequest.subclass: - return TrackRequest.subclass(*args_, **kwargs_) - else: - return TrackRequest(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_TrackID(self): - return self.TrackID - def set_TrackID(self, TrackID): - self.TrackID = TrackID - def add_TrackID(self, value): - self.TrackID.append(value) - def insert_TrackID_at(self, index, value): - self.TrackID.insert(index, value) - def replace_TrackID_at(self, index, value): - self.TrackID[index] = value - def get_USERID(self): - return self.USERID - def set_USERID(self, USERID): - self.USERID = USERID - def _hasContent(self): - if ( - self.TrackID - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='TrackRequest', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('TrackRequest') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'TrackRequest': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='TrackRequest') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='TrackRequest', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='TrackRequest'): - if self.USERID is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - outfile.write(' USERID=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.USERID), input_name='USERID')), )) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='TrackRequest', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - for TrackID_ in self.TrackID: - namespaceprefix_ = self.TrackID_nsprefix_ + ':' if (UseCapturedNS_ and self.TrackID_nsprefix_) else '' - TrackID_.export(outfile, level, namespaceprefix_, namespacedef_='', name_='TrackID', pretty_print=pretty_print) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('USERID', node) - if value is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - self.USERID = value - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'TrackID': - obj_ = TrackIDType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.TrackID.append(obj_) - obj_.original_tagname_ = 'TrackID' -# end class TrackRequest - - -class TrackIDType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ID=None, valueOf_=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.ID = _cast(None, ID) - self.ID_nsprefix_ = None - self.valueOf_ = valueOf_ - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, TrackIDType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if TrackIDType.subclass: - return TrackIDType.subclass(*args_, **kwargs_) - else: - return TrackIDType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_ID(self): - return self.ID - def set_ID(self, ID): - self.ID = ID - def get_valueOf_(self): return self.valueOf_ - def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_ - def _hasContent(self): - if ( - (1 if type(self.valueOf_) in [int,float] else self.valueOf_) - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='TrackIDType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('TrackIDType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'TrackIDType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='TrackIDType') - if self._hasContent(): - outfile.write('>') - outfile.write(self.convert_unicode(self.valueOf_)) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='TrackIDType', pretty_print=pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='TrackIDType'): - if self.ID is not None and 'ID' not in already_processed: - already_processed.add('ID') - outfile.write(' ID=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.ID), input_name='ID')), )) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='TrackIDType', fromsubclass_=False, pretty_print=True): - pass - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - self.valueOf_ = get_all_text_(node) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('ID', node) - if value is not None and 'ID' not in already_processed: - already_processed.add('ID') - self.ID = value - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - pass -# end class TrackIDType - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'TrackRequest' - rootClass = TrackRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'TrackRequest' - rootClass = TrackRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'TrackRequest' - rootClass = TrackRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'TrackRequest' - rootClass = TrackRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from track_request import *\n\n') - sys.stdout.write('import track_request as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "TrackIDType", - "TrackRequest" -] diff --git a/schemas/usps/karrio/schemas/usps/track_response.py b/schemas/usps/karrio/schemas/usps/track_response.py deleted file mode 100644 index e9af3d8bc3..0000000000 --- a/schemas/usps/karrio/schemas/usps/track_response.py +++ /dev/null @@ -1,3338 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:13 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/track_response.py') -# -# Command line arguments: -# ./schemas/TrackResponse.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/track_response.py" ./schemas/TrackResponse.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class TrackResponse(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, TrackInfo=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - if TrackInfo is None: - self.TrackInfo = [] - else: - self.TrackInfo = TrackInfo - self.TrackInfo_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, TrackResponse) - if subclass is not None: - return subclass(*args_, **kwargs_) - if TrackResponse.subclass: - return TrackResponse.subclass(*args_, **kwargs_) - else: - return TrackResponse(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_TrackInfo(self): - return self.TrackInfo - def set_TrackInfo(self, TrackInfo): - self.TrackInfo = TrackInfo - def add_TrackInfo(self, value): - self.TrackInfo.append(value) - def insert_TrackInfo_at(self, index, value): - self.TrackInfo.insert(index, value) - def replace_TrackInfo_at(self, index, value): - self.TrackInfo[index] = value - def _hasContent(self): - if ( - self.TrackInfo - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='TrackResponse', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('TrackResponse') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'TrackResponse': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='TrackResponse') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='TrackResponse', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='TrackResponse'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='TrackResponse', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - for TrackInfo_ in self.TrackInfo: - namespaceprefix_ = self.TrackInfo_nsprefix_ + ':' if (UseCapturedNS_ and self.TrackInfo_nsprefix_) else '' - TrackInfo_.export(outfile, level, namespaceprefix_, namespacedef_='', name_='TrackInfo', pretty_print=pretty_print) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'TrackInfo': - obj_ = TrackInfoType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.TrackInfo.append(obj_) - obj_.original_tagname_ = 'TrackInfo' -# end class TrackResponse - - -class TrackInfoType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ID=None, AdditionalInfo=None, ADPScripting=None, ARCHDATA=None, ArchiveRestoreInfo=None, AssociatedLabel=None, Class=None, ClassOfMailCode=None, DeliveryNotificationDate=None, DestinationCity=None, DestinationCountryCode=None, DestinationState=None, DestinationZip=None, EditedLabelID=None, EmailEnabled=None, ExpectedDeliveryDate=None, ExpectedDeliveryTime=None, GuaranteedDeliveryDate=None, GuaranteedDeliveryTime=None, GuaranteedDetails=None, KahalaIndicator=None, MailTypeCode=None, MPDATE=None, MPSUFFIX=None, OriginCity=None, OriginCountryCode=None, OriginState=None, OriginZip=None, PodEnabled=None, PredictedDeliveryDate=None, PredictedDeliveryTime=None, PDWStart=None, PDWEnd=None, RelatedRRID=None, RestoreEnabled=None, RRAMenabled=None, RreEnabled=None, Service=None, ServiceTypeCode=None, Status=None, StatusCategory=None, StatusSummary=None, TABLECODE=None, TpodEnabled=None, ValueofArticle=None, EnabledNotificationRequests=None, TrackSummary=None, TrackDetail=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.ID = _cast(None, ID) - self.ID_nsprefix_ = None - self.AdditionalInfo = AdditionalInfo - self.AdditionalInfo_nsprefix_ = None - self.ADPScripting = ADPScripting - self.ADPScripting_nsprefix_ = None - self.ARCHDATA = ARCHDATA - self.ARCHDATA_nsprefix_ = None - self.ArchiveRestoreInfo = ArchiveRestoreInfo - self.ArchiveRestoreInfo_nsprefix_ = None - self.AssociatedLabel = AssociatedLabel - self.AssociatedLabel_nsprefix_ = None - self.Class = Class - self.Class_nsprefix_ = None - self.ClassOfMailCode = ClassOfMailCode - self.ClassOfMailCode_nsprefix_ = None - self.DeliveryNotificationDate = DeliveryNotificationDate - self.DeliveryNotificationDate_nsprefix_ = None - self.DestinationCity = DestinationCity - self.DestinationCity_nsprefix_ = None - self.DestinationCountryCode = DestinationCountryCode - self.DestinationCountryCode_nsprefix_ = None - self.DestinationState = DestinationState - self.DestinationState_nsprefix_ = None - self.DestinationZip = DestinationZip - self.DestinationZip_nsprefix_ = None - self.EditedLabelID = EditedLabelID - self.EditedLabelID_nsprefix_ = None - self.EmailEnabled = EmailEnabled - self.EmailEnabled_nsprefix_ = None - self.ExpectedDeliveryDate = ExpectedDeliveryDate - self.ExpectedDeliveryDate_nsprefix_ = None - self.ExpectedDeliveryTime = ExpectedDeliveryTime - self.ExpectedDeliveryTime_nsprefix_ = None - self.GuaranteedDeliveryDate = GuaranteedDeliveryDate - self.GuaranteedDeliveryDate_nsprefix_ = None - self.GuaranteedDeliveryTime = GuaranteedDeliveryTime - self.GuaranteedDeliveryTime_nsprefix_ = None - self.GuaranteedDetails = GuaranteedDetails - self.GuaranteedDetails_nsprefix_ = None - self.KahalaIndicator = KahalaIndicator - self.KahalaIndicator_nsprefix_ = None - self.MailTypeCode = MailTypeCode - self.MailTypeCode_nsprefix_ = None - self.MPDATE = MPDATE - self.MPDATE_nsprefix_ = None - self.MPSUFFIX = MPSUFFIX - self.MPSUFFIX_nsprefix_ = None - self.OriginCity = OriginCity - self.OriginCity_nsprefix_ = None - self.OriginCountryCode = OriginCountryCode - self.OriginCountryCode_nsprefix_ = None - self.OriginState = OriginState - self.OriginState_nsprefix_ = None - self.OriginZip = OriginZip - self.OriginZip_nsprefix_ = None - self.PodEnabled = PodEnabled - self.PodEnabled_nsprefix_ = None - self.PredictedDeliveryDate = PredictedDeliveryDate - self.PredictedDeliveryDate_nsprefix_ = None - self.PredictedDeliveryTime = PredictedDeliveryTime - self.PredictedDeliveryTime_nsprefix_ = None - self.PDWStart = PDWStart - self.PDWStart_nsprefix_ = None - self.PDWEnd = PDWEnd - self.PDWEnd_nsprefix_ = None - self.RelatedRRID = RelatedRRID - self.RelatedRRID_nsprefix_ = None - self.RestoreEnabled = RestoreEnabled - self.RestoreEnabled_nsprefix_ = None - self.RRAMenabled = RRAMenabled - self.RRAMenabled_nsprefix_ = None - self.RreEnabled = RreEnabled - self.RreEnabled_nsprefix_ = None - self.Service = Service - self.Service_nsprefix_ = None - self.ServiceTypeCode = ServiceTypeCode - self.ServiceTypeCode_nsprefix_ = None - self.Status = Status - self.Status_nsprefix_ = None - self.StatusCategory = StatusCategory - self.StatusCategory_nsprefix_ = None - self.StatusSummary = StatusSummary - self.StatusSummary_nsprefix_ = None - self.TABLECODE = TABLECODE - self.TABLECODE_nsprefix_ = None - self.TpodEnabled = TpodEnabled - self.TpodEnabled_nsprefix_ = None - self.ValueofArticle = ValueofArticle - self.ValueofArticle_nsprefix_ = None - self.EnabledNotificationRequests = EnabledNotificationRequests - self.EnabledNotificationRequests_nsprefix_ = None - self.TrackSummary = TrackSummary - self.TrackSummary_nsprefix_ = None - if TrackDetail is None: - self.TrackDetail = [] - else: - self.TrackDetail = TrackDetail - self.TrackDetail_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, TrackInfoType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if TrackInfoType.subclass: - return TrackInfoType.subclass(*args_, **kwargs_) - else: - return TrackInfoType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_AdditionalInfo(self): - return self.AdditionalInfo - def set_AdditionalInfo(self, AdditionalInfo): - self.AdditionalInfo = AdditionalInfo - def get_ADPScripting(self): - return self.ADPScripting - def set_ADPScripting(self, ADPScripting): - self.ADPScripting = ADPScripting - def get_ARCHDATA(self): - return self.ARCHDATA - def set_ARCHDATA(self, ARCHDATA): - self.ARCHDATA = ARCHDATA - def get_ArchiveRestoreInfo(self): - return self.ArchiveRestoreInfo - def set_ArchiveRestoreInfo(self, ArchiveRestoreInfo): - self.ArchiveRestoreInfo = ArchiveRestoreInfo - def get_AssociatedLabel(self): - return self.AssociatedLabel - def set_AssociatedLabel(self, AssociatedLabel): - self.AssociatedLabel = AssociatedLabel - def get_Class(self): - return self.Class - def set_Class(self, Class): - self.Class = Class - def get_ClassOfMailCode(self): - return self.ClassOfMailCode - def set_ClassOfMailCode(self, ClassOfMailCode): - self.ClassOfMailCode = ClassOfMailCode - def get_DeliveryNotificationDate(self): - return self.DeliveryNotificationDate - def set_DeliveryNotificationDate(self, DeliveryNotificationDate): - self.DeliveryNotificationDate = DeliveryNotificationDate - def get_DestinationCity(self): - return self.DestinationCity - def set_DestinationCity(self, DestinationCity): - self.DestinationCity = DestinationCity - def get_DestinationCountryCode(self): - return self.DestinationCountryCode - def set_DestinationCountryCode(self, DestinationCountryCode): - self.DestinationCountryCode = DestinationCountryCode - def get_DestinationState(self): - return self.DestinationState - def set_DestinationState(self, DestinationState): - self.DestinationState = DestinationState - def get_DestinationZip(self): - return self.DestinationZip - def set_DestinationZip(self, DestinationZip): - self.DestinationZip = DestinationZip - def get_EditedLabelID(self): - return self.EditedLabelID - def set_EditedLabelID(self, EditedLabelID): - self.EditedLabelID = EditedLabelID - def get_EmailEnabled(self): - return self.EmailEnabled - def set_EmailEnabled(self, EmailEnabled): - self.EmailEnabled = EmailEnabled - def get_ExpectedDeliveryDate(self): - return self.ExpectedDeliveryDate - def set_ExpectedDeliveryDate(self, ExpectedDeliveryDate): - self.ExpectedDeliveryDate = ExpectedDeliveryDate - def get_ExpectedDeliveryTime(self): - return self.ExpectedDeliveryTime - def set_ExpectedDeliveryTime(self, ExpectedDeliveryTime): - self.ExpectedDeliveryTime = ExpectedDeliveryTime - def get_GuaranteedDeliveryDate(self): - return self.GuaranteedDeliveryDate - def set_GuaranteedDeliveryDate(self, GuaranteedDeliveryDate): - self.GuaranteedDeliveryDate = GuaranteedDeliveryDate - def get_GuaranteedDeliveryTime(self): - return self.GuaranteedDeliveryTime - def set_GuaranteedDeliveryTime(self, GuaranteedDeliveryTime): - self.GuaranteedDeliveryTime = GuaranteedDeliveryTime - def get_GuaranteedDetails(self): - return self.GuaranteedDetails - def set_GuaranteedDetails(self, GuaranteedDetails): - self.GuaranteedDetails = GuaranteedDetails - def get_KahalaIndicator(self): - return self.KahalaIndicator - def set_KahalaIndicator(self, KahalaIndicator): - self.KahalaIndicator = KahalaIndicator - def get_MailTypeCode(self): - return self.MailTypeCode - def set_MailTypeCode(self, MailTypeCode): - self.MailTypeCode = MailTypeCode - def get_MPDATE(self): - return self.MPDATE - def set_MPDATE(self, MPDATE): - self.MPDATE = MPDATE - def get_MPSUFFIX(self): - return self.MPSUFFIX - def set_MPSUFFIX(self, MPSUFFIX): - self.MPSUFFIX = MPSUFFIX - def get_OriginCity(self): - return self.OriginCity - def set_OriginCity(self, OriginCity): - self.OriginCity = OriginCity - def get_OriginCountryCode(self): - return self.OriginCountryCode - def set_OriginCountryCode(self, OriginCountryCode): - self.OriginCountryCode = OriginCountryCode - def get_OriginState(self): - return self.OriginState - def set_OriginState(self, OriginState): - self.OriginState = OriginState - def get_OriginZip(self): - return self.OriginZip - def set_OriginZip(self, OriginZip): - self.OriginZip = OriginZip - def get_PodEnabled(self): - return self.PodEnabled - def set_PodEnabled(self, PodEnabled): - self.PodEnabled = PodEnabled - def get_PredictedDeliveryDate(self): - return self.PredictedDeliveryDate - def set_PredictedDeliveryDate(self, PredictedDeliveryDate): - self.PredictedDeliveryDate = PredictedDeliveryDate - def get_PredictedDeliveryTime(self): - return self.PredictedDeliveryTime - def set_PredictedDeliveryTime(self, PredictedDeliveryTime): - self.PredictedDeliveryTime = PredictedDeliveryTime - def get_PDWStart(self): - return self.PDWStart - def set_PDWStart(self, PDWStart): - self.PDWStart = PDWStart - def get_PDWEnd(self): - return self.PDWEnd - def set_PDWEnd(self, PDWEnd): - self.PDWEnd = PDWEnd - def get_RelatedRRID(self): - return self.RelatedRRID - def set_RelatedRRID(self, RelatedRRID): - self.RelatedRRID = RelatedRRID - def get_RestoreEnabled(self): - return self.RestoreEnabled - def set_RestoreEnabled(self, RestoreEnabled): - self.RestoreEnabled = RestoreEnabled - def get_RRAMenabled(self): - return self.RRAMenabled - def set_RRAMenabled(self, RRAMenabled): - self.RRAMenabled = RRAMenabled - def get_RreEnabled(self): - return self.RreEnabled - def set_RreEnabled(self, RreEnabled): - self.RreEnabled = RreEnabled - def get_Service(self): - return self.Service - def set_Service(self, Service): - self.Service = Service - def get_ServiceTypeCode(self): - return self.ServiceTypeCode - def set_ServiceTypeCode(self, ServiceTypeCode): - self.ServiceTypeCode = ServiceTypeCode - def get_Status(self): - return self.Status - def set_Status(self, Status): - self.Status = Status - def get_StatusCategory(self): - return self.StatusCategory - def set_StatusCategory(self, StatusCategory): - self.StatusCategory = StatusCategory - def get_StatusSummary(self): - return self.StatusSummary - def set_StatusSummary(self, StatusSummary): - self.StatusSummary = StatusSummary - def get_TABLECODE(self): - return self.TABLECODE - def set_TABLECODE(self, TABLECODE): - self.TABLECODE = TABLECODE - def get_TpodEnabled(self): - return self.TpodEnabled - def set_TpodEnabled(self, TpodEnabled): - self.TpodEnabled = TpodEnabled - def get_ValueofArticle(self): - return self.ValueofArticle - def set_ValueofArticle(self, ValueofArticle): - self.ValueofArticle = ValueofArticle - def get_EnabledNotificationRequests(self): - return self.EnabledNotificationRequests - def set_EnabledNotificationRequests(self, EnabledNotificationRequests): - self.EnabledNotificationRequests = EnabledNotificationRequests - def get_TrackSummary(self): - return self.TrackSummary - def set_TrackSummary(self, TrackSummary): - self.TrackSummary = TrackSummary - def get_TrackDetail(self): - return self.TrackDetail - def set_TrackDetail(self, TrackDetail): - self.TrackDetail = TrackDetail - def add_TrackDetail(self, value): - self.TrackDetail.append(value) - def insert_TrackDetail_at(self, index, value): - self.TrackDetail.insert(index, value) - def replace_TrackDetail_at(self, index, value): - self.TrackDetail[index] = value - def get_ID(self): - return self.ID - def set_ID(self, ID): - self.ID = ID - def _hasContent(self): - if ( - self.AdditionalInfo is not None or - self.ADPScripting is not None or - self.ARCHDATA is not None or - self.ArchiveRestoreInfo is not None or - self.AssociatedLabel is not None or - self.Class is not None or - self.ClassOfMailCode is not None or - self.DeliveryNotificationDate is not None or - self.DestinationCity is not None or - self.DestinationCountryCode is not None or - self.DestinationState is not None or - self.DestinationZip is not None or - self.EditedLabelID is not None or - self.EmailEnabled is not None or - self.ExpectedDeliveryDate is not None or - self.ExpectedDeliveryTime is not None or - self.GuaranteedDeliveryDate is not None or - self.GuaranteedDeliveryTime is not None or - self.GuaranteedDetails is not None or - self.KahalaIndicator is not None or - self.MailTypeCode is not None or - self.MPDATE is not None or - self.MPSUFFIX is not None or - self.OriginCity is not None or - self.OriginCountryCode is not None or - self.OriginState is not None or - self.OriginZip is not None or - self.PodEnabled is not None or - self.PredictedDeliveryDate is not None or - self.PredictedDeliveryTime is not None or - self.PDWStart is not None or - self.PDWEnd is not None or - self.RelatedRRID is not None or - self.RestoreEnabled is not None or - self.RRAMenabled is not None or - self.RreEnabled is not None or - self.Service is not None or - self.ServiceTypeCode is not None or - self.Status is not None or - self.StatusCategory is not None or - self.StatusSummary is not None or - self.TABLECODE is not None or - self.TpodEnabled is not None or - self.ValueofArticle is not None or - self.EnabledNotificationRequests is not None or - self.TrackSummary is not None or - self.TrackDetail - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='TrackInfoType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('TrackInfoType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'TrackInfoType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='TrackInfoType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='TrackInfoType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='TrackInfoType'): - if self.ID is not None and 'ID' not in already_processed: - already_processed.add('ID') - outfile.write(' ID=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.ID), input_name='ID')), )) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='TrackInfoType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.AdditionalInfo is not None: - namespaceprefix_ = self.AdditionalInfo_nsprefix_ + ':' if (UseCapturedNS_ and self.AdditionalInfo_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAdditionalInfo>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.AdditionalInfo), input_name='AdditionalInfo')), namespaceprefix_ , eol_)) - if self.ADPScripting is not None: - namespaceprefix_ = self.ADPScripting_nsprefix_ + ':' if (UseCapturedNS_ and self.ADPScripting_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sADPScripting>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ADPScripting), input_name='ADPScripting')), namespaceprefix_ , eol_)) - if self.ARCHDATA is not None: - namespaceprefix_ = self.ARCHDATA_nsprefix_ + ':' if (UseCapturedNS_ and self.ARCHDATA_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sARCHDATA>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.ARCHDATA, input_name='ARCHDATA'), namespaceprefix_ , eol_)) - if self.ArchiveRestoreInfo is not None: - namespaceprefix_ = self.ArchiveRestoreInfo_nsprefix_ + ':' if (UseCapturedNS_ and self.ArchiveRestoreInfo_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sArchiveRestoreInfo>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ArchiveRestoreInfo), input_name='ArchiveRestoreInfo')), namespaceprefix_ , eol_)) - if self.AssociatedLabel is not None: - namespaceprefix_ = self.AssociatedLabel_nsprefix_ + ':' if (UseCapturedNS_ and self.AssociatedLabel_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAssociatedLabel>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.AssociatedLabel), input_name='AssociatedLabel')), namespaceprefix_ , eol_)) - if self.Class is not None: - namespaceprefix_ = self.Class_nsprefix_ + ':' if (UseCapturedNS_ and self.Class_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sClass>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Class), input_name='Class')), namespaceprefix_ , eol_)) - if self.ClassOfMailCode is not None: - namespaceprefix_ = self.ClassOfMailCode_nsprefix_ + ':' if (UseCapturedNS_ and self.ClassOfMailCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sClassOfMailCode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ClassOfMailCode), input_name='ClassOfMailCode')), namespaceprefix_ , eol_)) - if self.DeliveryNotificationDate is not None: - namespaceprefix_ = self.DeliveryNotificationDate_nsprefix_ + ':' if (UseCapturedNS_ and self.DeliveryNotificationDate_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDeliveryNotificationDate>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.DeliveryNotificationDate), input_name='DeliveryNotificationDate')), namespaceprefix_ , eol_)) - if self.DestinationCity is not None: - namespaceprefix_ = self.DestinationCity_nsprefix_ + ':' if (UseCapturedNS_ and self.DestinationCity_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDestinationCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.DestinationCity), input_name='DestinationCity')), namespaceprefix_ , eol_)) - if self.DestinationCountryCode is not None: - namespaceprefix_ = self.DestinationCountryCode_nsprefix_ + ':' if (UseCapturedNS_ and self.DestinationCountryCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDestinationCountryCode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.DestinationCountryCode), input_name='DestinationCountryCode')), namespaceprefix_ , eol_)) - if self.DestinationState is not None: - namespaceprefix_ = self.DestinationState_nsprefix_ + ':' if (UseCapturedNS_ and self.DestinationState_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDestinationState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.DestinationState), input_name='DestinationState')), namespaceprefix_ , eol_)) - if self.DestinationZip is not None: - namespaceprefix_ = self.DestinationZip_nsprefix_ + ':' if (UseCapturedNS_ and self.DestinationZip_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDestinationZip>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.DestinationZip, input_name='DestinationZip'), namespaceprefix_ , eol_)) - if self.EditedLabelID is not None: - namespaceprefix_ = self.EditedLabelID_nsprefix_ + ':' if (UseCapturedNS_ and self.EditedLabelID_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEditedLabelID>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.EditedLabelID), input_name='EditedLabelID')), namespaceprefix_ , eol_)) - if self.EmailEnabled is not None: - namespaceprefix_ = self.EmailEnabled_nsprefix_ + ':' if (UseCapturedNS_ and self.EmailEnabled_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEmailEnabled>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.EmailEnabled), input_name='EmailEnabled')), namespaceprefix_ , eol_)) - if self.ExpectedDeliveryDate is not None: - namespaceprefix_ = self.ExpectedDeliveryDate_nsprefix_ + ':' if (UseCapturedNS_ and self.ExpectedDeliveryDate_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sExpectedDeliveryDate>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ExpectedDeliveryDate), input_name='ExpectedDeliveryDate')), namespaceprefix_ , eol_)) - if self.ExpectedDeliveryTime is not None: - namespaceprefix_ = self.ExpectedDeliveryTime_nsprefix_ + ':' if (UseCapturedNS_ and self.ExpectedDeliveryTime_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sExpectedDeliveryTime>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ExpectedDeliveryTime), input_name='ExpectedDeliveryTime')), namespaceprefix_ , eol_)) - if self.GuaranteedDeliveryDate is not None: - namespaceprefix_ = self.GuaranteedDeliveryDate_nsprefix_ + ':' if (UseCapturedNS_ and self.GuaranteedDeliveryDate_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sGuaranteedDeliveryDate>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.GuaranteedDeliveryDate), input_name='GuaranteedDeliveryDate')), namespaceprefix_ , eol_)) - if self.GuaranteedDeliveryTime is not None: - namespaceprefix_ = self.GuaranteedDeliveryTime_nsprefix_ + ':' if (UseCapturedNS_ and self.GuaranteedDeliveryTime_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sGuaranteedDeliveryTime>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.GuaranteedDeliveryTime), input_name='GuaranteedDeliveryTime')), namespaceprefix_ , eol_)) - if self.GuaranteedDetails is not None: - namespaceprefix_ = self.GuaranteedDetails_nsprefix_ + ':' if (UseCapturedNS_ and self.GuaranteedDetails_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sGuaranteedDetails>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.GuaranteedDetails), input_name='GuaranteedDetails')), namespaceprefix_ , eol_)) - if self.KahalaIndicator is not None: - namespaceprefix_ = self.KahalaIndicator_nsprefix_ + ':' if (UseCapturedNS_ and self.KahalaIndicator_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sKahalaIndicator>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.KahalaIndicator), input_name='KahalaIndicator')), namespaceprefix_ , eol_)) - if self.MailTypeCode is not None: - namespaceprefix_ = self.MailTypeCode_nsprefix_ + ':' if (UseCapturedNS_ and self.MailTypeCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sMailTypeCode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.MailTypeCode), input_name='MailTypeCode')), namespaceprefix_ , eol_)) - if self.MPDATE is not None: - namespaceprefix_ = self.MPDATE_nsprefix_ + ':' if (UseCapturedNS_ and self.MPDATE_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sMPDATE>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.MPDATE), input_name='MPDATE')), namespaceprefix_ , eol_)) - if self.MPSUFFIX is not None: - namespaceprefix_ = self.MPSUFFIX_nsprefix_ + ':' if (UseCapturedNS_ and self.MPSUFFIX_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sMPSUFFIX>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.MPSUFFIX, input_name='MPSUFFIX'), namespaceprefix_ , eol_)) - if self.OriginCity is not None: - namespaceprefix_ = self.OriginCity_nsprefix_ + ':' if (UseCapturedNS_ and self.OriginCity_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sOriginCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.OriginCity), input_name='OriginCity')), namespaceprefix_ , eol_)) - if self.OriginCountryCode is not None: - namespaceprefix_ = self.OriginCountryCode_nsprefix_ + ':' if (UseCapturedNS_ and self.OriginCountryCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sOriginCountryCode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.OriginCountryCode), input_name='OriginCountryCode')), namespaceprefix_ , eol_)) - if self.OriginState is not None: - namespaceprefix_ = self.OriginState_nsprefix_ + ':' if (UseCapturedNS_ and self.OriginState_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sOriginState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.OriginState), input_name='OriginState')), namespaceprefix_ , eol_)) - if self.OriginZip is not None: - namespaceprefix_ = self.OriginZip_nsprefix_ + ':' if (UseCapturedNS_ and self.OriginZip_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sOriginZip>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.OriginZip), input_name='OriginZip')), namespaceprefix_ , eol_)) - if self.PodEnabled is not None: - namespaceprefix_ = self.PodEnabled_nsprefix_ + ':' if (UseCapturedNS_ and self.PodEnabled_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPodEnabled>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PodEnabled), input_name='PodEnabled')), namespaceprefix_ , eol_)) - if self.PredictedDeliveryDate is not None: - namespaceprefix_ = self.PredictedDeliveryDate_nsprefix_ + ':' if (UseCapturedNS_ and self.PredictedDeliveryDate_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPredictedDeliveryDate>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PredictedDeliveryDate), input_name='PredictedDeliveryDate')), namespaceprefix_ , eol_)) - if self.PredictedDeliveryTime is not None: - namespaceprefix_ = self.PredictedDeliveryTime_nsprefix_ + ':' if (UseCapturedNS_ and self.PredictedDeliveryTime_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPredictedDeliveryTime>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PredictedDeliveryTime), input_name='PredictedDeliveryTime')), namespaceprefix_ , eol_)) - if self.PDWStart is not None: - namespaceprefix_ = self.PDWStart_nsprefix_ + ':' if (UseCapturedNS_ and self.PDWStart_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPDWStart>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PDWStart), input_name='PDWStart')), namespaceprefix_ , eol_)) - if self.PDWEnd is not None: - namespaceprefix_ = self.PDWEnd_nsprefix_ + ':' if (UseCapturedNS_ and self.PDWEnd_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sPDWEnd>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.PDWEnd), input_name='PDWEnd')), namespaceprefix_ , eol_)) - if self.RelatedRRID is not None: - namespaceprefix_ = self.RelatedRRID_nsprefix_ + ':' if (UseCapturedNS_ and self.RelatedRRID_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRelatedRRID>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.RelatedRRID), input_name='RelatedRRID')), namespaceprefix_ , eol_)) - if self.RestoreEnabled is not None: - namespaceprefix_ = self.RestoreEnabled_nsprefix_ + ':' if (UseCapturedNS_ and self.RestoreEnabled_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRestoreEnabled>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.RestoreEnabled, input_name='RestoreEnabled'), namespaceprefix_ , eol_)) - if self.RRAMenabled is not None: - namespaceprefix_ = self.RRAMenabled_nsprefix_ + ':' if (UseCapturedNS_ and self.RRAMenabled_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRRAMenabled>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.RRAMenabled, input_name='RRAMenabled'), namespaceprefix_ , eol_)) - if self.RreEnabled is not None: - namespaceprefix_ = self.RreEnabled_nsprefix_ + ':' if (UseCapturedNS_ and self.RreEnabled_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sRreEnabled>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.RreEnabled, input_name='RreEnabled'), namespaceprefix_ , eol_)) - if self.Service is not None: - namespaceprefix_ = self.Service_nsprefix_ + ':' if (UseCapturedNS_ and self.Service_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sService>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Service), input_name='Service')), namespaceprefix_ , eol_)) - if self.ServiceTypeCode is not None: - namespaceprefix_ = self.ServiceTypeCode_nsprefix_ + ':' if (UseCapturedNS_ and self.ServiceTypeCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sServiceTypeCode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ServiceTypeCode), input_name='ServiceTypeCode')), namespaceprefix_ , eol_)) - if self.Status is not None: - namespaceprefix_ = self.Status_nsprefix_ + ':' if (UseCapturedNS_ and self.Status_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sStatus>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Status), input_name='Status')), namespaceprefix_ , eol_)) - if self.StatusCategory is not None: - namespaceprefix_ = self.StatusCategory_nsprefix_ + ':' if (UseCapturedNS_ and self.StatusCategory_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sStatusCategory>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.StatusCategory), input_name='StatusCategory')), namespaceprefix_ , eol_)) - if self.StatusSummary is not None: - namespaceprefix_ = self.StatusSummary_nsprefix_ + ':' if (UseCapturedNS_ and self.StatusSummary_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sStatusSummary>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.StatusSummary), input_name='StatusSummary')), namespaceprefix_ , eol_)) - if self.TABLECODE is not None: - namespaceprefix_ = self.TABLECODE_nsprefix_ + ':' if (UseCapturedNS_ and self.TABLECODE_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sTABLECODE>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.TABLECODE), input_name='TABLECODE')), namespaceprefix_ , eol_)) - if self.TpodEnabled is not None: - namespaceprefix_ = self.TpodEnabled_nsprefix_ + ':' if (UseCapturedNS_ and self.TpodEnabled_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sTpodEnabled>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.TpodEnabled, input_name='TpodEnabled'), namespaceprefix_ , eol_)) - if self.ValueofArticle is not None: - namespaceprefix_ = self.ValueofArticle_nsprefix_ + ':' if (UseCapturedNS_ and self.ValueofArticle_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sValueofArticle>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ValueofArticle), input_name='ValueofArticle')), namespaceprefix_ , eol_)) - if self.EnabledNotificationRequests is not None: - namespaceprefix_ = self.EnabledNotificationRequests_nsprefix_ + ':' if (UseCapturedNS_ and self.EnabledNotificationRequests_nsprefix_) else '' - self.EnabledNotificationRequests.export(outfile, level, namespaceprefix_, namespacedef_='', name_='EnabledNotificationRequests', pretty_print=pretty_print) - if self.TrackSummary is not None: - namespaceprefix_ = self.TrackSummary_nsprefix_ + ':' if (UseCapturedNS_ and self.TrackSummary_nsprefix_) else '' - self.TrackSummary.export(outfile, level, namespaceprefix_, namespacedef_='', name_='TrackSummary', pretty_print=pretty_print) - for TrackDetail_ in self.TrackDetail: - namespaceprefix_ = self.TrackDetail_nsprefix_ + ':' if (UseCapturedNS_ and self.TrackDetail_nsprefix_) else '' - TrackDetail_.export(outfile, level, namespaceprefix_, namespacedef_='', name_='TrackDetail', pretty_print=pretty_print) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('ID', node) - if value is not None and 'ID' not in already_processed: - already_processed.add('ID') - self.ID = value - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'AdditionalInfo': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'AdditionalInfo') - value_ = self.gds_validate_string(value_, node, 'AdditionalInfo') - self.AdditionalInfo = value_ - self.AdditionalInfo_nsprefix_ = child_.prefix - elif nodeName_ == 'ADPScripting': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ADPScripting') - value_ = self.gds_validate_string(value_, node, 'ADPScripting') - self.ADPScripting = value_ - self.ADPScripting_nsprefix_ = child_.prefix - elif nodeName_ == 'ARCHDATA': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'ARCHDATA') - ival_ = self.gds_validate_boolean(ival_, node, 'ARCHDATA') - self.ARCHDATA = ival_ - self.ARCHDATA_nsprefix_ = child_.prefix - elif nodeName_ == 'ArchiveRestoreInfo': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ArchiveRestoreInfo') - value_ = self.gds_validate_string(value_, node, 'ArchiveRestoreInfo') - self.ArchiveRestoreInfo = value_ - self.ArchiveRestoreInfo_nsprefix_ = child_.prefix - elif nodeName_ == 'AssociatedLabel': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'AssociatedLabel') - value_ = self.gds_validate_string(value_, node, 'AssociatedLabel') - self.AssociatedLabel = value_ - self.AssociatedLabel_nsprefix_ = child_.prefix - elif nodeName_ == 'Class': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Class') - value_ = self.gds_validate_string(value_, node, 'Class') - self.Class = value_ - self.Class_nsprefix_ = child_.prefix - elif nodeName_ == 'ClassOfMailCode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ClassOfMailCode') - value_ = self.gds_validate_string(value_, node, 'ClassOfMailCode') - self.ClassOfMailCode = value_ - self.ClassOfMailCode_nsprefix_ = child_.prefix - elif nodeName_ == 'DeliveryNotificationDate': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'DeliveryNotificationDate') - value_ = self.gds_validate_string(value_, node, 'DeliveryNotificationDate') - self.DeliveryNotificationDate = value_ - self.DeliveryNotificationDate_nsprefix_ = child_.prefix - elif nodeName_ == 'DestinationCity': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'DestinationCity') - value_ = self.gds_validate_string(value_, node, 'DestinationCity') - self.DestinationCity = value_ - self.DestinationCity_nsprefix_ = child_.prefix - elif nodeName_ == 'DestinationCountryCode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'DestinationCountryCode') - value_ = self.gds_validate_string(value_, node, 'DestinationCountryCode') - self.DestinationCountryCode = value_ - self.DestinationCountryCode_nsprefix_ = child_.prefix - elif nodeName_ == 'DestinationState': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'DestinationState') - value_ = self.gds_validate_string(value_, node, 'DestinationState') - self.DestinationState = value_ - self.DestinationState_nsprefix_ = child_.prefix - elif nodeName_ == 'DestinationZip' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'DestinationZip') - ival_ = self.gds_validate_integer(ival_, node, 'DestinationZip') - self.DestinationZip = ival_ - self.DestinationZip_nsprefix_ = child_.prefix - elif nodeName_ == 'EditedLabelID': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'EditedLabelID') - value_ = self.gds_validate_string(value_, node, 'EditedLabelID') - self.EditedLabelID = value_ - self.EditedLabelID_nsprefix_ = child_.prefix - elif nodeName_ == 'EmailEnabled': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'EmailEnabled') - value_ = self.gds_validate_string(value_, node, 'EmailEnabled') - self.EmailEnabled = value_ - self.EmailEnabled_nsprefix_ = child_.prefix - elif nodeName_ == 'ExpectedDeliveryDate': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ExpectedDeliveryDate') - value_ = self.gds_validate_string(value_, node, 'ExpectedDeliveryDate') - self.ExpectedDeliveryDate = value_ - self.ExpectedDeliveryDate_nsprefix_ = child_.prefix - elif nodeName_ == 'ExpectedDeliveryTime': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ExpectedDeliveryTime') - value_ = self.gds_validate_string(value_, node, 'ExpectedDeliveryTime') - self.ExpectedDeliveryTime = value_ - self.ExpectedDeliveryTime_nsprefix_ = child_.prefix - elif nodeName_ == 'GuaranteedDeliveryDate': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'GuaranteedDeliveryDate') - value_ = self.gds_validate_string(value_, node, 'GuaranteedDeliveryDate') - self.GuaranteedDeliveryDate = value_ - self.GuaranteedDeliveryDate_nsprefix_ = child_.prefix - elif nodeName_ == 'GuaranteedDeliveryTime': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'GuaranteedDeliveryTime') - value_ = self.gds_validate_string(value_, node, 'GuaranteedDeliveryTime') - self.GuaranteedDeliveryTime = value_ - self.GuaranteedDeliveryTime_nsprefix_ = child_.prefix - elif nodeName_ == 'GuaranteedDetails': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'GuaranteedDetails') - value_ = self.gds_validate_string(value_, node, 'GuaranteedDetails') - self.GuaranteedDetails = value_ - self.GuaranteedDetails_nsprefix_ = child_.prefix - elif nodeName_ == 'KahalaIndicator': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'KahalaIndicator') - value_ = self.gds_validate_string(value_, node, 'KahalaIndicator') - self.KahalaIndicator = value_ - self.KahalaIndicator_nsprefix_ = child_.prefix - elif nodeName_ == 'MailTypeCode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'MailTypeCode') - value_ = self.gds_validate_string(value_, node, 'MailTypeCode') - self.MailTypeCode = value_ - self.MailTypeCode_nsprefix_ = child_.prefix - elif nodeName_ == 'MPDATE': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'MPDATE') - value_ = self.gds_validate_string(value_, node, 'MPDATE') - self.MPDATE = value_ - self.MPDATE_nsprefix_ = child_.prefix - elif nodeName_ == 'MPSUFFIX' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'MPSUFFIX') - ival_ = self.gds_validate_integer(ival_, node, 'MPSUFFIX') - self.MPSUFFIX = ival_ - self.MPSUFFIX_nsprefix_ = child_.prefix - elif nodeName_ == 'OriginCity': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'OriginCity') - value_ = self.gds_validate_string(value_, node, 'OriginCity') - self.OriginCity = value_ - self.OriginCity_nsprefix_ = child_.prefix - elif nodeName_ == 'OriginCountryCode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'OriginCountryCode') - value_ = self.gds_validate_string(value_, node, 'OriginCountryCode') - self.OriginCountryCode = value_ - self.OriginCountryCode_nsprefix_ = child_.prefix - elif nodeName_ == 'OriginState': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'OriginState') - value_ = self.gds_validate_string(value_, node, 'OriginState') - self.OriginState = value_ - self.OriginState_nsprefix_ = child_.prefix - elif nodeName_ == 'OriginZip': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'OriginZip') - value_ = self.gds_validate_string(value_, node, 'OriginZip') - self.OriginZip = value_ - self.OriginZip_nsprefix_ = child_.prefix - elif nodeName_ == 'PodEnabled': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PodEnabled') - value_ = self.gds_validate_string(value_, node, 'PodEnabled') - self.PodEnabled = value_ - self.PodEnabled_nsprefix_ = child_.prefix - elif nodeName_ == 'PredictedDeliveryDate': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PredictedDeliveryDate') - value_ = self.gds_validate_string(value_, node, 'PredictedDeliveryDate') - self.PredictedDeliveryDate = value_ - self.PredictedDeliveryDate_nsprefix_ = child_.prefix - elif nodeName_ == 'PredictedDeliveryTime': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PredictedDeliveryTime') - value_ = self.gds_validate_string(value_, node, 'PredictedDeliveryTime') - self.PredictedDeliveryTime = value_ - self.PredictedDeliveryTime_nsprefix_ = child_.prefix - elif nodeName_ == 'PDWStart': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PDWStart') - value_ = self.gds_validate_string(value_, node, 'PDWStart') - self.PDWStart = value_ - self.PDWStart_nsprefix_ = child_.prefix - elif nodeName_ == 'PDWEnd': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'PDWEnd') - value_ = self.gds_validate_string(value_, node, 'PDWEnd') - self.PDWEnd = value_ - self.PDWEnd_nsprefix_ = child_.prefix - elif nodeName_ == 'RelatedRRID': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'RelatedRRID') - value_ = self.gds_validate_string(value_, node, 'RelatedRRID') - self.RelatedRRID = value_ - self.RelatedRRID_nsprefix_ = child_.prefix - elif nodeName_ == 'RestoreEnabled': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'RestoreEnabled') - ival_ = self.gds_validate_boolean(ival_, node, 'RestoreEnabled') - self.RestoreEnabled = ival_ - self.RestoreEnabled_nsprefix_ = child_.prefix - elif nodeName_ == 'RRAMenabled': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'RRAMenabled') - ival_ = self.gds_validate_boolean(ival_, node, 'RRAMenabled') - self.RRAMenabled = ival_ - self.RRAMenabled_nsprefix_ = child_.prefix - elif nodeName_ == 'RreEnabled': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'RreEnabled') - ival_ = self.gds_validate_boolean(ival_, node, 'RreEnabled') - self.RreEnabled = ival_ - self.RreEnabled_nsprefix_ = child_.prefix - elif nodeName_ == 'Service': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Service') - value_ = self.gds_validate_string(value_, node, 'Service') - self.Service = value_ - self.Service_nsprefix_ = child_.prefix - elif nodeName_ == 'ServiceTypeCode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ServiceTypeCode') - value_ = self.gds_validate_string(value_, node, 'ServiceTypeCode') - self.ServiceTypeCode = value_ - self.ServiceTypeCode_nsprefix_ = child_.prefix - elif nodeName_ == 'Status': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Status') - value_ = self.gds_validate_string(value_, node, 'Status') - self.Status = value_ - self.Status_nsprefix_ = child_.prefix - elif nodeName_ == 'StatusCategory': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'StatusCategory') - value_ = self.gds_validate_string(value_, node, 'StatusCategory') - self.StatusCategory = value_ - self.StatusCategory_nsprefix_ = child_.prefix - elif nodeName_ == 'StatusSummary': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'StatusSummary') - value_ = self.gds_validate_string(value_, node, 'StatusSummary') - self.StatusSummary = value_ - self.StatusSummary_nsprefix_ = child_.prefix - elif nodeName_ == 'TABLECODE': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'TABLECODE') - value_ = self.gds_validate_string(value_, node, 'TABLECODE') - self.TABLECODE = value_ - self.TABLECODE_nsprefix_ = child_.prefix - elif nodeName_ == 'TpodEnabled': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'TpodEnabled') - ival_ = self.gds_validate_boolean(ival_, node, 'TpodEnabled') - self.TpodEnabled = ival_ - self.TpodEnabled_nsprefix_ = child_.prefix - elif nodeName_ == 'ValueofArticle': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ValueofArticle') - value_ = self.gds_validate_string(value_, node, 'ValueofArticle') - self.ValueofArticle = value_ - self.ValueofArticle_nsprefix_ = child_.prefix - elif nodeName_ == 'EnabledNotificationRequests': - obj_ = EnabledNotificationRequestsType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.EnabledNotificationRequests = obj_ - obj_.original_tagname_ = 'EnabledNotificationRequests' - elif nodeName_ == 'TrackSummary': - obj_ = TrackSummaryType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.TrackSummary = obj_ - obj_.original_tagname_ = 'TrackSummary' - elif nodeName_ == 'TrackDetail': - obj_ = TrackDetailType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.TrackDetail.append(obj_) - obj_.original_tagname_ = 'TrackDetail' -# end class TrackInfoType - - -class EnabledNotificationRequestsType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, SMS=None, EMAIL=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.SMS = SMS - self.SMS_nsprefix_ = None - self.EMAIL = EMAIL - self.EMAIL_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, EnabledNotificationRequestsType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if EnabledNotificationRequestsType.subclass: - return EnabledNotificationRequestsType.subclass(*args_, **kwargs_) - else: - return EnabledNotificationRequestsType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_SMS(self): - return self.SMS - def set_SMS(self, SMS): - self.SMS = SMS - def get_EMAIL(self): - return self.EMAIL - def set_EMAIL(self, EMAIL): - self.EMAIL = EMAIL - def _hasContent(self): - if ( - self.SMS is not None or - self.EMAIL is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='EnabledNotificationRequestsType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('EnabledNotificationRequestsType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'EnabledNotificationRequestsType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='EnabledNotificationRequestsType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='EnabledNotificationRequestsType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='EnabledNotificationRequestsType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='EnabledNotificationRequestsType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.SMS is not None: - namespaceprefix_ = self.SMS_nsprefix_ + ':' if (UseCapturedNS_ and self.SMS_nsprefix_) else '' - self.SMS.export(outfile, level, namespaceprefix_, namespacedef_='', name_='SMS', pretty_print=pretty_print) - if self.EMAIL is not None: - namespaceprefix_ = self.EMAIL_nsprefix_ + ':' if (UseCapturedNS_ and self.EMAIL_nsprefix_) else '' - self.EMAIL.export(outfile, level, namespaceprefix_, namespacedef_='', name_='EMAIL', pretty_print=pretty_print) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'SMS': - obj_ = SMSType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.SMS = obj_ - obj_.original_tagname_ = 'SMS' - elif nodeName_ == 'EMAIL': - obj_ = EMAILType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.EMAIL = obj_ - obj_.original_tagname_ = 'EMAIL' -# end class EnabledNotificationRequestsType - - -class SMSType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, FD=None, AL=None, TD=None, UP=None, DND=None, FS=None, OA=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.FD = FD - self.FD_nsprefix_ = None - self.AL = AL - self.AL_nsprefix_ = None - self.TD = TD - self.TD_nsprefix_ = None - self.UP = UP - self.UP_nsprefix_ = None - self.DND = DND - self.DND_nsprefix_ = None - self.FS = FS - self.FS_nsprefix_ = None - self.OA = OA - self.OA_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, SMSType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if SMSType.subclass: - return SMSType.subclass(*args_, **kwargs_) - else: - return SMSType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_FD(self): - return self.FD - def set_FD(self, FD): - self.FD = FD - def get_AL(self): - return self.AL - def set_AL(self, AL): - self.AL = AL - def get_TD(self): - return self.TD - def set_TD(self, TD): - self.TD = TD - def get_UP(self): - return self.UP - def set_UP(self, UP): - self.UP = UP - def get_DND(self): - return self.DND - def set_DND(self, DND): - self.DND = DND - def get_FS(self): - return self.FS - def set_FS(self, FS): - self.FS = FS - def get_OA(self): - return self.OA - def set_OA(self, OA): - self.OA = OA - def _hasContent(self): - if ( - self.FD is not None or - self.AL is not None or - self.TD is not None or - self.UP is not None or - self.DND is not None or - self.FS is not None or - self.OA is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='SMSType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('SMSType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'SMSType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='SMSType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='SMSType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='SMSType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='SMSType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.FD is not None: - namespaceprefix_ = self.FD_nsprefix_ + ':' if (UseCapturedNS_ and self.FD_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFD>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.FD, input_name='FD'), namespaceprefix_ , eol_)) - if self.AL is not None: - namespaceprefix_ = self.AL_nsprefix_ + ':' if (UseCapturedNS_ and self.AL_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAL>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.AL, input_name='AL'), namespaceprefix_ , eol_)) - if self.TD is not None: - namespaceprefix_ = self.TD_nsprefix_ + ':' if (UseCapturedNS_ and self.TD_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sTD>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.TD, input_name='TD'), namespaceprefix_ , eol_)) - if self.UP is not None: - namespaceprefix_ = self.UP_nsprefix_ + ':' if (UseCapturedNS_ and self.UP_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sUP>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.UP, input_name='UP'), namespaceprefix_ , eol_)) - if self.DND is not None: - namespaceprefix_ = self.DND_nsprefix_ + ':' if (UseCapturedNS_ and self.DND_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDND>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.DND, input_name='DND'), namespaceprefix_ , eol_)) - if self.FS is not None: - namespaceprefix_ = self.FS_nsprefix_ + ':' if (UseCapturedNS_ and self.FS_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFS>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.FS, input_name='FS'), namespaceprefix_ , eol_)) - if self.OA is not None: - namespaceprefix_ = self.OA_nsprefix_ + ':' if (UseCapturedNS_ and self.OA_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sOA>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.OA, input_name='OA'), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'FD': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'FD') - ival_ = self.gds_validate_boolean(ival_, node, 'FD') - self.FD = ival_ - self.FD_nsprefix_ = child_.prefix - elif nodeName_ == 'AL': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'AL') - ival_ = self.gds_validate_boolean(ival_, node, 'AL') - self.AL = ival_ - self.AL_nsprefix_ = child_.prefix - elif nodeName_ == 'TD': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'TD') - ival_ = self.gds_validate_boolean(ival_, node, 'TD') - self.TD = ival_ - self.TD_nsprefix_ = child_.prefix - elif nodeName_ == 'UP': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'UP') - ival_ = self.gds_validate_boolean(ival_, node, 'UP') - self.UP = ival_ - self.UP_nsprefix_ = child_.prefix - elif nodeName_ == 'DND': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'DND') - ival_ = self.gds_validate_boolean(ival_, node, 'DND') - self.DND = ival_ - self.DND_nsprefix_ = child_.prefix - elif nodeName_ == 'FS': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'FS') - ival_ = self.gds_validate_boolean(ival_, node, 'FS') - self.FS = ival_ - self.FS_nsprefix_ = child_.prefix - elif nodeName_ == 'OA': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'OA') - ival_ = self.gds_validate_boolean(ival_, node, 'OA') - self.OA = ival_ - self.OA_nsprefix_ = child_.prefix -# end class SMSType - - -class EMAILType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, FD=None, AL=None, TD=None, UP=None, DND=None, FS=None, OA=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.FD = FD - self.FD_nsprefix_ = None - self.AL = AL - self.AL_nsprefix_ = None - self.TD = TD - self.TD_nsprefix_ = None - self.UP = UP - self.UP_nsprefix_ = None - self.DND = DND - self.DND_nsprefix_ = None - self.FS = FS - self.FS_nsprefix_ = None - self.OA = OA - self.OA_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, EMAILType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if EMAILType.subclass: - return EMAILType.subclass(*args_, **kwargs_) - else: - return EMAILType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_FD(self): - return self.FD - def set_FD(self, FD): - self.FD = FD - def get_AL(self): - return self.AL - def set_AL(self, AL): - self.AL = AL - def get_TD(self): - return self.TD - def set_TD(self, TD): - self.TD = TD - def get_UP(self): - return self.UP - def set_UP(self, UP): - self.UP = UP - def get_DND(self): - return self.DND - def set_DND(self, DND): - self.DND = DND - def get_FS(self): - return self.FS - def set_FS(self, FS): - self.FS = FS - def get_OA(self): - return self.OA - def set_OA(self, OA): - self.OA = OA - def _hasContent(self): - if ( - self.FD is not None or - self.AL is not None or - self.TD is not None or - self.UP is not None or - self.DND is not None or - self.FS is not None or - self.OA is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='EMAILType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('EMAILType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'EMAILType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='EMAILType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='EMAILType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='EMAILType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='EMAILType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.FD is not None: - namespaceprefix_ = self.FD_nsprefix_ + ':' if (UseCapturedNS_ and self.FD_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFD>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.FD, input_name='FD'), namespaceprefix_ , eol_)) - if self.AL is not None: - namespaceprefix_ = self.AL_nsprefix_ + ':' if (UseCapturedNS_ and self.AL_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAL>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.AL, input_name='AL'), namespaceprefix_ , eol_)) - if self.TD is not None: - namespaceprefix_ = self.TD_nsprefix_ + ':' if (UseCapturedNS_ and self.TD_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sTD>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.TD, input_name='TD'), namespaceprefix_ , eol_)) - if self.UP is not None: - namespaceprefix_ = self.UP_nsprefix_ + ':' if (UseCapturedNS_ and self.UP_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sUP>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.UP, input_name='UP'), namespaceprefix_ , eol_)) - if self.DND is not None: - namespaceprefix_ = self.DND_nsprefix_ + ':' if (UseCapturedNS_ and self.DND_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sDND>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.DND, input_name='DND'), namespaceprefix_ , eol_)) - if self.FS is not None: - namespaceprefix_ = self.FS_nsprefix_ + ':' if (UseCapturedNS_ and self.FS_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFS>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.FS, input_name='FS'), namespaceprefix_ , eol_)) - if self.OA is not None: - namespaceprefix_ = self.OA_nsprefix_ + ':' if (UseCapturedNS_ and self.OA_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sOA>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.OA, input_name='OA'), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'FD': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'FD') - ival_ = self.gds_validate_boolean(ival_, node, 'FD') - self.FD = ival_ - self.FD_nsprefix_ = child_.prefix - elif nodeName_ == 'AL': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'AL') - ival_ = self.gds_validate_boolean(ival_, node, 'AL') - self.AL = ival_ - self.AL_nsprefix_ = child_.prefix - elif nodeName_ == 'TD': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'TD') - ival_ = self.gds_validate_boolean(ival_, node, 'TD') - self.TD = ival_ - self.TD_nsprefix_ = child_.prefix - elif nodeName_ == 'UP': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'UP') - ival_ = self.gds_validate_boolean(ival_, node, 'UP') - self.UP = ival_ - self.UP_nsprefix_ = child_.prefix - elif nodeName_ == 'DND': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'DND') - ival_ = self.gds_validate_boolean(ival_, node, 'DND') - self.DND = ival_ - self.DND_nsprefix_ = child_.prefix - elif nodeName_ == 'FS': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'FS') - ival_ = self.gds_validate_boolean(ival_, node, 'FS') - self.FS = ival_ - self.FS_nsprefix_ = child_.prefix - elif nodeName_ == 'OA': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'OA') - ival_ = self.gds_validate_boolean(ival_, node, 'OA') - self.OA = ival_ - self.OA_nsprefix_ = child_.prefix -# end class EMAILType - - -class TrackSummaryType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, EventTime=None, EventDate=None, Event=None, EventCity=None, EventState=None, EventZIPCode=None, EventCountry=None, FirmName=None, Name=None, AuthorizedAgent=None, EventCode=None, ActionCode=None, ReasonCode=None, GeoCertified=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.EventTime = EventTime - self.EventTime_nsprefix_ = None - self.EventDate = EventDate - self.EventDate_nsprefix_ = None - self.Event = Event - self.Event_nsprefix_ = None - self.EventCity = EventCity - self.EventCity_nsprefix_ = None - self.EventState = EventState - self.EventState_nsprefix_ = None - self.EventZIPCode = EventZIPCode - self.EventZIPCode_nsprefix_ = None - self.EventCountry = EventCountry - self.EventCountry_nsprefix_ = None - self.FirmName = FirmName - self.FirmName_nsprefix_ = None - self.Name = Name - self.Name_nsprefix_ = None - self.AuthorizedAgent = AuthorizedAgent - self.AuthorizedAgent_nsprefix_ = None - self.EventCode = EventCode - self.EventCode_nsprefix_ = None - self.ActionCode = ActionCode - self.ActionCode_nsprefix_ = None - self.ReasonCode = ReasonCode - self.ReasonCode_nsprefix_ = None - self.GeoCertified = GeoCertified - self.GeoCertified_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, TrackSummaryType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if TrackSummaryType.subclass: - return TrackSummaryType.subclass(*args_, **kwargs_) - else: - return TrackSummaryType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_EventTime(self): - return self.EventTime - def set_EventTime(self, EventTime): - self.EventTime = EventTime - def get_EventDate(self): - return self.EventDate - def set_EventDate(self, EventDate): - self.EventDate = EventDate - def get_Event(self): - return self.Event - def set_Event(self, Event): - self.Event = Event - def get_EventCity(self): - return self.EventCity - def set_EventCity(self, EventCity): - self.EventCity = EventCity - def get_EventState(self): - return self.EventState - def set_EventState(self, EventState): - self.EventState = EventState - def get_EventZIPCode(self): - return self.EventZIPCode - def set_EventZIPCode(self, EventZIPCode): - self.EventZIPCode = EventZIPCode - def get_EventCountry(self): - return self.EventCountry - def set_EventCountry(self, EventCountry): - self.EventCountry = EventCountry - def get_FirmName(self): - return self.FirmName - def set_FirmName(self, FirmName): - self.FirmName = FirmName - def get_Name(self): - return self.Name - def set_Name(self, Name): - self.Name = Name - def get_AuthorizedAgent(self): - return self.AuthorizedAgent - def set_AuthorizedAgent(self, AuthorizedAgent): - self.AuthorizedAgent = AuthorizedAgent - def get_EventCode(self): - return self.EventCode - def set_EventCode(self, EventCode): - self.EventCode = EventCode - def get_ActionCode(self): - return self.ActionCode - def set_ActionCode(self, ActionCode): - self.ActionCode = ActionCode - def get_ReasonCode(self): - return self.ReasonCode - def set_ReasonCode(self, ReasonCode): - self.ReasonCode = ReasonCode - def get_GeoCertified(self): - return self.GeoCertified - def set_GeoCertified(self, GeoCertified): - self.GeoCertified = GeoCertified - def _hasContent(self): - if ( - self.EventTime is not None or - self.EventDate is not None or - self.Event is not None or - self.EventCity is not None or - self.EventState is not None or - self.EventZIPCode is not None or - self.EventCountry is not None or - self.FirmName is not None or - self.Name is not None or - self.AuthorizedAgent is not None or - self.EventCode is not None or - self.ActionCode is not None or - self.ReasonCode is not None or - self.GeoCertified is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='TrackSummaryType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('TrackSummaryType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'TrackSummaryType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='TrackSummaryType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='TrackSummaryType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='TrackSummaryType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='TrackSummaryType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.EventTime is not None: - namespaceprefix_ = self.EventTime_nsprefix_ + ':' if (UseCapturedNS_ and self.EventTime_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEventTime>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.EventTime), input_name='EventTime')), namespaceprefix_ , eol_)) - if self.EventDate is not None: - namespaceprefix_ = self.EventDate_nsprefix_ + ':' if (UseCapturedNS_ and self.EventDate_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEventDate>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.EventDate), input_name='EventDate')), namespaceprefix_ , eol_)) - if self.Event is not None: - namespaceprefix_ = self.Event_nsprefix_ + ':' if (UseCapturedNS_ and self.Event_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEvent>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Event), input_name='Event')), namespaceprefix_ , eol_)) - if self.EventCity is not None: - namespaceprefix_ = self.EventCity_nsprefix_ + ':' if (UseCapturedNS_ and self.EventCity_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEventCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.EventCity), input_name='EventCity')), namespaceprefix_ , eol_)) - if self.EventState is not None: - namespaceprefix_ = self.EventState_nsprefix_ + ':' if (UseCapturedNS_ and self.EventState_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEventState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.EventState), input_name='EventState')), namespaceprefix_ , eol_)) - if self.EventZIPCode is not None: - namespaceprefix_ = self.EventZIPCode_nsprefix_ + ':' if (UseCapturedNS_ and self.EventZIPCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEventZIPCode>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.EventZIPCode, input_name='EventZIPCode'), namespaceprefix_ , eol_)) - if self.EventCountry is not None: - namespaceprefix_ = self.EventCountry_nsprefix_ + ':' if (UseCapturedNS_ and self.EventCountry_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEventCountry>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.EventCountry), input_name='EventCountry')), namespaceprefix_ , eol_)) - if self.FirmName is not None: - namespaceprefix_ = self.FirmName_nsprefix_ + ':' if (UseCapturedNS_ and self.FirmName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFirmName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FirmName), input_name='FirmName')), namespaceprefix_ , eol_)) - if self.Name is not None: - namespaceprefix_ = self.Name_nsprefix_ + ':' if (UseCapturedNS_ and self.Name_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Name), input_name='Name')), namespaceprefix_ , eol_)) - if self.AuthorizedAgent is not None: - namespaceprefix_ = self.AuthorizedAgent_nsprefix_ + ':' if (UseCapturedNS_ and self.AuthorizedAgent_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAuthorizedAgent>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.AuthorizedAgent, input_name='AuthorizedAgent'), namespaceprefix_ , eol_)) - if self.EventCode is not None: - namespaceprefix_ = self.EventCode_nsprefix_ + ':' if (UseCapturedNS_ and self.EventCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEventCode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.EventCode), input_name='EventCode')), namespaceprefix_ , eol_)) - if self.ActionCode is not None: - namespaceprefix_ = self.ActionCode_nsprefix_ + ':' if (UseCapturedNS_ and self.ActionCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sActionCode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ActionCode), input_name='ActionCode')), namespaceprefix_ , eol_)) - if self.ReasonCode is not None: - namespaceprefix_ = self.ReasonCode_nsprefix_ + ':' if (UseCapturedNS_ and self.ReasonCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sReasonCode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ReasonCode), input_name='ReasonCode')), namespaceprefix_ , eol_)) - if self.GeoCertified is not None: - namespaceprefix_ = self.GeoCertified_nsprefix_ + ':' if (UseCapturedNS_ and self.GeoCertified_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sGeoCertified>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.GeoCertified, input_name='GeoCertified'), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'EventTime': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'EventTime') - value_ = self.gds_validate_string(value_, node, 'EventTime') - self.EventTime = value_ - self.EventTime_nsprefix_ = child_.prefix - elif nodeName_ == 'EventDate': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'EventDate') - value_ = self.gds_validate_string(value_, node, 'EventDate') - self.EventDate = value_ - self.EventDate_nsprefix_ = child_.prefix - elif nodeName_ == 'Event': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Event') - value_ = self.gds_validate_string(value_, node, 'Event') - self.Event = value_ - self.Event_nsprefix_ = child_.prefix - elif nodeName_ == 'EventCity': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'EventCity') - value_ = self.gds_validate_string(value_, node, 'EventCity') - self.EventCity = value_ - self.EventCity_nsprefix_ = child_.prefix - elif nodeName_ == 'EventState': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'EventState') - value_ = self.gds_validate_string(value_, node, 'EventState') - self.EventState = value_ - self.EventState_nsprefix_ = child_.prefix - elif nodeName_ == 'EventZIPCode' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'EventZIPCode') - ival_ = self.gds_validate_integer(ival_, node, 'EventZIPCode') - self.EventZIPCode = ival_ - self.EventZIPCode_nsprefix_ = child_.prefix - elif nodeName_ == 'EventCountry': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'EventCountry') - value_ = self.gds_validate_string(value_, node, 'EventCountry') - self.EventCountry = value_ - self.EventCountry_nsprefix_ = child_.prefix - elif nodeName_ == 'FirmName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FirmName') - value_ = self.gds_validate_string(value_, node, 'FirmName') - self.FirmName = value_ - self.FirmName_nsprefix_ = child_.prefix - elif nodeName_ == 'Name': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Name') - value_ = self.gds_validate_string(value_, node, 'Name') - self.Name = value_ - self.Name_nsprefix_ = child_.prefix - elif nodeName_ == 'AuthorizedAgent': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'AuthorizedAgent') - ival_ = self.gds_validate_boolean(ival_, node, 'AuthorizedAgent') - self.AuthorizedAgent = ival_ - self.AuthorizedAgent_nsprefix_ = child_.prefix - elif nodeName_ == 'EventCode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'EventCode') - value_ = self.gds_validate_string(value_, node, 'EventCode') - self.EventCode = value_ - self.EventCode_nsprefix_ = child_.prefix - elif nodeName_ == 'ActionCode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ActionCode') - value_ = self.gds_validate_string(value_, node, 'ActionCode') - self.ActionCode = value_ - self.ActionCode_nsprefix_ = child_.prefix - elif nodeName_ == 'ReasonCode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ReasonCode') - value_ = self.gds_validate_string(value_, node, 'ReasonCode') - self.ReasonCode = value_ - self.ReasonCode_nsprefix_ = child_.prefix - elif nodeName_ == 'GeoCertified': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'GeoCertified') - ival_ = self.gds_validate_boolean(ival_, node, 'GeoCertified') - self.GeoCertified = ival_ - self.GeoCertified_nsprefix_ = child_.prefix -# end class TrackSummaryType - - -class TrackDetailType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, EventTime=None, EventDate=None, Event=None, EventCity=None, EventState=None, EventZIPCode=None, EventCountry=None, FirmName=None, Name=None, AuthorizedAgent=None, GeoCertified=None, EventCode=None, ActionCode=None, ReasonCode=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.EventTime = EventTime - self.EventTime_nsprefix_ = None - self.EventDate = EventDate - self.EventDate_nsprefix_ = None - self.Event = Event - self.Event_nsprefix_ = None - self.EventCity = EventCity - self.EventCity_nsprefix_ = None - self.EventState = EventState - self.EventState_nsprefix_ = None - self.EventZIPCode = EventZIPCode - self.EventZIPCode_nsprefix_ = None - self.EventCountry = EventCountry - self.EventCountry_nsprefix_ = None - self.FirmName = FirmName - self.FirmName_nsprefix_ = None - self.Name = Name - self.Name_nsprefix_ = None - self.AuthorizedAgent = AuthorizedAgent - self.AuthorizedAgent_nsprefix_ = None - self.GeoCertified = GeoCertified - self.GeoCertified_nsprefix_ = None - self.EventCode = EventCode - self.EventCode_nsprefix_ = None - self.ActionCode = ActionCode - self.ActionCode_nsprefix_ = None - self.ReasonCode = ReasonCode - self.ReasonCode_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, TrackDetailType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if TrackDetailType.subclass: - return TrackDetailType.subclass(*args_, **kwargs_) - else: - return TrackDetailType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_EventTime(self): - return self.EventTime - def set_EventTime(self, EventTime): - self.EventTime = EventTime - def get_EventDate(self): - return self.EventDate - def set_EventDate(self, EventDate): - self.EventDate = EventDate - def get_Event(self): - return self.Event - def set_Event(self, Event): - self.Event = Event - def get_EventCity(self): - return self.EventCity - def set_EventCity(self, EventCity): - self.EventCity = EventCity - def get_EventState(self): - return self.EventState - def set_EventState(self, EventState): - self.EventState = EventState - def get_EventZIPCode(self): - return self.EventZIPCode - def set_EventZIPCode(self, EventZIPCode): - self.EventZIPCode = EventZIPCode - def get_EventCountry(self): - return self.EventCountry - def set_EventCountry(self, EventCountry): - self.EventCountry = EventCountry - def get_FirmName(self): - return self.FirmName - def set_FirmName(self, FirmName): - self.FirmName = FirmName - def get_Name(self): - return self.Name - def set_Name(self, Name): - self.Name = Name - def get_AuthorizedAgent(self): - return self.AuthorizedAgent - def set_AuthorizedAgent(self, AuthorizedAgent): - self.AuthorizedAgent = AuthorizedAgent - def get_GeoCertified(self): - return self.GeoCertified - def set_GeoCertified(self, GeoCertified): - self.GeoCertified = GeoCertified - def get_EventCode(self): - return self.EventCode - def set_EventCode(self, EventCode): - self.EventCode = EventCode - def get_ActionCode(self): - return self.ActionCode - def set_ActionCode(self, ActionCode): - self.ActionCode = ActionCode - def get_ReasonCode(self): - return self.ReasonCode - def set_ReasonCode(self, ReasonCode): - self.ReasonCode = ReasonCode - def _hasContent(self): - if ( - self.EventTime is not None or - self.EventDate is not None or - self.Event is not None or - self.EventCity is not None or - self.EventState is not None or - self.EventZIPCode is not None or - self.EventCountry is not None or - self.FirmName is not None or - self.Name is not None or - self.AuthorizedAgent is not None or - self.GeoCertified is not None or - self.EventCode is not None or - self.ActionCode is not None or - self.ReasonCode is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='TrackDetailType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('TrackDetailType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'TrackDetailType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='TrackDetailType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='TrackDetailType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='TrackDetailType'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='TrackDetailType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.EventTime is not None: - namespaceprefix_ = self.EventTime_nsprefix_ + ':' if (UseCapturedNS_ and self.EventTime_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEventTime>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.EventTime), input_name='EventTime')), namespaceprefix_ , eol_)) - if self.EventDate is not None: - namespaceprefix_ = self.EventDate_nsprefix_ + ':' if (UseCapturedNS_ and self.EventDate_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEventDate>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.EventDate), input_name='EventDate')), namespaceprefix_ , eol_)) - if self.Event is not None: - namespaceprefix_ = self.Event_nsprefix_ + ':' if (UseCapturedNS_ and self.Event_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEvent>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Event), input_name='Event')), namespaceprefix_ , eol_)) - if self.EventCity is not None: - namespaceprefix_ = self.EventCity_nsprefix_ + ':' if (UseCapturedNS_ and self.EventCity_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEventCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.EventCity), input_name='EventCity')), namespaceprefix_ , eol_)) - if self.EventState is not None: - namespaceprefix_ = self.EventState_nsprefix_ + ':' if (UseCapturedNS_ and self.EventState_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEventState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.EventState), input_name='EventState')), namespaceprefix_ , eol_)) - if self.EventZIPCode is not None: - namespaceprefix_ = self.EventZIPCode_nsprefix_ + ':' if (UseCapturedNS_ and self.EventZIPCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEventZIPCode>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.EventZIPCode, input_name='EventZIPCode'), namespaceprefix_ , eol_)) - if self.EventCountry is not None: - namespaceprefix_ = self.EventCountry_nsprefix_ + ':' if (UseCapturedNS_ and self.EventCountry_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEventCountry>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.EventCountry), input_name='EventCountry')), namespaceprefix_ , eol_)) - if self.FirmName is not None: - namespaceprefix_ = self.FirmName_nsprefix_ + ':' if (UseCapturedNS_ and self.FirmName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFirmName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FirmName), input_name='FirmName')), namespaceprefix_ , eol_)) - if self.Name is not None: - namespaceprefix_ = self.Name_nsprefix_ + ':' if (UseCapturedNS_ and self.Name_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Name), input_name='Name')), namespaceprefix_ , eol_)) - if self.AuthorizedAgent is not None: - namespaceprefix_ = self.AuthorizedAgent_nsprefix_ + ':' if (UseCapturedNS_ and self.AuthorizedAgent_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAuthorizedAgent>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.AuthorizedAgent, input_name='AuthorizedAgent'), namespaceprefix_ , eol_)) - if self.GeoCertified is not None: - namespaceprefix_ = self.GeoCertified_nsprefix_ + ':' if (UseCapturedNS_ and self.GeoCertified_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sGeoCertified>%s%s' % (namespaceprefix_ , self.gds_format_boolean(self.GeoCertified, input_name='GeoCertified'), namespaceprefix_ , eol_)) - if self.EventCode is not None: - namespaceprefix_ = self.EventCode_nsprefix_ + ':' if (UseCapturedNS_ and self.EventCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sEventCode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.EventCode), input_name='EventCode')), namespaceprefix_ , eol_)) - if self.ActionCode is not None: - namespaceprefix_ = self.ActionCode_nsprefix_ + ':' if (UseCapturedNS_ and self.ActionCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sActionCode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ActionCode), input_name='ActionCode')), namespaceprefix_ , eol_)) - if self.ReasonCode is not None: - namespaceprefix_ = self.ReasonCode_nsprefix_ + ':' if (UseCapturedNS_ and self.ReasonCode_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sReasonCode>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.ReasonCode), input_name='ReasonCode')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'EventTime': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'EventTime') - value_ = self.gds_validate_string(value_, node, 'EventTime') - self.EventTime = value_ - self.EventTime_nsprefix_ = child_.prefix - elif nodeName_ == 'EventDate': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'EventDate') - value_ = self.gds_validate_string(value_, node, 'EventDate') - self.EventDate = value_ - self.EventDate_nsprefix_ = child_.prefix - elif nodeName_ == 'Event': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Event') - value_ = self.gds_validate_string(value_, node, 'Event') - self.Event = value_ - self.Event_nsprefix_ = child_.prefix - elif nodeName_ == 'EventCity': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'EventCity') - value_ = self.gds_validate_string(value_, node, 'EventCity') - self.EventCity = value_ - self.EventCity_nsprefix_ = child_.prefix - elif nodeName_ == 'EventState': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'EventState') - value_ = self.gds_validate_string(value_, node, 'EventState') - self.EventState = value_ - self.EventState_nsprefix_ = child_.prefix - elif nodeName_ == 'EventZIPCode' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'EventZIPCode') - ival_ = self.gds_validate_integer(ival_, node, 'EventZIPCode') - self.EventZIPCode = ival_ - self.EventZIPCode_nsprefix_ = child_.prefix - elif nodeName_ == 'EventCountry': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'EventCountry') - value_ = self.gds_validate_string(value_, node, 'EventCountry') - self.EventCountry = value_ - self.EventCountry_nsprefix_ = child_.prefix - elif nodeName_ == 'FirmName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FirmName') - value_ = self.gds_validate_string(value_, node, 'FirmName') - self.FirmName = value_ - self.FirmName_nsprefix_ = child_.prefix - elif nodeName_ == 'Name': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Name') - value_ = self.gds_validate_string(value_, node, 'Name') - self.Name = value_ - self.Name_nsprefix_ = child_.prefix - elif nodeName_ == 'AuthorizedAgent': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'AuthorizedAgent') - ival_ = self.gds_validate_boolean(ival_, node, 'AuthorizedAgent') - self.AuthorizedAgent = ival_ - self.AuthorizedAgent_nsprefix_ = child_.prefix - elif nodeName_ == 'GeoCertified': - sval_ = child_.text - ival_ = self.gds_parse_boolean(sval_, node, 'GeoCertified') - ival_ = self.gds_validate_boolean(ival_, node, 'GeoCertified') - self.GeoCertified = ival_ - self.GeoCertified_nsprefix_ = child_.prefix - elif nodeName_ == 'EventCode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'EventCode') - value_ = self.gds_validate_string(value_, node, 'EventCode') - self.EventCode = value_ - self.EventCode_nsprefix_ = child_.prefix - elif nodeName_ == 'ActionCode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ActionCode') - value_ = self.gds_validate_string(value_, node, 'ActionCode') - self.ActionCode = value_ - self.ActionCode_nsprefix_ = child_.prefix - elif nodeName_ == 'ReasonCode': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'ReasonCode') - value_ = self.gds_validate_string(value_, node, 'ReasonCode') - self.ReasonCode = value_ - self.ReasonCode_nsprefix_ = child_.prefix -# end class TrackDetailType - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'TrackResponse' - rootClass = TrackResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'TrackResponse' - rootClass = TrackResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'TrackResponse' - rootClass = TrackResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'TrackResponse' - rootClass = TrackResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from track_response import *\n\n') - sys.stdout.write('import track_response as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "EMAILType", - "EnabledNotificationRequestsType", - "SMSType", - "TrackDetailType", - "TrackInfoType", - "TrackResponse", - "TrackSummaryType" -] diff --git a/schemas/usps/karrio/schemas/usps/zip_code_lookup_request.py b/schemas/usps/karrio/schemas/usps/zip_code_lookup_request.py deleted file mode 100644 index 048d0df37a..0000000000 --- a/schemas/usps/karrio/schemas/usps/zip_code_lookup_request.py +++ /dev/null @@ -1,1518 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:13 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/zip_code_lookup_request.py') -# -# Command line arguments: -# ./schemas/ZipCodeLookupRequest.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/zip_code_lookup_request.py" ./schemas/ZipCodeLookupRequest.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class ZipCodeLookupRequest(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, USERID=None, Address=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.USERID = _cast(None, USERID) - self.USERID_nsprefix_ = None - self.Address = Address - self.Address_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, ZipCodeLookupRequest) - if subclass is not None: - return subclass(*args_, **kwargs_) - if ZipCodeLookupRequest.subclass: - return ZipCodeLookupRequest.subclass(*args_, **kwargs_) - else: - return ZipCodeLookupRequest(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_Address(self): - return self.Address - def set_Address(self, Address): - self.Address = Address - def get_USERID(self): - return self.USERID - def set_USERID(self, USERID): - self.USERID = USERID - def _hasContent(self): - if ( - self.Address is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ZipCodeLookupRequest', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('ZipCodeLookupRequest') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'ZipCodeLookupRequest': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='ZipCodeLookupRequest') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='ZipCodeLookupRequest', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='ZipCodeLookupRequest'): - if self.USERID is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - outfile.write(' USERID=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.USERID), input_name='USERID')), )) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ZipCodeLookupRequest', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.Address is not None: - namespaceprefix_ = self.Address_nsprefix_ + ':' if (UseCapturedNS_ and self.Address_nsprefix_) else '' - self.Address.export(outfile, level, namespaceprefix_, namespacedef_='', name_='Address', pretty_print=pretty_print) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('USERID', node) - if value is not None and 'USERID' not in already_processed: - already_processed.add('USERID') - self.USERID = value - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'Address': - obj_ = AddressType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.Address = obj_ - obj_.original_tagname_ = 'Address' -# end class ZipCodeLookupRequest - - -class AddressType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ID=None, Address1=None, Address2=None, FirmName=None, City=None, State=None, Zip5=None, Zip4=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.ID = _cast(int, ID) - self.ID_nsprefix_ = None - self.Address1 = Address1 - self.Address1_nsprefix_ = None - self.Address2 = Address2 - self.Address2_nsprefix_ = None - self.FirmName = FirmName - self.FirmName_nsprefix_ = None - self.City = City - self.City_nsprefix_ = None - self.State = State - self.State_nsprefix_ = None - self.Zip5 = Zip5 - self.Zip5_nsprefix_ = None - self.Zip4 = Zip4 - self.Zip4_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, AddressType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if AddressType.subclass: - return AddressType.subclass(*args_, **kwargs_) - else: - return AddressType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_Address1(self): - return self.Address1 - def set_Address1(self, Address1): - self.Address1 = Address1 - def get_Address2(self): - return self.Address2 - def set_Address2(self, Address2): - self.Address2 = Address2 - def get_FirmName(self): - return self.FirmName - def set_FirmName(self, FirmName): - self.FirmName = FirmName - def get_City(self): - return self.City - def set_City(self, City): - self.City = City - def get_State(self): - return self.State - def set_State(self, State): - self.State = State - def get_Zip5(self): - return self.Zip5 - def set_Zip5(self, Zip5): - self.Zip5 = Zip5 - def get_Zip4(self): - return self.Zip4 - def set_Zip4(self, Zip4): - self.Zip4 = Zip4 - def get_ID(self): - return self.ID - def set_ID(self, ID): - self.ID = ID - def _hasContent(self): - if ( - self.Address1 is not None or - self.Address2 is not None or - self.FirmName is not None or - self.City is not None or - self.State is not None or - self.Zip5 is not None or - self.Zip4 is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='AddressType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('AddressType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'AddressType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='AddressType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='AddressType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='AddressType'): - if self.ID is not None and 'ID' not in already_processed: - already_processed.add('ID') - outfile.write(' ID="%s"' % self.gds_format_integer(self.ID, input_name='ID')) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='AddressType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.Address1 is not None: - namespaceprefix_ = self.Address1_nsprefix_ + ':' if (UseCapturedNS_ and self.Address1_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAddress1>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Address1), input_name='Address1')), namespaceprefix_ , eol_)) - if self.Address2 is not None: - namespaceprefix_ = self.Address2_nsprefix_ + ':' if (UseCapturedNS_ and self.Address2_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAddress2>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Address2), input_name='Address2')), namespaceprefix_ , eol_)) - if self.FirmName is not None: - namespaceprefix_ = self.FirmName_nsprefix_ + ':' if (UseCapturedNS_ and self.FirmName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFirmName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FirmName), input_name='FirmName')), namespaceprefix_ , eol_)) - if self.City is not None: - namespaceprefix_ = self.City_nsprefix_ + ':' if (UseCapturedNS_ and self.City_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.City), input_name='City')), namespaceprefix_ , eol_)) - if self.State is not None: - namespaceprefix_ = self.State_nsprefix_ + ':' if (UseCapturedNS_ and self.State_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.State), input_name='State')), namespaceprefix_ , eol_)) - if self.Zip5 is not None: - namespaceprefix_ = self.Zip5_nsprefix_ + ':' if (UseCapturedNS_ and self.Zip5_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sZip5>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.Zip5, input_name='Zip5'), namespaceprefix_ , eol_)) - if self.Zip4 is not None: - namespaceprefix_ = self.Zip4_nsprefix_ + ':' if (UseCapturedNS_ and self.Zip4_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sZip4>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Zip4), input_name='Zip4')), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('ID', node) - if value is not None and 'ID' not in already_processed: - already_processed.add('ID') - self.ID = self.gds_parse_integer(value, node, 'ID') - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'Address1': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Address1') - value_ = self.gds_validate_string(value_, node, 'Address1') - self.Address1 = value_ - self.Address1_nsprefix_ = child_.prefix - elif nodeName_ == 'Address2': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Address2') - value_ = self.gds_validate_string(value_, node, 'Address2') - self.Address2 = value_ - self.Address2_nsprefix_ = child_.prefix - elif nodeName_ == 'FirmName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FirmName') - value_ = self.gds_validate_string(value_, node, 'FirmName') - self.FirmName = value_ - self.FirmName_nsprefix_ = child_.prefix - elif nodeName_ == 'City': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'City') - value_ = self.gds_validate_string(value_, node, 'City') - self.City = value_ - self.City_nsprefix_ = child_.prefix - elif nodeName_ == 'State': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'State') - value_ = self.gds_validate_string(value_, node, 'State') - self.State = value_ - self.State_nsprefix_ = child_.prefix - elif nodeName_ == 'Zip5' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'Zip5') - ival_ = self.gds_validate_integer(ival_, node, 'Zip5') - self.Zip5 = ival_ - self.Zip5_nsprefix_ = child_.prefix - elif nodeName_ == 'Zip4': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Zip4') - value_ = self.gds_validate_string(value_, node, 'Zip4') - self.Zip4 = value_ - self.Zip4_nsprefix_ = child_.prefix -# end class AddressType - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'ZipCodeLookupRequest' - rootClass = ZipCodeLookupRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'ZipCodeLookupRequest' - rootClass = ZipCodeLookupRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'ZipCodeLookupRequest' - rootClass = ZipCodeLookupRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'ZipCodeLookupRequest' - rootClass = ZipCodeLookupRequest - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from zip_code_lookup_request import *\n\n') - sys.stdout.write('import zip_code_lookup_request as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "AddressType", - "ZipCodeLookupRequest" -] diff --git a/schemas/usps/karrio/schemas/usps/zip_code_lookup_response.py b/schemas/usps/karrio/schemas/usps/zip_code_lookup_response.py deleted file mode 100644 index 1c8145971d..0000000000 --- a/schemas/usps/karrio/schemas/usps/zip_code_lookup_response.py +++ /dev/null @@ -1,1533 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Sat Jun 18 01:03:13 2022 by generateDS.py version 2.40.13. -# Python 3.8.6 (v3.8.6:db455296be, Sep 23 2020, 13:31:39) [Clang 6.0 (clang-600.0.57)] -# -# Command line options: -# ('--no-namespace-defs', '') -# ('-o', './usps_lib/zip_code_lookup_response.py') -# -# Command line arguments: -# ./schemas/ZipCodeLookupResponse.xsd -# -# Command line: -# /Users/danielkobina/Workspace/project/karrio/.venv/karrio/bin/generateDS --no-namespace-defs -o "./usps_lib/zip_code_lookup_response.py" ./schemas/ZipCodeLookupResponse.xsd -# -# Current working directory (os.getcwd()): -# usps -# - -import sys -try: - ModulenotfoundExp_ = ModuleNotFoundError -except NameError: - ModulenotfoundExp_ = ImportError -from six.moves import zip_longest -import os -import re as re_ -import base64 -import datetime as datetime_ -import decimal as decimal_ -from lxml import etree as etree_ - - -Validate_simpletypes_ = True -SaveElementTreeNode = True -TagNamePrefix = "" -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - try: - if isinstance(infile, os.PathLike): - infile = os.path.join(infile) - except AttributeError: - pass - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -def parsexmlstring_(instring, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - element = etree_.fromstring(instring, parser=parser, **kwargs) - return element - -# -# Namespace prefix definition table (and other attributes, too) -# -# The module generatedsnamespaces, if it is importable, must contain -# a dictionary named GeneratedsNamespaceDefs. This Python dictionary -# should map element type names (strings) to XML schema namespace prefix -# definitions. The export method for any class for which there is -# a namespace prefix definition, will export that definition in the -# XML representation of that element. See the export method of -# any generated element type class for an example of the use of this -# table. -# A sample table is: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceDefs = { -# "ElementtypeA": "http://www.xxx.com/namespaceA", -# "ElementtypeB": "http://www.xxx.com/namespaceB", -# } -# -# Additionally, the generatedsnamespaces module can contain a python -# dictionary named GenerateDSNamespaceTypePrefixes that associates element -# types with the namespace prefixes that are to be added to the -# "xsi:type" attribute value. See the _exportAttributes method of -# any generated element type and the generation of "xsi:type" for an -# example of the use of this table. -# An example table: -# -# # File: generatedsnamespaces.py -# -# GenerateDSNamespaceTypePrefixes = { -# "ElementtypeC": "aaa:", -# "ElementtypeD": "bbb:", -# } -# - -try: - from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_ -except ModulenotfoundExp_ : - GenerateDSNamespaceDefs_ = {} -try: - from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_ -except ModulenotfoundExp_ : - GenerateDSNamespaceTypePrefixes_ = {} - -# -# You can replace the following class definition by defining an -# importable module named "generatedscollector" containing a class -# named "GdsCollector". See the default class definition below for -# clues about the possible content of that class. -# -try: - from generatedscollector import GdsCollector as GdsCollector_ -except ModulenotfoundExp_ : - - class GdsCollector_(object): - - def __init__(self, messages=None): - if messages is None: - self.messages = [] - else: - self.messages = messages - - def add_message(self, msg): - self.messages.append(msg) - - def get_messages(self): - return self.messages - - def clear_messages(self): - self.messages = [] - - def print_messages(self): - for msg in self.messages: - print("Warning: {}".format(msg)) - - def write_messages(self, outstream): - for msg in self.messages: - outstream.write("Warning: {}\n".format(msg)) - - -# -# The super-class for enum types -# - -try: - from enum import Enum -except ModulenotfoundExp_ : - Enum = object - -# -# The root super-class for element type classes -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ModulenotfoundExp_ as exp: - try: - from generatedssupersuper import GeneratedsSuperSuper - except ModulenotfoundExp_ as exp: - class GeneratedsSuperSuper(object): - pass - - class GeneratedsSuper(GeneratedsSuperSuper): - __hash__ = object.__hash__ - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def __str__(self): - settings = { - 'str_pretty_print': True, - 'str_indent_level': 0, - 'str_namespaceprefix': '', - 'str_name': self.__class__.__name__, - 'str_namespacedefs': '', - } - for n in settings: - if hasattr(self, n): - settings[n] = getattr(self, n) - if sys.version_info.major == 2: - from StringIO import StringIO - else: - from io import StringIO - output = StringIO() - self.export( - output, - settings['str_indent_level'], - pretty_print=settings['str_pretty_print'], - namespaceprefix_=settings['str_namespaceprefix'], - name_=settings['str_name'], - namespacedef_=settings['str_namespacedefs'] - ) - strval = output.getvalue() - output.close() - return strval - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_parse_string(self, input_data, node=None, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data).decode('ascii') - def gds_validate_base64(self, input_data, node=None, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % int(input_data) - def gds_parse_integer(self, input_data, node=None, input_name=''): - try: - ival = int(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires integer value: %s' % exp) - return ival - def gds_validate_integer(self, input_data, node=None, input_name=''): - try: - value = int(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires integer value') - return value - def gds_format_integer_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integer values') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % float(input_data)).rstrip('0') - def gds_parse_float(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires float or double value: %s' % exp) - return fval_ - def gds_validate_float(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires float value') - return value - def gds_format_float_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of float values') - return values - def gds_format_decimal(self, input_data, input_name=''): - return_value = '%s' % input_data - if '.' in return_value: - return_value = return_value.rstrip('0') - if return_value.endswith('.'): - return_value = return_value.rstrip('.') - return return_value - def gds_parse_decimal(self, input_data, node=None, input_name=''): - try: - decimal_value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return decimal_value - def gds_validate_decimal(self, input_data, node=None, input_name=''): - try: - value = decimal_.Decimal(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires decimal value') - return value - def gds_format_decimal_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return ' '.join([self.gds_format_decimal(item) for item in input_data]) - def gds_validate_decimal_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - decimal_.Decimal(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of decimal values') - return values - def gds_format_double(self, input_data, input_name=''): - return '%s' % input_data - def gds_parse_double(self, input_data, node=None, input_name=''): - try: - fval_ = float(input_data) - except (TypeError, ValueError) as exp: - raise_parse_error(node, 'Requires double or float value: %s' % exp) - return fval_ - def gds_validate_double(self, input_data, node=None, input_name=''): - try: - value = float(input_data) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires double or float value') - return value - def gds_format_double_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error( - node, 'Requires sequence of double or float values') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_parse_boolean(self, input_data, node=None, input_name=''): - input_data = input_data.strip() - if input_data in ('true', '1'): - bval = True - elif input_data in ('false', '0'): - bval = False - else: - raise_parse_error(node, 'Requires boolean value') - return bval - def gds_validate_boolean(self, input_data, node=None, input_name=''): - if input_data not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires boolean value ' - '(one of True, 1, False, 0)') - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_): - input_data = [str(s) for s in input_data] - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - value = self.gds_parse_boolean(value, node, input_name) - if value not in (True, 1, False, 0, ): - raise_parse_error( - node, - 'Requires sequence of boolean values ' - '(one of True, 1, False, 0)') - return values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % ( - time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. - # The target value must match at least one of the patterns - # in order for the test to succeed. - found1 = True - target = str(target) - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - mo = re_.search(patterns2, target) - if mo is not None and len(mo.group(0)) == len(target): - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - def gds_check_cardinality_( - self, value, input_name, - min_occurs=0, max_occurs=1, required=None): - if value is None: - length = 0 - elif isinstance(value, list): - length = len(value) - else: - length = 1 - if required is not None : - if required and length < 1: - self.gds_collector_.add_message( - "Required value {}{} is missing".format( - input_name, self.gds_get_node_lineno_())) - if length < min_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is below " - "the minimum allowed, " - "expected at least {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - min_occurs, length)) - elif length > max_occurs: - self.gds_collector_.add_message( - "Number of values for {}{} is above " - "the maximum allowed, " - "expected at most {}, found {}".format( - input_name, self.gds_get_node_lineno_(), - max_occurs, length)) - def gds_validate_builtin_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value, input_name=input_name) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_validate_defined_ST_( - self, validator, value, input_name, - min_occurs=None, max_occurs=None, required=None): - if value is not None: - try: - validator(value) - except GDSParseError as parse_error: - self.gds_collector_.add_message(str(parse_error)) - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - def get_class_obj_(self, node, default_class=None): - class_obj1 = default_class - if 'xsi' in node.nsmap: - classname = node.get('{%s}type' % node.nsmap['xsi']) - if classname is not None: - names = classname.split(':') - if len(names) == 2: - classname = names[1] - class_obj2 = globals().get(classname) - if class_obj2 is not None: - class_obj1 = class_obj2 - return class_obj1 - def gds_build_any(self, node, type_name=None): - # provide default value in case option --disable-xml is used. - content = "" - content = etree_.tostring(node, encoding="unicode") - return content - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.items())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - if ExternalEncoding: - encoding = ExternalEncoding - else: - encoding = 'utf-8' - return instring.encode(encoding) - else: - return instring - @staticmethod - def convert_unicode(instring): - if isinstance(instring, str): - result = quote_xml(instring) - elif sys.version_info.major == 2 and isinstance(instring, unicode): - result = quote_xml(instring).encode('utf8') - else: - result = GeneratedsSuper.gds_encode(str(instring)) - return result - def __eq__(self, other): - def excl_select_objs_(obj): - return (obj[0] != 'parent_object_' and - obj[0] != 'gds_collector_') - if type(self) != type(other): - return False - return all(x == y for x, y in zip_longest( - filter(excl_select_objs_, self.__dict__.items()), - filter(excl_select_objs_, other.__dict__.items()))) - def __ne__(self, other): - return not self.__eq__(other) - # Django ETL transform hooks. - def gds_djo_etl_transform(self): - pass - def gds_djo_etl_transform_db_obj(self, dbobj): - pass - # SQLAlchemy ETL transform hooks. - def gds_sqa_etl_transform(self): - return 0, None - def gds_sqa_etl_transform_db_obj(self, dbobj): - pass - def gds_get_node_lineno_(self): - if (hasattr(self, "gds_elementtree_node_") and - self.gds_elementtree_node_ is not None): - return ' near line {}'.format( - self.gds_elementtree_node_.sourceline) - else: - return "" - - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - return None - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = '' -# Set this to false in order to deactivate during export, the use of -# name space prefixes captured from the input document. -UseCapturedNS_ = True -CapturedNsmap_ = {} -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - s1 = s1.replace('\n', ' ') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - - -def find_attr_value_(attr_name, node): - attrs = node.attrib - attr_parts = attr_name.split(':') - value = None - if len(attr_parts) == 1: - value = attrs.get(attr_name) - elif len(attr_parts) == 2: - prefix, name = attr_parts - if prefix == 'xml': - namespace = 'http://www.w3.org/XML/1998/namespace' - else: - namespace = node.nsmap.get(prefix) - if namespace is not None: - value = attrs.get('{%s}%s' % (namespace, name, )) - return value - - -def encode_str_2_3(instr): - return instr - - -class GDSParseError(Exception): - pass - - -def raise_parse_error(node, msg): - if node is not None: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - TypeBase64 = 8 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace, - pretty_print=True): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export( - outfile, level, namespace, name_=name, - pretty_print=pretty_print) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % ( - self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s' % ( - self.name, - base64.b64encode(self.value), - self.name)) - def to_etree(self, element, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement( - element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self, mapping_=None, reverse_mapping_=None, nsmap_=None): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % ( - self.category, self.content_type, - self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write( - 'model_.MixedContainer(%d, %d, "%s",\n' % ( - self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0, - optional=0, child_attrs=None, choice=None): - self.name = name - self.data_type = data_type - self.container = container - self.child_attrs = child_attrs - self.choice = choice - self.optional = optional - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs - def get_child_attrs(self): return self.child_attrs - def set_choice(self, choice): self.choice = choice - def get_choice(self): return self.choice - def set_optional(self, optional): self.optional = optional - def get_optional(self): return self.optional - - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - - -class ZipCodeLookupResponse(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, Address=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - if Address is None: - self.Address = [] - else: - self.Address = Address - self.Address_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, ZipCodeLookupResponse) - if subclass is not None: - return subclass(*args_, **kwargs_) - if ZipCodeLookupResponse.subclass: - return ZipCodeLookupResponse.subclass(*args_, **kwargs_) - else: - return ZipCodeLookupResponse(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_Address(self): - return self.Address - def set_Address(self, Address): - self.Address = Address - def add_Address(self, value): - self.Address.append(value) - def insert_Address_at(self, index, value): - self.Address.insert(index, value) - def replace_Address_at(self, index, value): - self.Address[index] = value - def _hasContent(self): - if ( - self.Address - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ZipCodeLookupResponse', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('ZipCodeLookupResponse') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'ZipCodeLookupResponse': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='ZipCodeLookupResponse') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='ZipCodeLookupResponse', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='ZipCodeLookupResponse'): - pass - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='ZipCodeLookupResponse', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - for Address_ in self.Address: - namespaceprefix_ = self.Address_nsprefix_ + ':' if (UseCapturedNS_ and self.Address_nsprefix_) else '' - Address_.export(outfile, level, namespaceprefix_, namespacedef_='', name_='Address', pretty_print=pretty_print) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - pass - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'Address': - obj_ = AddressType.factory(parent_object_=self) - obj_.build(child_, gds_collector_=gds_collector_) - self.Address.append(obj_) - obj_.original_tagname_ = 'Address' -# end class ZipCodeLookupResponse - - -class AddressType(GeneratedsSuper): - __hash__ = GeneratedsSuper.__hash__ - subclass = None - superclass = None - def __init__(self, ID=None, Address1=None, Address2=None, City=None, FirmName=None, State=None, Urbanization=None, Zip5=None, Zip4=None, gds_collector_=None, **kwargs_): - self.gds_collector_ = gds_collector_ - self.gds_elementtree_node_ = None - self.original_tagname_ = None - self.parent_object_ = kwargs_.get('parent_object_') - self.ns_prefix_ = None - self.ID = _cast(int, ID) - self.ID_nsprefix_ = None - self.Address1 = Address1 - self.Address1_nsprefix_ = None - self.Address2 = Address2 - self.Address2_nsprefix_ = None - self.City = City - self.City_nsprefix_ = None - self.FirmName = FirmName - self.FirmName_nsprefix_ = None - self.State = State - self.State_nsprefix_ = None - self.Urbanization = Urbanization - self.Urbanization_nsprefix_ = None - self.Zip5 = Zip5 - self.Zip5_nsprefix_ = None - self.Zip4 = Zip4 - self.Zip4_nsprefix_ = None - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, AddressType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if AddressType.subclass: - return AddressType.subclass(*args_, **kwargs_) - else: - return AddressType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_ns_prefix_(self): - return self.ns_prefix_ - def set_ns_prefix_(self, ns_prefix): - self.ns_prefix_ = ns_prefix - def get_Address1(self): - return self.Address1 - def set_Address1(self, Address1): - self.Address1 = Address1 - def get_Address2(self): - return self.Address2 - def set_Address2(self, Address2): - self.Address2 = Address2 - def get_City(self): - return self.City - def set_City(self, City): - self.City = City - def get_FirmName(self): - return self.FirmName - def set_FirmName(self, FirmName): - self.FirmName = FirmName - def get_State(self): - return self.State - def set_State(self, State): - self.State = State - def get_Urbanization(self): - return self.Urbanization - def set_Urbanization(self, Urbanization): - self.Urbanization = Urbanization - def get_Zip5(self): - return self.Zip5 - def set_Zip5(self, Zip5): - self.Zip5 = Zip5 - def get_Zip4(self): - return self.Zip4 - def set_Zip4(self, Zip4): - self.Zip4 = Zip4 - def get_ID(self): - return self.ID - def set_ID(self, ID): - self.ID = ID - def _hasContent(self): - if ( - self.Address1 is not None or - self.Address2 is not None or - self.City is not None or - self.FirmName is not None or - self.State is not None or - self.Urbanization is not None or - self.Zip5 is not None or - self.Zip4 is not None - ): - return True - else: - return False - def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='AddressType', pretty_print=True): - imported_ns_def_ = GenerateDSNamespaceDefs_.get('AddressType') - if imported_ns_def_ is not None: - namespacedef_ = imported_ns_def_ - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None and name_ == 'AddressType': - name_ = self.original_tagname_ - if UseCapturedNS_ and self.ns_prefix_: - namespaceprefix_ = self.ns_prefix_ + ':' - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self._exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='AddressType') - if self._hasContent(): - outfile.write('>%s' % (eol_, )) - self._exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='AddressType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('%s' % (namespaceprefix_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def _exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='AddressType'): - if self.ID is not None and 'ID' not in already_processed: - already_processed.add('ID') - outfile.write(' ID="%s"' % self.gds_format_integer(self.ID, input_name='ID')) - def _exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='AddressType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.Address1 is not None: - namespaceprefix_ = self.Address1_nsprefix_ + ':' if (UseCapturedNS_ and self.Address1_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAddress1>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Address1), input_name='Address1')), namespaceprefix_ , eol_)) - if self.Address2 is not None: - namespaceprefix_ = self.Address2_nsprefix_ + ':' if (UseCapturedNS_ and self.Address2_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sAddress2>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Address2), input_name='Address2')), namespaceprefix_ , eol_)) - if self.City is not None: - namespaceprefix_ = self.City_nsprefix_ + ':' if (UseCapturedNS_ and self.City_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sCity>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.City), input_name='City')), namespaceprefix_ , eol_)) - if self.FirmName is not None: - namespaceprefix_ = self.FirmName_nsprefix_ + ':' if (UseCapturedNS_ and self.FirmName_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sFirmName>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.FirmName), input_name='FirmName')), namespaceprefix_ , eol_)) - if self.State is not None: - namespaceprefix_ = self.State_nsprefix_ + ':' if (UseCapturedNS_ and self.State_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sState>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.State), input_name='State')), namespaceprefix_ , eol_)) - if self.Urbanization is not None: - namespaceprefix_ = self.Urbanization_nsprefix_ + ':' if (UseCapturedNS_ and self.Urbanization_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sUrbanization>%s%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Urbanization), input_name='Urbanization')), namespaceprefix_ , eol_)) - if self.Zip5 is not None: - namespaceprefix_ = self.Zip5_nsprefix_ + ':' if (UseCapturedNS_ and self.Zip5_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sZip5>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.Zip5, input_name='Zip5'), namespaceprefix_ , eol_)) - if self.Zip4 is not None: - namespaceprefix_ = self.Zip4_nsprefix_ + ':' if (UseCapturedNS_ and self.Zip4_nsprefix_) else '' - showIndent(outfile, level, pretty_print) - outfile.write('<%sZip4>%s%s' % (namespaceprefix_ , self.gds_format_integer(self.Zip4, input_name='Zip4'), namespaceprefix_ , eol_)) - def build(self, node, gds_collector_=None): - self.gds_collector_ = gds_collector_ - if SaveElementTreeNode: - self.gds_elementtree_node_ = node - already_processed = set() - self.ns_prefix_ = node.prefix - self._buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self._buildChildren(child, node, nodeName_, gds_collector_=gds_collector_) - return self - def _buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('ID', node) - if value is not None and 'ID' not in already_processed: - already_processed.add('ID') - self.ID = self.gds_parse_integer(value, node, 'ID') - def _buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): - if nodeName_ == 'Address1': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Address1') - value_ = self.gds_validate_string(value_, node, 'Address1') - self.Address1 = value_ - self.Address1_nsprefix_ = child_.prefix - elif nodeName_ == 'Address2': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Address2') - value_ = self.gds_validate_string(value_, node, 'Address2') - self.Address2 = value_ - self.Address2_nsprefix_ = child_.prefix - elif nodeName_ == 'City': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'City') - value_ = self.gds_validate_string(value_, node, 'City') - self.City = value_ - self.City_nsprefix_ = child_.prefix - elif nodeName_ == 'FirmName': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'FirmName') - value_ = self.gds_validate_string(value_, node, 'FirmName') - self.FirmName = value_ - self.FirmName_nsprefix_ = child_.prefix - elif nodeName_ == 'State': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'State') - value_ = self.gds_validate_string(value_, node, 'State') - self.State = value_ - self.State_nsprefix_ = child_.prefix - elif nodeName_ == 'Urbanization': - value_ = child_.text - value_ = self.gds_parse_string(value_, node, 'Urbanization') - value_ = self.gds_validate_string(value_, node, 'Urbanization') - self.Urbanization = value_ - self.Urbanization_nsprefix_ = child_.prefix - elif nodeName_ == 'Zip5' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'Zip5') - ival_ = self.gds_validate_integer(ival_, node, 'Zip5') - self.Zip5 = ival_ - self.Zip5_nsprefix_ = child_.prefix - elif nodeName_ == 'Zip4' and child_.text: - sval_ = child_.text - ival_ = self.gds_parse_integer(sval_, node, 'Zip4') - ival_ = self.gds_validate_integer(ival_, node, 'Zip4') - self.Zip4 = ival_ - self.Zip4_nsprefix_ = child_.prefix -# end class AddressType - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - prefix_tag = TagNamePrefix + tag - rootClass = GDSClassesMapping.get(prefix_tag) - if rootClass is None: - rootClass = globals().get(prefix_tag) - return tag, rootClass - - -def get_required_ns_prefix_defs(rootNode): - '''Get all name space prefix definitions required in this XML doc. - Return a dictionary of definitions and a char string of definitions. - ''' - nsmap = { - prefix: uri - for node in rootNode.iter() - for (prefix, uri) in node.nsmap.items() - if prefix is not None - } - namespacedefs = ' '.join([ - 'xmlns:{}="{}"'.format(prefix, uri) - for prefix, uri in nsmap.items() - ]) - return nsmap, namespacedefs - - -def parse(inFileName, silence=False, print_warnings=True): - global CapturedNsmap_ - gds_collector = GdsCollector_() - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'ZipCodeLookupResponse' - rootClass = ZipCodeLookupResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode) - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_=namespacedefs, - pretty_print=True) - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseEtree(inFileName, silence=False, print_warnings=True, - mapping=None, reverse_mapping=None, nsmap=None): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'ZipCodeLookupResponse' - rootClass = ZipCodeLookupResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if mapping is None: - mapping = {} - if reverse_mapping is None: - reverse_mapping = {} - rootElement = rootObj.to_etree( - None, name_=rootTag, mapping_=mapping, - reverse_mapping_=reverse_mapping, nsmap_=nsmap) - reverse_node_mapping = rootObj.gds_reverse_node_mapping(mapping) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(str(content)) - sys.stdout.write('\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj, rootElement, mapping, reverse_node_mapping - - -def parseString(inString, silence=False, print_warnings=True): - '''Parse a string, create the object tree, and export it. - - Arguments: - - inString -- A string. This XML fragment should not start - with an XML declaration containing an encoding. - - silence -- A boolean. If False, export the object. - Returns -- The root object in the tree. - ''' - parser = None - rootNode= parsexmlstring_(inString, parser) - gds_collector = GdsCollector_() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'ZipCodeLookupResponse' - rootClass = ZipCodeLookupResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - if not SaveElementTreeNode: - rootNode = None - if not silence: - sys.stdout.write('\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def parseLiteral(inFileName, silence=False, print_warnings=True): - parser = None - doc = parsexml_(inFileName, parser) - gds_collector = GdsCollector_() - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'ZipCodeLookupResponse' - rootClass = ZipCodeLookupResponse - rootObj = rootClass.factory() - rootObj.build(rootNode, gds_collector_=gds_collector) - # Enable Python to collect the space used by the DOM. - if not SaveElementTreeNode: - doc = None - rootNode = None - if not silence: - sys.stdout.write('#from zip_code_lookup_response import *\n\n') - sys.stdout.write('import zip_code_lookup_response as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - if print_warnings and len(gds_collector.get_messages()) > 0: - separator = ('-' * 50) + '\n' - sys.stderr.write(separator) - sys.stderr.write('----- Warnings -- count: {} -----\n'.format( - len(gds_collector.get_messages()), )) - gds_collector.write_messages(sys.stderr) - sys.stderr.write(separator) - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - -RenameMappings_ = { -} - -# -# Mapping of namespaces to types defined in them -# and the file in which each is defined. -# simpleTypes are marked "ST" and complexTypes "CT". -NamespaceToDefMappings_ = {} - -__all__ = [ - "AddressType", - "ZipCodeLookupResponse" -] diff --git a/schemas/usps/schemas/AddressValidateRequest.xsd b/schemas/usps/schemas/AddressValidateRequest.xsd deleted file mode 100644 index 83a1ff85d6..0000000000 --- a/schemas/usps/schemas/AddressValidateRequest.xsd +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/AddressValidateResponse.xsd b/schemas/usps/schemas/AddressValidateResponse.xsd deleted file mode 100644 index cf6a471ecc..0000000000 --- a/schemas/usps/schemas/AddressValidateResponse.xsd +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/CarrierPickupAvailabilityRequest.xsd b/schemas/usps/schemas/CarrierPickupAvailabilityRequest.xsd deleted file mode 100644 index e88df95ff1..0000000000 --- a/schemas/usps/schemas/CarrierPickupAvailabilityRequest.xsd +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/CarrierPickupAvailabilityResponse.xsd b/schemas/usps/schemas/CarrierPickupAvailabilityResponse.xsd deleted file mode 100644 index 248c141b92..0000000000 --- a/schemas/usps/schemas/CarrierPickupAvailabilityResponse.xsd +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/CarrierPickupCancelRequest.xsd b/schemas/usps/schemas/CarrierPickupCancelRequest.xsd deleted file mode 100644 index f795062dc0..0000000000 --- a/schemas/usps/schemas/CarrierPickupCancelRequest.xsd +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/CarrierPickupCancelResponse.xsd b/schemas/usps/schemas/CarrierPickupCancelResponse.xsd deleted file mode 100644 index 3200cb85ef..0000000000 --- a/schemas/usps/schemas/CarrierPickupCancelResponse.xsd +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/CarrierPickupChangeRequest.xsd b/schemas/usps/schemas/CarrierPickupChangeRequest.xsd deleted file mode 100644 index 8c4ec6ce8e..0000000000 --- a/schemas/usps/schemas/CarrierPickupChangeRequest.xsd +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/CarrierPickupChangeResponse.xsd b/schemas/usps/schemas/CarrierPickupChangeResponse.xsd deleted file mode 100644 index e95b729ece..0000000000 --- a/schemas/usps/schemas/CarrierPickupChangeResponse.xsd +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/CarrierPickupInquiryRequest.xsd b/schemas/usps/schemas/CarrierPickupInquiryRequest.xsd deleted file mode 100644 index 62693a9124..0000000000 --- a/schemas/usps/schemas/CarrierPickupInquiryRequest.xsd +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/CarrierPickupInquiryResponse.xsd b/schemas/usps/schemas/CarrierPickupInquiryResponse.xsd deleted file mode 100644 index ddd5162dcb..0000000000 --- a/schemas/usps/schemas/CarrierPickupInquiryResponse.xsd +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/CarrierPickupScheduleRequest.xsd b/schemas/usps/schemas/CarrierPickupScheduleRequest.xsd deleted file mode 100644 index e3dfb118f4..0000000000 --- a/schemas/usps/schemas/CarrierPickupScheduleRequest.xsd +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/CarrierPickupScheduleResponse.xsd b/schemas/usps/schemas/CarrierPickupScheduleResponse.xsd deleted file mode 100644 index bffdac0d99..0000000000 --- a/schemas/usps/schemas/CarrierPickupScheduleResponse.xsd +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/CityStateLookupRequest.xsd b/schemas/usps/schemas/CityStateLookupRequest.xsd deleted file mode 100644 index 00fb571063..0000000000 --- a/schemas/usps/schemas/CityStateLookupRequest.xsd +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/CityStateLookupResponse.xsd b/schemas/usps/schemas/CityStateLookupResponse.xsd deleted file mode 100644 index b2937464a0..0000000000 --- a/schemas/usps/schemas/CityStateLookupResponse.xsd +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/EMRSV4.0BulkRequest.xsd b/schemas/usps/schemas/EMRSV4.0BulkRequest.xsd deleted file mode 100644 index 0b485a2d8e..0000000000 --- a/schemas/usps/schemas/EMRSV4.0BulkRequest.xsd +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/Error.xsd b/schemas/usps/schemas/Error.xsd deleted file mode 100644 index 447ae72804..0000000000 --- a/schemas/usps/schemas/Error.xsd +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/ExpressMailCommitmentRequest.xsd b/schemas/usps/schemas/ExpressMailCommitmentRequest.xsd deleted file mode 100644 index f780342a9b..0000000000 --- a/schemas/usps/schemas/ExpressMailCommitmentRequest.xsd +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/ExpressMailCommitmentResponse.xsd b/schemas/usps/schemas/ExpressMailCommitmentResponse.xsd deleted file mode 100644 index 24d8ebbda3..0000000000 --- a/schemas/usps/schemas/ExpressMailCommitmentResponse.xsd +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/FirstClassMailRequest.xsd b/schemas/usps/schemas/FirstClassMailRequest.xsd deleted file mode 100644 index 742c372c79..0000000000 --- a/schemas/usps/schemas/FirstClassMailRequest.xsd +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/FirstClassMailResponse.xsd b/schemas/usps/schemas/FirstClassMailResponse.xsd deleted file mode 100644 index 79bc0cbc0b..0000000000 --- a/schemas/usps/schemas/FirstClassMailResponse.xsd +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/HFPFacilityInfoRequest.xsd b/schemas/usps/schemas/HFPFacilityInfoRequest.xsd deleted file mode 100644 index dc9a238b3d..0000000000 --- a/schemas/usps/schemas/HFPFacilityInfoRequest.xsd +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/HFPFacilityInfoResponse.xsd b/schemas/usps/schemas/HFPFacilityInfoResponse.xsd deleted file mode 100644 index 45f171ca60..0000000000 --- a/schemas/usps/schemas/HFPFacilityInfoResponse.xsd +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/IntlRateV2Request.xsd b/schemas/usps/schemas/IntlRateV2Request.xsd deleted file mode 100644 index f6fcd7a6c6..0000000000 --- a/schemas/usps/schemas/IntlRateV2Request.xsd +++ /dev/null @@ -1,72 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/IntlRateV2Response.xsd b/schemas/usps/schemas/IntlRateV2Response.xsd deleted file mode 100644 index 4b43fbc858..0000000000 --- a/schemas/usps/schemas/IntlRateV2Response.xsd +++ /dev/null @@ -1,104 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/MRSV4.0Request.xsd b/schemas/usps/schemas/MRSV4.0Request.xsd deleted file mode 100644 index 295c020dbe..0000000000 --- a/schemas/usps/schemas/MRSV4.0Request.xsd +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/PTSEmailRequest.xsd b/schemas/usps/schemas/PTSEmailRequest.xsd deleted file mode 100644 index 1eb61c1b67..0000000000 --- a/schemas/usps/schemas/PTSEmailRequest.xsd +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/PTSEmailResult.xsd b/schemas/usps/schemas/PTSEmailResult.xsd deleted file mode 100644 index bc7f37333b..0000000000 --- a/schemas/usps/schemas/PTSEmailResult.xsd +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/PTSPODRequest.xsd b/schemas/usps/schemas/PTSPODRequest.xsd deleted file mode 100644 index 88df9d1839..0000000000 --- a/schemas/usps/schemas/PTSPODRequest.xsd +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/PTSPODResult.xsd b/schemas/usps/schemas/PTSPODResult.xsd deleted file mode 100644 index cad85f5c0a..0000000000 --- a/schemas/usps/schemas/PTSPODResult.xsd +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/PTSRRERequest.xsd b/schemas/usps/schemas/PTSRRERequest.xsd deleted file mode 100644 index 3d6deb1e83..0000000000 --- a/schemas/usps/schemas/PTSRRERequest.xsd +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/PTSRREResult.xsd b/schemas/usps/schemas/PTSRREResult.xsd deleted file mode 100644 index 8e6a920c77..0000000000 --- a/schemas/usps/schemas/PTSRREResult.xsd +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/PTSTPODResult.xsd b/schemas/usps/schemas/PTSTPODResult.xsd deleted file mode 100644 index a7e1f911e4..0000000000 --- a/schemas/usps/schemas/PTSTPODResult.xsd +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/PTSTPodRequest.xsd b/schemas/usps/schemas/PTSTPodRequest.xsd deleted file mode 100644 index 04bc7b0da1..0000000000 --- a/schemas/usps/schemas/PTSTPodRequest.xsd +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/PriorityMailRequest.xsd b/schemas/usps/schemas/PriorityMailRequest.xsd deleted file mode 100644 index 72fccbf75f..0000000000 --- a/schemas/usps/schemas/PriorityMailRequest.xsd +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/PriorityMailResponse.xsd b/schemas/usps/schemas/PriorityMailResponse.xsd deleted file mode 100644 index 0efd8d5dee..0000000000 --- a/schemas/usps/schemas/PriorityMailResponse.xsd +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/RateV4Request.xsd b/schemas/usps/schemas/RateV4Request.xsd deleted file mode 100644 index 931b0740c2..0000000000 --- a/schemas/usps/schemas/RateV4Request.xsd +++ /dev/null @@ -1,80 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/RateV4Response.xsd b/schemas/usps/schemas/RateV4Response.xsd deleted file mode 100644 index 2a98ba9448..0000000000 --- a/schemas/usps/schemas/RateV4Response.xsd +++ /dev/null @@ -1,85 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/SCANRequest.xsd b/schemas/usps/schemas/SCANRequest.xsd deleted file mode 100644 index 6fd27bf3a6..0000000000 --- a/schemas/usps/schemas/SCANRequest.xsd +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/SCANResponse.xsd b/schemas/usps/schemas/SCANResponse.xsd deleted file mode 100644 index f20e2ab8f9..0000000000 --- a/schemas/usps/schemas/SCANResponse.xsd +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - - - - - 65255 skipped - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/SDCGetLocationsRequest.xsd b/schemas/usps/schemas/SDCGetLocationsRequest.xsd deleted file mode 100644 index 2c5be3156d..0000000000 --- a/schemas/usps/schemas/SDCGetLocationsRequest.xsd +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/SDCGetLocationsResponse.xsd b/schemas/usps/schemas/SDCGetLocationsResponse.xsd deleted file mode 100644 index 2d6234bb0e..0000000000 --- a/schemas/usps/schemas/SDCGetLocationsResponse.xsd +++ /dev/null @@ -1,124 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/StandardBRequest.xsd b/schemas/usps/schemas/StandardBRequest.xsd deleted file mode 100644 index c572a80bb9..0000000000 --- a/schemas/usps/schemas/StandardBRequest.xsd +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/StandardBResponse.xsd b/schemas/usps/schemas/StandardBResponse.xsd deleted file mode 100644 index 9671fcfd48..0000000000 --- a/schemas/usps/schemas/StandardBResponse.xsd +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/TrackFieldRequest.xsd b/schemas/usps/schemas/TrackFieldRequest.xsd deleted file mode 100644 index eba9ad2979..0000000000 --- a/schemas/usps/schemas/TrackFieldRequest.xsd +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/TrackRequest.xsd b/schemas/usps/schemas/TrackRequest.xsd deleted file mode 100644 index a9b2b3b4a5..0000000000 --- a/schemas/usps/schemas/TrackRequest.xsd +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/TrackResponse.xsd b/schemas/usps/schemas/TrackResponse.xsd deleted file mode 100644 index 11020f5e11..0000000000 --- a/schemas/usps/schemas/TrackResponse.xsd +++ /dev/null @@ -1,132 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/ZipCodeLookupRequest.xsd b/schemas/usps/schemas/ZipCodeLookupRequest.xsd deleted file mode 100644 index 6b91e6a135..0000000000 --- a/schemas/usps/schemas/ZipCodeLookupRequest.xsd +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/ZipCodeLookupResponse.xsd b/schemas/usps/schemas/ZipCodeLookupResponse.xsd deleted file mode 100644 index 186c913b54..0000000000 --- a/schemas/usps/schemas/ZipCodeLookupResponse.xsd +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/eVSCancelRequest.xsd b/schemas/usps/schemas/eVSCancelRequest.xsd deleted file mode 100644 index b0ed32bb93..0000000000 --- a/schemas/usps/schemas/eVSCancelRequest.xsd +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/eVSCancelResponse.xsd b/schemas/usps/schemas/eVSCancelResponse.xsd deleted file mode 100644 index 949de222bf..0000000000 --- a/schemas/usps/schemas/eVSCancelResponse.xsd +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/eVSExpressMailIntlRequest.xsd b/schemas/usps/schemas/eVSExpressMailIntlRequest.xsd deleted file mode 100644 index 016382ac76..0000000000 --- a/schemas/usps/schemas/eVSExpressMailIntlRequest.xsd +++ /dev/null @@ -1,131 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/eVSExpressMailIntlResponse.xsd b/schemas/usps/schemas/eVSExpressMailIntlResponse.xsd deleted file mode 100644 index 2487d871e5..0000000000 --- a/schemas/usps/schemas/eVSExpressMailIntlResponse.xsd +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/eVSFirstClassMailIntlRequest.xsd b/schemas/usps/schemas/eVSFirstClassMailIntlRequest.xsd deleted file mode 100644 index f963009f19..0000000000 --- a/schemas/usps/schemas/eVSFirstClassMailIntlRequest.xsd +++ /dev/null @@ -1,120 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/eVSFirstClassMailIntlResponse.xsd b/schemas/usps/schemas/eVSFirstClassMailIntlResponse.xsd deleted file mode 100644 index 3da7c9b9da..0000000000 --- a/schemas/usps/schemas/eVSFirstClassMailIntlResponse.xsd +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/eVSGXGGetLabelRequest.xsd b/schemas/usps/schemas/eVSGXGGetLabelRequest.xsd deleted file mode 100644 index b98390b91a..0000000000 --- a/schemas/usps/schemas/eVSGXGGetLabelRequest.xsd +++ /dev/null @@ -1,132 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/eVSGXGGetLabelResponse.xsd b/schemas/usps/schemas/eVSGXGGetLabelResponse.xsd deleted file mode 100644 index 083f648324..0000000000 --- a/schemas/usps/schemas/eVSGXGGetLabelResponse.xsd +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/eVSICancelRequest.xsd b/schemas/usps/schemas/eVSICancelRequest.xsd deleted file mode 100644 index d46ef3dc37..0000000000 --- a/schemas/usps/schemas/eVSICancelRequest.xsd +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/eVSICancelResponse.xsd b/schemas/usps/schemas/eVSICancelResponse.xsd deleted file mode 100644 index 24d139a32f..0000000000 --- a/schemas/usps/schemas/eVSICancelResponse.xsd +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/eVSPriorityMailIntlRequest.xsd b/schemas/usps/schemas/eVSPriorityMailIntlRequest.xsd deleted file mode 100644 index 5ab37aaa2a..0000000000 --- a/schemas/usps/schemas/eVSPriorityMailIntlRequest.xsd +++ /dev/null @@ -1,136 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/schemas/usps/schemas/eVSPriorityMailIntlResponse.xsd b/schemas/usps/schemas/eVSPriorityMailIntlResponse.xsd deleted file mode 100644 index faca50a436..0000000000 --- a/schemas/usps/schemas/eVSPriorityMailIntlResponse.xsd +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/schemas/eVSRequest.xsd b/schemas/usps/schemas/eVSRequest.xsd deleted file mode 100644 index 01938fad1e..0000000000 --- a/schemas/usps/schemas/eVSRequest.xsd +++ /dev/null @@ -1,176 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/schemas/usps/schemas/eVSResponse.xsd b/schemas/usps/schemas/eVSResponse.xsd deleted file mode 100644 index 3420904cf6..0000000000 --- a/schemas/usps/schemas/eVSResponse.xsd +++ /dev/null @@ -1,53 +0,0 @@ - - - - - - - - over 115000 suppressed - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/schemas/usps/setup.py b/schemas/usps/setup.py deleted file mode 100644 index c9cd79549e..0000000000 --- a/schemas/usps/setup.py +++ /dev/null @@ -1,26 +0,0 @@ -"""Warning: This setup.py is only there for git install until poetry support git subdirectory""" -from setuptools import setup, find_namespace_packages - -with open("README.md", "r") as fh: - long_description = fh.read() - -setup( - name="carrier.usps", - version="2021.7", - description="USPS Web API Schemas Python Data Types library", - long_description=long_description, - long_description_content_type="text/markdown", - url="https://github.com/karrioapi/karrio", - author="Karrio", - author_email="hello@karrio.io", - license="Apache-2.0", - packages=find_namespace_packages(), - install_requires=["six", "lxml"], - classifiers=[ - "Intended Audience :: Developers", - "Operating System :: OS Independent", - "Programming Language :: Python :: 3", - ], - zip_safe=False, - include_package_data=True, -) diff --git a/sdk/extensions/colissimo/setup.py b/sdk/extensions/colissimo/_setup.py similarity index 100% rename from sdk/extensions/colissimo/setup.py rename to sdk/extensions/colissimo/_setup.py