scio_pypy / scio / client.py

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
# client.py -- soap classes for input and output
#
# Copyright (c) 2011, Leapfrog Online, LLC
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#     * Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#     * Neither the name of the Leapfrog Online, LLC nor the
#       names of its contributors may be used to endorse or promote products
#       derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

# TODO
# - schema types can extend enums. How the heck can that work?

from datetime import date, datetime, time
from decimal import Decimal
import itertools
import logging
from threading import RLock
from urllib2 import urlopen, Request, HTTPError

from dateutil.parser import parse as parse_date

from scio._etree import etree, ElementCls

log = logging.getLogger(__name__)

# soap contstants
NS_SOAP_ENV = "http://schemas.xmlsoap.org/soap/envelope/"
NS_SOAP_ENC = "http://schemas.xmlsoap.org/soap/encoding/"
NS_SOAP = 'http://schemas.xmlsoap.org/wsdl/soap/'
NS_SOAP12 = 'http://schemas.xmlsoap.org/wsdl/soap12/'
NS_XSI = "http://www.w3.org/2001/XMLSchema-instance"
NS_XSD = "http://www.w3.org/2001/XMLSchema"
NS_WSDL = 'http://schemas.xmlsoap.org/wsdl/'
SOAP_BODY = '{%s}Body' % NS_SOAP_ENV
SOAP_FAULT = '{%s}Fault' % NS_SOAP_ENV
SOAP_HEADER = '{%s}Header' % NS_SOAP_ENV

SOAPNS = {
    'soap-env': NS_SOAP_ENV,
    'soap-enc': NS_SOAP_ENC,
    'soap': NS_SOAP,
    'soap12': NS_SOAP12,
    'wsdl': NS_WSDL,
    'xsi': NS_XSI,
    'xsd': NS_XSD }

# singleton used by AttributeDescriptor
notset = object()

#
# SOAP client class and helpers
#
class Client(object):
    """
    WSDL client container class. Given an open wsdl file-like object,
    instantiating a Client builds SOAP types and service calls using a
    Factory, and provides access to them via the instance's ``type``
    and ``service`` attributes.

    :param wsdl_fp: A file-like object containing the wsdl to use to
                    construct the client types and methods.
    :param transport: The transport mechanism for communicating with
                      target services. Default: :func:`urlopen`.
    :param service_class: A class that will contain services. An
                          instance of this class will be available as
                          client.service.
    :param type_class: A class that will contain types. An instance of
                       this class will be available as client.type.
    :param reduce_callback: REQUIRED TO SUPPORT PICKLING! If you want to
                            be able to pickle and unpickle scio types,
                            you must supply a function that can, given
                            a class name, return a bare instance of the
                            type. This function *must* be defined at the
                            top level of a module and must be marked as
                            __safe_for_unpickle__. The reduce callback must
                            have a signature compatible with the typical
                            definition::

                              def reviver(classname, proto=object, args=()):
                                  return proto.__new__(getattr(
                                      some_client.type, classname), *args)

                            The ``proto`` parameter will only be used for
                            a number of basic types, including int
                            and arrays (list).
    """
    def __init__(self, wsdl_fp, transport=None,
                 service_class=None, type_class=None,
                 reduce_callback=None):
        self.wsdl = Factory(wsdl_fp)
        if transport is None:
            transport = urlopen
        if service_class is None:
            service_class = ServiceContainer
        if type_class is None:
            type_class = TypeContainer
        self.transport = transport
        self.service = service_class(self)
        self.type = type_class(self)
        self.reduce_callback = reduce_callback
        for tag, uri in SOAPNS.items():
            etree.register_namespace(tag, uri)
        self.wsdl.build(self)

    def envelope(self, request):
        """
        Given an InputMessage, wrap in in a SOAP envelope and produce
        an Element.
        """
        env = etree.Element('{%s}Envelope' % SOAPNS['soap-env'])
        if request.headers:
            header = etree.SubElement(
                env, '{%s}Header' % SOAPNS['soap-env'])
            for element in request.headerxml():
                if element is not None:
                    header.append(element)
        body = etree.SubElement(
            env, '{%s}Body' % SOAPNS['soap-env'])
        for element in request.toxml():
            if element is not None:
                body.append(element)
        return env

    def send(self, method, request):
        """
        Send the SOAP request for the given method. Don't call this directly
        (use the methods attached to a client's `service` attribute instead),
        but do override it in a subclass to mock a service or change how
        a request is sent.
        """
        response = self.transport(request).read()
        return self.handle_response(method, response)

    def handle_response(self, method, response):
        """
        Handle a seemingly successful response.
        """
        body, header = self.parse_response(method, response)
        return method.output(body, header)

    def parse_response(self, method, response):
        """
        Parse the response xml and return the soap body and header.
        """
        parsed = etree.fromstring(response)
        body = parsed.find(SOAP_BODY)
        if body is None:
            raise NotSOAP("No SOAP body found in response", response)
        self.raise_if_fault(method, body)
        body = body[0] # hacky? get the first real element
        header = parsed.find(SOAP_HEADER)
        return body, header

    def handle_error(self, method, err):
        """
        Handle an exception raised by a method call that may be a
        SOAP Fault.
        """
        try:
            response = err.fp.read()
        except AttributeError:
            response = None
        if response:
            try:
                parsed = etree.fromstring(response)
                body = parsed.find(SOAP_BODY)
                self.raise_if_fault(method, body)
            except SyntaxError:
                pass
        raise err # FIXME loses traceback

    def raise_if_fault(self, method, body):
        """
        Raise a SOAP Fault if one is found in the response body.
        """
        if body is None:
            return
        fault = body.find(SOAP_FAULT)
        if fault is not None:
            code = fault.find('faultcode')
            if code is not None:
                code = code.text
            string = fault.find('faultstring')
            if string is not None:
                string = string.text
            detail = fault.find('detail')
            if detail is not None:
                detail = detail.text
            raise Fault(method.location, method.name, code, string, detail)


class Fault(Exception):
    """
    SOAP Fault exception. The method that raised the fault, the faultcode,
    and faultstring are available as attributes of the exception.
    """
    def __init__(self, method_location, method_name, faultcode, faultstring, detail):
        self.method_location = method_location
        self.method_name = method_name
        self.faultcode = faultcode
        self.faultstring = faultstring
        self.detail = detail
        # for < 2.5 compatibility, can't call super()
        Exception.__init__(
            self, method_location, method_name, faultcode, faultstring, detail)

    def __str__(self):
        return "SOAP Fault %s:%s <%s> %s%s" % (
            self.method_location, self.method_name, self.faultcode,
            self.faultstring, self.detail and ": %s" % self.detail or '')

    def __unicode__(self):
        return unicode(str(self))


class NotSOAP(ValueError):
    """
    Exception thrown when a response is received that does not
    contain SOAP xml. The full response is available as the
    response attribute of the exception.
    """
    def __init__(self, msg, response, *arg, **kw):
        self.msg = msg
        self.response = response
        Exception.__init__(self, msg, *arg, **kw)

    def __str__(self):
        return "%s:\n%s" % (self.msg, self.response)


