trac-rpc-mq / t5437 / t5437-protocol_api-r7194.diff

   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
diff --git a/trunk/README.wiki b/trunk/README.wiki
--- a/trunk/README.wiki
+++ b/trunk/README.wiki
@@ -27,16 +27,22 @@
 
 == API Documentation ==
 
-The API documentation is available at `<project_url>/xmlrpc` and
-`<project_url/jsonrpc` for projects that have the plugin installed and enabled.
-It can be accessed by all users that have been granted `XML_RPC` permission.
+The API documentation is available at `<project_url>/rpc` for projects that
+have the plugin installed and enabled. It can be accessed by all users that
+have been granted `XML_RPC` permission.
 
-== Developing ==
+== Development ==
 
-The Trac RPC plugin has interfaces that make it possible to extend the set of
-methods available for remote procedure calls. See source for documentation.
+The Trac RPC plugin uses pluggable interfaces to do all its work. That means it
+is easy to extend, and currently supports:
+ * protocols; add a new protocol in addition to the builtin ones and read input
+   and answer request in whatever form and format needed.
+ * methods; adding new methods available for remote procedure calls that will
+   work for any enabled protocol.
 
-The source code can be obtained from: http://trac-hacks.org/svn/xmlrpcplugin/
+See source for documentation. The source code can be obtained from:
+
+http://trac-hacks.org/svn/xmlrpcplugin/
 
 For work on the plugin itself (for submitting patches and more), please verify
 patches by running unittests (requires Trac source code on path):
@@ -50,6 +56,7 @@
 and patches for bugs and enhancements. Special thanks to:
  * Matt Good
  * Steffen Pingel
+ * Olemis Lang
 
 == License ==
 
