summaryrefslogtreecommitdiff
path: root/doc/book/src/Programming-In-Apache-Qpid.xml
blob: af3a550567a6e2ef32a17ce9f119b836e5506d86 (plain)
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
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
<?xml version='1.0' encoding='utf-8' ?>
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" [
]>

<!--
   
   Licensed to the Apache Software Foundation (ASF) under one
   or more contributor license agreements.  See the NOTICE file
   distributed with this work for additional information
   regarding copyright ownership.  The ASF licenses this file
   to you under the Apache License, Version 2.0 (the
   "License"); you may not use this file except in compliance
   with the License.  You may obtain a copy of the License at
   
   http://www.apache.org/licenses/LICENSE-2.0
   
   Unless required by applicable law or agreed to in writing,
   software distributed under the License is distributed on an
   "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
   KIND, either express or implied.  See the License for the
   specific language governing permissions and limitations
   under the License.
   
  -->

<book id="client-api-tutorial">
  <title>Programming in Apache Qpid</title>
  <subtitle>Cross-Platform AMQP Messaging in Java JMS, .NET, C++, and Python</subtitle>

  <chapter>
    <title>Introduction</title>
    
    <para>Apache Qpid is a reliable, asynchronous messaging system that
      supports the AMQP messaging protocol in several common programming
      languages. Qpid is supported on most common platforms.
    </para>

    <itemizedlist>
      <listitem>
        <para>
          On the Java platform, Qpid uses the
          established <ulink url="http://java.sun.com/products/jms/">Java JMS
            API</ulink>. 
        </para>
      </listitem>
      <listitem>
        <para>
          On the .NET platform, Qpid defines
          a <ulink url="http://qpid.apache.org/wcf.html">WCF
            binding</ulink>.
        </para>
      </listitem>
      <listitem>
        <para>
          For Python and C++, Qpid defines its own messaging API, the
          <firstterm>Qpid Messaging API</firstterm>, which is
          conceptually similar in each supported language.
        </para>
      </listitem>
      <listitem>
        <para>
          Support for this API in Ruby will be added
          soon (Ruby currently uses an API that is closely
	  tied to the AMQP version).
        </para>
      </listitem>
    </itemizedlist>
  </chapter>

  <chapter>
    <title>Using the Qpid Messaging API</title>

    <para>The Qpid Messaging API is quite simple, consisting of only a
      handful of core classes.
    </para>

    <itemizedlist>

      <listitem>
        <para>
          A <firstterm>message</firstterm> consists of a standard set
          of fields (e.g. <literal>subject</literal>,
          <literal>reply-to</literal>), an application-defined set of
          properties, and message content (the main body of the
          message).
        </para>
      </listitem>
      
      <listitem>
        <para>
          A <firstterm>connection</firstterm> represents a network
          connection to a remote endpoint.
        </para>
      </listitem>
      
      <listitem>
        <para>
          A <firstterm>session</firstterm> provides a sequentially
          ordered context for sending and receiving
          <emphasis>messages</emphasis>. A session is obtained from a
          connection.
        </para>
      </listitem>
      
      <listitem>
        <para>
	  A <firstterm>sender</firstterm> sends messages to a target
	  using the <literal>sender.send</literal> method. A sender is
	  obtained from a session for a given target address.
        </para>
      </listitem>
      
      <listitem>
        <para>
	  A <firstterm>receiver</firstterm> receives messages from a
	  source using the <literal>receiver.fetch</literal> method.
	  A receiver is obtained from a session for a given source
	  address.
        </para>
      </listitem>
      
    </itemizedlist>

    <para>
      The following sections show how to use these classes in a
      simple messaging program.
    </para>

    <section>
      <title>A Simple Messaging Program in C++</title>

      <para>The following C++ program shows how to create a connection,
        create a session, send messages using a sender, and receive
        messages using a receiver.</para>

	<example>
	  <title>"Hello world!" in C++</title>
	  <programlisting lang="c++"><![CDATA[
#include <qpid/messaging/Connection.h>
#include <qpid/messaging/Message.h>
#include <qpid/messaging/Receiver.h>
#include <qpid/messaging/Sender.h>
#include <qpid/messaging/Session.h>

#include <iostream>

using namespace qpid::messaging;

int main(int argc, char** argv) {
    std::string broker = argc > 1 ? argv[1] : "localhost:5672";
    std::string address = argc > 2 ? argv[2] : "amq.topic";
    Connection connection(broker);
    try {
        connection.open();
        Session session = connection.createSession();

        Receiver receiver = session.createReceiver(address);
        Sender sender = session.createSender(address);

        sender.send(Message("Hello world!"));

        Message message = receiver.fetch(Duration::SECOND * 1);
        std::cout << message.getContent() << std::endl;
        session.acknowledge();
        
        connection.close();
        return 0;
    } catch(const std::exception& error) {
        std::cerr << error.what() << std::endl;
        connection.close();
        return 1;   
    }
}]]></programlisting>
      </example>


    </section>

    <section>
      <title>A Simple Messaging Program in Python</title>

      <para>The following Python program shows how to create a
        connection, create a session, send messages using a sender, and
        receive messages using a receiver.</para>

	<example>
	  <title>"Hello world!" in Python</title>
	  <programlisting lang="python"><![CDATA[
import sys
from qpid.messaging import *

broker =  "localhost:5672" if len(sys.argv)<2 else sys.argv[1]
address = "amq.topic" if len(sys.argv)<3 else sys.argv[2]

connection = Connection(broker)

try:
  connection.open()
  session = connection.session()

  sender = session.sender(address)
  receiver = session.receiver(address)

  sender.send(Message("Hello world!"));

  message = receiver.fetch(timeout=1)
  print message.content
  session.acknowledge() # acknowledge message receipt

except MessagingError,m:
  print m
finally:
  connection.close()
]]></programlisting>
	</example>

    </section>
    <section id="section-addresses">
      <title>Addresses</title>
      
      <para>An <firstterm>address</firstterm> is the name of a message
      target or message source. In the programs we have just seen, we
      used the address <literal>amq.topic</literal> (which is the name
      of an exchange on an AMQP 0-10 messaging broker).
      
      The methods that create senders and receivers require an
      address. The details of sending to a particular target or
      receiving from a particular source are then handled by the
      sender or receiver. A different target or source can be used
      simply by using a different address.
      </para>

      <para>An address resolves to a <firstterm>node</firstterm>. The
      Qpid Messaging API recognises two kinds of nodes,
      <firstterm>queues</firstterm> and <firstterm>topics</firstterm>

	   <footnote><para>The terms <emphasis>queue</emphasis> and
	   <emphasis>topic</emphasis> here were chosen to align with
	   their meaning in JMS. These two addressing 'patterns',
	   queue and topic, are sometimes refered as point-to-point
	   and publish-subscribe. AMQP 0-10 has an exchange type
	   called a <emphasis>topic exchange</emphasis>. When the term
	   <emphasis>topic</emphasis> occurs alone, it refers to a
	   Messaging API topic, not the topic
	   exchange.</para></footnote>.

      A queue stores each message until it has been received and
      acknowledged, and only one receiver can receive a given message
      <footnote><para>There are exceptions to this rule; for instance,
      a receiver can use <literal>browse</literal> mode, which leaves
      messages on the queue for other receivers to
      read.</para></footnote>

      A topic immediately delivers a message to all eligible
      receivers; if there are no eligible receivers, it discards the
      message.  In the AMQP 0-10 implementation of the API,
      
          <footnote><para>The AMQP 0-10 implementation is the only one
          that currently exists.</para></footnote>

      queues map to AMQP queues, and topics map to AMQP exchanges.

          <footnote><para>In AMQP 0-10, messages are sent to
          exchanges, and read from queues. The Messaging API also
          allows a sender to send messages to a queue; internally,
          Qpid implements this by sending the message to the default
          exchange, with the name of the queue as the routing key. The
          Messaging API also allows a receiver to receive messages
          from a topic; internally, Qpid implements this by setting up
          a private subscription queue for the receiver and binding
          the subscription queue to the exchange that corresponds to
          the topic.</para></footnote>
      </para>

      <para>In the rest of this tutorial, we present many examples
      using two programs that take an address as a command line
      parameter.  <command>spout</command> sends messages to the
      target address, <command>drain</command> receives messages from
      the source address.  The source code is available in both C++
      and Python, and can be found in the examples directory for each
      language. These programs can use any address string as a source
      or a destination, and have many command line options to
      configure behavior&mdash;use the <command>-h</command> option
      for documentation on these options. 

      <footnote><para>Currently, the Python and C++
      implementations of <command>drain</command> and
      <command>spout</command> have slightly different
      options. This tutorial uses the C++ implementation. The
      options will be reconciled in the near
      future.</para></footnote>


      The examples in this tutorial also use the
      <command>qpid-config</command> utility to configure AMQP 0-10
      queues and exchanges on a Qpid broker.
      </para>


      <example>
        <title>Queues</title>

        <para>Create a queue with <command>qpid-config</command>, send a message using
          <command>spout</command>, and read it using <command>drain</command>:</para>

        <screen>
$ qpid-config add queue hello-world
$ ./spout hello-world
$ ./drain hello-world

Message(properties={spout-id:c877e622-d57b-4df2-bf3e-6014c68da0ea:0}, content='')
        </screen>

        <para>The queue stored the message sent by <command>spout</command> and delivered
        it to <command>drain</command> when requested.</para>

	<para>Once the message has been delivered and and acknowledged
	by <command>drain</command>, it is no longer available on the queue. If we run
	<command>drain</command> one more time, no messages will be retrieved.</para>

        <screen>
$ ./drain hello-world
$
	</screen>

      </example>

      <example>
	<title>Topics</title>

	<para>This example is similar to the previous example, but it
	uses a topic instead of a queue.</para>

	<para>First, use <command>qpid-config</command> to remove the queue
	and create an exchange with the same name:</para>

        <screen>
$ qpid-config del queue hello-world
$ qpid-config add exchange topic hello-world
        </screen>

	<para>Now run <command>drain</command> and <command>spout</command> the same way we did in the previous example:</para>

	<screen>
$ ./spout hello-world
$ ./drain hello-world
$
        </screen>

        <para>Topics deliver messages immediately to any interested
        receiver, and do not store messages. Because there were no
        receivers at the time <command>spout</command> sent the
        message, it was simply discarded. When we ran
        <command>drain</command>, there were no messages to
        receive.</para>

	<para>Now let's run <command>drain</command> first, using the
	<literal>-t</literal> option to specify a timeout in seconds.
	While <command>drain</command> is waiting for messages,
	run <command>spout</command> in another window.</para>

        <para><emphasis>First Window:</emphasis></para>

        <screen>
$ ./drain -t 30 hello-word
        </screen>
        

        <para><emphasis>Second Window:</emphasis></para>

        <screen>
$ ./spout hello-word
        </screen>

        <para>Once <command>spout</command> has sent a message, return
          to the first window to see the output from
          <command>drain</command>:</para>

        <screen>