class TypeContainer(object):
    """
    Bucket that holds types defined in WSDL. Attached to client as `type`
    attribute.
    """
    def __init__(self, client):
        self._client = client


class MethodCall(object):
    """
    Pseudo-closure for a single SOAP method call.
    """
    def __init__(self, client, method):
        self.client = client
        self.method = method

    def __call__(self, *arg, **kw):
        request = self.format_request(*arg, **kw)
        try:
            response = self.send_request(request)
            log.debug("Response: %s", response)
            return response
        except HTTPError, e:
            if e.code in (202, 204):
                return self.client.handle_response(self.method, None)
            else:
                return self.client.handle_error(self.method, e)

    def format_request(self, *arg, **kw):
        request = self.client.envelope(self.method.input(*arg, **kw))
        req_xml = _tostring(request, self.client._tns)
        log.debug("Request: %s", req_xml)
        return Request(self.method.location, req_xml, self.headers())

    def send_request(self, request):
        return self.client.send(self.method, request)

    def headers(self):
        return {'Content-Type': 'text/xml',
                'SOAPAction': self.method.action}


class Method(object):
    """
    Definition of a single SOAP method, including the location, action, name
    and input and output classes.

    TODO: add a useful repr
    """
    def __init__(self, location, name, action, input, output):
        self.location = location
        self.name = name
        self.action = action
        self.input = input
        self.output = output


class ServiceContainer(object):
    """
    Bucket that holds service methods. Attached to client as `service`
    attribute.
    """
    method_class = MethodCall
    def __init__(self, client):
        self._methods = []
        self._client = client

    def __setattr__(self, attr, val):
        if attr.startswith('_'):
            self.__dict__[attr] = val
        else:
            meth = self.method_class(self._client, val)
            self._methods.append(meth)
            self.__dict__[attr] = meth

#
# Pickling support
#
class Pickleable(object):
    _client = None

    def __reduce__(self):
        try:
            base = self._base_type()
        except AttributeError:
            base = None
        try:
            args = self.__getnewargs__()
        except AttributeError:
            args = ()
        if self._client and self._client.reduce_callback:
            return (self._client.reduce_callback,
                    (self.__class__.__name__, base, args),
                    self.__getstate__())
        return object.__reduce__(self)

    def __getstate__(self):
        d = self.__dict__.copy()
        if hasattr(self, '__slots__'):
            d.update(dict((k, getattr(self, k)) for k in self.__slots__))
        if '_client' in d:
            del d['_client']
        return d

    def __setstate__(self, dct):
        if hasattr(self, '__slots__'):
            for k in self.__slots__:
                setattr(self, k, dct.pop(k))
        self.__dict__.update(dct)

#
# Types, elements and accessors
#
class Element(object):
    """
    Base class for xml elements and attributes
    """
    _tag = None
    _prefix = None
    _nsmap = None
    _namespace = None
    _typemap = {} # intentional
    _position = 0

    @classmethod
    def fromxml(cls, element):
        """
        Convert value from xml. Override in typed subclasses
        to do type conversion.
        """
        return element.text

    @classmethod
    def empty(cls):
        """Return an empty instance of this class."""
        return cls()

    def toxml(self, tag=None, namespace=None, nsmap=None, empty=False):
        if tag is None:
            tag = self._tag
        if namespace is None:
            namespace = self._namespace
        if nsmap is None:
            nsmap = self._nsmap
        if tag is None or namespace is None or nsmap is None:
            raise ValueError("%s has no associated xml context" % self)
        try:
            value = unicode(self)
        except TypeError:
            value = None
        tag = '{%s}%s' % (namespace, tag)
        e = etree.Element(tag)
        if value is not None and value != u'':
            e.text = value
        return e


class SimpleTypeMeta(type):
    """
    Metaclass that registers each simple type in the Element typemap.
    """
    def __init__(cls, name, bases, dct):
        if dct.get('xsi_type', None):
            Element._typemap[dct['xsi_type'][1]] = cls
        super(SimpleTypeMeta, cls).__init__(name, bases, dct)


class SimpleType(Element):
    """
    Base class mixin for simple types. Allows simple types to be set by
    passing xml elements to their constructors.
    """
    __metaclass__ = SimpleTypeMeta
    xsi_type = None
    def __new__(cls, *arg, **kw):
        newarg, newkw = cls.adapt_args(arg, kw)
        base = cls._base_type()
        inst = base.__new__(cls, *newarg, **newkw)
        inst.__init__(*newarg, **newkw)
        return inst

    @classmethod
    def adapt_args(cls, arg, kw):
        """
        Adapt incoming arguments -- which may include xml Elements -- to
        the argument list expected by the native class of this type.
        """
        newarg = []
        for a in arg:
            if isinstance(a, ElementCls):
                val = cls.fromxml(a)
                if val is not None:
                    newarg.append(val)
            else:
                newarg.append(a)
        return newarg, kw

    @classmethod
    def empty(cls):
        # unset simple types are None, to distinguish from
        # eg those set to empty string or 0
        """Return an empty instance of this class. Empty SimpleTypes are
        always None."""
        return None

    @classmethod
    def _base_type(cls):
        # FIXME this is pretty hacky
        for t in cls.__mro__:
            if t.__module__ != cls.__module__:
                return t

class IntType(SimpleType, int):
    xsi_type = (NS_XSD, 'int')


class LongType(SimpleType, long):
    xsi_type = (NS_XSD, 'long')


class StringType(SimpleType, unicode):
    xsi_type = (NS_XSD, 'string')


class DecimalType(SimpleType, Decimal):
    xsi_type = (NS_XSD, 'decimal')


class FloatType(SimpleType, float):
    xsi_type = (NS_XSD, 'float')


class DateTimeType(SimpleType, datetime):
    xsi_type = (NS_XSD, 'dateTime')

    @classmethod
    def adapt_args(cls, arg, kw):
        newarg, newkw = SimpleType.adapt_args(arg, kw)
        if len(newarg) == 1:
            try:
                dt = parse_date(newarg[0])
                newarg = (dt.year, dt.month, dt.day,
                          # microsecond always 0
                          dt.hour, dt.minute, dt.second, 0,
                          dt.tzinfo)
            except ValueError:
                # may be binary date 'string' from a pickle, let it through
                pass
        return newarg, newkw

    def __str__(self):
        return str(unicode(self))

    def __unicode__(self):
        return unicode(self.isoformat('T'))


class DateType(SimpleType, date):
    xsi_type = (NS_XSD, 'date')

    @classmethod
    def adapt_args(cls, arg, kw):
        newarg, newkw = SimpleType.adapt_args(arg, kw)
        if len(newarg) == 1:
            try:
                dt = parse_date(newarg[0])
                newarg = (dt.year, dt.month, dt.day)
            except ValueError:
                # may be binary date 'string' from a pickle, let it through
                pass
        return newarg, newkw

    def __str__(self):
        return str(unicode(self))

    def __unicode__(self):
        return unicode(self.isoformat())