diff --git a/trunk/setup.cfg b/trunk/setup.cfg
new file mode 100644
--- /dev/null
+++ b/trunk/setup.cfg
@@ -0,0 +1,3 @@
+[egg_info]
+tag_build = 
+tag_svn_revision = true
diff --git a/trunk/setup.py b/trunk/setup.py
--- a/trunk/setup.py
+++ b/trunk/setup.py
@@ -10,19 +10,20 @@
 
 setup(
     name='TracXMLRPC',
-    version='1.0.6',
+    version='1.1.0',
     license='BSD',
     author='Alec Thomas',
     author_email='alec@swapoff.org',
     maintainer='Odd Simon Simonsen',
     maintainer_email='simon-code@bvnetwork.no',
     url='http://trac-hacks.org/wiki/XmlRpcPlugin',
-    description='XML-RPC interface to Trac',
+    description='RPC interface to Trac',
     zip_safe=True,
     test_suite = 'tracrpc.tests.suite',
     packages=find_packages(exclude=['*.tests']),
     package_data={
-        'tracrpc': ['templates/*.html']
+        'tracrpc': ['templates/*.html', 'htdocs/js/*.js', \
+                    'htdocs/css/*.css']
         },
     entry_points={
         'trac.plugins': 'TracXMLRPC = tracrpc'
diff --git a/trunk/tracrpc/__init__.py b/trunk/tracrpc/__init__.py
--- a/trunk/tracrpc/__init__.py
+++ b/trunk/tracrpc/__init__.py
@@ -7,6 +7,8 @@
 """
 
 from tracrpc.api import *
+from tracrpc.json_rpc import *
+from tracrpc.xml_rpc import *
 from tracrpc.web_ui import *
 from tracrpc.ticket import *
 from tracrpc.wiki import *
diff --git a/trunk/tracrpc/api.py b/trunk/tracrpc/api.py
--- a/trunk/tracrpc/api.py
+++ b/trunk/tracrpc/api.py
@@ -6,23 +6,29 @@
 (c) 2009      ::: www.CodeResort.com - BV Network AS (simon-code@bvnetwork.no)
 """
 
+import inspect
+import types
+from datetime import datetime
+import xmlrpclib
+
 from trac.core import *
 from trac.perm import IPermissionRequestor
-import inspect
-import types
-import xmlrpclib
-import datetime
 
-try:
-    set = set
-except:
-    from sets import Set as set
+__all__ = ['expose_rpc', 'IRPCProtocol', 'IXMLRPCHandler', 'AbstractRPCHandler',
+            'Method', 'XMLRPCSystem', 'Binary', 'RPCError']
+
+class Binary(xmlrpclib.Binary):
+    """ RPC Binary type. Currently == xmlrpclib.Binary. """
+    pass
+
+class RPCError(TracError):
+    """ Error class for general RPC-related errors. """
+    pass
 
 RPC_TYPES = {int: 'int', bool: 'boolean', str: 'string', float: 'double',
-             xmlrpclib.DateTime: 'dateTime.iso8601', xmlrpclib.Binary: 'base64',
+             datetime: 'dateTime.iso8601', Binary: 'base64',
              list: 'array', dict: 'struct', None : 'int'}
 
-
 def expose_rpc(permission, return_type, *arg_types):
     """ Decorator for exposing a method as an RPC call with the given
     signature. """
@@ -35,7 +41,29 @@
     return decorator
 
 
+class IRPCProtocol(Interface):
+    
+    def rpc_info():
+        """ Returns a tuple of (name, docs). Method provides
+        general information about the protocol used for the RPC HTML view.
+        
+        name: Shortname like 'XML-RPC'.
+        docs: Documentation for the protocol.
+        """
+
+    def rpc_match():
+        """ Return an iterable of (path_item, content_type) combinations that
+        will be handled by the protocol.
+        
+        path_item: Single word to use for matching against
+                   (/login)?/<path_item>. Answer to 'rpc' only if possible.
+        content_type: Starts-with check of 'Content-Type' request header. """
+
+    def rpc_process(req, content_type):
+        """ Process the RPC request and finalize response. """
+
 class IXMLRPCHandler(Interface):
+
     def xmlrpc_namespace():
         """ Provide the namespace in which a set of methods lives.
             This can be overridden if the 'name' element is provided by
@@ -56,7 +84,6 @@
         followed by argument types.
         """
 
-
 class AbstractRPCHandler(Component):
     implements(IXMLRPCHandler)
     abstract = True
@@ -180,7 +207,7 @@
                 p = Method(provider, *candidate)
                 if p.name == method:
                     return p
-        raise xmlrpclib.Fault(1, 'RPC method "%s" not found' % method)
+        raise RPCError('RPC method "%s" not found' % method)
         
     # Exported methods
     def all_methods(self, req):
@@ -199,10 +226,8 @@
         for signature in signatures:
             try:
                 yield self.get_method(signature['methodName'])(req, signature['params'])
-            except xmlrpclib.Fault, e:
+            except Exception, e:
                 yield e
-            except Exception, e:
-                yield xmlrpclib.Fault(2, "'%s' while executing '%s()'" % (str(e), signature['methodName']))
 
     def listMethods(self, req):
         """ This method returns a list of strings, one for each (non-system)
diff --git a/trunk/tracrpc/htdocs/css/rpc.css b/trunk/tracrpc/htdocs/css/rpc.css
new file mode 100644
--- /dev/null
+++ b/trunk/tracrpc/htdocs/css/rpc.css
@@ -0,0 +1,13 @@
+#rpc-toc {
+    display: none;
+    float: right;
+    width: 15em;
+}
+#rpc-toc.wiki-toc h4 {
+    text-align: center;
+}
+#rpc-toc ul {
+    margin: 0;
+    padding: 0.3em 0.15em;
+    list-style-type: none;
+}
diff --git a/trunk/tracrpc/htdocs/js/rpc.js b/trunk/tracrpc/htdocs/js/rpc.js
new file mode 100644
--- /dev/null
+++ b/trunk/tracrpc/htdocs/js/rpc.js
@@ -0,0 +1,28 @@
+(function($) {
+    $(document).ready(function () {
+        // Create a Table of Contents (TOC)
+        $('#content .wikipage')
+            .prepend('<div id="rpc-toc" class="wiki-toc"><h4>Contents</h4><ul /></div>');
+        function toc_entry(_this, item) {
+            return $('<li><a href="#' + _this.id + '" title="'
+                     + $(item).text().replace(/^\s+|\s+$/g, '')
+                     + '">' + _this.id + '</a></li>');
+        }
+        var ul = $('#rpc-toc ul');
+        $("#content").find("*[id]").each(function(index, item) {
+            var elem = undefined;
+            if (this.tagName == 'H2') {
+                elem = toc_entry(this, item);
+                elem.css('padding-top', '0.5em');
+            }
+            if (this.tagName == 'H3') {
+                elem = toc_entry(this, item);
+                elem.css('padding-left', '1.2em');
+            }
+            ul.append(elem);
+        });
+        $('#rpc-toc').toggle();
+        // Add anchors to headings
+        $("#content").find("h2,h3").addAnchor("Link here");
+    });
+})(jQuery);
diff --git a/trunk/tracrpc/json_rpc.py b/trunk/tracrpc/json_rpc.py
new file mode 100644
--- /dev/null
+++ b/trunk/tracrpc/json_rpc.py
@@ -0,0 +1,203 @@
+# -*- coding: utf-8 -*-
+"""
+License: BSD
+
+(c) 2009      ::: www.CodeResort.com - BV Network AS (simon-code@bvnetwork.no)
+"""
+
+import re
+import datetime
+from types import GeneratorType
+
+from trac.core import *
+from trac.perm import PermissionError
+from trac.resource import ResourceNotFound
+from trac.util.datefmt import utc
+from trac.util.text import to_unicode
+
+from tracrpc.api import IRPCProtocol, XMLRPCSystem, Binary
+from tracrpc.util import exception_to_unicode, empty, prepare_docs
+
+__all__ = ['JsonRpcProtocol']
+
+try:
+    import json
+    if not (hasattr(json, 'JSONEncoder') \
+            and hasattr(json, 'JSONDecoder')):
+        raise AttributeError("Incorrect JSON library found.")
+except (ImportError, AttributeError):
+    import simplejson as json
+
+class TracRpcJSONEncoder(json.JSONEncoder):
+    """ Extending the JSON encoder to support some additional types:
+    1. datetime.datetime => {'__jsonclass__': ["datetime", "<rfc3339str>"]}
+    2. tracrpc.api.Binary => {'__jsonclass__': ["binary", "<base64str>"]}
+    3. empty => '' """
+
+    def default(self, obj):
+        if isinstance(obj, datetime.datetime):
+            # http://www.ietf.org/rfc/rfc3339.txt
+            return {'__jsonclass__': ["datetime",
+                            obj.strftime('%Y-%m-%dT%H:%M:%S')]}
+        elif isinstance(obj, Binary):
+            return {'__jsonclass__': ["binary",
+                            obj.data.encode("base64")]}
+        elif obj is empty:
+            return ''
+        else:
+            return json.JSONEncoder(self, obj)
+
+class TracRpcJSONDecoder(json.JSONDecoder):
+    """ Extending the JSON decoder to support some additional types:
+    1. {'__jsonclass__': ["datetime", "<rfc3339str>"]} => datetime.datetime
+    2. {'__jsonclass__': ["binary", "<base64str>"]} => tracrpc.api.Binary """
+
+    dt = re.compile(
+        '^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,}))?')
+
+    def _normalize(self, obj):
+        """ Helper to traverse JSON decoded object for custom types. """
+        if isinstance(obj, tuple):
+            return tuple(self._normalize(item) for item in obj)
+        elif isinstance(obj, list):
+            return [self._normalize(item) for item in obj]
+        elif isinstance(obj, dict):
+            if obj.keys() == ['__jsonclass__']:
+                kind, val = obj['__jsonclass__']
+                if kind == 'datetime':
+                    dt = self.dt.match(val)
+                    if not dt:
+                        raise Exception(
+                                "Invalid datetime string (%s)" % val)
+                    dt = tuple([int(i) for i in dt.groups() if i])
+                    kw_args = {'tzinfo': utc}
+                    return datetime.datetime(*dt, **kw_args)
+                elif kind == 'binary':
+                    try:
+                        bin = val.decode("base64")
+                        return Binary(bin)
+                    except:
+                        raise Exception("Invalid base64 string")
+                else:
+                    raise Exception("Unknown __jsonclass__: %s" % kind)
+            else:
+                return dict(self._normalize(obj.items()))
+        elif isinstance(obj, basestring):
+            return to_unicode(obj)
+        else:
+            return obj
+
+    def decode(self, obj, *args, **kwargs):
+        obj = json.JSONDecoder.decode(self, obj, *args, **kwargs)
+        return self._normalize(obj)
+
+class JsonRpcProtocol(Component):
+    r"""
+    Example `POST` request using `curl` with `Content-Type` header
+    and body:
+ 
+    {{{
+    user: ~ > cat body.json
+    {"params": ["WikiStart"], "method": "wiki.getPage", "id": 123}
+    user: ~ > curl -H "Content-Type: application/json" --data @body.json ${req.abs_href.rpc()}
+    {"id": 123, "error": null, "result": "= Welcome to....
+    }}}
+    
+    Implementation details:
+    
+      * JSON-RPC has no formalized type system, so a class-hint system is used
+        for input and output of non-standard types:
+        * `{"__jsonclass__": ["datetime", "YYYY-MM-DDTHH:MM:SS"]} => DateTime (UTC)`
+        * `{"__jsonclass__": ["binary", "<base64-encoded>"]} => Binary`
+      * `"id"` is optional, and any marker value received with a
+        request is returned with the response.
+    """
+
+    implements(IRPCProtocol)
+
+    # IRPCProtocol methods
+
+    def rpc_info(self):
+        return ('JSON-RPC', prepare_docs(self.__doc__))
+
+    def rpc_match(self):
+        yield('rpc', 'application/json')
+        # Legacy path - provided for backwards compatibility:
+        yield ('jsonrpc', 'application/json')
+
+    def rpc_process(self, req, content_type):
+        """ Handles JSON-RPC requests """
+        if not json:
+            self.log.debug("RPC(json) call ignored (not available).")
+            self._send_response(req, "Error: JSON-RPC not available.\n",
+                                content_type)
+        try:
+            data = json.load(req, cls=TracRpcJSONDecoder)
+        except Exception, e:
+            # Abort with exception - no data can be read
+            self.log.error("RPC(json) decode error %s" % \
+                    exception_to_unicode(e, traceback=True))
+            response = json.dumps(self._json_error(e, -32700),
+                                    cls=TracRpcJSONEncoder)
+            self._send_response(req, response + '\n', content_type)
+            return
+        self.log.debug("RPC(json) call by '%s': %s" % (req.authname, data))
+        args = data.get('params') or []
+        r_id = data.get('id', None)
+        method = data.get('method', '')
+        try:
+            req.perm.require('XML_RPC') # Need at least XML_RPC
+            if method == 'system.multicall': # Custom multicall
+                results = []
+                for mc in args:
+                    results.append(self._json_call(req, mc.get('method', ''),
+                        mc.get('params') or [], mc.get('id') or r_id))
+                response = {'result': results, 'error': None, 'id': r_id}
+            else:
+                response = self._json_call(req, method, args, r_id)
+            try: # JSON encoding
+                self.log.debug("RPC(json) result: %s" % repr(response))
+                response = json.dumps(response, cls=TracRpcJSONEncoder)
+            except Exception, e:
+                response = json.dumps(self._json_error(e, r_id=r_id),
+                                        cls=TracRpcJSONEncoder)
+        except Exception, e:
+            self.log.error("RPC(json) error %s" % exception_to_unicode(e,
+                                                    traceback=True))
+            response = json.dumps(self._json_error(e, r_id=r_id),
+                            cls=TracRpcJSONEncoder)
+        self.log.debug("RPC(json) encoded result: %s" % response)
+        self._send_response(req, response + '\n', content_type)
+
+    # Internal methods
+
+    def _send_response(self, req, response, content_type='application/json'):
+        response = to_unicode(response).encode("utf-8")
+        req.send_response(200)
+        req.send_header('Content-Type', content_type)
+        req.send_header('Content-Length', len(response))
+        req.end_headers()
+        req.write(response)
+
+    def _json_call(self, req, method, args, r_id=None):
+        """ Call method and create response dictionary. """
+        try:
+            result = (XMLRPCSystem(self.env).get_method(method)(req, args))[0]
+            if isinstance(result, GeneratorType):
+                result = list(result)
+            return {'result': result, 'error': None, 'id': r_id}
+        except Exception, e:
+            return self._json_error(e, r_id=r_id)
+
+    def _json_error(self, e, c=None, r_id=None):
+        """ Makes a response dictionary that is an error. """
+        if isinstance(e, PermissionError):
+            c = 403
+        if isinstance(e, ResourceNotFound):
+            c = 404
+        c = c or hasattr(e, 'code') and e.code or -32603
+        return {'result': None, 'id': r_id, 'error': {
+                'name': hasattr(e, 'name') and e.name or 'JSONRPCError',
+                'code': c,
+                'message': to_unicode(e)}}
+
diff --git a/trunk/tracrpc/search.py b/trunk/tracrpc/search.py
--- a/trunk/tracrpc/search.py
+++ b/trunk/tracrpc/search.py
@@ -7,14 +7,13 @@
 """
 
 from trac.core import *
-from tracrpc.api import IXMLRPCHandler
 from trac.search.api import ISearchSource
 from trac.search.web_ui import SearchModule
+from trac.util.compat import set
 
-try:
-    a = set()
-except:
-    from sets import Set as set
+from tracrpc.api import IXMLRPCHandler
+
+__all__ = ['SearchRPC']
 
 class SearchRPC(Component):
     """ Search Trac. """
diff --git a/trunk/tracrpc/templates/rpc.html b/trunk/tracrpc/templates/rpc.html
new file mode 100644
--- /dev/null
+++ b/trunk/tracrpc/templates/rpc.html
@@ -0,0 +1,80 @@
+<!DOCTYPE html
+    PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
+    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml"
+      xmlns:py="http://genshi.edgewall.org/"
+      xmlns:xi="http://www.w3.org/2001/XInclude">
+  <xi:include href="layout.html" />
+  <xi:include href="macros.html" />
+  <head>
+    <title>Remote Procedure Call (RPC)</title>
+  </head>
+  
+  <body>
+    <div id="content" class="wiki">
+      <div class="wikipage searchable">
+        <h1>Remote Procedure Call (RPC)</h1>
+        <p><strong>Installed API version :</strong> ${rpc.version} </p>
+        <h2 id="Protocols">Protocol reference:</h2>
+        <p>Below you will find a detailed description of all the RPC 
+          protocols installed in this environment. This includes 
+          supported content types as well as target URLs for 
+          anonymous and authenticated access. Use this 
+          information to interact with this environment from 
+          a remote location.
+        </p>
+        <p>Libraries for remote procedure calls and parsing exists
+          for most major languages and platforms - use a tested, standard library
+          for consistent results.</p>
+        <dl py:for="protocol in rpc.protocols">
+          <h3 id="${protocol[0]}">${protocol[0]}</h3>
+          <dd>
+            <p>For ${protocol[0]} protocol, use any one of:</p>
+            <ul>
+              <li py:for="h, ct in protocol[2]">
+                <tt>{'Content-Type': '$ct'}</tt> header with request to:
+                <ul>
+                  <li><a href="${req.abs_href(h)}">${req.abs_href(h)}</a> 
+                  for anonymous access</li>
+                  <li><a href="${req.abs_href.login(h)}">${req.abs_href.login(h)}</a>
+                  for authenticated access</li>
+                </ul>
+              </li>
+            </ul>
+          <div>
+            ${wiki_to_html(context, expand_docs(protocol[1], locals()['__data__']))}
+          </div>
+          </dd>
+        </dl>
+  
+        <h2 id="Methods">RPC exported functions</h2>
+  
+        <div id="searchable">
+          <dl py:for="key in sorted(rpc.functions)" py:with="namespace = rpc.functions[key]">
+            <h3 id="${'xmlrpc.' + to_unicode(namespace.namespace)}">
+              ${namespace.namespace} - ${namespace.description}
+            </h3>
+            <dd>
+              <table class="listing tickets">
+                <thead>
+                  <tr>
+                    <th style="width:40%">Function</th>
+                    <th style="width:45%">Description</th>
+                    <th style="width:15%">Permission required</th>
+                  </tr>
+                </thead>
+                <tbody py:for="idx, function in enumerate(namespace.methods)">
+                  <tr class="${'color3-' + (idx % 2 == 0 and 'even' or 'odd')}">
+                    <td style="padding-left:4em;text-indent:-4em">${function[0]}</td>
+                    <td>${function[1]}</td>
+                    <td>${function[2] or "By resource"}</td>
+                  </tr>
+                </tbody>
+              </table>
+            </dd>
+          </dl>
+        </div>
+      </div>
+    </div>
+  </body>
+</html>
diff --git a/trunk/tracrpc/templates/xmlrpclist.html b/trunk/tracrpc/templates/xmlrpclist.html
deleted file mode 100644
--- a/trunk/tracrpc/templates/xmlrpclist.html
+++ /dev/null
@@ -1,112 +0,0 @@
-<!DOCTYPE html
-    PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
-    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml"
-      xmlns:py="http://genshi.edgewall.org/"
-      xmlns:xi="http://www.w3.org/2001/XInclude">
-  <xi:include href="layout.html" />
-  <xi:include href="macros.html" />
-  <head>
-    <title>XML-RPC</title>
-  </head>
-  <body>
-
-    <div id="content" class="wiki">
-      <h1>Remote Procedure Call (RPC) Interface</h1>
-      <dl>
-        <dt>API Status:</dt>
-          <dd>XML-RPC is <strong>available</strong></dd>
-          <dd>JSON-RPC is <strong>
-            ${xmlrpc.json and 'available' or 'not available'}</strong></dd>
-      </dl>
-
-      <h2>RPC exported functions</h2>
-
-      <div id="searchable">
-        <dl py:for="key in sorted(xmlrpc.functions)" py:with="namespace = xmlrpc.functions[key]">
-          <dt>
-            <h3 id="${'xmlrpc.' + to_unicode(namespace.namespace)}">
-              ${namespace.namespace} - ${namespace.description}
-            </h3>
-          </dt>
-          <dd>
-            <table class="listing tickets">
-              <thead>
-                <tr>
-                  <th style="width:40%">Function</th>
-                  <th style="width:45%">Description</th>
-                  <th style="width:15%">Permission required</th>
-                </tr>
-              </thead>
-              <tbody py:for="idx, function in enumerate(namespace.methods)">
-                <tr class="${'color3-' + (idx % 2 == 0 and 'even' or 'odd')}">
-                  <td style="padding-left:4em;text-indent:-4em">${function[0]}</td>
-                  <td>${function[1]}</td>
-                  <td>${function[2] or "By resource"}</td>
-                </tr>
-              </tbody>
-            </table>
-          </dd>
-        </dl>
-      </div>
-      
-      <h2>Calling Methods</h2>
-      <p>XML and JSON libraries for remote procedure calls and parsing exists
-        for all major languages and platforms - use a tested, standard library
-        for consistent results.</p>
-      <p>The following are examples for illustration only, and shows raw
-        access to RPC using <tt>curl</tt> (with Content-Type and Body for POST request):</p>
-      <div class="help">
-        <h4>XML-RPC example</h4>
-        <pre>
-user: ~ &gt; cat body.xml
-&lt;?xml version="1.0"?&gt;
-&lt;methodCall&gt;
-&lt;methodName&gt;wiki.getPage&lt;/methodName&gt;
-&lt;params&gt;
-&lt;param&gt;&lt;string&gt;WikiStart&lt;/string&gt;&lt;/param&gt;
-&lt;/params&gt;
-&lt;/methodCall&gt;
-user: ~ &gt; curl -H "Content-Type: application/xml" --data @body.xml ${req.abs_href.xmlrpc()}
-&lt;?xml version='1.0'?&gt;
-&lt;methodResponse&gt;
-&lt;params&gt;
-&lt;param&gt;
-&lt;value&gt;&lt;string&gt;= Welcome to....
-      </pre>
-      <ul>
-        <li>Use <tt>${req.abs_href.login('xmlrpc')}</tt> with basic
-            authentication for user context.</li>
-      </ul>
-      </div>
-      <div>
-        <h4>JSON-RPC example</h4>
-        <pre>
-user: ~ &gt; cat body.json
-{"params": ["WikiStart"], "method": "wiki.getPage", "id": 123}
-user: ~ &gt; curl -H "Content-Type: application/json" --data @body.json ${req.abs_href.jsonrpc()}
-{"id": 123, "error": null, "result": "= Welcome to....
-        </pre>
-        <ul>
-          <li>JSON-RPC has no formalized type system, so a class-hint system is used
-              for input and output of non-standard types:
-            <ul>
-              <li><tt>{"__jsonclass__": ["datetime", "YYYY-MM-DDTHH:MM:SS"]}</tt>
-                  = DateTime (UTC)</li>
-              <li><tt>{"__jsonclass__": ["binary", "&lt;base64-encoded&gt;"]}</tt>
-                  = Binary</li>
-            </ul>
-          </li>
-          <li><tt>"id"</tt> is optional, and any marker value received with a
-            request is returned with the response.</li>
-          <li>Use <tt>${req.abs_href.login('jsonrpc')}</tt> with basic
-            authentication for user context.</li>
-        </ul>
-      </div>
-      
-      <script type="text/javascript">
-        addHeadingLinks(document.getElementById("searchable"));
-      </script>
-    </div>
-  </body>
-</html>
diff --git a/trunk/tracrpc/tests/__init__.py b/trunk/tracrpc/tests/__init__.py
--- a/trunk/tracrpc/tests/__init__.py
+++ b/trunk/tracrpc/tests/__init__.py
@@ -38,16 +38,16 @@
             self._tracadmin('permission', 'add', 'anonymous', 'XML_RPC')
             print "Created test environment: %s" % self.dirname
             parts = urllib2.urlparse.urlsplit(self.url)
-            self.url_anon = '%s://%s:%s/xmlrpc' % (parts[0], parts[1],
+            # Regular URIs
+            self.url_anon = '%s://%s:%s/rpc' % (parts[0], parts[1],
                                 self.port)
+            self.url_auth = '%s://%s:%s/login/rpc' % (parts[0],
+                                parts[1], self.port)
+            # URIs with user:pass as part of URL
             self.url_user = '%s://user:user@%s:%s/login/xmlrpc' % \
                                 (parts[0], parts[1], self.port)
             self.url_admin = '%s://admin:admin@%s:%s/login/xmlrpc' % \
                                 (parts[0], parts[1], self.port)
-            self.url_anon_json = '%s://%s:%s/jsonrpc' % (parts[0], parts[1],
-                                self.port)
-            self.url_auth_json = '%s://%s:%s/login/jsonrpc' % (parts[0],
-                                parts[1], self.port)
             print "Starting web server: %s:%s\n" % (self.url, self.port)
             self.restart()
             SvnFunctionalTestEnvironment.post_create(self, env)
@@ -68,10 +68,12 @@
 
     def suite():
         suite = unittest.TestSuite()
-        import tracrpc.tests.xml
-        suite.addTest(tracrpc.tests.xml.suite())
-        import tracrpc.tests.json
-        suite.addTest(tracrpc.tests.json.suite())
+        import tracrpc.tests.api
+        suite.addTest(tracrpc.tests.api.suite())
+        import tracrpc.tests.xml_rpc
+        suite.addTest(tracrpc.tests.xml_rpc.suite())
+        import tracrpc.tests.json_rpc
+        suite.addTest(tracrpc.tests.json_rpc.suite())
         import tracrpc.tests.ticket
         suite.addTest(tracrpc.tests.ticket.suite())
         import tracrpc.tests.wiki
diff --git a/trunk/tracrpc/tests/api.py b/trunk/tracrpc/tests/api.py
new file mode 100644
--- /dev/null
+++ b/trunk/tracrpc/tests/api.py
@@ -0,0 +1,78 @@
+# -*- coding: utf-8 -*-
+"""
+License: BSD
+
+(c) 2009      ::: www.CodeResort.com - BV Network AS (simon-code@bvnetwork.no)
+"""
+
+import os
+import unittest
+import urllib2
+
+from tracrpc.tests import rpc_testenv
+
+from tracrpc.api import IRPCProtocol
+
+from trac.core import *
+from trac.test import Mock
+
+class ProtocolProviderTestCase(unittest.TestCase):
+
+    def test_invalid_content_type(self):
+        req = urllib2.Request(rpc_testenv.url_anon,
+                    headers={'Content-Type': 'text/plain'})
+        try:
+            resp = urllib2.urlopen(req)
+            self.fail("Expected urllib2.HTTPError")
+        except urllib2.HTTPError, e:
+            self.assertEquals(e.code, 415)
+            self.assertEquals(e.msg, "Unsupported Media Type")
+            self.assertEquals(e.fp.read(),
+                "No protocol matching Content-Type 'text/plain' at path '/rpc'.")
+
+    def test_valid_provider(self):
+        # Confirm the request won't work before adding plugin
+        req = urllib2.Request(rpc_testenv.url_anon,
+                        headers={'Content-Type': 'application/x-tracrpc-test'})
+        try:
+            resp = urllib2.urlopen(req)
+            self.fail("Expected urllib2.HTTPError")
+        except urllib2.HTTPError, e:
+            self.assertEquals(e.code, 415)
+        # Make a new plugin 
+        provider = os.path.join(rpc_testenv.tracdir, 'plugins', 'DummyProvider.py')
+        open(provider, 'w').write(
+            "from trac.core import *\n"
+            "from tracrpc.api import *\n"
+            "class DummyProvider(Component):\n"
+            "    implements(IRPCProtocol)\n"
+            "    def rpc_info(self):\n"
+            "        yield ('TEST-RPC', 'No Docs!')\n"
+            "    def rpc_match(self):\n"
+            "        yield ('rpc', 'application/x-tracrpc-test')\n"
+            "    def rpc_process(self, req, content_type):\n"
+            "        response = 'Got a result!'\n"
+            "        req.send_response(200)\n"
+            "        req.send_header('Content-Type', content_type)\n"
+            "        req.send_header('Content-Length', len(response))\n"
+            "        req.end_headers()\n"
+            "        req.write(response)\n")
+        rpc_testenv.restart()
+        try:
+            req = urllib2.Request(rpc_testenv.url_anon,
+                        headers={'Content-Type': 'application/x-tracrpc-test'})
+            resp = urllib2.urlopen(req)
+            self.assertEquals(200, resp.code)
+            self.assertEquals("Got a result!", resp.read())
+            self.assertEquals(resp.headers['Content-Type'],
+                                                'application/x-tracrpc-test')
+        finally:
+            # Clean up so that provider don't affect further tests
+            os.unlink(provider)
+            rpc_testenv.restart()
+
+def suite():
+    return unittest.makeSuite(ProtocolProviderTestCase)
+
+if __name__ == '__main__':
+    unittest.main(defaultTest='suite')
diff --git a/trunk/tracrpc/tests/json.py b/trunk/tracrpc/tests/json_rpc.py
rename from trunk/tracrpc/tests/json.py
rename to trunk/tracrpc/tests/json_rpc.py
--- a/trunk/tracrpc/tests/json.py
+++ b/trunk/tracrpc/tests/json_rpc.py
@@ -9,9 +9,9 @@
 import os
 import shutil
 import urllib2
-from StringIO import StringIO
 
-from tracrpc.web_ui import json
+from tracrpc.json_rpc import json
+from tracrpc.util import StringIO
 
 if json:
     from tracrpc.tests import rpc_testenv
@@ -19,7 +19,7 @@
     class JsonTestCase(unittest.TestCase):
         
         def _anon_req(self, data):
-            req = urllib2.Request(rpc_testenv.url_anon_json,
+            req = urllib2.Request(rpc_testenv.url_anon,
                         headers={'Content-Type': 'application/json'})
             req.data = json.dumps(data)
             resp = urllib2.urlopen(req)
@@ -29,10 +29,10 @@
             password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
             handler = urllib2.HTTPBasicAuthHandler(password_mgr)
             password_mgr.add_password(realm=None,
-                          uri=rpc_testenv.url_auth_json,
+                          uri=rpc_testenv.url_auth,
                           user=user,
                           passwd=user)
-            req = urllib2.Request(rpc_testenv.url_auth_json,
+            req = urllib2.Request(rpc_testenv.url_auth,
                         headers={'Content-Type': 'application/json'})
             req.data = json.dumps(data)
             resp = urllib2.build_opener(handler).open(req)
@@ -116,7 +116,7 @@
                                          'id': 'no-perm'})
                 self.assertEquals(None, result['result'])
                 self.assertEquals('no-perm', result['id'])
-                self.assertEquals(-32600, result['error']['code'])
+                self.assertEquals(403, result['error']['code'])
                 self.assertTrue('XML_RPC' in result['error']['message'])
             finally:
                 # Add back the default permission for further tests
@@ -142,6 +142,31 @@
             self.assertTrue('listMethods() takes exactly 2 arguments' \
                                 in result['error']['message'])
 
+        def test_call_permission(self):
+            # Test missing call-specific permission
+            result = self._anon_req({'method': 'ticket.component.delete',
+                    'params': ['component1'], 'id': 2332})
+            self.assertEquals(None, result['result'])
+            self.assertEquals(2332, result['id'])
+            self.assertEquals(403, result['error']['code'])
+            self.assertEquals(result['error']['message'],
+                'TICKET_ADMIN privileges are required to perform this operation')
+
+        def test_resource_not_found(self):
+            # A Ticket resource
+            result = self._anon_req({'method': 'ticket.get',
+                    'params': [2147483647], 'id': 3443})
+            self.assertEquals(result['id'], 3443)
+            self.assertEquals(result['error']['code'], 404)
+            self.assertEquals(result['error']['message'],
+                     'Ticket 2147483647 does not exist.')
+            # A Wiki resource
+            result = self._anon_req({'method': 'wiki.getPage',
+                    'params': ["Test", 10], 'id': 3443})
+            self.assertEquals(result['error']['code'], 404)
+            self.assertEquals(result['error']['message'],
+                     'Wiki page "Test" does not exist at version 10')
+
     def suite():
         return unittest.makeSuite(JsonTestCase)
 else:
diff --git a/trunk/tracrpc/tests/ticket.py b/trunk/tracrpc/tests/ticket.py
--- a/trunk/tracrpc/tests/ticket.py
+++ b/trunk/tracrpc/tests/ticket.py
@@ -32,7 +32,11 @@
                   [['action_reassign_reassign_owner', 'admin', []]]],
                   ['accept', 'accept',
                   "The owner will change from (none) to admin. Next status will be 'accepted'.", []]]
-        self.assertEquals(default, actions)
+        # Some action text was changed in trac:changeset:9041 - adjust default for test
+        if 'will be changed' in actions[2][2]:
+            default[2][2] = default[2][2].replace('will change', 'will be changed')
+            default[3][2] = default[3][2].replace('will change', 'will be changed')
+        self.assertEquals(actions, default)
         self.admin.ticket.delete(tid)
 
     def test_getAvailableActions_DeleteTicket(self):
@@ -41,9 +45,11 @@
         self.assertEquals(False,
                 'delete' in self.admin.ticket.getAvailableActions(tid))
         env = rpc_testenv.get_trac_environment()
+        delete_plugin = os.path.join(rpc_testenv.tracdir,
+                                    'plugins', 'DeleteTicket.py')
         shutil.copy(os.path.join(
             rpc_testenv.trac_src, 'sample-plugins', 'workflow', 'DeleteTicket.py'),
-            os.path.join(rpc_testenv.tracdir, 'plugins'))
+                    delete_plugin)
         env.config.set('ticket', 'workflow',
                 'ConfigurableTicketWorkflow,DeleteTicketActionController')
         env.config.save()
@@ -57,6 +63,9 @@
         rpc_testenv.restart()
         self.assertEquals(False,
                 'delete' in self.admin.ticket.getAvailableActions(tid))
+        # Clean up
+        os.unlink(delete_plugin)
+        rpc_testenv.restart()
 
     def test_FineGrainedSecurity(self):
         self.assertEquals(1, self.admin.ticket.create('abc', '123', {}))
diff --git a/trunk/tracrpc/tests/wiki.py b/trunk/tracrpc/tests/wiki.py
--- a/trunk/tracrpc/tests/wiki.py
+++ b/trunk/tracrpc/tests/wiki.py
@@ -9,11 +9,11 @@
 
 import xmlrpclib
 import os
-from StringIO import StringIO
 
 from trac.util.compat import sorted
 
 from tracrpc.tests import rpc_testenv
+from tracrpc.util import StringIO
 
 class RpcWikiTestCase(unittest.TestCase):
     
diff --git a/trunk/tracrpc/tests/xml.py b/trunk/tracrpc/tests/xml_rpc.py
rename from trunk/tracrpc/tests/xml.py
rename to trunk/tracrpc/tests/xml_rpc.py
--- a/trunk/tracrpc/tests/xml.py
+++ b/trunk/tracrpc/tests/xml_rpc.py
@@ -28,7 +28,7 @@
                                         'XML_RPC')
             self.fail("Revoked permissions not taken effect???")
         except xmlrpclib.Fault, e:
-            self.assertEquals(1, e.faultCode)
+            self.assertEquals(403, e.faultCode)
             self.assertTrue('XML_RPC' in e.faultString)
             rpc_testenv._tracadmin('permission', 'add', 'anonymous',
                                         'XML_RPC')
@@ -46,7 +46,7 @@
             self.admin.system.listMethods("hello")
             self.fail("Oops. Wrong argspec accepted???")
         except xmlrpclib.Fault, e:
-            self.assertEquals(2, e.faultCode)
+            self.assertEquals(1, e.faultCode)
             self.assertTrue("listMethods() takes exactly 2 arguments" \
                                     in e.faultString)
 
@@ -67,6 +67,38 @@
         self.assertEquals(unicode, type(result[3]['summary']))
         self.admin.ticket.delete(t_id)
 
+    def test_to_and_from_datetime(self):
+        from datetime import datetime
+        from trac.util.datefmt import to_datetime, utc
+        from tracrpc.xml_rpc import to_xmlrpc_datetime, from_xmlrpc_datetime
+        now = to_datetime(None, utc)
+        now_timetuple = now.timetuple()[:6]
+        xmlrpc_now = to_xmlrpc_datetime(now)
+        self.assertTrue(isinstance(xmlrpc_now, xmlrpclib.DateTime),
+                "Expected xmlprc_now to be an xmlrpclib.DateTime")
+        self.assertEquals(xmlrpc_now.timetuple()[:6], now_timetuple)
+        now_from_xmlrpc = from_xmlrpc_datetime(xmlrpc_now)
+        self.assertTrue(isinstance(now_from_xmlrpc, datetime),
+                "Expected now_from_xmlrpc to be a datetime")
+        self.assertEquals(now_from_xmlrpc.timetuple()[:6], now_timetuple)
+        self.assertEquals(now_from_xmlrpc.tzinfo, utc)
+
+    def test_resource_not_found(self):
+        # A Ticket resource
+        try:
+            self.admin.ticket.get(2147483647)
+        except Exception, e:
+            self.assertEquals(e.faultCode, 404)
+            self.assertEquals(e.faultString, 
+                    'Ticket 2147483647 does not exist.')
+        # A Wiki resource
+        try:
+            self.admin.wiki.getPage("Test", 10)
+        except Exception, e:
+            self.assertEquals(e.faultCode, 404)
+            self.assertEquals(e.faultString,
+                    'Wiki page "Test" does not exist at version 10')
+
 def suite():
     return unittest.makeSuite(RpcXmlTestCase)
 
diff --git a/trunk/tracrpc/ticket.py b/trunk/tracrpc/ticket.py
--- a/trunk/tracrpc/ticket.py
+++ b/trunk/tracrpc/ticket.py
@@ -6,10 +6,15 @@
 (c) 2009      ::: www.CodeResort.com - BV Network AS (simon-code@bvnetwork.no)
 """
 
+import inspect
+from datetime import datetime
+
+import genshi
+
 from trac.attachment import Attachment
 from trac.core import *
 from trac.perm import PermissionError
-from trac.resource import Resource
+from trac.resource import Resource, ResourceNotFound
 import trac.ticket.model as model
 import trac.ticket.query as query
 from trac.ticket.api import TicketSystem
@@ -18,13 +23,10 @@
 from trac.web.chrome import add_warning
 from trac.util.datefmt import to_datetime, to_timestamp, utc
 
-import genshi
+from tracrpc.api import IXMLRPCHandler, expose_rpc, Binary
+from tracrpc.util import StringIO
 
-import inspect
-import xmlrpclib
-from StringIO import StringIO
-
-from tracrpc.api import IXMLRPCHandler, expose_rpc
+__all__ = ['TicketRPC']
 
 class TicketRPC(Component):
     """ An interface to Trac's ticketing system. """
@@ -37,7 +39,7 @@
 
     def xmlrpc_methods(self):
         yield (None, ((list,), (list, str)), self.query)
-        yield (None, ((list, xmlrpclib.DateTime),), self.getRecentChanges)
+        yield (None, ((list, datetime),), self.getRecentChanges)
         yield (None, ((list, int),), self.getAvailableActions)
         yield (None, ((list, int),), self.getActions)
         yield (None, ((list, int),), self.get)
@@ -46,10 +48,10 @@
         yield (None, ((None, int),), self.delete)
         yield (None, ((dict, int), (dict, int, int)), self.changeLog)
         yield (None, ((list, int),), self.listAttachments)
-        yield (None, ((xmlrpclib.Binary, int, str),), self.getAttachment)
+        yield (None, ((Binary, int, str),), self.getAttachment)
         yield (None,
-               ((str, int, str, str, xmlrpclib.Binary, bool),
-                (str, int, str, str, xmlrpclib.Binary)),
+               ((str, int, str, str, Binary, bool),
+                (str, int, str, str, Binary)),
                self.putAttachment)
         yield (None, ((bool, int, str),), self.deleteAttachment)
         yield ('TICKET_VIEW', ((list,),), self.getTicketFields)
@@ -243,13 +245,13 @@
         """ returns the content of an attachment. """
         attachment = Attachment(self.env, 'ticket', ticket, filename)
         req.perm(attachment.resource).require('ATTACHMENT_VIEW')
-        return xmlrpclib.Binary(attachment.open().read())
+        return Binary(attachment.open().read())
 
     def putAttachment(self, req, ticket, filename, description, data, replace=True):
         """ Add an attachment, optionally (and defaulting to) overwriting an
         existing one. Returns filename."""
         if not model.Ticket(self.env, ticket).exists:
-            raise TracError('Ticket "%s" does not exist' % ticket)
+            raise ResourceNotFound('Ticket "%s" does not exist' % ticket)
         if replace:
             try:
                 attachment = Attachment(self.env, 'ticket', ticket, filename)
@@ -267,7 +269,7 @@
     def deleteAttachment(self, req, ticket, filename):
         """ Delete an attachment. """
         if not model.Ticket(self.env, ticket).exists:
-            raise TracError('Ticket "%s" does not exists' % ticket)
+            raise ResourceNotFound('Ticket "%s" does not exists' % ticket)
         attachment = Attachment(self.env, 'ticket', ticket, filename)
         req.perm(attachment.resource).require('ATTACHMENT_DELETE')
         attachment.delete()
diff --git a/trunk/tracrpc/util.py b/trunk/tracrpc/util.py
--- a/trunk/tracrpc/util.py
+++ b/trunk/tracrpc/util.py
@@ -6,24 +6,12 @@
 (c) 2009      ::: www.CodeResort.com - BV Network AS (simon-code@bvnetwork.no)
 """
 
-import datetime
-import time
-import xmlrpclib
+from trac.util.compat import any
 
-from trac.util.datefmt import utc
-
-### PUBLIC
-
-def to_xmlrpc_datetime(dt):
-    """ Convert a datetime.datetime object to a xmlrpclib DateTime object """
-    return xmlrpclib.DateTime(dt.utctimetuple())
-
-def from_xmlrpc_datetime(data):
-    """Return datetime (in utc) from XMLRPC datetime string (is always utc)"""
-    t = list(time.strptime(data.value, "%Y%m%dT%H:%M:%S")[0:6])
-    return apply(datetime.datetime, t, {'tzinfo': utc})
-
-### INTERNAL / COMPAT
+try:
+  from cStringIO import StringIO
+except ImportError:
+  from StringIO import StringIO
 
 try:
     # Method only available in Trac 0.11.3 or higher
@@ -44,3 +32,13 @@
     from trac.util.text import empty
 except ImportError:
     empty = None
+
+def accepts_mimetype(req, mimetype):
+    if isinstance(mimetype, basestring):
+      mimetype = (mimetype,)
+    accept = (req.get_header('Accept') or '').split(',')
+    return any(x.strip().startswith(y) for x in accept for y in mimetype)
+
+def prepare_docs(text, indent=4):
+    r"""Remove leading whitespace"""
+    return ''.join(l[indent:] for l in text.splitlines(True))
diff --git a/trunk/tracrpc/web_ui.py b/trunk/tracrpc/web_ui.py
--- a/trunk/tracrpc/web_ui.py
+++ b/trunk/tracrpc/web_ui.py
@@ -6,305 +6,133 @@
 (c) 2009      ::: www.CodeResort.com - BV Network AS (simon-code@bvnetwork.no)
 """
 
-import re
-import xmlrpclib
-import datetime
-import base64
-from StringIO import StringIO
 from pkg_resources import resource_filename
-from types import GeneratorType
 
-import genshi
+from genshi.builder import tag
+from genshi.template.base import TemplateSyntaxError, BadDirectiveError
+from genshi.template.text import TextTemplate
 
 from trac.core import *
-from trac.perm import PermissionError
-from trac.util.datefmt import utc
-from trac.util.text import to_unicode
+from trac.util.translation import _
+from trac.web.api import RequestDone, HTTPUnsupportedMediaType
 from trac.web.main import IRequestHandler
-from trac.web.chrome import ITemplateProvider, add_stylesheet
+from trac.web.chrome import ITemplateProvider, INavigationContributor, \
+                            add_stylesheet, add_script, add_ctxtnav
 from trac.wiki.formatter import wiki_to_oneliner
 
-from tracrpc.api import IXMLRPCHandler, XMLRPCSystem
-from tracrpc.util import from_xmlrpc_datetime, to_xmlrpc_datetime
-from tracrpc.util import exception_to_unicode, empty
+from tracrpc.api import XMLRPCSystem, IRPCProtocol
+from tracrpc.util import accepts_mimetype
 
-try:
-    try:
-        import json
-        if not (hasattr(json, 'JSONEncoder') \
-                and hasattr(json, 'JSONDecoder')):
-            raise AttributeError("Incorrect JSON library found.")
-    except (ImportError, AttributeError):
-        import simplejson as json
+__all__ = ['RPCWeb']
 
-    class TracRpcJSONEncoder(json.JSONEncoder):
-        """ Extending the JSON encoder to support some additional types:
-        1. datetime.datetime => {'__jsonclass__': ["datetime", "<rfc3339str>"]}
-        2. xmlrpclib.Fault => unicode
-        3. xmlrpclib.Binary => {'__jsonclass__': ["binary", "<base64str>"]} """
+class RPCWeb(Component):
+    """ Handle RPC calls from HTTP clients, as well as presenting a list of
+        methods available to the currently logged in user. Browsing to
+        <trac>/rpc or <trac>/login/rpc will display this list. """
 
-        def default(self, obj):
-            if isinstance(obj, datetime.datetime):
-                # http://www.ietf.org/rfc/rfc3339.txt
-                return {'__jsonclass__': ["datetime",
-                                obj.strftime('%Y-%m-%dT%H:%M:%S')]}
-            elif isinstance(obj, xmlrpclib.Binary):
-                return {'__jsonclass__': ["binary",
-                                obj.data.encode("base64")]}
-            elif isinstance(obj, xmlrpclib.Fault):
-                return to_unicode(obj)
-            else:
-                return json.JSONEncoder(self, obj)
+    implements(IRequestHandler, ITemplateProvider, INavigationContributor)
 
-    class TracRpcJSONDecoder(json.JSONDecoder):
-        """ Extending the JSON decoder to support some additional types:
-        1. {'__jsonclass__': ["datetime", "<rfc3339str>"]} => datetime.datetime
-        2. {'__jsonclass__': ["binary", "<base64str>"]} => xmlrpclib.Binary """
-
-        dt = re.compile(
-            '^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,}))?')
-
-        def _normalize(self, obj):
-            """ Helper to traverse JSON decoded object for custom types. """
-            if isinstance(obj, tuple):
-                return tuple(self._normalize(item) for item in obj)
-            elif isinstance(obj, list):
-                return [self._normalize(item) for item in obj]
-            elif isinstance(obj, dict):
-                if obj.keys() == ['__jsonclass__']:
-                    kind, val = obj['__jsonclass__']
-                    if kind == 'datetime':
-                        dt = self.dt.match(val)
-                        if not dt:
-                            raise Exception(
-                                    "Invalid datetime string (%s)" % val)
-                        dt = tuple([int(i) for i in dt.groups() if i])
-                        kw_args = {'tzinfo': utc}
-                        return datetime.datetime(*dt, **kw_args)
-                    elif kind == 'binary':
-                        try:
-                            bin = val.decode("base64")
-                            return xmlrpclib.Binary(bin)
-                        except:
-                            raise Exception("Invalid base64 string")
-                    else:
-                        raise Exception("Unknown __jsonclass__: %s" % kind)
-                else:
-                    return dict(self._normalize(obj.items()))
-            elif isinstance(obj, basestring):
-                return to_unicode(obj)
-            else:
-                return obj
-
-        def decode(self, obj, *args, **kwargs):
-            obj = json.JSONDecoder.decode(self, obj, *args, **kwargs)
-            return self._normalize(obj)
-    
-except ImportError:
-    json = None
-
-class XMLRPCWeb(Component):
-    """ Handle XML-RPC calls from HTTP clients, as well as presenting a list of
-        methods available to the currently logged in user. Browsing to
-        <trac>/xmlrpc or <trac>/login/xmlrpc will display this list. """
-
-    content_type_re = re.compile(r'(text|application)/(xml|json)')
-
-    implements(IRequestHandler, ITemplateProvider)
+    protocols = ExtensionPoint(IRPCProtocol)
 
     # IRequestHandler methods
+
     def match_request(self, req):
-        if req.path_info in ('/login/xmlrpc', '/xmlrpc'):
-            return True
-        if req.path_info in ('/login/jsonrpc', '/jsonrpc'):
-            return True
-
-    def _send_response(self, req, response, content_type='application/xml'):
-        response = to_unicode(response).encode("utf-8")
-        req.send_response(200)
-        req.send_header('Content-Type', content_type)
-        req.send_header('Content-Length', len(response))
-        req.end_headers()
-        req.write(response)
+        """ Look for available protocols serving at requested path and
+            content-type. """
+        content_type = req.get_header('Content-Type') or 'text/html'
+        must_handle_request = req.path_info in ('/rpc', '/login/rpc')
+        for protocol in self.protocols:
+            for p_path, p_type in protocol.rpc_match():
+                if req.path_info in ['/%s' % p_path, '/login/%s' % p_path]:
+                    must_handle_request = True
+                    if content_type.startswith(p_type):
+                        req.args['protocol'] = protocol
+                        return True
+        # No protocol call, need to handle for docs or error if handled path
+        return must_handle_request
 
     def process_request(self, req):
+        protocol = req.args.get('protocol', None)
+        content_type = req.get_header('Content-Type') or 'text/html'
+        if protocol:
+            # Perform the method call
+            protocol.rpc_process(req, content_type)
+            raise RequestDone
+        elif accepts_mimetype(req, 'text/html'):
+            return self._dump_docs(req)
+        else:
+            # Attempt at API call gone wrong. Raise a plain-text 415 error
+            body = "No protocol matching Content-Type '%s' at path '%s'." % (
+                                                content_type, req.path_info)
+            req.send_error(None, template='', content_type='text/plain',
+                    status=HTTPUnsupportedMediaType.code, env=None, data=body)
 
-        content_type = req.get_header('Content-Type') or 'text/html'
-        if not self.content_type_re.match(content_type):
-            # Dump RPC functions
-            req.perm.require('XML_RPC') # Need at least XML_RPC
-            namespaces = {}
-            for method in XMLRPCSystem(self.env).all_methods(req):
-                namespace = method.namespace.replace('.', '_')
-                if namespace not in namespaces:
-                    namespaces[namespace] = {
-                        'description' : wiki_to_oneliner(
-                                            method.namespace_description,
-                                            self.env, req=req),
-                        'methods' : [],
-                        'namespace' : method.namespace,
-                        }
-                try:
-                    namespaces[namespace]['methods'].append(
-                                (method.signature,
-                                wiki_to_oneliner(
-                                    method.description, self.env, req=req),
-                                method.permission))
-                except Exception, e:
-                    from StringIO import StringIO
-                    import traceback
-                    out = StringIO()
-                    traceback.print_exc(file=out)
-                    raise Exception('%s: %s\n%s' % (method.name, str(e), out.getvalue()))
-            add_stylesheet(req, 'common/css/wiki.css')
-            return ('xmlrpclist.html', {'xmlrpc': {'functions': namespaces,
-                                    'json': json and True or False}}, None)
+    def _dump_docs(self, req):
+        # Dump RPC documentation
+        req.perm.require('XML_RPC') # Need at least XML_RPC
+        namespaces = {}
+        for method in XMLRPCSystem(self.env).all_methods(req):
+            namespace = method.namespace.replace('.', '_')
+            if namespace not in namespaces:
+                namespaces[namespace] = {
+                    'description' : wiki_to_oneliner(
+                                    method.namespace_description,
+                                    self.env, req=req),
+                    'methods' : [],
+                    'namespace' : method.namespace,
+                    }
+            try:
+                namespaces[namespace]['methods'].append(
+                        (method.signature,
+                        wiki_to_oneliner(
+                            method.description, self.env, req=req),
+                        method.permission))
+            except Exception, e:
+                from tracrpc.util import StringIO
+                import traceback
+                out = StringIO()
+                traceback.print_exc(file=out)
+                raise Exception('%s: %s\n%s' % (method.name,
+                                                str(e), out.getvalue()))
+        add_stylesheet(req, 'common/css/wiki.css')
+        add_stylesheet(req, 'tracrpc/css/rpc.css')
+        add_script(req, 'tracrpc/js/rpc.js')
+        return ('rpc.html', 
+                {'rpc': {'functions': namespaces,
+                         'protocols': [p.rpc_info() + (list(p.rpc_match()),) \
+                                  for p in self.protocols],
+                         'version': __import__('tracrpc', ['__version__']).__version__
+                        },
+                 'expand_docs': self._expand_docs
+                 },
+                None)
 
-        # Handle RPC call
-        if content_type.startswith('application/json'):
-            if json:
-                self.process_json_request(req, content_type)
-            else:
-                self.log.debug("RPC(json) call ignored (not available).")
-                self._send_response(req, "Error: JSON-RPC not available.\n",
-                                    content_type)
-        else:
-            self.process_xml_request(req, content_type)
+    def _expand_docs(self, docs, ctx):
+        try :
+            tmpl = TextTemplate(docs)
+            return tmpl.generate(**dict(ctx.items())).render()
+        except (TemplateSyntaxError, BadDirectiveError), exc:
+            self.log.exception("Syntax error rendering protocol documentation")
+            return "'''Syntax error:''' [[BR]] %s" % (str(exc),)
+        except Exception:
+            self.log.exception("Runtime error rendering protocol documentation")
+            return "Error rendering protocol documentation. " \
+                       "Contact your '''Trac''' administrator for details"
 
-    def process_xml_request(self, req, content_type):
-        """ Handles XML-RPC requests """
-        args, method = xmlrpclib.loads(req.read(int(req.get_header('Content-Length'))))
-        self.log.debug("RPC(xml) call by '%s', method '%s' with args: %s" \
-                                    % (req.authname, method, repr(args)))
-        args = self._normalize_xml_input(args)
-        try:
-            req.perm.require('XML_RPC') # Need at least XML_RPC
-            result = XMLRPCSystem(self.env).get_method(method)(req, args)
-            self.env.log.debug("RPC(xml) '%s' result: %s" % (method, repr(result)))
-            result = tuple(self._normalize_xml_output(result))
-            self._send_response(req, xmlrpclib.dumps(result, methodresponse=True), content_type)
-        except PermissionError, e:
-            self._send_response(req, xmlrpclib.dumps(xmlrpclib.Fault(1, to_unicode(e))),
-                                    content_type)
-        except xmlrpclib.Fault, e:
-            self.log.error(e)
-            self._send_response(req, xmlrpclib.dumps(e), content_type)
-        except Exception, e:
-            self.log.error(e)
-            import traceback
-            from StringIO import StringIO
-            out = StringIO()
-            traceback.print_exc(file = out)
-            self.log.error(out.getvalue())
-            self._send_response(req, xmlrpclib.dumps(xmlrpclib.Fault(2, "'%s' while executing '%s()'" % (str(e), method))))
+    # ITemplateProvider methods
 
-    def process_json_request(self, req, content_type):
-        """ Handles JSON-RPC requests """
-        try:
-            data = json.load(req, cls=TracRpcJSONDecoder)
-        except Exception, e:
-            # Abort with exception - no data can be read
-            self.log.error("RPC(json) decode error %s" % \
-                    exception_to_unicode(e, traceback=True))
-            response = json.dumps(self._json_error(e, -32700),
-                                    cls=TracRpcJSONEncoder)
-            self._send_response(req, response + '\n', content_type)
-            return
-        self.log.debug("RPC(json) call by '%s': %s" % (req.authname, data))
-        args = data.get('params') or []
-        r_id = data.get('id', None)
-        method = data.get('method', '')
-        try:
-            req.perm.require('XML_RPC') # Need at least XML_RPC
-            if method == 'system.multicall': # Custom multicall
-                results = []
-                for mc in args:
-                    results.append(self._json_call(req, mc.get('method', ''),
-                        mc.get('params') or [], mc.get('id') or r_id))
-                response = {'result': results, 'error': None, 'id': r_id}
-            else:
-                response = self._json_call(req, method, args, r_id)
-            try: # JSON encoding
-                self.log.debug("RPC(json) result: %s" % repr(response))
-                response = json.dumps(response, cls=TracRpcJSONEncoder)
-            except Exception, e:
-                response = json.dumps(self._json_error(e, r_id=r_id),
-                                        cls=TracRpcJSONEncoder)
-        except PermissionError, e:
-            response = json.dumps(self._json_error(e, -32600, r_id=r_id),
-                cls=TracRpcJSONEncoder)
-        except Exception, e:
-            self.log.error("RPC(json) error %s" % exception_to_unicode(e,
-                                                    traceback=True))
-            response = json.dumps(self._json_error(e), cls=TracRpcJSONEncoder)
-        self.log.debug("RPC(json) encoded result: %s" % response)
-        self._send_response(req, response + '\n', content_type)
-
-    def _json_call(self, req, method, args, r_id=None):
-        """ Call method and create response dictionary. """
-        try:
-            result = (XMLRPCSystem(self.env).get_method(method)(req, args))[0]
-            if isinstance(result, GeneratorType):
-                result = list(result)
-            return {'result': result, 'error': None, 'id': r_id}
-        except Exception, e:
-            return self._json_error(e, r_id=r_id)
-
-    def _json_error(self, e, c=-32603, r_id=None):
-        """ Makes a response dictionary that is an error. """
-        return {'result': None, 'id': r_id, 'error': {
-                'name': 'JSONRPCError', 'code': c, 'message': to_unicode(e)}}
-
-    def _normalize_xml_input(self, args):
-        """ Normalizes arguments (at any level - traversing dicts and lists):
-        1. xmlrpc.DateTime is converted to Python datetime
-        2. String line-endings same as from web (`\n` => `\r\n`)
-        """
-        new_args = []
-        for arg in args:
-            # self.env.log.debug("arg %s, type %s" % (arg, type(arg)))
-            if isinstance(arg, xmlrpclib.DateTime):
-                new_args.append(from_xmlrpc_datetime(arg))
-            elif isinstance(arg, basestring):
-                new_args.append(arg.replace("\n", "\r\n"))
-            elif isinstance(arg, dict):
-                for key in arg.keys():
-                    arg[key] = self._normalize_xml_input([arg[key]])[0]
-                new_args.append(arg)
-            elif isinstance(arg, list) or isinstance(arg, tuple):
-                new_args.append(self._normalize_xml_input(arg))
-            else:
-                new_args.append(arg)
-        return new_args
-
-    def _normalize_xml_output(self, result):
-        """ Normalizes and converts output (traversing it):
-        1. None => ''
-        2. datetime => xmlrpclib.DateTime
-        3. genshi.builder.Fragment|genshi.core.Markup => unicode
-        """
-        new_result = []
-        for res in result:
-            if isinstance(res, datetime.datetime):
-                new_result.append(to_xmlrpc_datetime(res))
-            elif res is None or res is empty:
-                new_result.append('')
-            elif isinstance(res, genshi.builder.Fragment) \
-                        or isinstance(res, genshi.core.Markup):
-                new_result.append(to_unicode(res))
-            elif isinstance(res, dict):
-                for key in res.keys():
-                    res[key] = self._normalize_xml_output([res[key]])[0]
-                new_result.append(res)
-            elif isinstance(res, list) or isinstance(res, tuple):
-                new_result.append(self._normalize_xml_output(res))
-            else:
-                new_result.append(res)
-        return new_result
-
-    # ITemplateProvider
     def get_htdocs_dirs(self):
-        return []
+        yield ('tracrpc', resource_filename(__name__, 'htdocs'))
 
     def get_templates_dirs(self):
-        return [resource_filename(__name__, 'templates')]
+        yield resource_filename(__name__, 'templates')
+
+    # INavigationContributor methods
+
+    def get_active_navigation_item(self, req):
+        pass
+
+    def get_navigation_items(self, req):
+        if req.perm.has_permission('XML_RPC'):
+            yield ('metanav', 'rpc',
+                   tag.a('RPC API', href=req.href.rpc(), accesskey=1))
diff --git a/trunk/tracrpc/wiki.py b/trunk/tracrpc/wiki.py
--- a/trunk/tracrpc/wiki.py
+++ b/trunk/tracrpc/wiki.py
@@ -6,22 +6,21 @@
 (c) 2009      ::: www.CodeResort.com - BV Network AS (simon-code@bvnetwork.no)
 """
 
-try:
-    from cStringIO import StringIO
-except ImportError:
-    from StringIO import StringIO
-import xmlrpclib
 import os
+from datetime import datetime
 
+from trac.attachment import Attachment
 from trac.core import *
-from trac.resource import Resource
+from trac.resource import Resource, ResourceNotFound
 from trac.util.datefmt import to_timestamp, to_datetime, utc
 from trac.wiki.api import WikiSystem
 from trac.wiki.model import WikiPage
 from trac.wiki.formatter import wiki_to_html
-from trac.attachment import Attachment
 
-from tracrpc.api import IXMLRPCHandler, expose_rpc
+from tracrpc.api import IXMLRPCHandler, expose_rpc, Binary
+from tracrpc.util import StringIO
+
+__all__ = ['WikiRPC']
 
 class WikiRPC(Component):
     """Superset of the
@@ -36,7 +35,7 @@
         return 'wiki'
 
     def xmlrpc_methods(self):
-        yield (None, ((dict, xmlrpclib.DateTime),), self.getRecentChanges)
+        yield (None, ((dict, datetime),), self.getRecentChanges)
         yield ('WIKI_VIEW', ((int,),), self.getRPCVersionSupported)
         yield (None, ((str, str), (str, str, int),), self.getPage)
         yield (None, ((str, str, int),), self.getPage, 'getPageVersion')
@@ -47,10 +46,10 @@
         yield (None, ((dict, str, int),), self.getPageInfo, 'getPageInfoVersion')
         yield (None, ((bool, str, str, dict),), self.putPage)
         yield (None, ((list, str),), self.listAttachments)
-        yield (None, ((xmlrpclib.Binary, str),), self.getAttachment)
-        yield (None, ((bool, str, xmlrpclib.Binary),), self.putAttachment)
-        yield (None, ((bool, str, str, str, xmlrpclib.Binary),
-                               (bool, str, str, str, xmlrpclib.Binary, bool)),
+        yield (None, ((Binary, str),), self.getAttachment)
+        yield (None, ((bool, str, Binary),), self.putAttachment)
+        yield (None, ((bool, str, str, str, Binary),
+                               (bool, str, str, str, Binary, bool)),
                                self.putAttachmentEx)
         yield (None, ((bool, str),(bool, str, int)), self.deletePage)
         yield (None, ((bool, str),), self.deleteAttachment)
@@ -90,7 +89,7 @@
             msg = 'Wiki page "%s" does not exist' % pagename
             if version is not None:
                 msg += ' at version %s' % version
-            raise xmlrpclib.Fault(0, msg)
+            raise ResourceNotFound(msg)
 
     def getPageHTML(self, req, pagename, version=None):
         """ Return page in rendered HTML, latest version. """
@@ -156,7 +155,7 @@
         pagename, filename = os.path.split(path)
         attachment = Attachment(self.env, 'wiki', pagename, filename)
         req.perm(attachment.resource).require('ATTACHMENT_VIEW')
-        return xmlrpclib.Binary(attachment.open().read())
+        return Binary(attachment.open().read())
 
     def putAttachment(self, req, path, data):
         """ (over)writes an attachment. Returns True if successful.
@@ -173,7 +172,7 @@
         
         Use this method if you don't care about WikiRPC compatibility. """
         if not WikiPage(self.env, pagename).exists:
-            raise TracError, 'Wiki page "%s" does not exist' % pagename
+            raise ResourceNotFound, 'Wiki page "%s" does not exist' % pagename
         if replace:
             try:
                 attachment = Attachment(self.env, 'wiki', pagename, filename)
@@ -192,7 +191,7 @@
         """ Delete an attachment. """
         pagename, filename = os.path.split(path)
         if not WikiPage(self.env, pagename).exists:
-            raise TracError, 'Wiki page "%s" does not exist' % pagename
+            raise ResourceNotFound, 'Wiki page "%s" does not exist' % pagename
         attachment = Attachment(self.env, 'wiki', pagename, filename)
         req.perm(attachment.resource).require('ATTACHMENT_DELETE')
         attachment.delete()
diff --git a/trunk/tracrpc/xml_rpc.py b/trunk/tracrpc/xml_rpc.py
new file mode 100644
--- /dev/null
+++ b/trunk/tracrpc/xml_rpc.py
@@ -0,0 +1,182 @@
+# -*- coding: utf-8 -*-
+"""
+License: BSD
+
+(c) 2005-2008 ::: Alec Thomas (alec@swapoff.org)
+(c) 2009      ::: www.CodeResort.com - BV Network AS (simon-code@bvnetwork.no)
+"""
+
+import datetime
+import time
+import xmlrpclib
+
+import genshi
+
+from trac.core import *
+from trac.perm import PermissionError
+from trac.resource import ResourceNotFound
+from trac.util.datefmt import utc
+from trac.util.text import to_unicode
+
+from tracrpc.api import XMLRPCSystem, IRPCProtocol, Binary
+from tracrpc.util import empty, prepare_docs
+
+__all__ = ['XmlRpcProtocol']
+
+def to_xmlrpc_datetime(dt):
+    """ Convert a datetime.datetime object to a xmlrpclib DateTime object """
+    return xmlrpclib.DateTime(dt.utctimetuple())
+
+def from_xmlrpc_datetime(data):
+    """Return datetime (in utc) from XMLRPC datetime string (is always utc)"""
+    t = list(time.strptime(data.value, "%Y%m%dT%H:%M:%S")[0:6])
+    return apply(datetime.datetime, t, {'tzinfo': utc})
+
+class XmlRpcProtocol(Component):
+    r"""
+    There should be XML-RPC client implementations available for all
+    popular programming languages.
+    Example call using `curl`:
+
+    {{{
+    user: ~ > cat body.xml
+    <?xml version="1.0"?>
+    <methodCall>
+    <methodName>wiki.getPage</methodName>
+    <params>
+    <param><string>WikiStart</string></param>
+    </params>
+    </methodCall>
+    
+    user: ~ > curl -H "Content-Type: application/xml" --data @body.xml ${req.abs_href.rpc()}
+    <?xml version='1.0'?>
+    <methodResponse>
+    <params>
+    <param>
+    <value><string>= Welcome to....
+    }}}
+    
+    The following snippet illustrates how to perform authenticated calls in Python.
+    
+    {{{
+    >>> from xmlrpclib import ServerProxy
+    >>> p = ServerProxy('${req.abs_href.login('rpc').replace('://', '://%s:your_password@' % authname)}')
+    >>> p.system.getAPIVersion()
+    [${', '.join(rpc.version.split('.'))}]
+    }}}
+    """
+
+    implements(IRPCProtocol)
+
+    # IRPCProtocol methods
+
+    def rpc_info(self):
+        return ('XML-RPC', prepare_docs(self.__doc__))
+
+    def rpc_match(self):
+        yield ('rpc', 'application/xml')
+        yield ('rpc', 'text/xml')
+        # Legacy path - provided for backwards compatibility:
+        yield ('xmlrpc', 'application/xml')
+        yield ('xmlrpc', 'text/xml')
+
+    def rpc_process(self, req, content_type):
+        """ Handles XML-RPC requests """
+        args, method = xmlrpclib.loads(
+                        req.read(int(req.get_header('Content-Length'))))
+        self.log.debug("RPC(xml) call by '%s', method '%s' with args: %s" \
+                                    % (req.authname, method, repr(args)))
+        args = self._normalize_xml_input(args)
+        try:
+            req.perm.require('XML_RPC') # Need at least XML_RPC
+            result = XMLRPCSystem(self.env).get_method(method)(req, args)
+            self.env.log.debug("RPC(xml) '%s' result: %s" % (
+                                                        method, repr(result)))
+            result = tuple(self._normalize_xml_output(result))
+            self._send_response(req,
+                    xmlrpclib.dumps(result, methodresponse=True), content_type)
+        except PermissionError, e:
+            self._send_response(req,
+                    xmlrpclib.dumps(
+                        xmlrpclib.Fault(403, to_unicode(e))), content_type)
+        except ResourceNotFound, e:
+            self._send_response(req,
+                    xmlrpclib.dumps(
+                        xmlrpclib.Fault(404, to_unicode(e))), content_type)
+        except Exception, e:
+            self.log.error(e)
+            import traceback
+            from tracrpc.util import StringIO
+            out = StringIO()
+            traceback.print_exc(file = out)
+            self.log.error(out.getvalue())
+            err_code = hasattr(e, 'code') and e.code or 1
+            self._send_response(req,
+                    xmlrpclib.dumps(
+                        xmlrpclib.Fault(err_code,
+                            "'%s' while executing '%s()'" % (str(e), method))))
+
+    # Internal methods
+
+    def _send_response(self, req, response, content_type='application/xml'):
+        response = to_unicode(response).encode("utf-8")
+        req.send_response(200)
+        req.send_header('Content-Type', content_type)
+        req.send_header('Content-Length', len(response))
+        req.end_headers()
+        req.write(response)
+
+    def _normalize_xml_input(self, args):
+        """ Normalizes arguments (at any level - traversing dicts and lists):
+        1. xmlrpc.DateTime is converted to Python datetime
+        2. tracrpc.api.Binary => xmlrpclib.Binary
+        2. String line-endings same as from web (`\n` => `\r\n`)
+        """
+        new_args = []
+        for arg in args:
+            # self.env.log.debug("arg %s, type %s" % (arg, type(arg)))
+            if isinstance(arg, xmlrpclib.DateTime):
+                new_args.append(from_xmlrpc_datetime(arg))
+            elif isinstance(arg, xmlrpclib.Binary):
+                arg.__class__ = Binary
+                new_args.append(arg)
+            elif isinstance(arg, basestring):
+                new_args.append(arg.replace("\n", "\r\n"))
+            elif isinstance(arg, dict):
+                for key, val in arg.items():
+                    arg[key], = self._normalize_xml_input([val])
+                new_args.append(arg)
+            elif isinstance(arg, (list, tuple)):
+                new_args.append(self._normalize_xml_input(arg))
+            else:
+                new_args.append(arg)
+        return new_args
+
+    def _normalize_xml_output(self, result):
+        """ Normalizes and converts output (traversing it):
+        1. None => ''
+        2. datetime => xmlrpclib.DateTime
+        3. Binary => xmlrpclib.Binary
+        4. genshi.builder.Fragment|genshi.core.Markup => unicode
+        """
+        new_result = []
+        for res in result:
+            if isinstance(res, datetime.datetime):
+                new_result.append(to_xmlrpc_datetime(res))
+            elif isinstance(res, Binary):
+                res.__class__ = xmlrpclib.Binary
+                new_result.append(res)
+            elif res is None or res is empty:
+                new_result.append('')
+            elif isinstance(res, (genshi.builder.Fragment, \
+                                  genshi.core.Markup)):
+                new_result.append(to_unicode(res))
+            elif isinstance(res, dict):
+                for key, val in res.items():
+                    res[key], = self._normalize_xml_output([val])
+                new_result.append(res)
+            elif isinstance(res, list) or isinstance(res, tuple):
+                new_result.append(self._normalize_xml_output(res))
+            else:
+                new_result.append(res)
+        return new_result
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.