Message(properties={spout-id:7da2d27d-93e6-4803-8a61-536d87b8d93f:0}, content='')
        </screen>

        <para>You can run <command>drain</command> in several separate
          windows; each creates a subscription for the exchange, and
          each receives all messages sent to the exchange.</para>

      </example>

      <section>
	<title>Address Strings</title>

	<para>So far, our examples have used address strings that
	contain only the name of a node. An <firstterm>address
	string</firstterm> can also contain a
	<firstterm>subject</firstterm> and
	<firstterm>options</firstterm>.</para>
      
	<para>The syntax for an address string is:</para>
      
	<programlisting><![CDATA[
address_string ::=  <address> [ / <subject> ] [ ; <options> ]
options ::=  { <key> : <value>, ... }
]]></programlisting>
      
	<para>Addresses, subjects, and keys are strings.  Values can
	be numbers, strings (with optional single or double quotes),
	maps, or lists. A complete BNF for address strings appears in
	<xref linkend="section-address-string-bnf"/>.</para>


	<para>So far, the address strings in this tutorial have used
	only addresses. The following sections show how to use
	subjects and options.</para>

      </section>

      <section>
	<title>Subjects</title>


	<para>Every message has a property called
	<firstterm>subject</firstterm>, which is analogous to the
	subject on an email message. If no subject is specified, the
	message's subject is null. For convenience, address strings
	also allow a subject. If a sender's address contains a
	subject, it is used as the default subject for the messages
	it sends. 

	If a receiver's address contains a subject, it is used to
	select only messages that match the subject&mdash;the matching
	algorithm depends on the message source.
      </para>

      <para>
	In AMQP 0-10, each exchange type has its own matching
	algorithm, and queues do not provide filtering. This is
	discussed in <xref linkend="section-amqp0-10-mapping"/>.
      </para>

      <note>
	<para>
	  Currently, a receiver bound to a queue ignores subjects,
	  receiving messages from the queue without filtering.

	  In the future, if a receiver is bound to a queue, and its
	  address contains a subject, the subject will be used as a
	  selector to filter messages.
	</para>
      </note>


      <example>
        <title>Using subjects</title>

        <para>In this example we show how subjects affect message
        flow.</para>

        <para>First, let's use <command>qpid-config</command> to create a topic exchange.</para>

        <screen>
$ qpid-config add exchange topic news-service
        </screen>

        <para>Now we use drain to receive messages from <literal>news-service</literal> that match the subject <literal>sports</literal>.</para>
        <para><emphasis>First Window:</emphasis></para>
        <screen>
$ ./drain -t 30 news-service/sports
        </screen>

        <para>In a second window, let's send messages to <literal>news-service</literal> using two different subjects:</para>

        <para><emphasis>Second Window:</emphasis></para>
        <screen>
$ ./spout news-service/sports
$ ./spout news-service/news
        </screen>

        <para>Now look at the first window, the message with the
        subject <literal>sports</literal> has been received, but not
        the message with the subject <literal>news</literal>:</para>

        <screen>
Message(properties={qpid.subject:sports, spout-id:9441674e-a157-4780-a78e-f7ccea998291:0}, content='')
        </screen>

        <para>If you run <command>drain</command> in multiple
          windows using the same subject, all instances of
          <command>drain</command> receive the messages for that
          subject.</para>
      </example>
        

        <para>The AMQP exchange type we are using here,
        <literal>amq.topic</literal>, can also do more sophisticated
        matching.

	A sender's subject can contain multiple words separated by a
	<quote>.</quote> delimiter. For instance, in a news
	application, the sender might use subjects like
	<literal>usa.news</literal>, <literal>usa.weather</literal>,
	<literal>europe.news</literal>, or
	<literal>europe.weather</literal>. 

	The receiver's subject can include wildcard characters&mdash;
	<quote>#</quote> matches one or more words in the message's
	subject, <quote>*</quote> matches a single word. 

	For instance, if the subject in the source address is
	<literal>*.news</literal>, it matches messages with the
	subject <literal>europe.news</literal> or
	<literal>usa.news</literal>; if it is
	<literal>europe.#</literal>, it matches messages with subjects
	like <literal>europe.news</literal> or
	<literal>europe.pseudo.news</literal>.</para>

	  <example>
	    <title>Subjects with multi-word keys</title>

	    <para>This example uses drain and spout to demonstrate the
	    use of subjects with two-word keys.</para>

	    <para>Let's use <command>drain</command> with the subject
	    <literal>*.news</literal> to listen for messages in which
	    the second word of the key is
	    <literal>news</literal>.</para>

	    <para><emphasis>First Window:</emphasis></para>
	
	    <screen>