class TimeType(SimpleType, time):
    xsi_type = (NS_XSD, 'time')

    @classmethod
    def adapt_args(cls, arg, kw):
        newarg, newkw = SimpleType.adapt_args(arg, kw)
        if len(newarg) == 1:
            dt = parse_date(newarg[0])
            # microsecond always 0
            newarg = (dt.hour, dt.minute, dt.second, 0, dt.tzinfo)
        return newarg, newkw

    def __str__(self):
        return str(unicode(self))

    def __unicode__(self):
        return unicode(self.isoformat())


# bool is notsubclassable, so this type just normalizes to the
# string values 'true' or 'false'
class BooleanType(SimpleType, unicode):
    xsi_type = (NS_XSD, 'boolean')
    true_vals = ('true', '1', 1)

    @classmethod
    def adapt_args(cls, arg, kw):
        newarg, newkw = SimpleType.adapt_args(arg, kw)
        if len(newarg) == 1:
            if str(newarg[0]).lower() in cls.true_vals:
                newarg = ('true',)
            else:
                newarg = ('false',)
        return newarg, newkw

    def __nonzero__(self):
        return self == u'true'


class EnumType(Element, Pickleable):
    """
    Element representing a SOAP Enum. Subclasses have a defined set
    of allowed values.
    """
    _values = ()
    _attributes = ()
    _children = ()
    _content_type = None # FIXME this should be setable

    def __init__(self, val=None, **kw):
        err = False
        self.value = None
        if val is not None:
            try:
                val = val.text
            except AttributeError:
                pass
            if val in self._values:
                self.value = val
            elif ' ' in val:
                # enums may be a space-separated list of flags
                # still only one real value though -- not a true
                # list. So we just check to make sure all values
                # are legal, but store the original space-separated
                # string
                parts = val.split(' ')
                for part in parts:
                     if not part.strip() in self._values:
                         err = True
                         break
                self.value = val
            else:
                err = True
            if err:
                raise ValueError("Illegal enum value %s for %s (allowed: %s)" %
                                 (val, self.__class__.__name__, self._values))
        super(EnumType, self).__init__(**kw)

    def __unicode__(self):
        return self.value
    __str__ = __unicode__

    def __repr__(self):
        return "%s.%s" % (self.__class__.__name__, self.value)

    @classmethod
    def empty(cls):
        # Like simple types, an empty enum is just None, to avoid collisions
        # with any blank-looking enum values
        return None


class UnionType(Element, Pickleable):
    _values = ()
    _attributes = ()
    _children = ()
    _content_type = None # FIXME this should be setable

    def __init__(self, val=None, **kw):
        self.value = None
        if val is not None:
            try:
                self.value = val.text
            except AttributeError:
                self.value = val
        super(UnionType, self).__init__(**kw)

    def __unicode__(self):
        if self.value is None:
            return u''
        return unicode(self.value)
    __str__ = __unicode__

    def __repr__(self):
        return "%s.%s" % (self.__class__.__name__, self.value)

    @classmethod
    def empty(cls):
        return None


class AnyType(object):
    """
    Factory for runtime type lookups. When given an 'anyType' element, the
    client must look up the type to deserialize to from the type given
    by the element, in some attribute with a local name of 'type'.
    """
    client = None
    # needed because I get used as an Element, though I'm not really one
    _tag = _namespace = _nsmap = _prefix = None

    def __init__(self, client):
        self.client = client
        self.__name__ = '<AnyType>'

    def __call__(self, value=None, **kw):
        if value is None:
            return
        valtype = xsi_type(value)
        if not valtype:
            return
        # Can't create types at runtime, only find them
        valcls = self.client.wsdl.resolve(valtype, allow_ref=False)
        return valcls(value, **kw)

    @classmethod
    def empty(cls):
        """Return an empty instance. Like simple types, an empty anyType
        is just None."""
        return None


class AnyAttribute(object):
    """Minimal wrapper for untyped extra attributes.
    """
    def __init__(self, name):
        self.name = name


class ArrayType(list, Pickleable):
    _arrayType = None
    _client = None
    _tag = _namespace = _nsmap = _prefix = None

    def __init__(self, iterable=()):
        for item in iterable:
            self.append(self._arrayType(item))

    def __reduce__(self):
        if self._client and self._client.reduce_callback:
            return (self._client.reduce_callback,
                    (self.__class__.__name__, list),
                    self.__getstate__(),
                    iter(i for i in self))
        return object.__reduce__(self)


class ComplexType(Element, Pickleable):
    """
    Base class for SOAP complexTypes, at least the ones that look like
    classes. For each complexType in a WSDL document, the Factory creates
    a ComplexType subclass with the appropriate children and attributes.
    """
    _content = None
    _content_type = None
    _attributes = ()
    _children = ()
    _substitutions = None
    _arg = () # TODO
    _abstract = False
    _client = None
    _type_attr = None
    _type_value = None
    _child_count = 0
    any_attribute = False

    def __new__(cls, element=None, **kw):
        # Similar to AnyType()(element), but just finds the
        # class. AnyType() calls cls(), which if done here,
        # results in obj.__init__() getting called twice.
        if cls._abstract and cls._client and element is not None:
            valtype = xsi_type(element)
            if valtype:
                cls = cls._client.wsdl.resolve(valtype, allow_ref=False)
        return object.__new__(cls)

    def __init__(self, element=None, **kw):
        self.qns = '{%s}' % self._namespace
        # FIXME allow element to be a dict, eg:
        # Foo.Address = {'Zip': '12345', 'StreetAddress': '101 street lane'}
        # FIXME support positional args, including assignment
        # of scio classes to children via positional args
        if element is not None:
            content = None
            if isinstance(element, ElementCls):
                attrs = set(attr.name for attr in self._attributes)
                kids = set(child.name for child in self._children)
                kids_subs = self._child_substitutions()
                content = element.text
                tagns = ns(element.tag)
                for attr, aval in element.attrib.items():
                    # check instead that any attr ns matches
                    # element ns (or that it is local)
                    if ns(attr) not in set([None, tagns]):
                        continue
                    aname = local(attr)
                    if self.any_attribute and aname not in attrs:
                        self._attributes.append(AnyAttribute(aname))
                    setattr(self, aname, aval)
                for el in element:
                    if el.text is not None or el.attrib or len(el):
                        name = local(el.tag)
                        if name in kids:
                            setattr(self, name, el)
                        else:
                            # substitutionGroups
                            real_cls, real_name = kids_subs.get(name, (None, None))
                            if real_cls:
                                setattr(self, real_name, real_cls(el))
                                # FIXME Or for unnamed subelements:
                                # setattr(self, name, real_cls(el))
                        # TODO handle any tag, ref any_attribute above
            else:
                content = element
            if content is not None:
                # support type conversion
                if self._content_type:
                    self._content = self._content_type(content)
                else:
                    self._content = content
        for k, v in kw.items():
            # This assures that subelements have correct element name
            # when they are passed in as ComplexType() instances
            if not getattr(v, '_tag', None):
                try:
                    v._name = k
                except AttributeError:
                    # builtins and such
                    pass
            setattr(self, k, v)

    def _child_substitutions(self):
        # FIXME this is a hack, feels like I'm poking through
        # things I shouldn't be from here.
        key = '_child_substitutions_'
        if not hasattr(self.__class__, key):
            subs = {}
            for child in self._children:
                if not hasattr(child.type, '_substitutions'):
                    continue
                for sub_name, sub in child.type._substitutions.items():
                    subs[sub_name] = (sub, child.name)
            setattr(self.__class__, key, subs)
        return getattr(self, key)

    def _items(self):
        items = []
        for a in self._attributes + self._children:
            # access the internal key not the real attribute to
            # avoid autovivification
            val = getattr(self, "_%s_" % a.name, None)
            if val is not None:
                items.append((a.name, val))
        return items

    def __repr__(self):
        props = []
        if self._content is not None:
            props.append('_content=%r' % self._content)
        for name, val in self._items():
            props.append('%s=%r' % (name, val))
        return '%s(%s)' % (self.__class__.__name__,
                           ', '.join(props))

    def __unicode__(self):
        if self._content is not None:
            return unicode(self._content)
        return u''

    __str__ = __unicode__

    def __nonzero__(self):
        return bool(self._content or self._items())

    def __iter__(self):
        if self:
            return iter([self])
        return iter([])

    def toxml(self, tag=None, namespace=None, nsmap=None, empty=False):
        if tag is None:
            tag = self._tag
        if namespace is None:
            namespace = self._namespace
        if nsmap is None:
            nsmap = self._nsmap
        if tag is None or namespace is None or nsmap is None:
            raise ValueError("%s has no associated xml context" % self)
        if self._content is not None:
            value = unicode(self._content)
        else:
            value = None
        tag = '{%s}%s' % (namespace, tag)
        e = etree.Element(tag)
        if self._type_attr and self._type_value:
            e.attrib[self._type_attr] = self._type_value
        if isinstance(value, basestring):
            e.text = value
        elif isinstance(value, ElementCls):
            e.append(value)
        for attr in self._attributes:
            at_val = getattr(self, attr.name, None)
            if at_val is not None:
                e.attrib["{%s}%s" % (namespace, attr.name)] = unicode(at_val)
        for child in self._children:
            # use private accessors to avoid autovivification
            # since we're potentially passing empty=True to children
            # and we don't want to render all possible children, only
            # those with actual values.
            key = "_%s_" % child.name
            ch_val = getattr(self, key, None)
            if ch_val is not None:
                if isinstance(ch_val, list):
                    for ch in ch_val:
                        ch_el = ch.toxml(child.name, namespace, nsmap, empty)
                        if ch_el is not None:
                            e.append(ch_el)
                else:
                    ch_el = ch_val.toxml(child.name, namespace, nsmap, empty)
                    if ch_el is not None:
                        e.append(ch_el)
        if not empty and e.text is None and not e.attrib and not len(e):
            return None
        return e


class AttributeDescriptor(object):
    """
    AttributeDescriptors are used as properties of complex types each one models
    an attribute or element that is part of the complex type. The descriptor
    mediates access to the type instance, which holds the value.
    """
    required = False
    name = None
    min = max = None

    def __init__(self, name, type_=None, required=False, min=None, max=None,
                 doc=None, **kw):
        self.name = name
        if type_ is None:
            type_ = StringType
        self.type = type_
        self.required = required
        self.min = min
        self.max = max
        if doc is not None:
            self.__doc__ = doc

    def __str__(self):
        return "%s(%s:%s)" % (
            self.__class__.__name__, self.name, self.type.__class__.__name__)

    def __get__(self, obj, cls):
        if obj is None:
            return self
        key = '_%s_' % self.name
        val = getattr(obj, key, notset)
        if val is notset:
            # ComplexTypes should not return None, but fresh
            # empty versions of themselves if not set -- of course
            # for this to work they have to *become set* when
            # accessed for the first time. This enables you to say:
            # Foo.Bar.Baz = 1 even if Foo.Bar has not yet been set.
            val = self.type.empty()
            setattr(obj, key, val)
        return val

    def __set__(self, obj, value):
        # convert from node or other xml value into simple value
        # # print self.name, obj, value, self.type
        key = '_%s_' % self.name

        if isinstance(value, (list, tuple)):
            new = []
            for item in value:
                if not isinstance(item, self.type):
                    item = self._new(item)
                item._position = obj._child_count
                obj._child_count += 1
                new.append(item)
            setattr(obj, key, new)
            return

        if self.isanytype() or not isinstance(value, self.type):
            value = self._new(value)

        # remember the order in which we saw assignments
        value._position = obj._child_count
        obj._child_count += 1

        # sort of hacky set/append combo
        # this is needed to handle parsing multiple values out of xml
        curval = getattr(obj, key, None)
        if curval is not None and (self.max == 'unbounded' or self.max > 1):
            if not isinstance(curval, list):
                curval = [curval]
            curval.append(value)
            value = curval
        setattr(obj, key, value)

    def __delete__(self, obj):
        delattr(obj, '_%s_' % self.name)

    def _new(self, value):
        return self.type(value)

    def isanytype(self):
        return (isinstance(self.type, AnyType)
                or getattr(self.type, '_abstract', False))


class InputMessage(object):
    """
    Base of the marshalling chain for input messages. Call this with
    positional or keyword arguments appropriate to the message, and
    get back a formatter whose toxml() method will yield xml Elements
    for inclusion in a SOAP message.
    """
    def __init__(self, tag, namespace, nsmap, parts, style, literal, headers):
        self.tag = tag
        self.namespace = namespace
        self.nsmap = nsmap
        self.parts = parts
        self.style = style
        self.literal = literal
        self.headers = headers
        self.formatter = self._pick_formatter()

    def __call__(self, *arg, **kw):
        tag = self.tag
        namespace = self.namespace
        nsmap = self.nsmap
        header_fmt = []
        for name, cls in self.headers:
            val = kw.pop(name, None)
            if val is not None:
                header_fmt.append((name, cls(val)))
        if len(self.parts) == 1:
            return self.formatter(
                tag, namespace, nsmap, [
                    (part_tag, cls(*arg, **kw))
                    for part_tag, cls in self.parts],
                header_fmt
                )
        else:
            # map each arg in args to one part
            parts_fmt = []
            alist = list(arg)
            for part_tag, cls in self.parts:
                fmt = cls(alist.pop(0), **kw)
                parts_fmt.append((part_tag, fmt))
            return self.formatter(tag, namespace, nsmap, parts_fmt, header_fmt)

    def _pick_formatter(self):
        if self.style == 'document':
            # decide whether wrapped or not
            wrapper = self._is_wrapper()
            if self.literal:
                if wrapper:
                    return DocumentLiteralWrapperInputFormatter
                else:
                    return DocumentLiteralInputFormatter
            elif wrapper:
                return DocumentEncodedWrapperInputFormatter # FIXME
            else:
                return DocumentEncodedInputFormatter # FIXME
        elif self.style == 'rpc':
            if self.literal:
                return RpcLiteralInputFormatter
            else:
                return RpcEncodedInputFormatter

    def _is_wrapper(self):
        if len(self.parts) != 1:
            return False
        part = self.parts[0][1]
        if part._tag != self.tag:
            return False
        return True