$ ./drain -t 30 news-service/*.news
	    </screen>

	    <para>Now let's send messages using several different
	    two-word keys:</para>

	    <para><emphasis>Second Window:</emphasis></para>

	    <screen>
$ ./spout news-service/usa.news
$ ./spout news-service/usa.sports
$ ./spout news-service/europe.sports
$ ./spout news-service/europe.news
	    </screen>

	    <para>In the first window, the messages with
	    <literal>news</literal> in the second word of the key have
	    been received:</para>

	    <screen>
Message(properties={qpid.subject:usa.news, spout-id:73fc8058-5af6-407c-9166-b49a9076097a:0}, content='')
Message(properties={qpid.subject:europe.news, spout-id:f72815aa-7be4-4944-99fd-c64c9747a876:0}, content='')
	    </screen>


	    <para>Next, let's use <command>drain</command> with the
	    subject <literal>#.news</literal> to match any sequence of
	    words that ends with <literal>news</literal>.</para>

	    <para><emphasis>First Window:</emphasis></para>

	    <screen>
$ ./drain -t 30 news-service/#.news
	    </screen>

	    <para>In the second window, let's send messages using a
	    variety of different multi-word keys:</para>

	    <para><emphasis>Second Window:</emphasis></para>

	    <screen>
$ ./spout news-service/news
$ ./spout news-service/sports
$ ./spout news-service/usa.news
$ ./spout news-service/usa.sports
$ ./spout news-service/usa.faux.news
$ ./spout news-service/usa.faux.sports
	    </screen>

        <para>In the first window, messages with
        <literal>news</literal> in the last word of the key have been
        received:</para>

        <screen>
Message(properties={qpid.subject:news, spout-id:cbd42b0f-c87b-4088-8206-26d7627c9640:0}, content='')
Message(properties={qpid.subject:usa.news, spout-id:234a78d7-daeb-4826-90e1-1c6540781eac:0}, content='')
Message(properties={qpid.subject:usa.faux.news, spout-id:6029430a-cfcb-4700-8e9b-cbe4a81fca5f:0}, content='')
        </screen>
      </example>

    </section>

    <section>
      <title>Address String Options</title>

      <para>
        The options in an address string contain additional
        information for the senders or receivers created for it,
        including:
      </para>
      <itemizedlist>
        <listitem>
          <para>
            Policies for assertions about the node to which an address
            refers.
	  </para>
	  <para>
	    For instance, in the address string <literal>my-queue;
	    {assert: always, node:{ type: queue }}</literal>, the node
	    named <literal>my-queue</literal> must be a queue; if not,
	    the address does not resolve to a node, and an exception
	    is raised.
          </para>
        </listitem>
        <listitem>
          <para>
            Policies for automatically creating or deleting the node to which an address refers.
	  </para>
	  <para>
	    For instance, in the address string <literal>xoxox ; {create: always}</literal>, 
	    the queue <literal>xoxox</literal> is created, if it does
	    not exist, before the address is resolved.
          </para>
        </listitem>
        <listitem>
          <para>
            Extension points that can be used for sender/receiver configuration.
	  </para>
	  <para>
	    For instance, if the address for a receiver is
	    <literal>my-queue; {mode: browse}</literal>, the receiver
	    works in <literal>browse</literal> mode, leaving messages
	    on the queue so other receivers can receive them.
          </para>
        </listitem>
      </itemizedlist>


      <para>
        Let's use some examples to show how these different kinds of
        address string options affect the behavior of senders and
        receives.
      </para>
      
      
      <para>
	First, let's use the <literal>assert</literal> option to
	ensure that the address resolves to a node of the required
	type.
      </para>


      <example>
	<title>Assertions on Nodes</title>

	<para>Let's use <command>qpid-config</command> to create a
        queue and a topic.</para>

	<screen>
$ qpid-config add queue my-queue
$ qpid-config add exchange topic my-topic
	</screen>
      
	<para>
        We can now use the address specified to drain to assert that it is
        of a particular type:
	</para>

	<screen>
$ ./drain 'my-queue; {assert: always, node:{ type: queue }}'
$ ./drain 'my-queue; {assert: always, node:{ type: topic }}'
2010-04-20 17:30:46 warning Exception received from broker: not-found: not-found: Exchange not found: my-queue (../../src/qpid/broker/ExchangeRegistry.cpp:92) [caused by 2 \x07:\x01]
Exchange my-queue does not exist
	</screen>

	<para>
        The first attempt passed without error as my-queue is indeed a
        queue. The second attempt however failed; my-queue is not a
        topic.
	</para>
      
	<para>
        We can do the same thing for my-topic:
	</para>

	<screen>
$ ./drain 'my-topic; {assert: always, node:{ type: topic }}'
$ ./drain 'my-topic; {assert: always, node:{ type: queue }}'
2010-04-20 17:31:01 warning Exception received from broker: not-found: not-found: Queue not found: my-topic (../../src/qpid/broker/SessionAdapter.cpp:754) [caused by 1 \x08:\x01]
Queue my-topic does not exist
	</screen>
      </example>

      <para>Now let's use the <literal>create</literal> option to
      create the queue <literal>xoxox</literal> if it does not already
      exist:</para>

      <example>
	<title>Creating a Queue Automatically</title>

	<para><emphasis>First Window:</emphasis></para>
	<screen>$ ./drain -t 30 "xoxox ; {create: always}"</screen>

	<para>In previous examples, we created the queue before
	listening for messages on it. Using <literal>create:
	always</literal>, the queue is automatically created if it
	does not exist. Now we can send messages to this queue:</para>

	<para><emphasis>Second Window:</emphasis></para>
	<screen>$ ./spout "xoxox ; {create: always}"</screen>
	
	<para>Returning to the first window, we see that <command>drain</command> has received this message:</para>

	<screen>Message(properties={spout-id:1a1a3842-1a8b-4f88-8940-b4096e615a7d:0}, content='')</screen>
      </example>

      <!--
         TODO: Add some x-declare, x-subscribe, link, x-bindings examples
        -->

      <para>Other options specify message transfer semantics; for
      instance, they may state whether messages should be consumed or
      read in browsing mode, or specify reliability
      characteristics. The following example uses the
      <literal>browse</literal> option to receive messages without
      removing them from a queue.</para>

      <example>
        <title>Browsing a Queue</title>
        <para>
          Let's use the browse mode to receive messages without
          removing them from the queue. First we send three messages to the
          queue:
        </para>
        <screen>
$ ./spout my-queue --content one
$ ./spout my-queue --content two
$ ./spout my-queue --content three
        </screen>
        
        <para>Now we use drain to get those messages, using the browse option:</para>
        <screen>
$ ./drain 'my-queue; {mode: browse}'
Message(properties={spout-id:fbb93f30-0e82-4b6d-8c1d-be60eb132530:0}, content='one')
Message(properties={spout-id:ab9e7c31-19b0-4455-8976-34abe83edc5f:0}, content='two')
Message(properties={spout-id:ea75d64d-ea37-47f9-96a9-d38e01c97925:0}, content='three')
        </screen>
        
        <para>We can confirm the messages are still on the queue by repeating the drain:</para>
        <screen>
$ ./drain 'my-queue; {mode: browse}'
Message(properties={spout-id:fbb93f30-0e82-4b6d-8c1d-be60eb132530:0}, content='one')
Message(properties={spout-id:ab9e7c31-19b0-4455-8976-34abe83edc5f:0}, content='two')
Message(properties={spout-id:ea75d64d-ea37-47f9-96a9-d38e01c97925:0}, content='three')
        </screen>
      </example>

      <!--
         TODO: Add some reliability option examples
        -->

      <table pgwide="1">
        <title>Address String Options</title>
        <tgroup cols="3">
          <thead>
	    <colspec colnum="1" colwidth="1*"/>
	    <colspec colnum="2" colwidth="3*"/>
	    <colspec colnum="3" colwidth="3*"/>
	    <row>
	      <entry>option</entry>
	      <entry>value</entry>
	      <entry>semantics</entry>
	    </row>
          </thead>
          <tbody>
	    <row>
	      <entry>
	        assert
	      </entry>
	      <entry>
	        one of: always, never, sender or receiver
	      </entry>
	      <entry>
	        Asserts that the properties specified in the node option
	        match whatever the address resolves to. If they do not,
	        resolution fails and an exception is raised. <!-- ###
	                                                          Which exception -->
	      </entry>
	    </row>

	    <row>
	      <entry>
	        create
	      </entry>
	      <entry>
                one of: always, never, sender or receiver
	      </entry>
	      <entry>
	        Creates the node to which an address refers if it does
	        not exist. No error is raised if the node does
	        exist. The details of the node may be specified in the
	        node option.
	      </entry>
	    </row>
	    <row>
	      <entry>
	        delete
	      </entry>
	      <entry>
                one of: always, never, sender or receiver
	      </entry>
	      <entry>
	        Delete the node when the sender or receiver is closed.
	      </entry>
	    </row>
	    <row>
	      <entry>
	        node
	      </entry>
	      <entry>
	        A nested map containing the entries shown in <xref linkend="table-node-properties"/>.
	      </entry>
	      <entry>
                Specifies properties of the node to which the address
                refers. These are used in conjunction with the assert or
                create options.
	      </entry>
	    </row>
	    <row>
	      <entry>
	        link
	      </entry>
	      <entry>
	        A nested map containing the entries shown in <xref linkend="table-link-properties"/>.
	      </entry>
	      <entry>
                Used to control the establishment of a conceptual link
                from the client application to or from the target/source
                address.
	      </entry>
	    </row>
	    <row>
	      <entry>
	        mode
	      </entry>
	      <entry>
	        one of: browse, consume
	      </entry>
	      <entry>
                This option is only of relevance for source addresses
                that resolve to a queue. If browse is specified the
                messages delivered to the receiver are left on the queue
                rather than being removed. If consume is specified the
                normal behaviour applies; messages are removed from teh
                queue once the client acknoweldges their receipt.
	      </entry>
	    </row>
          </tbody>
        </tgroup>
      </table>


      <table id="table-node-properties" pgwide="1">
        <title>Node Properties</title>
        <tgroup cols="3">
          <thead>
	    <colspec colnum="1" colwidth="1*"/>
	    <colspec colnum="2" colwidth="3*"/>
	    <colspec colnum="3" colwidth="3*"/>
	    <row>
	      <entry>property</entry>
	      <entry>value</entry>
	      <entry>semantics</entry>
	    </row>
          </thead>
          <tbody>
	    <row>
	      <entry>
	        type
	      </entry>
	      <entry>
	        topic, queue
	      </entry>
	      <entry>
	      </entry>
	    </row>
	    <row>
	      <entry>
	        durable
	      </entry>	       
	      <entry>
	        True, False
	      </entry>
	      <entry>
                Indicates whether the node survives a loss of
                volatile storage e.g. if the broker is restarted.
	      </entry>
	    </row>
	    <row>
	      <entry>
	        x-declare
	      </entry>
	      <entry>
	        A nested map whose values correspond to the valid fields
	        on an AMQP 0-10 queue-declare or exchange-declare
	        command.
	      </entry>
	      <entry>
                These values are used to fine tune the creation or
                assertion process. Note however that they are protocol
                specific.
	      </entry>
	    </row>
	    <row>
	      <entry>
	        x-bindings
	      </entry>
	      <entry>
	        A nested list in which each binding is represented by
	        a map. The entries of the map for a binding contain
	        the fields that describe an AMQP 0-10 binding. Here is
	        the format for x-bindings:

<programlisting><![CDATA[
[
 {
  exchange: <exchange>,
  queue: <queue>,
  key: <key>,
  arguments: { 
    <key_1>: <value_1>, 
    ..., 
    <key_n>: <value_n> }
 },
 ...
]
]]></programlisting>
	      </entry>
	      <entry>
                In conjunction with the create option, each of these
                bindings is established as the address is resolved. In
                conjunction with the assert option, the existence of
                each of these bindings is verified during
                resolution. Again, these are protocol specific.
	      </entry>
	    </row>
          </tbody>
        </tgroup>
      </table>

      <table id="table-link-properties" pgwide="1">
        <title>Link Properties</title>
        <tgroup cols="3">
          <thead>
	    <colspec colnum="1" colwidth="1*"/>
	    <colspec colnum="2" colwidth="3*"/>
	    <colspec colnum="3" colwidth="3*"/>
	    <row>
	      <entry>option</entry>
	      <entry>value</entry>
	      <entry>semantics</entry>
	    </row>
          </thead>
          <tbody>
	    <row>
	      <entry>
	        reliability
	      </entry>
	      <entry>
	        one of: unreliable, at-least-once, at-most-once, exactly-once
	      </entry>
	      <entry>
	      </entry>
	    </row>
	    <row>
	      <entry>
	        durable
	      </entry>	       
	      <entry>
	        True, False
	      </entry>
	      <entry>
                Indicates whether the link survives a loss of
                volatile storage e.g. if the broker is restarted.
	      </entry>
	    </row>
	    <row>
	      <entry>
	        x-declare
	      </entry>
	      <entry>
	        A nested map whose values correspond to the valid fields
	        of an AMQP 0-10 queue-declare command.
	      </entry>
	      <entry>
                These values can be used to customise the subscription
	        queue in the case of receiving from an exchange. Note
	        however that they are protocol specific.
	      </entry>
	    </row>
	    <row>
	      <entry>
	        x-subscribe
	      </entry>
	      <entry>
	        A nested map whose values correspond to the valid fields
	        of an AMQP 0-10 message-subscribe command.
	      </entry>
	      <entry>
                These values can be used to customise the subscription.
	      </entry>
	    </row>
	    <row>
	      <entry>
	        x-bindings
	      </entry>
	      <entry>
	        A nested list each of whose entries is a map that may
	        contain fields (queue, exchange, key and arguments)
	        describing an AMQP 0-10 binding.
	      </entry>
	      <entry>
                These bindings are established during resolution
                independent of the create option. They are considered
                logically part of the linking process rather than of
                node creation.
	      </entry>
	    </row>
          </tbody>
        </tgroup>
      </table>

    </section>


  <section id="section-address-string-bnf">
    <title>Address String Grammar</title>

    <para>This section provides a formal grammar for address strings.</para>

    <formalpara>
      <title>Tokens</title>
      <para>The following regular expressions define the tokens used
      to parse address strings:</para></formalpara>
<programlisting><![CDATA[
LBRACE: \\{
RBRACE: \\}
LBRACK: \\[
RBRACK: \\]
COLON:  :
SEMI:   ;
SLASH:  /
COMMA:  ,
NUMBER: [+-]?[0-9]*\\.?[0-9]+
ID:     [a-zA-Z_](?:[a-zA-Z0-9_-]*[a-zA-Z0-9_])?
STRING: "(?:[^\\\\"]|\\\\.)*"|\'(?:[^\\\\\']|\\\\.)*\'
ESC:    \\\\[^ux]|\\\\x[0-9a-fA-F][0-9a-fA-F]|\\\\u[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]
SYM:    [.#*%@$^!+-]
WSPACE: [ \\n\\r\\t]+
]]></programlisting>

    <formalpara>
      <title>Grammar</title>
      <para>The formal grammar for addresses is given below:</para>
    </formalpara>

    <programlisting><![CDATA[
address := name [ "/" subject ] [ ";" options ]
   name := ( part | quoted )+
subject := ( part | quoted | "/" )*
 quoted := STRING / ESC
   part := LBRACE / RBRACE / COLON / COMMA / NUMBER / ID / SYM
options := map
    map := "{" ( keyval ( "," keyval )* )? "}"
 keyval "= ID ":" value
  value := NUMBER / STRING / ID / map / list
   list := "[" ( value ( "," value )* )? "]"
   ]]></programlisting>


    <formalpara>
      <title>Address String Options</title>
      <para>The address string options map supports the following parameters:</para>
    </formalpara>

    <programlisting><![CDATA[
<name> [ / <subject> ] ; {
  create: always | sender | receiver | never,
  delete: always | sender | receiver | never,
  assert: always | sender | receiver | never,
  mode: browse | consume,
  node: {
    type: queue | topic,
    durable: True | False,
    x-declare: { ... <declare-overrides> ... },
    x-bindings: [<binding_1>, ... <binding_n>]
  },
  link: {
    name: <link-name>,
    durable: True | False,
    reliability: unreliable | at-most-once | at-least-once | exactly-once,
    x-declare: { ... <declare-overrides> ... },
    x-bindings: [<binding_1>, ... <binding_n>],
    x-subscribe: { ... <subscribe-overrides> ... }
  }
}
]]></programlisting>


    <itemizedlist>
      <title>Create, Delete, and Assert Policies</title>
      <para>The create, delete, and assert policies specify who should
      perfom the associated action:</para>
      <listitem><para><emphasis>always</emphasis>: the action is performed by any messaging client</para></listitem>
      <listitem><para><emphasis>sender</emphasis>: the action is only performed by a sender</para></listitem>
      <listitem><para><emphasis>receiver</emphasis>: the action is only performed by a receiver</para></listitem>
      <listitem><para><emphasis>never</emphasis>: the action is never performed (this is the default)</para></listitem>
    </itemizedlist>

    <itemizedlist>
      <title>Node-Type</title>
      <para>The node-type is one of:</para>
       <listitem><para><emphasis>topic</emphasis>: in the AMQP 0-10
       mapping, a topic node defaults to the topic exchange, x-declare
       may be used to specify other exchange types</para></listitem>
       <listitem><para><emphasis>queue</emphasis>: this is the default node-type</para></listitem>
    </itemizedlist>
  </section>


</section>

<section>
      <title>Logging</title>

      <section>
	<title>Logging in C++</title>
	<para>The Qpidd broker and C++ clients can both use environment
	variables to enable logging. Use QPID_LOG_ENABLE to set the
	level of logging you are interested in (trace, debug, info,
	notice, warning, error, or critical):</para>

<screen>
$ export QPID_LOG_ENABLE="warning+"
</screen>

      <para>The Qpidd broker and C++ clients use QPID_LOG_OUTPUT to
      determine where logging output should be sent. This is either a
      file name or the special values stderr, stdout, or syslog:</para>

<screen>
export QPID_LOG_TO_FILE="/tmp/myclient.out"
</screen>

      </section>
	
	<section>
		<title>Logging in Python</title>
		<para>
			The Python client library supports logging using the standard Python logging module. The easiest way to do logging is to use the <command>basicConfig()</command>, which reports all warnings and errors:
		</para>
		
<programlisting>from logging import basicConfig
basicConfig()
</programlisting>
		<para>
			Qpidd also provides a convenience method that makes it easy to specify the level of logging desired. For instance, the following code enables logging at the <command>DEBUG</command> level:
		</para>
		
<programlisting>from qpid.log import enable, DEBUG
enable("qpid.messaging.io", DEBUG)
</programlisting>
		<para>
			For more information on Python logging, see <ulink url="http://docs.python.org/lib/node425.html">http://docs.python.org/lib/node425.html</ulink>. For more information on Qpid logging, use <command>$ pydoc qpid.log</command>.
		</para>
	</section>
</section>

    
<section>
      <title>Reconnect and Failover</title>
      <para>Connections in the Qpid Messaging API support automatic
      reconnect if a connection is lost. This is done using connection
      options. The following example shows how to use connection options in C++ and Python.</para>

      <example>
	<title>Specifying Connection Options in C++ and Python</title>

	<para>In C++, these options are set using <function>Connection::setOption()</function>:</para>

      <programlisting><![CDATA[
Connection connection(broker);
connection.setOption("reconnect", true);
try {
    connection.open();
    !!! SNIP !!!
      ]]></programlisting>

	<para>In Python, these options are set using named arguments in
      the <function>Connection</function> constructor:</para>

      <programlisting><![CDATA[
connection = Connection("localhost:5672", reconnect=True)
try:
  connection.open()
  !!! SNIP !!!
      ]]></programlisting>

      <para>See the reference documentation for details on how to set
      these on connections for each language.</para>
      </example>

      <para>The following table lists the connection options that can
      be used.</para>

      <table pgwide="1">
        <title>Connection Options</title>
        <tgroup cols="3">
          <thead>
	    <colspec colnum="1" colwidth="1*"/>
	    <colspec colnum="2" colwidth="1*"/>
	    <colspec colnum="3" colwidth="3*"/>
	    <row>
	      <entry>option</entry>
	      <entry>value</entry>
	      <entry>semantics</entry>
	    </row>
          </thead>
          <tbody>
	    <row>
	      <entry>
	        reconnect
	      </entry>
	      <entry>
	        True, False
	      </entry>
	      <entry>
	        Transparently reconnect if the connection is lost.
	      </entry>
	    </row>
	    <row>
	      <entry>
	        reconnect_timeout
	      </entry>
	      <entry>
	        N
	      </entry>
	      <entry>
	        Total number of seconds to continue reconnection attempts before giving up and raising an exception.
	      </entry>
	    </row>
	    <row>
	      <entry>
	        reconnect_limit
	      </entry>
	      <entry>
	        N
	      </entry>
	      <entry>
	        Maximum number of reconnection attempts before giving up and raising an exception.
	      </entry>
	    </row>
	    <row>
	      <entry>
	        reconnect_interval_min
	      </entry>
	      <entry>
	        N
	      </entry>
	      <entry>
	        Minimum number of seconds between reconnection attempts. The first reconnection attempt is made immediately; if that fails, the first reconnection delay is set to the value of <literal>reconnect_interval_min</literal>; if that attempt fails, the reconnect interval increases exponentially until a reconnection attempt succeeds or <literal>reconnect_interval_max</literal> is reached.
	      </entry>
	    </row>
	    <row>
	      <entry>
	        reconnect_interval_max
	      </entry>
	      <entry>
	        N
	      </entry>
	      <entry>
	        Maximum reconnect interval.
	      </entry>
	    </row>
	    <row>
	      <entry>
	        reconnect_interval
	      </entry>
	      <entry>
	        N
	      </entry>
	      <entry>
	        Sets both <literal>reconnection_interval_min</literal> and <literal>reconnection_interval_max</literal> to the same value.
	      </entry>
	    </row>
          </tbody>
        </tgroup>
      </table>
    </section>

    <section>
      <title>Receiving Messages from Multiple Sources</title>

      <para>A receiver can only read from one source, but many
      programs need to be able to read messages from many sources,
      preserving the original sequence of the messages. In the Qpid
      Messaging API, a program can ask a session for the <quote>next
      receiver</quote>; that is, the receiver that is responsible for
      the next available message. The following example shows how this
      is done in C++ and Python.</para>

      <example>
	<title>Receiving Messages from Multiple Sources</title>

	<para>C++:</para>

	<programlisting><![CDATA[
Receiver receiver1 = session.createReceiver(address1);
Receiver receiver2 = session.createReceiver(address2);

Message message =  session.nextReceiver().fetch();
session.acknowledge(); // acknowledge message receipt
std::cout << message.getContent() << std::endl;
]]>	  </programlisting>

	<para>Python:</para>
	<programlisting><![CDATA[
receiver1 = session.receiver(address1)
receiver2 = session.receiver(address)
message = session.next_receiver().fetch()
print message.content
]]>	  </programlisting>
      </example>
    </section>

    <section>
      <title>Request / Response</title>
      <para>Request / Response applications use the reply-to property,
      described in <xref
      linkend="table-amqp0-10-message-properties"/>, to allow a server
      to respond to the client that sent a message. A server sets up a
      service queue, with a name known to clients. A client creates a
      private queue for the server's response, creates a message for a
      request, sets the request's reply-to property to the address of
      the client's response queue, and sends the request to the
      service queue. The server sends the response to the address
      specified in the request's reply-to property.
      </para>
      <example>
	<title>Request / Response Applications in C++</title>

	<para>This example shows the C++ code for a client and server
	that use the request / response pattern.</para>

	<para>The server creates a service queue and waits for a
	message to arrive. If it receives a message, it sends a
	message back to the sender.</para>

	<programlisting><![CDATA[Receiver receiver = session.createReceiver("service_queue; {create: always}");

Message request = receiver.fetch();
const Address&amp; address = request.getReplyTo(); // Get "reply-to" from request ...
if (address) {
  Sender sender = session.createSender(address); // ... send response to "reply-to"
  Message response("pong!");
  sender.send(response);
  session.acknowledge();
}
     ]]></programlisting>

	<para>The client creates a sender for the service queue, and
	also creates a response queue that is deleted when the
	client closes the receiver for the response queue. In the C++
	client, if the address starts with the character
	<literal>#</literal>, it is given a unique name.</para>

	<programlisting><![CDATA[
Sender sender = session.createSender("service_queue");

Address responseQueue("#response-queue; {create:always, delete:always}");
Receiver receiver = session.createReceiver(responseQueue);

Message request;
request.setReplyTo(responseQueue);
request.setContent("ping");
sender.send(request);
Message response = receiver.fetch();
std::cout << request.getContent() << " -> " << response.getContent() << std::endl;
]]>	  </programlisting>

	<para>The client sends the string <literal>ping</literal> to
	the server. The server sends the response
	<literal>pong</literal> back to the same client, using the
	<varname>replyTo</varname> property.</para>

      </example>
<!--
      <example>
	<title>Request / Response Applications in Python</title>
	<programlisting>### TODO</programlisting>
      </example>
-->
    </section>
    <section id="section-Maps">
      <title>Maps in Message Content</title>
      
      <para>Many messaging applications need to exchange data across
      languages and platforms, using the native datatypes of each
      programming language. AMQP provides a set of portable datatypes,
      but does not directly support a set of named type/value
      pairs. Java JMS provides the <classname>MapMessage</classname>
      interface, which allows sets of named type/value pairs, but does
      not provide a set of portable datatypes.</para> 

      <para>The Qpid Messaging API supports maps in message
      content. Unlike JMS, any message can contain maps. These maps
      are supported in each language using the conventions of the
      language. In Java, we implement the
      <classname>MapMessage</classname> interface; in Python, we
      support <classname>dict</classname> and
      <classname>list</classname> in message content; in C++, we
      provide the <classname>Variant::Map</classname> and
      <classname>Variant::List</classname> classes to represent maps
      and lists. In all languages, messages are encoded using AMQP's
      portable datatypes.
      </para>

      <tip>
      <para>Because of the differences in type systems among
      languages, the simplest way to provide portable messages is to
      rely on maps, lists, strings, 64 bit signed integers, and
      doubles for messages that need to be exchanged across languages
      and platforms.</para>
      </tip>

      <section id="section-Python-Maps">
	<title>Qpid Maps in Python</title>

	<para>In Python, Qpid supports the <classname>dict</classname> and <classname>list</classname> types directly in message content. The following code shows how to send these structures in a message:</para>

	<example>
	  <title>Sending Qpid Maps in Python</title>
	  <programlisting><![CDATA[
from qpid.messaging import *
# !!! SNIP !!!

content = {'Id' : 987654321, 'name' : 'Widget', 'percent' : 0.99}
content['colours'] = ['red', 'green', 'white']
content['dimensions'] = {'length' : 10.2, 'width' : 5.1,'depth' : 2.0};
content['parts'] = [ [1,2,5], [8,2,5] ]
content['specs'] = {'colors' : content['colours'], 
                    'dimensions' : content['dimensions'], 
                    'parts' : content['parts'] }
message = Message(content=content)
sender.send(message)
    ]]>   </programlisting>
	</example>


      <para>The following table shows the datatypes that can be sent in a Python map message,
 and the corresponding datatypes that will be received by clients in Java or C++.</para>
      

	<table id="table-Python-Maps" >
	<title>Python Datatypes in Maps</title>
	<tgroup cols="3">
	  <thead>
	    <row>
	      <entry>Python Datatype</entry>
	      <entry>&rarr; C++</entry>
	      <entry>&rarr; Java</entry>
	    </row>
	  </thead>
	  <tbody>
   	    <row><entry>bool</entry><entry>bool</entry><entry>boolean</entry></row>
	    <row><entry>integer</entry><entry>long</entry><entry>long</entry></row>
	    <row><entry>long</entry><entry>long</entry><entry>long</entry></row>
	    <row><entry>float</entry><entry>double</entry><entry>double</entry></row>
	    <row><entry>unicode</entry><entry>string</entry><entry>java.lang.String</entry></row>
	    <row><entry>uuid</entry><entry>qpid::types::Uuid</entry><entry>java.util.UUID</entry></row>
	    <row><entry>dict</entry><entry>Variant::Map</entry><entry>java.util.Map</entry></row>
	    <row><entry>list</entry><entry>Variant::List</entry><entry>java.util.List</entry></row>
	  </tbody>
	</tgroup>
      </table>

      </section>




      <section id="section-cpp-Maps">
	<title>Qpid Maps in C++</title>


	<para>In C++, Qpid defines the the
	<classname>Variant::Map</classname> and
	<classname>Variant::List</classname> types, which can be
	encoded into message content. The following code shows how to
	send these structures in a message:</para>

	<example>
	  <title>Sending Qpid Maps in C++</title>
	<programlisting><![CDATA[
using namespace qpid::types;

// !!! SNIP !!!

Message message;
Variant::Map content;
content["id"] = 987654321;
content["name"] = "Widget";
content["percent"] = 0.99;
Variant::List colours;
colours.push_back(Variant("red"));
colours.push_back(Variant("green"));
colours.push_back(Variant("white"));
content["colours"] = colours;

Variant::Map dimensions;
dimensions["length"] = 10.2;
dimensions["width"] = 5.1;
dimensions["depth"] = 2.0;
content["dimensions"]= dimensions; 

Variant::List part1;
part1.push_back(Variant(1));
part1.push_back(Variant(2));
part1.push_back(Variant(5));
 
Variant::List part2;
part2.push_back(Variant(8));
part2.push_back(Variant(2));
part2.push_back(Variant(5));
 
Variant::List parts;
parts.push_back(part1);
parts.push_back(part2);
content["parts"]= parts; 

Variant::Map specs;
specs["colours"] = colours; 
specs["dimensions"] = dimensions; 
specs["parts"] = parts; 
content["specs"] = specs;

encode(content, message);
sender.send(message, true);
]]>     </programlisting>
	</example>

	<para>The following table shows the datatypes that can be sent
	in a C++ map message, and the corresponding datatypes that
	will be received by clients in Java and Python.</para>
      
	<table  id="table-cpp-Maps">
	<title>C++ Datatypes in Maps</title>
	<tgroup cols="3">
	  <thead>
	    <row>
	      <entry>C++ Datatype</entry>
	      <entry>&rarr; Python</entry>
	      <entry>&rarr; Java</entry>
	    </row>
	  </thead>
	  <tbody>
   	    <row><entry>bool</entry><entry>bool</entry><entry>boolean</entry></row>
  	    <row><entry>unsigned char</entry><entry>unicode</entry><entry>char</entry></row>
	    <row><entry>unsigned short int</entry><entry>integer | long</entry><entry>short</entry></row>
	    <row><entry>unsigned int</entry><entry>integer | long</entry><entry>integer</entry></row>
	    <row><entry>unsigned long</entry><entry>integer | long</entry><entry>long</entry></row>
	    <row><entry>char</entry><entry>unicode</entry><entry>char</entry></row>
	    <row><entry>short</entry><entry>integer | long</entry><entry>short</entry></row>
	    <row><entry>int</entry><entry>integer | long</entry><entry>integer</entry></row>
	    <row><entry>long</entry><entry>integer | long</entry><entry>long</entry></row>
	    <row><entry>float</entry><entry>float</entry><entry>float</entry></row>
	    <row><entry>double</entry><entry>float</entry><entry>double</entry></row>
	    <row><entry>string</entry><entry>unicode</entry><entry>java.lang.String</entry></row>
	    <row><entry>qpid::types::Uuid</entry><entry>uuid</entry><entry>java.util.UUID</entry></row>
	    <row><entry>Variant::Map</entry><entry>dict</entry><entry>java.util.Map</entry></row>
	    <row><entry>Variant::List</entry><entry>list</entry><entry>java.util.List</entry></row>
	  </tbody>
	</tgroup>
      </table>
      </section>

      
</section> 
        <section>
      <title>Performance</title>
      <para>
         Clients can often be made significantly faster by batching acknowledgements and setting the capacity of receivers to allow prefetch. 	
      </para>
      <section>
	<title>Batching Acknowledgements</title>

	<para>Many of the simple examples we have shown retrieve a message and immediately acknowledge it. Because each acknowledgement results in network traffic, you can dramatically increase performance by acknowledging messages in batches. For instance, an application can read a number of related messages, then acknowledge the entire batch, or an application can acknowledge after a certain number of messages have been received or a certain time period has elapsed. Messages are not removed from the broker until they are acknowledged, so guaranteed delivery is still available when batching acknowledgements.</para>
      </section>


      <section>
	<title>Prefetch</title>   

	<para>By default, a receiver retrieves the next message from the server, one message at a time, which provides intuitive results when writing and debugging programs, but does not provide optimum performance. To create an input buffer, set the capacity of the receiver to the size of the desired input buffer; for many applications, a capacity of 100 performs well. </para>

<!--
###	sender: capacity of replay buffer (not yet acknowledged messages), these are resent with failover
-->

	<example>
	  <title>Prefetch</title>
	  
	  <para>C++</para>
	  <programlisting>
Receiver receiver = session.createReceiver(address);
receiver.setCapacity(100);
Message message = receiver.fetch();
	  </programlisting>
<!--
	  <para>Python</para>
	  <programlisting>
	  </programlisting>
-->
  
	</example>
      </section>

    </section>

    <section>
      <title>Reliability</title>

      <section>
	<title>Guaranteed Delivery</title>

	<para>If a queue is durable, the queue survives a messaging
	broker crash, as well as any durable messages that have been
	placed on the queue. These messages will be delivered when the
	messaging broker is restarted. Delivery is guaranteed if and
	only if both the message and the queue are durable. Guaranteed
	delivery requires a persistence module, such as the one
	available from <ulink
	url="http://QpidComponents.org">QpidComponents.org</ulink>.</para>

	<example>
	  <title>Guaranteed Delivery</title>

	  <para>C++:</para>

	  <programlisting><![CDATA[
Sender sender = session.createSender("durable-queue");

Message message("Hello world!");
message.setDurable(1);

sender.send(Message("Hello world!"));
]]></programlisting>
	</example>
<!--
	  <para>Python:</para>
-->
<!--	</example>

	<section>
	  <title>Cluster Failover </title>
	</section>
-->

      </section>

    </section>

<!--
    <section>
      <title>Security</title>
##########
    </section>
-->

    <section>
      <title>Transactions</title>
      <para>In AMQP, transactions cover the semantics of enqueues and
      dequeues.</para>

      <para>When sending messages, a transaction tracks enqueues
      without actually delivering the messages, a commit places
      messages on their queues, and a rollback discards the
      enqueues.</para>

      <para>When receiving messages, a transaction tracks dequeues
      without actually removing acknowledged messages, a commit
      removes all acknowledged messages, and a rollback discards
      acknowledgements. A rollback does not release the message, it
      must be explicitly released to return it to the queue.</para>

      <example>
	<title>Transactions</title>
	<para>C++:</para>
	<programlisting><![CDATA[
Connection connection(broker);
Session session =  connection.createTransactionalSession();
...
if (smellsOk())
   session.commit();
else 
   session.rollback();
   ]]></programlisting>
<!--
	<para>Python</para>
	<programlisting><![CDATA[
### TODO
   ]]></programlisting>
-->
      </example>

    </section>





  <section>
      <title>XML Exchange</title>

      <para>The XML Exchange is an AMQP 0-10 custom exchange provided by the Apache Qpid C++ broker. It allows messages to be filtered using XQuery; queries can address either message properties or XML content in the body of the message.</para>

      <para>An instance of the XML Exchange must be added before it can be used:</para>

      <programlisting>
$ qpid-config add exchange xml xml
      </programlisting>

      <para>When using the XML exchange, a sender's address string must provide a subject, e.g. <literal>xml/weather</literal>.</para>

      <para>If a receiver that is using the XML exchange also provides a subject, it receives messages if the subject exactly matches a message's subject.</para>


      <para>When using the XML Exchange, a receiver normally provides an XQuery as an x-binding argument. If the query contains a context item (a path starting with <quote>.</quote>), then it is applied to the content of the message, which must be well-formed XML. For instance, <literal>./weather</literal> is a valid XQuery, which matches any message in which the root element is named <literal>weather</literal>. Here is an address string that contains this query:</para>

      <programlisting><![CDATA[
xml; {
 link: { 
  x-bindings: [{ exchange:xml, key:weather, arguments:{xquery:"./weather"} }] 
 } 
}
  ]]></programlisting>

      <para>Note that each x-binding is created in addition to any other bindings that may exist, and each x-binding must include the exchange name, the key, and the xquery. If you specify the subject in the address string (e.g. <literal>xml/weather; link ...</literal>), it creates a binding that is used in addition to the x-bindings; the binding created for the subject matches any message whose subject is <literal>weather</literal>, the binding created for the x-binding matches any message that satisfies the query, i.e. any message with a root element named <literal>weather</literal>.
      </para>


      <para>The XML Exchange can also be used to query message properties by declaring an external variable with the same name as each property that is to be queried. The following XQuery queries the <literal>control</literal> property, as well as the content of the message:</para>

      <programlisting><![CDATA[
declare variable $control external;
./message/id mod 2 = 1 or $control = 'end'
]]></programlisting>

      <para>If the XQuery addresses message content, and the message is not well-formed XML, the message will not be received. If the XQuery does not query message content, the message need not contain XML.</para>


      <example>
	<title>Using the XML Exchange with <command>drain</command></title>

	<para>The following shows the arguments used with <command>drain</command> to retrieve messages whose root element is named <literal>weather</literal>:</para>

	<programlisting><![CDATA[
$ ./drain -f "xml; {link:{x-bindings: [{exchange: xml, key:"weather", 
arguments:{xquery:\"./weather\"}}]}}"
 ]]></programlisting> 
      </example>

      <example>
	<title>Using the XML Exchange with C++</title>

	<para>In C++, it is convenient to place an XQuery in a string, and use a <classname>stringstream</classname> to add the query to the template for an address string that specifies an x-binding.</para>

	<programlisting><![CDATA[
std::string query = 
  "let $w := ./weather "
  "return $w/station = 'Raleigh-Durham International Airport (KRDU)' "
  "   and $w/temperature_f > 50"
  "   and $w/temperature_f - $w/dewpoint > 5"
  "   and $w/wind_speed_mph > 7"
  "   and $w/wind_speed_mph < 20";

stringstream address;

address << "xml; {"
  " link: { "
  "  x-bindings: [{ exchange: xml, key: weather, arguments: { xquery:\"" 
     << query 
     << "\"} }] "
  " } "
  "}";


Receiver receiver = session.createReceiver(address.str());
Message response = receiver.fetch();
session.acknowledge();
std::cout << response.getContent() << std::endl;

      ]]></programlisting>
      </example>


      <example>
	<title>Using the XML Exchange with Python</title>

	<para>In Python, it is often convenient to place the query in
	a separate string, and use the repr() value of the query
	string in an address template string.</para>

	<programlisting><![CDATA[
# Set up the receiver
  query = """
   let $w := ./weather
   return $w/station = 'Raleigh-Durham International Airport (KRDU)'
      and $w/temperature_f > 50
      and $w/temperature_f - $w/dewpoint > 5
      and $w/wind_speed_mph > 7
      and $w/wind_speed_mph < 20   """

  address = """
    xml; {
       link: { 
         x-bindings: [{ exchange: xml, key: weather, arguments: { xquery: %r} }] 
       } 
    }
    """ % query

  receiver = session.receiver(address)

# Retrieve matching message from the receiver and print it

  message = receiver.fetch(timeout=1)
  print message.content
  session.acknowledge()
	]]></programlisting>
      </example>

    </section>

<section id="section-amqp0-10-mapping">
    <title>The AMQP 0-10 mapping</title>

    <para>
      This section describes the AMQP 0-10 mapping for the Qpid
      Messaging API.
    </para>
    <para>
        The interaction with the broker triggered by creating a sender
        or receiver depends on what the specified address resolves
        to. Where the node type is not specified in the address, the
        client queries the broker to determine whether it refers to a
        queue or an exchange.
    </para>
    <para>
        When sending to a queue, the queue's name is set as the
        routing key and the message is transfered to the default (or
        nameless) exchange. When sending to an exchange, the message
        is transfered to that exchange and the routing key is set to
        the message subject if one is specified. A default subject may
        be specified in the target address. The subject may also be
        set on each message individually to override the default if
        required. In each case any specified subject is also added as
        a qpid.subject entry in the application-headers field of the
        message-properties.
      </para>
      <para>
        When receiving from a queue, any subject in the source address
        is currently ignored. The client sends a message-subscribe
        request for the queue in question. The accept-mode is
        determined by the reliability option in the link properties;
        for unreliable links the accept-mode is none, for reliable
        links it is explicit. The default for a queue is reliable. The
        acquire-mode is determined by the value of the mode option. If
        the mode is set to browse the acquire mode is not-acquired,
        otherwise it is set to pre-acquired. The exclusive and
        arguments fields in the message-subscribe command can be
        controlled using the x-subscribe map.
      </para>
      <para>
        When receiving from an exchange, the client creates a
        subscription queue and binds that to the exchange. The
        subscription queue's arguments can be specified using the
        x-declare map within the link properties. The reliability
        option determines most of the other parameters. If the
        reliability is set to unreliable then an auto-deleted,
        exclusive queue is used meaning that if the client or
        connection fails messages may be lost. For exactly-once the
        queue is not set to be auto-deleted. The durability of the
        subscription queue is determined by the durable option in the
        link properties. The binding process depends on the type of
        the exchange the source address resolves to.
      </para>

      <itemizedlist>
        <listitem>
          <para>
            For a topic exchange, if no subject is specified and no
            x-bindings are defined for the link, the subscription
            queue is bound using a wildcard matching any routing key
            (thus satisfying the expectation that any message sent to
            that address will be received from it). If a subject is
            specified in the source address however, it is used for
            the binding key (this means that the subject in the source
            address may be a binding pattern including wildcards).
          </para>
        </listitem>
        <listitem>
          <para>
            For a fanout exchange the binding key is irrelevant to
            matching. A receiver created from a source address that
            resolves to a fanout exchange receives all messages
            sent to that exchange regardless of any subject the source
            address may contain. An x-bindings element in the link
            properties should be used if there is any need to set the
            arguments to the bind.
          </para>
        </listitem>
        <listitem>
          <para>
            For a direct exchange, the subject is used as the binding
            key. If no subject is specified an empty string is used as
            the binding key.
          </para>
        </listitem>
        <listitem>
          <para>
            For a headers exchange, if no subject is specified the
            binding arguments simply contain an x-match entry and no
            other entries, causing all messages to match. If a subject
            is specified then the binding arguments contain an x-match
            entry set to all and an entry for qpid.subject whose value
            is the subject in the source address (this means the
            subject in the source address must match the message
            subject exactly). For more control the x-bindings element
            in the link properties must be used.
          </para>
        </listitem>
        <listitem>
          <para>
            For the XML exchange,<footnote><para>Note that the XML
            exchange is not a standard AMQP exchange type. It is a
            Qpid extension and is currently only supported by the C++
            broker.</para></footnote> if a subject is specified it is
            used as the binding key and an XQuery is defined that
            matches any message with that value for
            qpid.subject. Again this means that only messages whose
            subject exactly match that specified in the source address
            are received. If no subject is specified then the empty
            string is used as the binding key with an xquery that will
            match any message (this means that only messages with an
            empty string as the routing key will be received). For more
            control the x-bindings element in the link properties must
            be used. A source address that resolves to the XML
            exchange must contain either a subject or an x-bindings
            element in the link properties as there is no way at
            present to receive any message regardless of routing key.
          </para>
        </listitem>
      </itemizedlist>

      <para>
        If an x-bindings list is present in the link options a binding
        is created for each element within that list. Each element is
        a nested map that may contain values named queue, exchange,
        key or arguments. If the queue value is absent the queue name
        the address resolves to is implied. If the exchange value is
        absent the exchange name the address resolves to is implied.
      </para>

      <para>The following table shows how Qpid Messaging API message
        properties are mapped to AMQP 0-10 message properties and
        delivery properties. In this table <varname>msg</varname>
        refers to the Message class defined in the Qpid Messaging API,
        <varname>mp</varname> refers to an AMQP 0-10
        <varname>message-properties</varname> struct, and
        <varname>dp</varname> refers to an AMQP 0-10
        <varname>delivery-properties</varname> struct.</para>

      <table id="table-amqp0-10-message-properties" pgwide="1">
        <title>Mapping to AMQP 0-10 Message Properties</title>
        <tgroup cols="3">
          <thead>
	    <colspec colnum="1" colname="Python API" colwidth="3*"/>
	    <colspec colnum="2" colname="C++ API" colwidth="3*"/>
	    <colspec colnum="3" colname="AMPQ 0-10 Property" colwidth="6*"/>
	    <row>
	      <entry>Python API</entry>
	      <entry>C++ API</entry>
	      <entry>AMQP 0-10 Property<footnote><para>In these entries, <literal>mp</literal> refers to an AMQP message property, and <literal>dp</literal> refers to an AMQP delivery property.</para></footnote></entry>
	    </row>
          </thead>
          <tbody>
	    <row>
	      <entry>msg.id</entry><entry>msg.{get,set}MessageId()</entry><entry>mp.message_id</entry>
	    </row>
	    <row>
	      <entry>msg.subject</entry><entry>msg.{get,set}Subject()</entry><entry>mp.application_headers["qpid.subject"]</entry>
	    </row>
	    <row>
	      <entry>msg.user_id</entry><entry>msg.{get,set}UserId()</entry><entry>mp.user_id</entry>
	    </row>
	    <row>
	      <entry>msg.reply_to</entry><entry>msg.{get,set}ReplyTo()</entry><entry>mp.reply_to<footnote><para>The reply_to is converted from the protocol representation into an address.</para></footnote></entry>
	    </row>
	    <row>
	      <entry>msg.correlation_id</entry><entry>msg.{get,set}CorrelationId()</entry><entry>mp.correlation_id</entry>
	    </row>
	    <row>
	      <entry>msg.durable</entry><entry>msg.{get,set}Durable()</entry><entry>dp.delivery_mode == delivery_mode.persistent<footnote><para>Note that msg.durable is a boolean, not an enum.</para></footnote></entry>
	    </row>
	    <row>
	      <entry>msg.priority</entry><entry>msg.{get,set}Priority()</entry><entry>dp.priority</entry>
	    </row>
	    <row>
	      <entry>msg.ttl</entry><entry>msg.{get,set}Ttl()</entry><entry>dp.ttl</entry>
	    </row>
	    <row>
	      <entry>msg.redelivered</entry><entry>msg.{get,set}Redelivered()</entry><entry>dp.redelivered</entry>
	    </row>
	    <row><entry>msg.properties</entry><entry>msg.{get,set}Properties()</entry><entry>mp.application_headers</entry>
	    </row>
	    <row>
	      <entry>msg.content_type</entry><entry>msg.{get,set}ContentType()</entry><entry>mp.content_type</entry>
	    </row>
          </tbody>
        </tgroup>
      </table>
      
    </section>
  </chapter>


  <chapter id="QpidJMS">
    <title>Using the Qpid JMS client</title>
    <section>
      <title>A Simple Messaging Program in Java JMS</title>
      
      <para>The following program shows how to use address strings and
      JNDI for Qpid programs that use Java JMS.</para>

      <para>The Qpid JMS client uses Qpid Messaging API <xref
      linkend="section-addresses"/> to identify sources and
      targets. This program uses a JNDI file that defines a connection
      factory for the broker we are using, and the address of the
      topic exchange node that we bind the sender and receiver
      to. (The syntax of a ConnectionURL is given in <xref
      linkend="QpidJNDI"/>.)</para>

      <example>
	<title>JNDI Properties File for "Hello world!" example</title>
      <programlisting><![CDATA[
java.naming.factory.initial 
  = org.apache.qpid.jndi.PropertiesFileInitialContextFactory

# connectionfactory.[jndiname] = [ConnectionURL]
connectionfactory.qpidConnectionfactory 
  = amqp://guest:guest@clientid/test?brokerlist='tcp://localhost:5672'
# destination.[jndiname] = [address_string]
destination.topicExchange = amq.topic
]]></programlisting>
      </example>

      <para>In the Java JMS code, we use create a JNDI context, use the context to find a connection factory and create and start a connection, create a session, and create a destination that corresponds to the topic exchange. Then we create a sender and a receiver, send a message with the sender, and receive it with the receiver. This code should be straightforward for anyone familiar with Java JMS.</para>

      <example>
	<title>"Hello world!" in Java</title>
	<programlisting lang="java"><![CDATA[
package org.apache.qpid.example.jmsexample.hello;

import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import java.util.Properties;

public class Hello {

  public Hello() {
  }

  public static void main(String[] args) {
    Hello producer = new Hello();
    producer.runTest();
  }

  private void runTest() {
    try {
      Properties properties = new Properties();
      properties.load(this.getClass().getResourceAsStream("hello.properties"));
      Context context = new InitialContext(properties);

      ConnectionFactory connectionFactory 
                    = (ConnectionFactory) context.lookup("qpidConnectionfactory");
      Connection connection = connectionFactory.createConnection();
      connection.start();

      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      Destination destination = (Destination) context.lookup("topicExchange");

      MessageProducer messageProducer = session.createProducer(destination);
      MessageConsumer messageConsumer = session.createConsumer(destination);

      TextMessage message = session.createTextMessage("Hello world!");
      messageProducer.send(message);

      message = (TextMessage)messageConsumer.receive();
      System.out.println(message.getText());

      connection.close();
      context.close();
    }
    catch (Exception exp) {
      exp.printStackTrace();
    }
  }
}
]]></programlisting>
      </example>

    </section>

    <section id="QpidJNDI">
      <title>Apache Qpid JNDI Properties for AMQP Messaging</title>


      <para>
	Apache Qpid defines JNDI properties that can be used to specify JMS Connections and Destinations. Here is a typical JNDI properties file:
      </para>

      <example>
	<title>JNDI Properties File</title>
    <programlisting><![CDATA[
java.naming.factory.initial 
  = org.apache.qpid.jndi.PropertiesFileInitialContextFactory

# connectionfactory.[jndiname] = [ConnectionURL]
connectionfactory.qpidConnectionfactory 
  = amqp://guest:guest@clientid/test?brokerlist='tcp://localhost:5672'
# destination.[jndiname] = [address_string]
destination.topicExchange = amq.topic
]]></programlisting>
      </example>

      <para>The following sections describe the JNDI properties that Qpid uses.</para>

      
      <section>
        <title>JNDI Properties for Apache Qpid</title>
        <para>
	  Apache Qpid supports the properties shown in the following table:
        </para>
        <table>
	  <title>JNDI Properties supported by Apache Qpid</title>
	  <tgroup cols="2">
	    <thead>
	      <row>
	        <entry>
		  Property
	        </entry>
	        <entry>
		  Purpose
	        </entry>
	      </row>
	    </thead>
	    <tbody>
	      <row>
	        <entry>
		  connectionfactory.&lt;jndiname&gt;
	        </entry>
	        <entry>
		  <para>
		    The Connection URL that the connection factory uses to perform connections.
		  </para>
	        </entry>
	      </row>
	      <row>
	        <entry>
		  queue.&lt;jndiname&gt;
	        </entry>
	        <entry>
		  <para>
		    A JMS queue, which is implemented as an amq.direct exchange in Apache Qpid.
		  </para>
	        </entry>
	      </row>
	      <row>
	        <entry>
		  topic.&lt;jndiname&gt;
	        </entry>
	        <entry>
		  <para>
		    A JMS topic, which is implemented as an amq.topic exchange in Apache Qpid.
		  </para>
	        </entry>
	      </row>
	      <row>
	        <entry>
		  destination.&lt;jndiname&gt;
	        </entry>
	        <entry>
		  <para>
		    Can be used for defining all amq destinations,
		    queues, topics and header matching, using an
		    address string.  

		    <footnote><para>Binding URLs, which were used in
		    earlier versions of the Qpid Java JMS client, can
		    still be used instead of address
		    strings.</para></footnote>
		  </para>
	        </entry>
	      </row>
	    </tbody>
	  </tgroup>
        </table>
      </section>
      
      <section>
        <title>Connection URLs</title>
        <para>
	  In JNDI properties, a Connection URL specifies properties for a connection. The format for a Connection URL is:
        </para>
        
        <programlisting>amqp://[&lt;user&gt;:&lt;pass&gt;@][&lt;clientid&gt;]&lt;virtualhost&gt;[?&lt;option&gt;=&#39;&lt;value&gt;&#39;[&amp;&lt;option&gt;=&#39;&lt;value&gt;&#39;]]
        </programlisting>
        <para>
	  For instance, the following Connection URL specifies a user name, a password, a client ID, a virtual host ("test"), a broker list with a single broker, and a TCP host with the host name <quote>localhost</quote> using port 5672:
        </para>
        
        <programlisting>amqp://username:password@clientid/test?brokerlist=&#39;tcp://localhost:5672&#39;
        </programlisting>
        <para>
	  Apache Qpid supports the following properties in Connection URLs:
        </para>
        <table pgwide="1">
	  <title>Connection URL Properties</title>
	  <tgroup cols="3">
	    <thead>
	      <row>
	        <entry>
		  Option
	        </entry>
	        <entry>
		  Type
	        </entry>
	        <entry>
		  Description
	        </entry>
	      </row>
	    </thead>
	    <tbody>
	      <row>
	        <entry>
		  brokerlist
	        </entry>
	        <entry>
		  see below
	        </entry>
	        <entry>
		  The broker to use for this connection. In the current release, precisely one broker must be specified.
	        </entry>
	      </row>
	      <row>
	        <entry>
		  maxprefetch
	        </entry>
	        <entry>
		  --
	        </entry>
	        <entry>
		  The maximum number of pre-fetched messages per destination.
	        </entry>
	      </row>
	      <row>
	        <entry>
		  sync_publish
	        </entry>
	        <entry>
           {'persistent' | 'all'}
	        </entry>
	        <entry>
          A sync command is sent after every persistent message to guarantee that it has been received; if the value is 'persistent', this is done only for persistent messages.
	        </entry>
	      </row>
	      <row>
	        <entry>
		  sync_ack
	        </entry>
	        <entry>
           Boolean
	        </entry>
	        <entry>
          A sync command is sent after every acknowledgement to guarantee that it has been received.
	        </entry>
	      </row>
          <row>
	        <entry>
		  use_legacy_map_msg_format
	        </entry>
	        <entry>
          Boolean
	        </entry>
	        <entry>
          If you are using JMS Map messages and deploying a new client with any JMS client older than 0.7 release, you must set this to true to ensure the older clients can understand the map message encoding.
	        </entry>
	      </row>
          <row>
	        <entry>
		  failover
	        </entry>
	        <entry>
           {'roundrobin' | 'failover_exchange'}
	        </entry>
	        <entry>
          If roundrobin is selected it will try each broker given in the broker list.
          If failover_exchange is selected it connects to the initial broker given in the broker URL and will receive membership updates via the failover exchange.
	        </entry>
	      </row>
	    </tbody>
	  </tgroup>
        </table>
        <para>
	  Broker lists are specified using a URL in this format:
        </para>
        
        <programlisting>brokerlist=&lt;transport&gt;://&lt;host&gt;[:&lt;port&gt;](?&lt;param>=&lt;value>)?(&amp;&lt;param>=&lt;value>)*</programlisting>
        <para>
	  For instance, this is a typical broker list:
        </para>
        
        <programlisting>brokerlist=&#39;tcp://localhost:5672&#39;
        </programlisting>

	<para>
	  A broker list can contain more than one broker address; if so, the connection is made to the first broker in the list that is available. In general, it is better to use the failover exchange when using multiple brokers, since it allows applications to fail over if a broker goes down.
	</para>

	<example>
	  <title>Broker Lists</title>
	<para>A broker list can specify properties to be used when connecting to the broker, such as security options. This broker list specifies options for a Kerberos connection using GSSAPI:</para>
	<programlisting><![CDATA[
amqp://guest:guest@test/test?sync_ack='true'
    &brokerlist='tcp://ip1:5672?sasl_mechs='GSSAPI'
	]]></programlisting>

	<para>This broker list specifies SSL options:</para>

	<programlisting><![CDATA[
amqp://guest:guest@test/test?sync_ack='true'
   &brokerlist='tcp://ip1:5672?ssl='true'&ssl_cert_alias='cert1'
	]]></programlisting>
	</example>

	<para>The following broker list options are supported.</para>

        <table pgwide="1">
	  <title>Broker List Options</title>
	  <tgroup cols="3">
	    <thead>
	      <row>
	        <entry>
		  Option
	        </entry>
	        <entry>
		  Type
	        </entry>
	        <entry>
		  Description
	        </entry>
	      </row>
	    </thead>
	    <tbody>
	      <row>
	        <entry>
		  heartbeat
	        </entry>
	        <entry>
		  integer
	        </entry>
	        <entry>
		  frequency of heartbeat messages (in seconds)
	        </entry>
	      </row>
	      <row>
	        <entry>
		  sasl_mechs
	        </entry>
	        <entry>
		  --
	        </entry>
	        <entry>
		  For secure applications, we suggest CRAM-MD5,
		  DIGEST-MD5, or GSSAPI. The ANONYMOUS method is not
		  secure. The PLAIN method is secure only when used
		  together with SSL. For Kerberos, sasl_mechs must be
		  set to GSSAPI, sasl_protocol must be set to the
		  principal for the qpidd broker, e.g. qpidd/, and
		  sasl_server must be set to the host for the SASL
		  server, e.g. sasl.com.  SASL External is supported
		  using SSL certification, e.g.
		  <literal>ssl='true'&amp;sasl_mechs='EXTERNAL'</literal>
	        </entry>
	      </row>
	      <row>
	        <entry>
		  sasl_encryption
	        </entry>
	        <entry>
          Boolean  
	        </entry>
	        <entry>
          If <literal>sasl_encryption='true'</literal>, the JMS client attempts to negotiate a security layer with the broker using GSSAPI to encrypt the connection. Note that for this to happen, GSSAPI must be selected as the sasl_mech.
	        </entry>
	      </row>
	      <row>
	        <entry>
		  ssl
	        </entry>
	        <entry>
		  Boolean
	        </entry>
	        <entry>
		  If <literal>ssl='true'</literal>, the JMS client will encrypt the connection using SSL.
	        </entry>
	      </row>
	      <row>
	        <entry>
		  tcp_nodelay
	        </entry>
	        <entry>
		  Boolean
	        </entry>
	        <entry>
		  If <literal>tcp_nodelay='true'</literal>, TCP packet
		  batching is disabled.
	        </entry>
	      </row>
	      <row>
	        <entry>
		  sasl_protocol
	        </entry>
	        <entry>
		  --
	        </entry>
	        <entry>
		  Used only for
		  Kerberos. <literal>sasl_protocol</literal> must be
		  set to the principal for the qpidd broker,
		  e.g. <literal>qpidd/</literal>
	        </entry>
	      </row>
	      <row>
	        <entry>
		  sasl_server
	        </entry>
	        <entry>
		  --
	        </entry>
	        <entry>
		  For Kerberos, sasl_mechs must be set to GSSAPI,
		  sasl_server must be set to the host for the SASL
		  server, e.g. <literal>sasl.com</literal>.
	        </entry>
	      </row>
	      <row>
	        <entry>
		  trust_store
	        </entry>
	        <entry>
		  --
	        </entry>
	        <entry>
		  path to Keberos trust store
	        </entry>
	      </row>
	      <row>
	        <entry>
		  trust_store_password
	        </entry>
	        <entry>
	        </entry>
	        <entry>
		  Kerberos trust store password
	        </entry>
	      </row>
	      <row>
	        <entry>
		  key_store
	        </entry>
	        <entry>
	        </entry>
	        <entry>
		  path to Kerberos key store
	        </entry>
	      </row>
	      <row>
	        <entry>
		  key_store_password
	        </entry>
	        <entry>
		  --
	        </entry>
	        <entry>
		  Kerberos key store password
	        </entry>
	      </row>
	      <row>
	        <entry>
		  ssl_verify_hostname
	        </entry>
	        <entry>
		  Boolean
	        </entry>
	        <entry>
		  When using SSL you can enable hostname verification
		  by using "ssl_verify_hostname=true" in the broker
		  URL.
	        </entry>
	      </row>
	      <row>
	        <entry>
		  ssl_cert_alias
	        </entry>
	        <entry>

	        </entry>
	        <entry>
          If multiple certificates are present in the keystore, the alias will be used to extract the correct certificate.
	        </entry>
	      </row>
	    </tbody>
	  </tgroup>
	</table>
      </section>
    </section>  

    <section>
      <title>Java JMS Message Properties</title>

      <para>The following table shows how Qpid Messaging API message
        properties are mapped to AMQP 0-10 message properties and
        delivery properties. In this table <varname>msg</varname>
        refers to the Message class defined in the Qpid Messaging API,
        <varname>mp</varname> refers to an AMQP 0-10
        <varname>message-properties</varname> struct, and
        <varname>dp</varname> refers to an AMQP 0-10
        <varname>delivery-properties</varname> struct.</para>

      <table >
        <title>Java JMS Mapping to AMQP 0-10 Message Properties</title>
        <tgroup cols="2">
          <thead>
	    <row>
	      <entry>Java JMS Message Property</entry>
	      <entry>AMQP 0-10 Property<footnote><para>In these entries, <literal>mp</literal> refers to an AMQP message property, and <literal>dp</literal> refers to an AMQP delivery property.</para></footnote></entry>

	    </row>
          </thead>
          <tbody>
	    <row>
	      <entry>JMSMessageID</entry><entry>mp.message_id</entry>
	    </row>
	    <row>
	      <entry>qpid.subject<footnote><para>This is a custom JMS property, set automatically by the Java JMS client implementation.</para></footnote></entry><entry>mp.application_headers["qpid.subject"]</entry>
	    </row>
	    <row>
	      <entry>JMSXUserID</entry><entry>mp.user_id</entry>
	    </row>
	    <row>
	      <entry>JMSReplyTo</entry><entry>mp.reply_to<footnote><para>The reply_to is converted from the protocol representation into an address.</para></footnote></entry>
	    </row>
	    <row>
	      <entry>JMSCorrelationID</entry><entry>mp.correlation_id</entry>
	    </row>
	    <row>
	      <entry>JMSDeliveryMode</entry><entry>dp.delivery_mode</entry>
	    </row>
	    <row>
	      <entry>JMSPriority</entry><entry>dp.priority</entry>
	    </row>
	    <row>
	      <entry>JMSExpiration</entry><entry>dp.ttl<footnote><para>JMSExpiration = dp.ttl + currentTime</para></footnote></entry>
	    </row>
	    <row>
	      <entry>JMSRedelivered</entry><entry>dp.redelivered</entry>
	    </row>
	    <row>
	      <entry>JMS Properties</entry><entry>mp.application_headers</entry>
	    </row>
	    <row>
	      <entry>JMSType</entry><entry>mp.content_type</entry>
	    </row>
          </tbody>
        </tgroup>
      </table>
      
    </section>

    <section id="section-JMS-MapMessage">
      <title>JMS MapMessage Types</title>

      <para>Qpid supports the Java JMS <classname>MapMessage</classname> interface, which provides support for maps in messages. The following code shows how to send a <classname>MapMessage</classname> in Java JMS.</para>

      <example>
	<title>Sending a Java JMS MapMessage</title>
      <programlisting><![CDATA[
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.MapMessage;
import javax.jms.MessageProducer;
import javax.jms.Session;

import org.apache.qpid.client.AMQAnyDestination;
import org.apache.qpid.client.AMQConnection;

import edu.emory.mathcs.backport.java.util.Arrays;

// !!! SNIP !!!

MessageProducer producer = session.createProducer(queue);

MapMessage m = session.createMapMessage();
m.setIntProperty("Id", 987654321);
m.setStringProperty("name", "Widget");
m.setDoubleProperty("price", 0.99);

List<String> colors = new ArrayList<String>();
colors.add("red");
colors.add("green");
colors.add("white");        
m.setObject("colours", colors);

Map<String,Double> dimensions = new HashMap<String,Double>();
dimensions.put("length",10.2);
dimensions.put("width",5.1);
dimensions.put("depth",2.0);
m.setObject("dimensions",dimensions);

List<List<Integer>> parts = new ArrayList<List<Integer>>();
parts.add(Arrays.asList(new Integer[] {1,2,5}));
parts.add(Arrays.asList(new Integer[] {8,2,5}));
m.setObject("parts", parts);

Map<String,Object> specs = new HashMap<String,Object>();
specs.put("colours", colors);
specs.put("dimensions", dimensions);
specs.put("parts", parts);
m.setObject("specs",specs);

producer.send(m);
      ]]></programlisting>
      </example>

      <para>The following table shows the datatypes that can be sent in a <classname>MapMessage</classname>, and the corresponding datatypes that will be received by clients in Python or C++.</para>
      
      <table id="table-Java-Maps">
	<title>Java Datatypes in Maps</title>
	<tgroup cols="3">
	  <thead>
	    <row>
	      <entry>Java Datatype</entry>
	      <entry>&rarr; Python</entry>
	      <entry>&rarr; C++</entry>
	    </row>
	  </thead>
	  <tbody>
   	    <row><entry>boolean</entry><entry>bool</entry><entry>bool</entry></row>
	    <row><entry>char</entry><entry>unicode<footnote><para>The Python string will contain one Unicode character</para></footnote></entry><entry>int</entry></row>
	    <row><entry>short</entry><entry>integer | long</entry><entry>short</entry></row>
	    <row><entry>integer</entry><entry>integer | long</entry><entry>int</entry></row>
	    <row><entry>long</entry><entry>integer | long</entry><entry>long</entry></row>
	    <row><entry>float</entry><entry>float</entry><entry>float</entry></row>
	    <row><entry>double</entry><entry>float</entry><entry>double</entry></row>
	    <row><entry>java.lang.String</entry><entry>unicode</entry><entry>std::string</entry></row>
	    <row><entry>java.util.UUID</entry><entry>uuid</entry><entry>qpid::types::Uuid</entry></row>
	    <row><entry>java.util.Map</entry><entry>dict</entry><entry>Variant::Map</entry></row>
	    <row><entry>java.util.List</entry><entry>list</entry><entry>Variant::List</entry></row>
	  </tbody>
	</tgroup>
      </table>

    </section>

    <section>
      <title>Java JMS Selector Syntax</title>
      <para>The AMQP Java JMS Messaging Client supports the following syntax for JMS selectors.</para>


      <formalpara><title>Comments:</title>
      <para>
      <programlisting><![CDATA[LINE_COMMENT: "--" (~["\n","\r"])* EOL
EOL: "\n"|"\r"|"\r\n"
BLOCK_COMMENT: "/*" (~["*"])* "*" ("*" | (~["*","/"] (~["*"])* "*"))* "/"
]]></programlisting>
      </para>
      </formalpara>

      <formalpara><title>Reserved Words (case insensitive)</title>
      <para>
      <programlisting><![CDATA[NOT:     "NOT"
AND:     "AND"
OR:      "OR"
BETWEEN: "BETWEEN"
LIKE:    "LIKE"
ESCAPE:  "ESCAPE"
IN:      "IN"
IS:      "IS"
TRUE:    "TRUE"
FALSE:   "FALSE"
NULL:    "NULL"
]]></programlisting>
      </para>
      </formalpara>

      <formalpara><title>Literals (case insensitive)</title>
      <para>
      <programlisting><![CDATA[DECIMAL_LITERAL:        ["1"-"9"] (["0"-"9"])* (["l","L"])?
HEX_LITERAL:            "0" ["x","X"] (["0"-"9","a"-"f","A"-"F"])+
OCTAL_LITERAL:          "0" (["0"-"7"])*
FLOATING_POINT_LITERAL: ( 
 (["0"-"9"])+ "." (["0"-"9"])* (<EXPONENT>)? // eg: 5.5 or 5. or 5.5E10 or 5.E10
  | "." (["0"-"9"])+ (<EXPONENT>)?           // eg: .5 or .5E10
  | (["0"-"9"])+ <EXPONENT>                  // eg: 5E10
)                 
EXPONENT:               "E" (["+","-"])? (["0"-"9"])+
STRING_LITERAL:         "'" ( ("''") | ~["'"] )*  "'"
]]></programlisting>
      </para>
      </formalpara>


      <formalpara><title>Identifiers (case insensitive)</title>
      <para>
      <programlisting><![CDATA[ID : ["a"-"z", "_", "$"] (["a"-"z","0"-"9","_", "$"])*
QUOTED_ID : "\"" ( ("\"\"") | ~["\""] )*  "\""
]]></programlisting>
      </para>
      </formalpara>


      <formalpara><title>Grammar</title>
      <para>
      <programlisting><![CDATA[JmsSelector        := orExpression
orExpression       := ( andExpression ( <OR> andExpression )* )
andExpression      := ( equalityExpression ( <AND> equalityExpression )* )
equalityExpression := ( comparisonExpression (   "=" comparisonExpression
                                                 | "<>" comparisonExpression
                                                 | <IS> <NULL>
                                                 | <IS> <NOT> <NULL> )* )
comparisonExpression := 
    ( addExpression 
      (   ">" addExpression
        | ">=" addExpression
        | "<" addExpression
        | "<=" addExpression
        | <LIKE> stringLitteral ( <ESCAPE> stringLitteral )?
        | <NOT> <LIKE> <STRING_LITERAL> ( <ESCAPE> <STRING_LITERAL> )?
        | <BETWEEN> addExpression <AND> addExpression
        | <NOT> <BETWEEN> addExpression <AND> addExpression
        | <IN> "(" <STRING_LITERAL> ( "," <STRING_LITERAL> )* ")"
        | <NOT> <IN> "(" <STRING_LITERAL> ( "," <STRING_LITERAL> )* ")" 
      )*  
    )

addExpression := multExpr ( ( "+" multExpr | "-" multExpr ) )*
multExpr      := unaryExpr ( "*" unaryExpr | "/" unaryExpr | "%" unaryExpr )*
unaryExpr     := ( "+" unaryExpr | "-" unaryExpr | <NOT> unaryExpr | primaryExpr )
primaryExpr   := ( literal | variable | "(" orExpression ")" )
literal       := (   <STRING_LITERAL>
                   | <DECIMAL_LITERAL>
                   | <HEX_LITERAL>
                   | <OCTAL_LITERAL>
                   | <FLOATING_POINT_LITERAL>
                   | <TRUE>
                   | <FALSE>
                   | <NULL> 
                 )

variable             := ( <ID> | <QUOTED_ID> )]]></programlisting>
      </para>
      </formalpara>

    </section>

  </chapter>
</book>

<!--
   - client code remains exactly the same, but routing behavior
   changes
   - exchanges drop messages if nobody is listening, so we need to
   start drain first
   - drain will exit immediately if the source is empty (note that
   this is actually a semantic guarantee provided by the API, we
   know for a fact that the source is empty when drain/fetch
   reports it, no fudge factor timeout is required [this assumes
   nobody is concurrently publishing of course])
   - drain -f invokes blocking fetch (you could use a timeout here also)
  -->