class InputFormatter(object):
    """
    Base class for input message formatters
    """
    def __init__(self, tag, namespace, nsmap, parts, headers):
        self.tag = tag
        self.namespace = namespace
        self.nsmap = nsmap
        self.parts = parts
        self.headers = headers

    def toxml(self):
        raise NotImplemented

    def headerxml(self):
        for name, hdr in self.headers:
            yield hdr.toxml(name, self.namespace, self.nsmap)


class DocumentLiteralWrapperInputFormatter(InputFormatter):
    """
    Input message formatter that formats a document literal message
    with wrapper. This means that the body of the message is simply
    the serialized xml of the single message part, which must be
    a complexType element with the same name as the operation.
    """
    def toxml(self):
        _, part = self.parts[0]
        yield part.toxml(part._tag, self.namespace, self.nsmap, empty=True)


class DocumentLiteralInputFormatter(InputFormatter):
    """
    Input message formatter for non-wrapped document literal messages.
    The main difference between this type of message and wrapped types
    is that there may be > 1 input part, and they are not all necessarily
    contained in an element with the same name as the operation.
    """
    def toxml(self):
        for part_tag, part in self.parts:
            yield part.toxml(part_tag, self.namespace, self.nsmap, empty=True)


class RpcLiteralInputFormatter(InputFormatter):
    """
    Input message formatting in the RPC literal style. A top-level element
    named after the operation wraps each input part, which may be a
    complexType or simple type.
    """
    def toxml(self):
        tag = '{%s}%s' % (self.namespace, self.tag)
        e = etree.Element(tag)
        for part_tag, type_ in self.parts:
            if part_tag:
                # print "appending", part_tag, type_
                part_xml = type_.toxml(part_tag, self.namespace, self.nsmap)
                if part_xml is not None:
                    e.append(part_xml)
        yield e


class RpcEncodedInputFormatter(InputFormatter):
    """
    Input message formatter for rpc/enc style. A top-level element
    named after the operation wraps each input part, which may be a complex
    or simple type. Each part's xml includes an xsi:type attribute with
    the value being the namespaced type of the element.
    """
    def toxml(self):
        tag = '{%s}%s' % (self.namespace, self.tag)
        nsmap = SOAPNS.copy()
        nsmap.update(self.nsmap)
        backmap = dict(zip(nsmap.values(), nsmap.keys()))
        e = etree.Element(tag)
        for part_tag, type_ in self.parts:
            if part_tag:
                part_xml = type_.toxml(part_tag, self.namespace, self.nsmap)
                if part_xml is not None:
                    if type_.xsi_type:
                        ns, local = type_.xsi_type
                        prefix = backmap[ns]
                    part_xml.attrib['{%s}type' % NS_XSI] = (
                        '%s:%s' % (prefix, local))
                    e.append(part_xml)
        yield e


class OutputMessage(object):
    """
    Unmarshaller for SOAP responses. This class probably needs subclasses
    for all of the different binding styles.
    """
    def __init__(self, tag, namespace, nsmap, parts, headers):
        self.tag = tag
        self.namespace = namespace
        self.nsmap = nsmap
        self.parts = parts
        self.headers = headers

    def __call__(self, body, header=None):
        result = []
        local_tag = local(body.tag)
        # print [(name, part) for name, part in self.parts]
        for part_tag, part in self.parts:
            # print name, part.name, tname
            if part_tag is None:
                part_tag = part._tag
            if part_tag is None:
                raise ValueError("No part tag for part %s" % part)
            if local_tag in (part_tag, part._tag):
                result.append(part(body))
            else:
                # ns = body.nsmap[body.prefix]
                part_el = None
                # print "{%s}%s {%s}%s" % (ns, part.name, ns, name)
                if part._tag:
                    part_el = body.find(part._tag)
                if part_el is None:
                    part_el = body.find(part_tag)
                if part_el is not None:
                    result.append(part(part_el))
                else:
                    log.debug(
                        "No element found in %s  for part %s/%s",
                        body, part_tag, part._tag)
        if header is not None:
            headers = {}
            for header_tag, part in self.headers:
                header_el = header.find('{%s}%s' % (self.namespace, header_tag))
                if header_el is not None:
                    headers[header_tag] = part(header_el)
            if headers:
                result.append(headers)
        if len(result) == 1:
            return result[0]
        return tuple(result)


#
# The wsdl type factory.
#
class Factory(object):
    """
    WSDL type factory.
    """
    _typemap = Element._typemap.copy()
    _typemap.update({
        'integer': IntType,
        'positiveInteger': IntType,
        'short': IntType,
        'unsignedInt': IntType,
        'long': LongType,
        'byte': StringType,
        'double': FloatType,
        'base64Binary': StringType,
        'anyURI': StringType,
        'language': StringType,
        'token': StringType,
        # FIXME: probably timedelta, but needs parsing.
        # It looks like P29DT23H54M58S
        'duration': StringType
        })

    _simple_tag = '{http://www.w3.org/2001/XMLSchema}simpleType'
    _enum_tag =  '{http://www.w3.org/2001/XMLSchema}enumeration'
    _attr_tag = '{http://www.w3.org/2001/XMLSchema}attribute'
    _seq_tag = '{http://www.w3.org/2001/XMLSchema}sequence'
    _all_tag = '{http://www.w3.org/2001/XMLSchema}all'
    _cplx_tag = '{http://www.w3.org/2001/XMLSchema}complexContent'
    _ext_tag = '{http://www.w3.org/2001/XMLSchema}extension'
    _spl_tag = '{http://www.w3.org/2001/XMLSchema}simpleContent'
    _element_tag = '{http://www.w3.org/2001/XMLSchema}element'
    _choice_tag = '{http://www.w3.org/2001/XMLSchema}choice'
    _restr_tag = '{http://www.w3.org/2001/XMLSchema}restriction'
    _any_attr_tag = '{http://www.w3.org/2001/XMLSchema}anyAttribute'
    _list_tag = '{http://www.w3.org/2001/XMLSchema}list'

    def __init__(self, wsdl_file):
        self.wsdl = etree.parse(wsdl_file).getroot()
        self.nsmap = {None: None} # FIXME
        self._lock = RLock()
        self._lock.acquire()
        try:
            self._typemap = self._typemap.copy()
        finally:
            self._lock.release()

    def build(self, client):
        """
        Generate classes and methods for types and bindings defined in
        the wsdl file. Classes and methods become attributes of the type
        and service containers of the given client instance, respectively.
        """
        self._lock.acquire()
        try:
            self._build(client)
            return client
        finally:
            self._lock.release()

    def resolve(self, name, allow_ref=True):
        """
        Resolve a class name to a class.
        """
        try:
            return self._typemap[name]
        except KeyError:
            if allow_ref:
                return TypeRef(name, self)
            raise

    def _build(self, client):
        self._refs = []
        element = '{%s}element' % NS_XSD
        cpxtype = '{%s}complexType' % NS_XSD
        spltype = '{%s}simpleType' % NS_XSD
        types = [element, cpxtype, spltype]
        soap_ports = ['{%s}port' % NS_WSDL]
        self.tns = client._tns = self.wsdl.get('targetNamespace')
        for typetag in types:
            for t in self.wsdl.getiterator(typetag):
                self._build_type(t, client)
        for porttag in soap_ports:
            for t in self.wsdl.getiterator(porttag):
                self._build_method(t, client)
        self._resolve_refs()

    def _build_type(self, t, client):
        parent = None
        force_name = None
        name = t.get('name', None)
        if name is None:
            return
        if self._is_element(t):
            typel = t.find('{%s}complexType' % NS_XSD)
            if typel is None:
                typel = t.find('{%s}simpleType' % NS_XSD)
            if typel is None:
                return # FIXME element.type ?
            force_name = False
            # this case looks like:
            # <xs:element name="XXX"><xs:complexType>...
            # name and other attribs are in parent (t) but
            # type details are in child (typel)
            force_name = True
            parent = t
            t = typel
        self._make_class(
            client, t, name=name, force_name=force_name, parent=parent)

    def _resolve_refs(self):
        # print "refs to resolve", self._refs
        for client_type, name in self._refs:
            ref = getattr(client_type, name)
            if isinstance(ref, TypeRef):
                setattr(client_type, name, ref())
        self._refs = []

    def _build_method(self, t, client):
        service = client.service
        location = t[0].get('location')
        binding_name = local_attr(t.get('binding'))
        binding = self.wsdl.find(".//{%s}binding[@name='%s']" %
                                  (NS_WSDL, binding_name))
        style = self._binding_style(binding)
        ptype_name = local_attr(binding.get('type'))
        ptype = self.wsdl.find(".//{%s}portType[@name='%s']" %
                                (NS_WSDL, ptype_name))
        for op in binding.findall('{%s}operation' % NS_WSDL):
            name = local_attr(op.attrib['name'])
            params = op.attrib.get('parameterOrder', '').split(' ')
            try:
                (action, op_style, literal,
                 in_headers, out_headers) = self._op_info(op)
            except SyntaxError:
                # FIXME not a soap op after all??
                continue
            if not op_style:
                if not style:
                    raise SyntaxError("Neither binding nor operation style found")
                op_style = style
            port_op = ptype.find("{%s}operation[@name='%s']" %
                                 (NS_WSDL, name))
            in_msg_name = local_attr(port_op.find(
                '{%s}input' % NS_WSDL).attrib['message'])
            out_msg_name = local_attr(port_op.find(
                '{%s}output' % NS_WSDL).attrib['message'])
            in_types = self.wsdl.findall(
                ".//{%s}message[@name='%s']/{%s}part" %
                (NS_WSDL, in_msg_name, NS_WSDL))
            out_types = self.wsdl.findall(
                './/{%s}message[@name="%s"]/{%s}part' %
                (NS_WSDL, out_msg_name, NS_WSDL))
            in_msg = self._make_input_msg(client, name, in_types, params,
                                          op_style, literal, in_headers)
            out_msg = self._make_output_msg(client, name, out_types,
                                            op_style, literal, out_headers)
            setattr(service, name,
                    Method(location, name, action, in_msg, out_msg))

    def _make_input_msg(self, client, name, types, params, op_style, literal,
                        headers):
        # FIXME use params! There's useful information there...
        parts = []
        header_parts = []
        for t in types:
            if not 'name' in t.attrib:
                continue
            part_name = t.attrib['name']
            if 'element' in t.attrib:
                parts.append(
                    (part_name, self._make_class(client, t.attrib['element'])))
            elif 'type' in t.attrib:
                parts.append(
                    (part_name, self._make_class(client, t.attrib['type'])))
        for h_name, h_type in headers:
            header_parts.append((h_name, self._make_class(client, h_type)))
        namespace = self.tns
        nsmap = {None: namespace}
        return InputMessage(name, namespace, nsmap, parts, op_style, literal,
                            header_parts)

    def _make_output_msg(self, client, name, types, op_style, literal, headers):
        parts = []
        header_parts = []
        for t in types:
            if not 'name' in t.attrib:
                continue
            part_name = t.attrib['name']
            if 'element' in t.attrib:
                parts.append(
                    (part_name, self._make_class(client, t.attrib['element'])))
            elif 'type' in t.attrib:
                parts.append(
                    (part_name, self._make_class(client, t.attrib['type'])))
        for h_name, h_type in headers:
            header_parts.append((h_name, self._make_class(client, h_type)))
        namespace = self.tns
        nsmap = {None: namespace}
        return OutputMessage(name, namespace, nsmap, parts, header_parts)

    def _make_class(self, client, type_, name=None, force_name=False,
                    parent=None):
        client_type = client.type
        prefix = None #self._tns

        if isinstance(type_, basestring):
            # catch known types
            key = local_attr(type_)
            if key in self._typemap:
                return self._typemap[key]
            if key == 'anyType':
                # anyType must be bound to client, since
                # it requires run-time type lookup
                return self._anyType(client)
            # ... or find the definition in wsdl
            type_ = self._find_type(type_)

        if name is None:
            name = type_.get('name')

        # can't build a class without a name
        if name is None:
            return

        # in cache?
        cls = self._typemap.get(name, None)
        if cls is not None:
            if isinstance(cls, TypeRef):
                self._refs.append((client_type, name))
            if not hasattr(client_type, name):
                setattr(client_type, name, cls)
            return cls

        # short circuit for enums
        if self._is_enum(type_):
            cls = self._make_enum(type_, client, self.tns, name)
            self._typemap[name] = cls
            setattr(client_type, name, cls)
            return cls
        # short circuit for arrays
        elif self._is_array(type_):
            cls = self._make_array(type_, client, self.tns, name)
            self._typemap[name] = cls
            setattr(client_type, name, cls)
            return cls
        # short circuit for unions
        elif self._is_union(type_):
            cls = self._make_union(type_, client, self.tns, name)
            self._typemap[name] = cls
            setattr(client_type, name, cls)
            return cls
        # short circuit for simpleTypes
        elif self._is_simple(type_):
            cls = self._make_simple(type_, client, self.tns, name)
            self._typemap[name] = cls
            setattr(client_type, name, cls)
            return cls

        # In case a type is self-referential, we need something in
        # the typemap before we start processing children
        self._typemap[name] = TypeRef(name, self)

        # the body dict of the class
        namespace = self.tns
        data = {'_attributes': [],
                '_children': [],
                '_substitutions': {},
                '_nsmap': {None: namespace},
                '_prefix': prefix,
                '_namespace': namespace,
                '_client': client,
                'xsd_type': (namespace, name)}
        # this handles cases where the xml element name is always
        # forced to the name in the wsdl
        if force_name:
            data['_tag'] = name
        bases = (ComplexType,)

        for e in type_:
            # create attribute or element for each one
            # FIXME how to handle 'any attribute' ?
            # FIXME how to handle restrictions?
            if e.tag == self._attr_tag:      # attribute
                self._add_attribute(client, data, e)
            elif e.tag in (self._seq_tag,
                           self._all_tag,
                           self._choice_tag): # sequence of elements
                self._add_children(client, data, e)
            elif e.tag == self._cplx_tag:    # subclass
                e = e[0]
                if e.tag == self._ext_tag:
                    bases = (self._make_class(client, e.attrib['base']),)
                for se in e:
                    if se.tag == self._attr_tag:
                        self._add_attribute(client, data, se)
                    elif se.tag in (self._seq_tag,
                                    self._all_tag,
                                    self._choice_tag):
                        self._add_children(client, data, se)
            elif e.tag == self._spl_tag:      # subclass of builtin
                e = e[0]
                if e.tag == self._ext_tag:
                    # type for class's _content attribute
                    # to allow it to be properly converted
                    data['_content_type'] = self.resolve(
                        local_attr(e.attrib['base']))
                for se in e:
                    if se.tag == self._attr_tag:
                        self._add_attribute(client, data, se)
                    elif se.tag in (self._seq_tag, self._all_tag):
                        self._add_children(client, data, se)
            elif e.tag == self._any_attr_tag:
                data['any_attribute'] = True
        # add attributes/children from parent classes to my lists
        for base in bases:
            data['_attributes'] = list(base._attributes) + data['_attributes']
            data['_children'] = list(base._children) + data['_children']

        # track any typerefs in attributes/children
        for attr in data['_attributes']:
            if isinstance(attr.type, TypeRef):
                self._refs.append((attr, 'type'))
        for child in data['_children']:
            if isinstance(child.type, TypeRef):
                self._refs.append((child, 'type'))

        # mark abstract classes as such
        if type_.get('abstract', None) == 'true':
            data['_abstract'] = True
        else:
            # otherwise base class's abstractness pollutes subclasses
            data['_abstract'] = False
            if self._any_abstract(bases):
                data['_type_attr'] = '{%s}type' % NS_XSI
                data['_type_value'] = name

        cls = type(name, bases, data)

        # add to substitutionGroup
        substitutionGroup = type_.get('substitutionGroup')
        if parent is not None and not substitutionGroup:
            substitutionGroup = parent.get('substitutionGroup')
        if substitutionGroup:
            group_cls = self._make_class(
                client,
                local_attr(substitutionGroup)
                )
            group_cls._substitutions[name] = cls

        # track typeref in _content_type
        if isinstance(cls._content_type, TypeRef):
            self._refs.append((cls, '_content_type'))
        self._typemap[name] = cls
        setattr(client_type, name, cls)
        return cls

    def _add_attribute(self, client, data, element):
        try:
            name = element.attrib['name']
        except KeyError:
            # not a true attribute -- a restriction or something
            # that we don't care about (for now)
            return
        # attribute may reference a type, or may include a complexType
        # or other type definition inline, or may be a list
        type_ref = None
        try:
            type_ref = element.attrib['type']
        except KeyError:
            restr = self._find_restriction(element[0])
            if restr is not None:
                type_ref = local_attr(restr.get('base'))

        if type_ref:
            attr = AttributeDescriptor(
                name=name,
                type_=self._make_class(client, type_ref),
                required=element.get('use', None) == 'required')
        elif (len(element) and
              len(element[0]) and 
              element[0][0].tag == self._list_tag):
            # not really a simple type -- a list
            type_ = self._make_list(
                element[0][0], client, self.tns, name)
            attr = AttributeDescriptor(
                name=name,
                type_=type_)
        else:
            raise NotImplemented("Unable to add attribute for %s" %
                                 etree.tostring(element))
        data[name] = attr
        data['_attributes'].append(attr)

    def _add_children(self, client, data, element):
        for se in self._children(element):
            name = se.attrib.get('name')
            # ref for substitutionGroup
            type_ = se.attrib.get('ref')
            if type_:
                if not name:
                    # FIXME: or leave as None,
                    # see ComplexType.__init__ real_cls
                    name = local_attr(type_)
                type_ = self._make_class(client, type_)
            else:
                # element may n reference a type, or may include a complexType
                # or other type definition inline
                try:
                    type_ref = se.attrib['type']
                except KeyError:
                    type_ref = se[0]
                type_ = self._make_class(client, type_ref)

            el = AttributeDescriptor(
                name=name,
                type_=type_,
                min=se.get('minOccurs'),
                max=se.get('maxOccurs'))
            data[name] = el
            data['_children'].append(el)

    def _is_array(self, element):
        try:
            restr = element[0][0]
            if not local(restr.tag) == 'restriction':
                return False
            prefix, kind = restr.attrib['base'].split(':')
            return kind == 'Array'
        except (IndexError, TypeError, KeyError, ValueError):
            return False

    def _is_enum(self, element):
        if not element.tag == self._simple_tag:
            return False
        # Note: find_enumerations returns a list now, but
        # in case it returns an iterator in future (as it did in past)
        # listify
        enums = list(self._find_enumerations(element))
        if not enums:
            return False
        return True

    def _is_union(self, element):
        if not element.tag == self._simple_tag:
            return False
        try:
            if local(element[0].tag) == 'union':
                return True
        except (IndexError, TypeError):
            return False

    def _is_simple(self, element):
        return element.tag == self._simple_tag

    def _is_element(self, element):
        return local(element.tag) == 'element'

    def _any_abstract(self, bases):
        for cls in bases:
            if getattr(cls, '_abstract', None):
                return True
            base_bases = getattr(cls, '__bases__', [])
            if base_bases and self._any_abstract(base_bases):
                return True
        return False

    def _make_enum(self, element, client, namespace, name):
        vals = []
        data = {}
        for e in self._find_enumerations(element):
            # FIXME could be typed (int, etc)
            try:
                val = e.attrib['value']
                vals.append(val)
                data[val] = val
            except KeyError:
                pass # enumeration value without a name? we can't use it
        data['_values'] = vals
        data['_client'] = client
        data['xsd_type'] = (namespace, name)
        return type(element.attrib['name'], (EnumType,), data)

    def _make_array(self, element, client, namespace, name):
        # look for restriction on array type, that is the
        # type for each item. Make a list container
        # with the appropriate item type.
        array_spec = element[0][0][0]
        tag = local(array_spec.tag)
        if tag == 'attribute':
            array_type, junk = element[0][0][0].get(
                '{%s}arrayType' % NS_WSDL).split('[', 1)
            array_type = local_attr(array_type)
        elif tag == 'sequence':
            array_type = local_attr(array_spec[0].get('type'))
        # anyType can't be found by resolve, it's special
        # (putting anyType in the typemap results in anyType
        # objects resolving themselves to AnyType rather than
        # the correct type at runtime), so we have to special
        # case it here
        if array_type == 'anyType':
            array_type = AnyType
        else:
            array_type = self.resolve(array_type)
        bases = (ArrayType,)
        data = {'_arrayType': array_type,
                '_client': client,
                'xsd_type': (namespace, name)}
        cls = type(name, bases, data)
        if isinstance(array_type, TypeRef):
            self._refs.append((cls, '_arrayType'))
        return cls

    def _make_list(self, element, client, namespace, name):
        # implemented as ArrayType subclass since arrays and lists
        # mean the same thing on the python side
        list_type = local_attr(element.get('itemType'))
        if list_type == 'anyType':
            list_type = AnyType
        else:
            list_type = self.resolve(list_type)
        data = {'_arrayType': list_type,
                '_client': client,
                'xsd_type': (namespace, name)}
        cls = type(name, (ArrayType,), data)
        if isinstance(list_type, TypeRef):
            self._refs.append((cls, '_arrayType'))
        return cls

    def _make_union(self, element, client, namespace, name):
        # Totally fake for the moment.
        # FIXME: union the restrictions when we care about restrictions
        #base_types = element[0].attrib['memberTypes'].split(' ')
        #base_clses = [self.resolve(local_attr(base_type), allow_ref=False)
        #              for base_type in base_types]
        # Cases of union so far are int+enum, so string for now
        #base_cls = self.resolve('string', allow_ref=False)
        base_cls = UnionType
        data = {'xsd_type': (namespace, name),
                '_tag': name,
                '_client': client,
                '_namespace': namespace,
                '_nsmap': self.nsmap} # FIXME prefix?
        cls = type(name, (base_cls,), data)
        return cls

    def _make_simple(self, element, client, namespace, name):
        base_type = local_attr(self._find_restriction(element).get('base'))
        base_cls = self.resolve(base_type, allow_ref=False)
        data = {'xsd_type': (namespace, name),
                '_tag': name,
                '_client': client,
                '_namespace': namespace,
                '_nsmap': self.nsmap} # FIXME prefix?
        cls = type(name, (Pickleable, base_cls,), data)
        return cls

    def _children(self, element):
        # FIXME for element.tag == _all_tag,
        # force minOccurs -> 0, maxOccurs -> 1
        for e in element:
            if e.tag == self._element_tag:
                yield e
            elif e.tag == self._choice_tag:
                # items in choice inherit maxOccurs setting from choice
                # this allows multiple DataOffer children, for example
                max = e.get('maxOccurs')
                for se in e:
                    if max:
                        se.attrib['maxOccurs'] = max
                    yield se

    def _find_type(self, name):
        name = local_attr(name)
        # print "Find definition for class %s" % name
        type_nodes = list(itertools.chain(
                self.wsdl.findall(
                    ".//{%s}complexType[@name='%s']" % (NS_XSD, name)),
                self.wsdl.findall(
                    ".//{%s}simpleType[@name='%s']" % (NS_XSD, name))))
        if type_nodes:
            return type_nodes[0]
        # could also be element -> type reference
        elem_refs = filter(None, [
            t.get('type')
            for t in self.wsdl.findall(
                ".//{%s}element[@name='%s']" % (NS_XSD, name))])
        if elem_refs:
            type_name = elem_refs[0]
            return self._find_type(type_name)
        raise Exception("Could not find definition of class %s" % name)

    def _find_enumerations(self, element):
        restr = self._find_restriction(element)
        if restr is None:
            return []
        return restr.findall(self._enum_tag)

    def _find_restriction(self, element):
        restr = element.find(self._restr_tag)
        if restr is not None:
            return restr
        try:
            next = element[0]
        except IndexError:
            next = None
        if next is None:
            return
        return self._find_restriction(next)

    def _anyType(self, client):
        return AnyType(client)

    def _binding_style(self, binding):
        soap_binding = binding.find('{%s}binding' % NS_SOAP)
        if soap_binding is None:
            soap_binding = binding.find('{%s}binding' % NS_SOAP12)
        if soap_binding is None:
            soap_binding = binding.find('binding')
        if soap_binding is None:
            return None
        return soap_binding.get('style')

    def _op_info(self, op):
        soap_op = op.find('{%s}operation' % NS_SOAP)
        if soap_op is None:
            soap_op = op.find('{%s}operation' % NS_SOAP12)
        if soap_op is None:
            soap_op = op.find('operation')
        if soap_op is None:
            raise SyntaxError("No SOAP operation found in %s" %
                              etree.tostring(op))
        action = soap_op.attrib['soapAction']
        op_style = soap_op.get('style')
        # FIXME is it reasonable to assume that input and output
        # are the same? Is it ok to ignore the encoding style?
        input = op.find('{%s}input' % NS_WSDL)
        literal = input[0].get('use') == 'literal'

        # the header message points at a wsdl:message somewhere in the doc
        # the part names the part of that message that goes in the header
        # so to get the type we need to find the message and then get the
        # element or type attribute of the named part
        in_headers = [self._find_message_part(h.get('message'), h.get('part'))
                      for h in input.findall('{%s}header' % NS_SOAP)]
        output = op.find('{%s}output' % NS_WSDL)
        out_headers = [self._find_message_part(h.get('message'), h.get('part'))
                       for h in output.findall('{%s}header' % NS_SOAP)]
        return action, op_style, literal, in_headers, out_headers

    def _find_message_part(self, message, part):
        message = local_attr(message)
        part = self.wsdl.find(
            ".//{%s}message[@name='%s']/{%s}part[@name='%s']" %
            (NS_WSDL, message, NS_WSDL, part))
        return (part.get('name'), part.get('element') or part.get('type'))


class TypeRef(object):
    def __init__(self, name, factory):
        self.name = name
        self.factory = factory

    def __call__(self):
        return self.factory.resolve(self.name, allow_ref=False)


def ns(tag):
    if not tag.startswith('{'):
        return None
    return tag[1:tag.find('}')]


def local(tag):
    return tag[tag.find('}')+1:]


def local_attr(attr):
    if ':' in attr:
        _, attr = attr.split(':')
    return attr


def xsi_type(element):
    # Types and their values are generally namespaced, but we don't
    # want the namespaces here.
    for key, val in element.attrib.items():
        if local(key) == 'type':
            return local_attr(val)


def _tostring(elem, default_namespace, encoding=None, method=None):
    class dummy:
        pass
    data = []
    fl = dummy()
    fl.write = data.append
    etree.ElementTree(elem).write(fl, encoding=encoding, method=method,
                                  default_namespace=default_namespace)
    return "".join(data)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.