API Overview API Index Package Overview Direct link to this page
JDK 1.6
  java.net. URI View Javadoc
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
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505

/*
 * @(#)URI.java	1.48 06/06/12
 *
 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
 * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

package java.net;

import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CoderResult;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.CharacterCodingException;
import java.text.Normalizer;
import sun.nio.cs.ThreadLocalCoders;

import java.lang.Character;		// for javadoc
import java.lang.NullPointerException;	// for javadoc


/**
 * Represents a Uniform Resource Identifier (URI) reference.
 *
 * <p> Aside from some minor deviations noted below, an instance of this 
 * class represents a URI reference as defined by
 * <a href="http://www.ietf.org/rfc/rfc2396.txt""><i>RFC&nbsp;2396: Uniform
 * Resource Identifiers (URI): Generic Syntax</i></a>, amended by <a
 * href="http://www.ietf.org/rfc/rfc2732.txt"><i>RFC&nbsp;2732: Format for
 * Literal IPv6 Addresses in URLs</i></a>. The Literal IPv6 address format
 * also supports scope_ids. The syntax and usage of scope_ids is described
 * <a href="Inet6Address.html#scoped">here</a>.
 * This class provides constructors for creating URI instances from
 * their components or by parsing their string forms, methods for accessing the
 * various components of an instance, and methods for normalizing, resolving,
 * and relativizing URI instances.  Instances of this class are immutable.
 *
 *
 * <h4> URI syntax and components </h4>
 *
 * At the highest level a URI reference (hereinafter simply "URI") in string
 * form has the syntax
 *
 * <blockquote>
 * [<i>scheme</i><tt><b>:</b></tt><i></i>]<i>scheme-specific-part</i>[<tt><b>#</b></tt><i>fragment</i>]
 * </blockquote>
 *
 * where square brackets [...] delineate optional components and the characters
 * <tt><b>:</b></tt> and <tt><b>#</b></tt> stand for themselves.
 *
 * <p> An <i>absolute</i> URI specifies a scheme; a URI that is not absolute is
 * said to be <i>relative</i>.  URIs are also classified according to whether
 * they are <i>opaque</i> or <i>hierarchical</i>.
 *
 * <p> An <i>opaque</i> URI is an absolute URI whose scheme-specific part does
 * not begin with a slash character (<tt>'/'</tt>).  Opaque URIs are not
 * subject to further parsing.  Some examples of opaque URIs are:
 *
 * <blockquote><table cellpadding=0 cellspacing=0 summary="layout">
 * <tr><td><tt>mailto:java-net@java.sun.com</tt><td></tr>
 * <tr><td><tt>news:comp.lang.java</tt><td></tr>
 * <tr><td><tt>urn:isbn:096139210x</tt></td></tr>
 * </table></blockquote>
 *
 * <p> A <i>hierarchical</i> URI is either an absolute URI whose
 * scheme-specific part begins with a slash character, or a relative URI, that
 * is, a URI that does not specify a scheme.  Some examples of hierarchical
 * URIs are:
 *
 * <blockquote>
 * <tt>http://java.sun.com/j2se/1.3/</tt><br>
 * <tt>docs/guide/collections/designfaq.html#28</tt><br>
 * <tt>../../../demo/jfc/SwingSet2/src/SwingSet2.java</tt><br>
 * <tt>file:///~/calendar</tt>
 * </blockquote>
 *
 * <p> A hierarchical URI is subject to further parsing according to the syntax
 *
 * <blockquote>
 * [<i>scheme</i><tt><b>:</b></tt>][<tt><b>//</b></tt><i>authority</i>][<i>path</i>][<tt><b>?</b></tt><i>query</i>][<tt><b>#</b></tt><i>fragment</i>]
 * </blockquote>
 *
 * where the characters <tt><b>:</b></tt>, <tt><b>/</b></tt>,
 * <tt><b>?</b></tt>, and <tt><b>#</b></tt> stand for themselves.  The
 * scheme-specific part of a hierarchical URI consists of the characters
 * between the scheme and fragment components.
 *
 * <p> The authority component of a hierarchical URI is, if specified, either
 * <i>server-based</i> or <i>registry-based</i>.  A server-based authority
 * parses according to the familiar syntax
 *
 * <blockquote>
 * [<i>user-info</i><tt><b>@</b></tt>]<i>host</i>[<tt><b>:</b></tt><i>port</i>]
 * </blockquote>
 *
 * where the characters <tt><b>@</b></tt> and <tt><b>:</b></tt> stand for
 * themselves.  Nearly all URI schemes currently in use are server-based.  An
 * authority component that does not parse in this way is considered to be
 * registry-based.
 *
 * <p> The path component of a hierarchical URI is itself said to be absolute
 * if it begins with a slash character (<tt>'/'</tt>); otherwise it is
 * relative.  The path of a hierarchical URI that is either absolute or
 * specifies an authority is always absolute.
 *
 * <p> All told, then, a URI instance has the following nine components:
 *
 * <blockquote><table summary="Describes the components of a URI:scheme,scheme-specific-part,authority,user-info,host,port,path,query,fragment">
 * <tr><th><i>Component</i></th><th><i>Type</i></th></tr>
 * <tr><td>scheme</td><td><tt>String</tt></td></tr>
 * <tr><td>scheme-specific-part&nbsp;&nbsp;&nbsp;&nbsp;</td><td><tt>String</tt></td></tr>
 * <tr><td>authority</td><td><tt>String</tt></td></tr>
 * <tr><td>user-info</td><td><tt>String</tt></td></tr>
 * <tr><td>host</td><td><tt>String</tt></td></tr>
 * <tr><td>port</td><td><tt>int</tt></td></tr>
 * <tr><td>path</td><td><tt>String</tt></td></tr>
 * <tr><td>query</td><td><tt>String</tt></td></tr>
 * <tr><td>fragment</td><td><tt>String</tt></td></tr>
 * </table></blockquote>
 *
 * In a given instance any particular component is either <i>undefined</i> or
 * <i>defined</i> with a distinct value.  Undefined string components are
 * represented by <tt>null</tt>, while undefined integer components are
 * represented by <tt>-1</tt>.  A string component may be defined to have the
 * empty string as its value; this is not equivalent to that component being
 * undefined.
 *
 * <p> Whether a particular component is or is not defined in an instance
 * depends upon the type of the URI being represented.  An absolute URI has a
 * scheme component.  An opaque URI has a scheme, a scheme-specific part, and
 * possibly a fragment, but has no other components.  A hierarchical URI always
 * has a path (though it may be empty) and a scheme-specific-part (which at
 * least contains the path), and may have any of the other components.  If the
 * authority component is present and is server-based then the host component
 * will be defined and the user-information and port components may be defined.
 *
 *
 * <h4> Operations on URI instances </h4>
 *
 * The key operations supported by this class are those of
 * <i>normalization</i>, <i>resolution</i>, and <i>relativization</i>.
 *
 * <p> <i>Normalization</i> is the process of removing unnecessary <tt>"."</tt>
 * and <tt>".."</tt> segments from the path component of a hierarchical URI.
 * Each <tt>"."</tt> segment is simply removed.  A <tt>".."</tt> segment is
 * removed only if it is preceded by a non-<tt>".."</tt> segment.
 * Normalization has no effect upon opaque URIs.
 *
 * <p> <i>Resolution</i> is the process of resolving one URI against another,
 * <i>base</i> URI.  The resulting URI is constructed from components of both
 * URIs in the manner specified by RFC&nbsp;2396, taking components from the
 * base URI for those not specified in the original.  For hierarchical URIs,
 * the path of the original is resolved against the path of the base and then
 * normalized.  The result, for example, of resolving
 *
 * <blockquote>
 * <tt>docs/guide/collections/designfaq.html#28&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt>(1)
 * </blockquote>
 *
 * against the base URI <tt>http://java.sun.com/j2se/1.3/</tt> is the result
 * URI
 *
 * <blockquote>
 * <tt>http://java.sun.com/j2se/1.3/docs/guide/collections/designfaq.html#28</tt>
 * </blockquote>
 *
 * Resolving the relative URI
 *
 * <blockquote>
 * <tt>../../../demo/jfc/SwingSet2/src/SwingSet2.java&nbsp;&nbsp;&nbsp;&nbsp;</tt>(2)
 * </blockquote>
 *
 * against this result yields, in turn,
 *
 * <blockquote>
 * <tt>http://java.sun.com/j2se/1.3/demo/jfc/SwingSet2/src/SwingSet2.java</tt>
 * </blockquote>
 *
 * Resolution of both absolute and relative URIs, and of both absolute and
 * relative paths in the case of hierarchical URIs, is supported.  Resolving
 * the URI <tt>file:///~calendar</tt> against any other URI simply yields the
 * original URI, since it is absolute.  Resolving the relative URI (2) above
 * against the relative base URI (1) yields the normalized, but still relative,
 * URI
 *
 * <blockquote>
 * <tt>demo/jfc/SwingSet2/src/SwingSet2.java</tt>
 * </blockquote>
 *
 * <p> <i>Relativization</i>, finally, is the inverse of resolution: For any
 * two normalized URIs <i>u</i> and&nbsp;<i>v</i>,
 *
 * <blockquote>
 *   <i>u</i><tt>.relativize(</tt><i>u</i><tt>.resolve(</tt><i>v</i><tt>)).equals(</tt><i>v</i><tt>)</tt>&nbsp;&nbsp;and<br>
 *   <i>u</i><tt>.resolve(</tt><i>u</i><tt>.relativize(</tt><i>v</i><tt>)).equals(</tt><i>v</i><tt>)</tt>&nbsp;&nbsp;.<br>
 * </blockquote>
 *
 * This operation is often useful when constructing a document containing URIs
 * that must be made relative to the base URI of the document wherever
 * possible.  For example, relativizing the URI
 *
 * <blockquote>
 * <tt>http://java.sun.com/j2se/1.3/docs/guide/index.html</tt>
 * </blockquote>
 *
 * against the base URI
 *
 * <blockquote>
 * <tt>http://java.sun.com/j2se/1.3</tt>
 * </blockquote>
 *
 * yields the relative URI <tt>docs/guide/index.html</tt>.
 *
 *
 * <h4> Character categories </h4>
 *
 * RFC&nbsp;2396 specifies precisely which characters are permitted in the
 * various components of a URI reference.  The following categories, most of
 * which are taken from that specification, are used below to describe these
 * constraints:
 *
 * <blockquote><table cellspacing=2 summary="Describes categories alpha,digit,alphanum,unreserved,punct,reserved,escaped,and other">
 *   <tr><th valign=top><i>alpha</i></th>
 *       <td>The US-ASCII alphabetic characters,
 * 	  <tt>'A'</tt>&nbsp;through&nbsp;<tt>'Z'</tt>
 * 	  and <tt>'a'</tt>&nbsp;through&nbsp;<tt>'z'</tt></td></tr>
 *   <tr><th valign=top><i>digit</i></th>
 *       <td>The US-ASCII decimal digit characters,
 *       <tt>'0'</tt>&nbsp;through&nbsp;<tt>'9'</tt></td></tr>
 *   <tr><th valign=top><i>alphanum</i></th>
 *       <td>All <i>alpha</i> and <i>digit</i> characters</td></tr>
 *   <tr><th valign=top><i>unreserved</i>&nbsp;&nbsp;&nbsp;&nbsp;</th>
 *       <td>All <i>alphanum</i> characters together with those in the string
 * 	  <tt>"_-!.~'()*"</tt></td></tr>
 *   <tr><th valign=top><i>punct</i></th>
 *       <td>The characters in the string <tt>",;:$&+="</tt></td></tr>
 *   <tr><th valign=top><i>reserved</i></th>
 *       <td>All <i>punct</i> characters together with those in the string
 * 	  <tt>"?/[]@"</tt></td></tr>
 *   <tr><th valign=top><i>escaped</i></th>
 *       <td>Escaped octets, that is, triplets consisting of the percent
 *           character (<tt>'%'</tt>) followed by two hexadecimal digits
 *           (<tt>'0'</tt>-<tt>'9'</tt>, <tt>'A'</tt>-<tt>'F'</tt>, and
 *           <tt>'a'</tt>-<tt>'f'</tt>)</td></tr>
 *   <tr><th valign=top><i>other</i></th>
 *       <td>The Unicode characters that are not in the US-ASCII character set,
 *           are not control characters (according to the {@link
 *           java.lang.Character#isISOControl(char) Character.isISOControl}
 * 	     method), and are not space characters (according to the {@link
 * 	     java.lang.Character#isSpaceChar(char) Character.isSpaceChar}
 * 	     method)&nbsp;&nbsp;<i>(<b>Deviation from RFC 2396</b>, which is
 * 	     limited to US-ASCII)</i></td></tr>
 * </table></blockquote>
 *
 * <p><a name="legal-chars"></a> The set of all legal URI characters consists of
 * the <i>unreserved</i>, <i>reserved</i>, <i>escaped</i>, and <i>other</i>
 * characters.
 *
 *
 * <h4> Escaped octets, quotation, encoding, and decoding </h4>
 *
 * RFC 2396 allows escaped octets to appear in the user-info, path, query, and
 * fragment components.  Escaping serves two purposes in URIs:
 *
 * <ul>
 *
 *   <li><p> To <i>encode</i> non-US-ASCII characters when a URI is required to
 *   conform strictly to RFC&nbsp;2396 by not containing any <i>other</i>
 *   characters.  </p></li>
 *
 *   <li><p> To <i>quote</i> characters that are otherwise illegal in a
 *   component.  The user-info, path, query, and fragment components differ
 *   slightly in terms of which characters are considered legal and illegal.
 *   </p></li>
 *
 * </ul>
 *
 * These purposes are served in this class by three related operations:
 *
 * <ul>
 *
 *   <li><p><a name="encode"></a> A character is <i>encoded</i> by replacing it
 *   with the sequence of escaped octets that represent that character in the
 *   UTF-8 character set.  The Euro currency symbol (<tt>'&#92;u20AC'</tt>),
 *   for example, is encoded as <tt>"%E2%82%AC"</tt>.  <i>(<b>Deviation from
 *   RFC&nbsp;2396</b>, which does not specify any particular character
 *   set.)</i> </p></li>
 *
 *   <li><p><a name="quote"></a> An illegal character is <i>quoted</i> simply by
 *   encoding it.  The space character, for example, is quoted by replacing it
 *   with <tt>"%20"</tt>.  UTF-8 contains US-ASCII, hence for US-ASCII
 *   characters this transformation has exactly the effect required by
 *   RFC&nbsp;2396. </p></li>
 *
 *   <li><p><a name="decode"></a>
 *   A sequence of escaped octets is <i>decoded</i> by
 *   replacing it with the sequence of characters that it represents in the
 *   UTF-8 character set.  UTF-8 contains US-ASCII, hence decoding has the
 *   effect of de-quoting any quoted US-ASCII characters as well as that of
 *   decoding any encoded non-US-ASCII characters.  If a <a
 *   href="../nio/charset/CharsetDecoder.html#ce">decoding error</a> occurs
 *   when decoding the escaped octets then the erroneous octets are replaced by
 *   <tt>'&#92;uFFFD'</tt>, the Unicode replacement character.  </p></li>
 *
 * </ul>
 *
 * These operations are exposed in the constructors and methods of this class
 * as follows:
 *
 * <ul>
 *
 *   <li><p> The {@link #URI(java.lang.String) <code>single-argument
 *   constructor</code>} requires any illegal characters in its argument to be
 *   quoted and preserves any escaped octets and <i>other</i> characters that
 *   are present.  </p></li>
 *
 *   <li><p> The {@link
 *   #URI(java.lang.String,java.lang.String,java.lang.String,int,java.lang.String,java.lang.String,java.lang.String)
 *   <code>multi-argument constructors</code>} quote illegal characters as
 *   required by the components in which they appear.  The percent character
 *   (<tt>'%'</tt>) is always quoted by these constructors.  Any <i>other</i>
 *   characters are preserved.  </p></li>
 *
 *   <li><p> The {@link #getRawUserInfo() getRawUserInfo}, {@link #getRawPath()
 *   getRawPath}, {@link #getRawQuery() getRawQuery}, {@link #getRawFragment()
 *   getRawFragment}, {@link #getRawAuthority() getRawAuthority}, and {@link
 *   #getRawSchemeSpecificPart() getRawSchemeSpecificPart} methods return the
 *   values of their corresponding components in raw form, without interpreting
 *   any escaped octets.  The strings returned by these methods may contain
 *   both escaped octets and <i>other</i> characters, and will not contain any
 *   illegal characters.  </p></li>
 *
 *   <li><p> The {@link #getUserInfo() getUserInfo}, {@link #getPath()
 *   getPath}, {@link #getQuery() getQuery}, {@link #getFragment()
 *   getFragment}, {@link #getAuthority() getAuthority}, and {@link
 *   #getSchemeSpecificPart() getSchemeSpecificPart} methods decode any escaped
 *   octets in their corresponding components.  The strings returned by these
 *   methods may contain both <i>other</i> characters and illegal characters,
 *   and will not contain any escaped octets.  </p></li>
 *
 *   <li><p> The {@link #toString() toString} method returns a URI string with
 *   all necessary quotation but which may contain <i>other</i> characters.
 *   </p></li>
 *
 *   <li><p> The {@link #toASCIIString() toASCIIString} method returns a fully
 *   quoted and encoded URI string that does not contain any <i>other</i>
 *   characters.  </p></li>
 *
 * </ul>
 *
 *
 * <h4> Identities </h4>
 *
 * For any URI <i>u</i>, it is always the case that
 *
 * <blockquote>
 * <tt>new URI(</tt><i>u</i><tt>.toString()).equals(</tt><i>u</i><tt>)</tt>&nbsp;.
 * </blockquote>
 *
 * For any URI <i>u</i> that does not contain redundant syntax such as two
 * slashes before an empty authority (as in <tt>file:///tmp/</tt>&nbsp;) or a
 * colon following a host name but no port (as in
 * <tt>http://java.sun.com:</tt>&nbsp;), and that does not encode characters
 * except those that must be quoted, the following identities also hold:
 *
 * <blockquote>
 * <tt>new URI(</tt><i>u</i><tt>.getScheme(),<br>
 * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt><i>u</i><tt>.getSchemeSpecificPart(),<br>
 * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt><i>u</i><tt>.getFragment())<br>
 * .equals(</tt><i>u</i><tt>)</tt>
 * </blockquote>
 *
 * in all cases,
 *
 * <blockquote>
 * <tt>new URI(</tt><i>u</i><tt>.getScheme(),<br>
 * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt><i>u</i><tt>.getUserInfo(),&nbsp;</tt><i>u</i><tt>.getAuthority(),<br>
 * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt><i>u</i><tt>.getPath(),&nbsp;</tt><i>u</i><tt>.getQuery(),<br>
 * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt><i>u</i><tt>.getFragment())<br>
 * .equals(</tt><i>u</i><tt>)</tt>
 * </blockquote>
 *
 * if <i>u</i> is hierarchical, and
 *
 * <blockquote>
 * <tt>new URI(</tt><i>u</i><tt>.getScheme(),<br>
 * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt><i>u</i><tt>.getUserInfo(),&nbsp;</tt><i>u</i><tt>.getHost(),&nbsp;</tt><i>u</i><tt>.getPort(),<br>
 * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt><i>u</i><tt>.getPath(),&nbsp;</tt><i>u</i><tt>.getQuery(),<br>
 * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt><i>u</i><tt>.getFragment())<br>
 * .equals(</tt><i>u</i><tt>)</tt>
 * </blockquote>
 *
 * if <i>u</i> is hierarchical and has either no authority or a server-based
 * authority.
 *
 *
 * <h4> URIs, URLs, and URNs </h4>
 *
 * A URI is a uniform resource <i>identifier</i> while a URL is a uniform
 * resource <i>locator</i>.  Hence every URL is a URI, abstractly speaking, but
 * not every URI is a URL.  This is because there is another subcategory of
 * URIs, uniform resource <i>names</i> (URNs), which name resources but do not
 * specify how to locate them.  The <tt>mailto</tt>, <tt>news</tt>, and
 * <tt>isbn</tt> URIs shown above are examples of URNs.
 *
 * <p> The conceptual distinction between URIs and URLs is reflected in the
 * differences between this class and the {@link URL} class.
 *
 * <p> An instance of this class represents a URI reference in the syntactic
 * sense defined by RFC&nbsp;2396.  A URI may be either absolute or relative.
 * A URI string is parsed according to the generic syntax without regard to the
 * scheme, if any, that it specifies.  No lookup of the host, if any, is
 * performed, and no scheme-dependent stream handler is constructed.  Equality,
 * hashing, and comparison are defined strictly in terms of the character
 * content of the instance.  In other words, a URI instance is little more than
 * a structured string that supports the syntactic, scheme-independent
 * operations of comparison, normalization, resolution, and relativization.
 *
 * <p> An instance of the {@link URL} class, by contrast, represents the
 * syntactic components of a URL together with some of the information required
 * to access the resource that it describes.  A URL must be absolute, that is,
 * it must always specify a scheme.  A URL string is parsed according to its
 * scheme.  A stream handler is always established for a URL, and in fact it is
 * impossible to create a URL instance for a scheme for which no handler is
 * available.  Equality and hashing depend upon both the scheme and the
 * Internet address of the host, if any; comparison is not defined.  In other
 * words, a URL is a structured string that supports the syntactic operation of
 * resolution as well as the network I/O operations of looking up the host and
 * opening a connection to the specified resource.
 *
 *
 * @version 1.48, 06/06/12
 * @author Mark Reinhold
 * @since 1.4
 *
 * @see <a href="http://ietf.org/rfc/rfc2279.txt"><i>RFC&nbsp;2279: UTF-8, a
 * transformation format of ISO 10646</i></a>, <br><a
 * href="http://www.ietf.org/rfc/rfc2373.txt"><i>RFC&nbsp;2373: IPv6 Addressing
 * Architecture</i></a>, <br><a
 * href="http://www.ietf.org/rfc/rfc2396.txt""><i>RFC&nbsp;2396: Uniform
 * Resource Identifiers (URI): Generic Syntax</i></a>, <br><a
 * href="http://www.ietf.org/rfc/rfc2732.txt"><i>RFC&nbsp;2732: Format for
 * Literal IPv6 Addresses in URLs</i></a>, <br><a
 * href="URISyntaxException.html">URISyntaxException</a>
 */

public final class URI implements Comparable<URI>, Serializable
{

    // Note: Comments containing the word "ASSERT" indicate places where a
    // throw of an InternalError should be replaced by an appropriate assertion
    // statement once asserts are enabled in the build.

    static final long serialVersionUID = -6052424284110960213L;


    // -- Properties and components of this instance --

    // Components of all URIs: [<scheme>:]<scheme-specific-part>[#<fragment>]
    private transient String scheme;		// null ==> relative URI
    private transient String fragment;

    // Hierarchical URI components: [//<authority>]<path>[?<query>]
    private transient String authority;		// Registry or server

    // Server-based authority: [<userInfo>@]<host>[:<port>]
    private transient String userInfo;
    private transient String host;		// null ==> registry-based
    private transient int port = -1;		// -1 ==> undefined

    // Remaining components of hierarchical URIs
    private transient String path;		// null ==> opaque
    private transient String query;

    // The remaining fields may be computed on demand

    private volatile transient String schemeSpecificPart;
    private volatile transient int hash;	// Zero ==> undefined

    private volatile transient String decodedUserInfo = null;
    private volatile transient String decodedAuthority = null;
    private volatile transient String decodedPath = null;
    private volatile transient String decodedQuery = null;
    private volatile transient String decodedFragment = null;
    private volatile transient String decodedSchemeSpecificPart = null;

    /**
     * The string form of this URI.
     *
     * @serial
     */
    private volatile String string;		// The only serializable field



    // -- Constructors and factories --

    private URI() { }				// Used internally

    /**
     * Constructs a URI by parsing the given string.
     *
     * <p> This constructor parses the given string exactly as specified by the
     * grammar in <a
     * href="http://www.ietf.org/rfc/rfc2396.txt">RFC&nbsp;2396</a>,
     * Appendix&nbsp;A, <b><i>except for the following deviations:</i></b> </p>
     *
     * <ul type=disc>
     *
     *   <li><p> An empty authority component is permitted as long as it is
     *   followed by a non-empty path, a query component, or a fragment
     *   component.  This allows the parsing of URIs such as
     *   <tt>"file:///foo/bar"</tt>, which seems to be the intent of
     *   RFC&nbsp;2396 although the grammar does not permit it.  If the
     *   authority component is empty then the user-information, host, and port
     *   components are undefined. </p></li>
     *
     *   <li><p> Empty relative paths are permitted; this seems to be the
     *   intent of RFC&nbsp;2396 although the grammar does not permit it.  The
     *   primary consequence of this deviation is that a standalone fragment
     *   such as <tt>"#foo"</tt> parses as a relative URI with an empty path
     *   and the given fragment, and can be usefully <a
     *   href="#resolve-frag">resolved</a> against a base URI.
     *
     *   <li><p> IPv4 addresses in host components are parsed rigorously, as
     *   specified by <a
     *   href="http://www.ietf.org/rfc/rfc2732.txt">RFC&nbsp;2732</a>: Each
     *   element of a dotted-quad address must contain no more than three
     *   decimal digits.  Each element is further constrained to have a value
     *   no greater than 255. </p></li>
     *
     *   <li> <p> Hostnames in host components that comprise only a single
     *   domain label are permitted to start with an <i>alphanum</i> 
     *   character. This seems to be the intent of <a
     *   href="http://www.ietf.org/rfc/rfc2396.txt">RFC&nbsp;2396</a>
     *   section&nbsp;3.2.2 although the grammar does not permit it. The
     *   consequence of this deviation is that the authority component of a
     *   hierarchical URI such as <tt>s://123</tt>, will parse as a server-based 
     *   authority. </p></li>
     *
     *   <li><p> IPv6 addresses are permitted for the host component.  An IPv6
     *   address must be enclosed in square brackets (<tt>'['</tt> and
     *   <tt>']'</tt>) as specified by <a
     *   href="http://www.ietf.org/rfc/rfc2732.txt">RFC&nbsp;2732</a>.  The
     *   IPv6 address itself must parse according to <a
     *   href="http://www.ietf.org/rfc/rfc2373.txt">RFC&nbsp;2373</a>.  IPv6
     *   addresses are further constrained to describe no more than sixteen
     *   bytes of address information, a constraint implicit in RFC&nbsp;2373
     *   but not expressible in the grammar. </p></li>
     *
     *   <li><p> Characters in the <i>other</i> category are permitted wherever
     *   RFC&nbsp;2396 permits <i>escaped</i> octets, that is, in the
     *   user-information, path, query, and fragment components, as well as in
     *   the authority component if the authority is registry-based.  This
     *   allows URIs to contain Unicode characters beyond those in the US-ASCII
     *   character set. </p></li>
     *
     * </ul>
     *
     * @param  str   The string to be parsed into a URI
     *
     * @throws  NullPointerException
     *          If <tt>str</tt> is <tt>null</tt>
     *
     * @throws  URISyntaxException
     *          If the given string violates RFC&nbsp;2396, as augmented
     *          by the above deviations
     */
    public URI(String str) throws URISyntaxException {
	new Parser(str).parse(false);
    }

    /**
     * Constructs a hierarchical URI from the given components.
     *
     * <p> If a scheme is given then the path, if also given, must either be
     * empty or begin with a slash character (<tt>'/'</tt>).  Otherwise a
     * component of the new URI may be left undefined by passing <tt>null</tt>
     * for the corresponding parameter or, in the case of the <tt>port</tt>
     * parameter, by passing <tt>-1</tt>.
     *
     * <p> This constructor first builds a URI string from the given components
     * according to the rules specified in <a
     * href="http://www.ietf.org/rfc/rfc2396.txt">RFC&nbsp;2396</a>,
     * section&nbsp;5.2, step&nbsp;7: </p>
     *
     * <ol>
     *
     *   <li><p> Initially, the result string is empty. </p></li>
     *
     *   <li><p> If a scheme is given then it is appended to the result,
     *   followed by a colon character (<tt>':'</tt>).  </p></li>
     *
     *   <li><p> If user information, a host, or a port are given then the
     *   string <tt>"//"</tt> is appended.  </p></li>
     *
     *   <li><p> If user information is given then it is appended, followed by
     *   a commercial-at character (<tt>'@'</tt>).  Any character not in the
     *   <i>unreserved</i>, <i>punct</i>, <i>escaped</i>, or <i>other</i>
     *   categories is <a href="#quote">quoted</a>.  </p></li>
     *
     *   <li><p> If a host is given then it is appended.  If the host is a
     *   literal IPv6 address but is not enclosed in square brackets
     *   (<tt>'['</tt> and <tt>']'</tt>) then the square brackets are added.
     *   </p></li>
     *
     *   <li><p> If a port number is given then a colon character
     *   (<tt>':'</tt>) is appended, followed by the port number in decimal.
     *   </p></li>
     *
     *   <li><p> If a path is given then it is appended.  Any character not in
     *   the <i>unreserved</i>, <i>punct</i>, <i>escaped</i>, or <i>other</i>
     *   categories, and not equal to the slash character (<tt>'/'</tt>) or the
     *   commercial-at character (<tt>'@'</tt>), is quoted.  </p></li>
     *
     *   <li><p> If a query is given then a question-mark character
     *   (<tt>'?'</tt>) is appended, followed by the query.  Any character that
     *   is not a <a href="#legal-chars">legal URI character</a> is quoted.
     *   </p></li>
     *
     *   <li><p> Finally, if a fragment is given then a hash character
     *   (<tt>'#'</tt>) is appended, followed by the fragment.  Any character
     *   that is not a legal URI character is quoted.  </p></li>
     *
     * </ol>
     *
     * <p> The resulting URI string is then parsed as if by invoking the {@link
     * #URI(String)} constructor and then invoking the {@link
     * #parseServerAuthority()} method upon the result; this may cause a {@link
     * URISyntaxException} to be thrown.  </p>
     *
     * @param   scheme    Scheme name
     * @param   userInfo  User name and authorization information
     * @param   host      Host name
     * @param   port      Port number
     * @param   path      Path
     * @param   query     Query
     * @param   fragment  Fragment
     *
     * @throws URISyntaxException
     *         If both a scheme and a path are given but the path is relative,
     *         if the URI string constructed from the given components violates
     *         RFC&nbsp;2396, or if the authority component of the string is
     *         present but cannot be parsed as a server-based authority
     */
    public URI(String scheme,
               String userInfo, String host, int port,
               String path, String query, String fragment)
	throws URISyntaxException
    {
	String s = toString(scheme, null,
			    null, userInfo, host, port,
			    path, query, fragment);
	checkPath(s, scheme, path);
	new Parser(s).parse(true);
    }

    /**
     * Constructs a hierarchical URI from the given components.
     *
     * <p> If a scheme is given then the path, if also given, must either be
     * empty or begin with a slash character (<tt>'/'</tt>).  Otherwise a
     * component of the new URI may be left undefined by passing <tt>null</tt>
     * for the corresponding parameter.
     *
     * <p> This constructor first builds a URI string from the given components
     * according to the rules specified in <a
     * href="http://www.ietf.org/rfc/rfc2396.txt">RFC&nbsp;2396</a>,
     * section&nbsp;5.2, step&nbsp;7: </p>
     *
     * <ol>
     *
     *   <li><p> Initially, the result string is empty.  </p></li>
     *
     *   <li><p> If a scheme is given then it is appended to the result,
     *   followed by a colon character (<tt>':'</tt>).  </p></li>
     *
     *   <li><p> If an authority is given then the string <tt>"//"</tt> is
     *   appended, followed by the authority.  If the authority contains a
     *   literal IPv6 address then the address must be enclosed in square
     *   brackets (<tt>'['</tt> and <tt>']'</tt>).  Any character not in the
     *   <i>unreserved</i>, <i>punct</i>, <i>escaped</i>, or <i>other</i>
     *   categories, and not equal to the commercial-at character
     *   (<tt>'@'</tt>), is <a href="#quote">quoted</a>.  </p></li>
     *
     *   <li><p> If a path is given then it is appended.  Any character not in
     *   the <i>unreserved</i>, <i>punct</i>, <i>escaped</i>, or <i>other</i>
     *   categories, and not equal to the slash character (<tt>'/'</tt>) or the
     *   commercial-at character (<tt>'@'</tt>), is quoted.  </p></li>
     *
     *   <li><p> If a query is given then a question-mark character
     *   (<tt>'?'</tt>) is appended, followed by the query.  Any character that
     *   is not a <a href="#legal-chars">legal URI character</a> is quoted.
     *   </p></li>
     *
     *   <li><p> Finally, if a fragment is given then a hash character
     *   (<tt>'#'</tt>) is appended, followed by the fragment.  Any character
     *   that is not a legal URI character is quoted.  </p></li>
     *
     * </ol>
     *
     * <p> The resulting URI string is then parsed as if by invoking the {@link
     * #URI(String)} constructor and then invoking the {@link
     * #parseServerAuthority()} method upon the result; this may cause a {@link
     * URISyntaxException} to be thrown.  </p>
     *
     * @param   scheme     Scheme name
     * @param   authority  Authority
     * @param   path       Path
     * @param   query      Query
     * @param   fragment   Fragment
     *
     * @throws URISyntaxException
     *         If both a scheme and a path are given but the path is relative,
     *         if the URI string constructed from the given components violates
     *         RFC&nbsp;2396, or if the authority component of the string is
     *         present but cannot be parsed as a server-based authority
     */
    public URI(String scheme,
	       String authority,
	       String path, String query, String fragment)
	throws URISyntaxException
    {
	String s = toString(scheme, null,
			    authority, null, null, -1,
			    path, query, fragment);
	checkPath(s, scheme, path);
	new Parser(s).parse(false);
    }

    /**
     * Constructs a hierarchical URI from the given components.
     *
     * <p> A component may be left undefined by passing <tt>null</tt>.
     *
     * <p> This convenience constructor works as if by invoking the
     * seven-argument constructor as follows:
     *
     * <blockquote><tt>
     * new&nbsp;{@link #URI(String, String, String, int, String, String, String)
     * URI}(scheme,&nbsp;null,&nbsp;host,&nbsp;-1,&nbsp;path,&nbsp;null,&nbsp;fragment);
     * </tt></blockquote>
     *
     * @param   scheme    Scheme name
     * @param   host      Host name
     * @param   path      Path
     * @param   fragment  Fragment
     *
     * @throws  URISyntaxException
     *          If the URI string constructed from the given components
     *          violates RFC&nbsp;2396
     */
    public URI(String scheme, String host, String path, String fragment)
	throws URISyntaxException
    {
	this(scheme, null, host, -1, path, null, fragment);
    }

    /**
     * Constructs a URI from the given components.
     *
     * <p> A component may be left undefined by passing <tt>null</tt>.
     *
     * <p> This constructor first builds a URI in string form using the given
     * components as follows:  </p>
     *
     * <ol>
     *
     *   <li><p> Initially, the result string is empty.  </p></li>
     *
     *   <li><p> If a scheme is given then it is appended to the result,
     *   followed by a colon character (<tt>':'</tt>).  </p></li>
     *
     *   <li><p> If a scheme-specific part is given then it is appended.  Any
     *   character that is not a <a href="#legal-chars">legal URI character</a>
     *   is <a href="#quote">quoted</a>.  </p></li>
     *
     *   <li><p> Finally, if a fragment is given then a hash character
     *   (<tt>'#'</tt>) is appended to the string, followed by the fragment.
     *   Any character that is not a legal URI character is quoted.  </p></li>
     *
     * </ol>
     *
     * <p> The resulting URI string is then parsed in order to create the new
     * URI instance as if by invoking the {@link #URI(String)} constructor;
     * this may cause a {@link URISyntaxException} to be thrown.  </p>
     *
     * @param   scheme    Scheme name
     * @param   ssp       Scheme-specific part
     * @param   fragment  Fragment
     *
     * @throws  URISyntaxException
     *          If the URI string constructed from the given components
     *          violates RFC&nbsp;2396
     */
    public URI(String scheme, String ssp, String fragment)
	throws URISyntaxException
    {
	new Parser(toString(scheme, ssp,
			    null, null, null, -1,
			    null, null, fragment))
	    .parse(false);
    }

    /**
     * Creates a URI by parsing the given string.
     *
     * <p> This convenience factory method works as if by invoking the {@link
     * #URI(String)} constructor; any {@link URISyntaxException} thrown by the
     * constructor is caught and wrapped in a new {@link
     * IllegalArgumentException} object, which is then thrown.
     *
     * <p> This method is provided for use in situations where it is known that
     * the given string is a legal URI, for example for URI constants declared
     * within in a program, and so it would be considered a programming error
     * for the string not to parse as such.  The constructors, which throw
     * {@link URISyntaxException} directly, should be used situations where a
     * URI is being constructed from user input or from some other source that
     * may be prone to errors.  </p>
     *
     * @param  str   The string to be parsed into a URI
     * @return The new URI
     *
     * @throws  NullPointerException
     *          If <tt>str</tt> is <tt>null</tt>
     *
     * @throws  IllegalArgumentException
     *          If the given string violates RFC&nbsp;2396
     */
    public static URI create(String str) {
	try {
	    return new URI(str);
	} catch (URISyntaxException x) {
	    IllegalArgumentException y = new IllegalArgumentException();
	    y.initCause(x);
	    throw y;
	}
    }


    // -- Operations --

    /**
     * Attempts to parse this URI's authority component, if defined, into
     * user-information, host, and port components.
     *
     * <p> If this URI's authority component has already been recognized as
     * being server-based then it will already have been parsed into
     * user-information, host, and port components.  In this case, or if this
     * URI has no authority component, this method simply returns this URI.
     *
     * <p> Otherwise this method attempts once more to parse the authority
     * component into user-information, host, and port components, and throws
     * an exception describing why the authority component could not be parsed
     * in that way.
     *
     * <p> This method is provided because the generic URI syntax specified in
     * <a href="http://www.ietf.org/rfc/rfc2396.txt">RFC&nbsp;2396</a>
     * cannot always distinguish a malformed server-based authority from a
     * legitimate registry-based authority.  It must therefore treat some
     * instances of the former as instances of the latter.  The authority
     * component in the URI string <tt>"//foo:bar"</tt>, for example, is not a
     * legal server-based authority but it is legal as a registry-based
     * authority.
     *
     * <p> In many common situations, for example when working URIs that are
     * known to be either URNs or URLs, the hierarchical URIs being used will
     * always be server-based.  They therefore must either be parsed as such or
     * treated as an error.  In these cases a statement such as
     *
     * <blockquote>
     * <tt>URI </tt><i>u</i><tt> = new URI(str).parseServerAuthority();</tt>
     * </blockquote>
     *
     * <p> can be used to ensure that <i>u</i> always refers to a URI that, if
     * it has an authority component, has a server-based authority with proper
     * user-information, host, and port components.  Invoking this method also
     * ensures that if the authority could not be parsed in that way then an
     * appropriate diagnostic message can be issued based upon the exception
     * that is thrown. </p>
     *
     * @return  A URI whose authority field has been parsed
     *          as a server-based authority
     *
     * @throws  URISyntaxException
     *          If the authority component of this URI is defined
     *          but cannot be parsed as a server-based authority
     *          according to RFC&nbsp;2396
     */
    public URI parseServerAuthority()
	throws URISyntaxException
    {
	// We could be clever and cache the error message and index from the
	// exception thrown during the original parse, but that would require
	// either more fields or a more-obscure representation.
	if ((host != null) || (authority == null))
	    return this;
	defineString();
	new Parser(string).parse(true);
	return this;
    }

    /**
     * Normalizes this URI's path.
     *
     * <p> If this URI is opaque, or if its path is already in normal form,
     * then this URI is returned.  Otherwise a new URI is constructed that is
     * identical to this URI except that its path is computed by normalizing
     * this URI's path in a manner consistent with <a
     * href="http://www.ietf.org/rfc/rfc2396.txt">RFC&nbsp;2396</a>,
     * section&nbsp;5.2, step&nbsp;6, sub-steps&nbsp;c through&nbsp;f; that is:
     * </p>
     *
     * <ol>
     *
     *   <li><p> All <tt>"."</tt> segments are removed. </p></li>
     *
     *   <li><p> If a <tt>".."</tt> segment is preceded by a non-<tt>".."</tt>
     *   segment then both of these segments are removed.  This step is
     *   repeated until it is no longer applicable. </p></li>
     *
     *   <li><p> If the path is relative, and if its first segment contains a
     *   colon character (<tt>':'</tt>), then a <tt>"."</tt> segment is
     *   prepended.  This prevents a relative URI with a path such as
     *   <tt>"a:b/c/d"</tt> from later being re-parsed as an opaque URI with a
     *   scheme of <tt>"a"</tt> and a scheme-specific part of <tt>"b/c/d"</tt>.
     *   <b><i>(Deviation from RFC&nbsp;2396)</i></b> </p></li>
     *
     * </ol>
     *
     * <p> A normalized path will begin with one or more <tt>".."</tt> segments
     * if there were insufficient non-<tt>".."</tt> segments preceding them to
     * allow their removal.  A normalized path will begin with a <tt>"."</tt>
     * segment if one was inserted by step 3 above.  Otherwise, a normalized
     * path will not contain any <tt>"."</tt> or <tt>".."</tt> segments. </p>
     *
     * @return  A URI equivalent to this URI,
     *          but whose path is in normal form
     */
    public URI normalize() {
	return normalize(this);
    }

    /**
     * Resolves the given URI against this URI.
     *
     * <p> If the given URI is already absolute, or if this URI is opaque, then
     * the given URI is returned.
     *
     * <p><a name="resolve-frag"></a> If the given URI's fragment component is
     * defined, its path component is empty, and its scheme, authority, and
     * query components are undefined, then a URI with the given fragment but
     * with all other components equal to those of this URI is returned.  This
     * allows a URI representing a standalone fragment reference, such as
     * <tt>"#foo"</tt>, to be usefully resolved against a base URI.
     *
     * <p> Otherwise this method constructs a new hierarchical URI in a manner
     * consistent with <a
     * href="http://www.ietf.org/rfc/rfc2396.txt">RFC&nbsp;2396</a>,
     * section&nbsp;5.2; that is: </p>
     *
     * <ol>
     *
     *   <li><p> A new URI is constructed with this URI's scheme and the given
     *   URI's query and fragment components. </p></li>
     *
     *   <li><p> If the given URI has an authority component then the new URI's
     *   authority and path are taken from the given URI. </p></li>
     *
     *   <li><p> Otherwise the new URI's authority component is copied from
     *   this URI, and its path is computed as follows: </p></li>
     *
     *   <ol type=a>
     *
     *     <li><p> If the given URI's path is absolute then the new URI's path
     *     is taken from the given URI. </p></li>
     *
     *     <li><p> Otherwise the given URI's path is relative, and so the new
     *     URI's path is computed by resolving the path of the given URI
     *     against the path of this URI.  This is done by concatenating all but
     *     the last segment of this URI's path, if any, with the given URI's
     *     path and then normalizing the result as if by invoking the {@link
     *     #normalize() normalize} method. </p></li>
     *
     *   </ol>
     *
     * </ol>
     *
     * <p> The result of this method is absolute if, and only if, either this
     * URI is absolute or the given URI is absolute.  </p>
     *
     * @param  uri  The URI to be resolved against this URI
     * @return The resulting URI
     *
     * @throws  NullPointerException
     *          If <tt>uri</tt> is <tt>null</tt>
     */
    public URI resolve(URI uri) {
	return resolve(this, uri);
    }

    /**
     * Constructs a new URI by parsing the given string and then resolving it
     * against this URI.
     *
     * <p> This convenience method works as if invoking it were equivalent to
     * evaluating the expression <tt>{@link #resolve(java.net.URI)
     * resolve}(URI.{@link #create(String) create}(str))</tt>. </p>
     *
     * @param  str   The string to be parsed into a URI
     * @return The resulting URI
     *
     * @throws  NullPointerException
     *          If <tt>str</tt> is <tt>null</tt>
     *
     * @throws  IllegalArgumentException
     *          If the given string violates RFC&nbsp;2396
     */
    public URI resolve(String str) {
	return resolve(URI.create(str));
    }

    /**
     * Relativizes the given URI against this URI.
     *
     * <p> The relativization of the given URI against this URI is computed as
     * follows: </p>
     *
     * <ol>
     *
     *   <li><p> If either this URI or the given URI are opaque, or if the
     *   scheme and authority components of the two URIs are not identical, or
     *   if the path of this URI is not a prefix of the path of the given URI,
     *   then the given URI is returned. </p></li>
     *
     *   <li><p> Otherwise a new relative hierarchical URI is constructed with
     *   query and fragment components taken from the given URI and with a path
     *   component computed by removing this URI's path from the beginning of
     *   the given URI's path. </p></li>
     *
     * </ol>
     *
     * @param  uri  The URI to be relativized against this URI
     * @return The resulting URI
     *
     * @throws  NullPointerException
     *          If <tt>uri</tt> is <tt>null</tt>
     */
    public URI relativize(URI uri) {
	return relativize(this, uri);
    }

    /**
     * Constructs a URL from this URI.
     *
     * <p> This convenience method works as if invoking it were equivalent to
     * evaluating the expression <tt>new&nbsp;URL(this.toString())</tt> after
     * first checking that this URI is absolute. </p>
     *
     * @return  A URL constructed from this URI
     *
     * @throws  IllegalArgumentException
     *          If this URL is not absolute
     *
     * @throws  MalformedURLException
     *          If a protocol handler for the URL could not be found,
     *          or if some other error occurred while constructing the URL
     */
    public URL toURL()
	throws MalformedURLException {
	if (!isAbsolute())
	    throw new IllegalArgumentException("URI is not absolute");
	return new URL(toString());
    }

    // -- Component access methods --

    /**
     * Returns the scheme component of this URI.
     *
     * <p> The scheme component of a URI, if defined, only contains characters
     * in the <i>alphanum</i> category and in the string <tt>"-.+"</tt>.  A
     * scheme always starts with an <i>alpha</i> character. <p>
     *
     * The scheme component of a URI cannot contain escaped octets, hence this
     * method does not perform any decoding.
     *
     * @return  The scheme component of this URI,
     *          or <tt>null</tt> if the scheme is undefined
     */
    public String getScheme() {
	return scheme;
    }

    /**
     * Tells whether or not this URI is absolute.
     *
     * <p> A URI is absolute if, and only if, it has a scheme component. </p>
     *
     * @return  <tt>true</tt> if, and only if, this URI is absolute
     */
    public boolean isAbsolute() {
	return scheme != null;
    }

    /**
     * Tells whether or not this URI is opaque.
     *
     * <p> A URI is opaque if, and only if, it is absolute and its
     * scheme-specific part does not begin with a slash character ('/').
     * An opaque URI has a scheme, a scheme-specific part, and possibly
     * a fragment; all other components are undefined. </p>
     *
     * @return  <tt>true</tt> if, and only if, this URI is opaque
     */
    public boolean isOpaque() {
        return path == null;
    }

    /**
     * Returns the raw scheme-specific part of this URI.  The scheme-specific
     * part is never undefined, though it may be empty.
     *
     * <p> The scheme-specific part of a URI only contains legal URI
     * characters. </p>
     *
     * @return  The raw scheme-specific part of this URI
     *          (never <tt>null</tt>)
     */
    public String getRawSchemeSpecificPart() {
	defineSchemeSpecificPart();
	return schemeSpecificPart;
    }

    /**
     * Returns the decoded scheme-specific part of this URI.
     *
     * <p> The string returned by this method is equal to that returned by the
     * {@link #getRawSchemeSpecificPart() getRawSchemeSpecificPart} method
     * except that all sequences of escaped octets are <a
     * href="#decode">decoded</a>.  </p>
     *
     * @return  The decoded scheme-specific part of this URI
     *          (never <tt>null</tt>)
     */
    public String getSchemeSpecificPart() {
	if (decodedSchemeSpecificPart == null)
	    decodedSchemeSpecificPart = decode(getRawSchemeSpecificPart());
	return decodedSchemeSpecificPart;
    }

    /**
     * Returns the raw authority component of this URI.
     *
     * <p> The authority component of a URI, if defined, only contains the
     * commercial-at character (<tt>'@'</tt>) and characters in the
     * <i>unreserved</i>, <i>punct</i>, <i>escaped</i>, and <i>other</i>
     * categories.  If the authority is server-based then it is further
     * constrained to have valid user-information, host, and port
     * components. </p>
     *
     * @return  The raw authority component of this URI,
     *          or <tt>null</tt> if the authority is undefined
     */
    public String getRawAuthority() {
	return authority;
    }

    /**
     * Returns the decoded authority component of this URI.
     *
     * <p> The string returned by this method is equal to that returned by the
     * {@link #getRawAuthority() getRawAuthority} method except that all
     * sequences of escaped octets are <a href="#decode">decoded</a>.  </p>
     *
     * @return  The decoded authority component of this URI,
     *          or <tt>null</tt> if the authority is undefined
     */
    public String getAuthority() {
	if (decodedAuthority == null)
	    decodedAuthority = decode(authority);
	return decodedAuthority;
    }

    /**
     * Returns the raw user-information component of this URI.
     *
     * <p> The user-information component of a URI, if defined, only contains
     * characters in the <i>unreserved</i>, <i>punct</i>, <i>escaped</i>, and
     * <i>other</i> categories. </p>
     *
     * @return  The raw user-information component of this URI,
     *          or <tt>null</tt> if the user information is undefined
     */
    public String getRawUserInfo() {
	return userInfo;
    }

    /**
     * Returns the decoded user-information component of this URI.
     *
     * <p> The string returned by this method is equal to that returned by the
     * {@link #getRawUserInfo() getRawUserInfo} method except that all
     * sequences of escaped octets are <a href="#decode">decoded</a>.  </p>
     *
     * @return  The decoded user-information component of this URI,
     *          or <tt>null</tt> if the user information is undefined
     */
    public String getUserInfo() {
	if ((decodedUserInfo == null) && (userInfo != null))
	    decodedUserInfo = decode(userInfo);
	return decodedUserInfo;
    }

    /**
     * Returns the host component of this URI.
     *
     * <p> The host component of a URI, if defined, will have one of the
     * following forms: </p>
     *
     * <ul type=disc>
     *
     *   <li><p> A domain name consisting of one or more <i>labels</i>
     *   separated by period characters (<tt>'.'</tt>), optionally followed by
     *   a period character.  Each label consists of <i>alphanum</i> characters
     *   as well as hyphen characters (<tt>'-'</tt>), though hyphens never
     *   occur as the first or last characters in a label. The rightmost
     *   label of a domain name consisting of two or more labels, begins
     *   with an <i>alpha</i> character. </li>
     *
     *   <li><p> A dotted-quad IPv4 address of the form
     *   <i>digit</i><tt>+.</tt><i>digit</i><tt>+.</tt><i>digit</i><tt>+.</tt><i>digit</i><tt>+</tt>,
     *   where no <i>digit</i> sequence is longer than three characters and no
     *   sequence has a value larger than 255. </p></li>
     *
     *   <li><p> An IPv6 address enclosed in square brackets (<tt>'['</tt> and
     *   <tt>']'</tt>) and consisting of hexadecimal digits, colon characters
     *   (<tt>':'</tt>), and possibly an embedded IPv4 address.  The full
     *   syntax of IPv6 addresses is specified in <a
     *   href="http://www.ietf.org/rfc/rfc2373.txt"><i>RFC&nbsp;2373: IPv6
     *   Addressing Architecture</i></a>.  </p></li>
     *
     * </ul>
     *
     * The host component of a URI cannot contain escaped octets, hence this
     * method does not perform any decoding.
     *
     * @return  The host component of this URI,
     *          or <tt>null</tt> if the host is undefined
     */
    public String getHost() {
	return host;
    }

    /**
     * Returns the port number of this URI.
     *
     * <p> The port component of a URI, if defined, is a non-negative
     * integer. </p>
     *
     * @return  The port component of this URI,
     *          or <tt>-1</tt> if the port is undefined
     */
    public int getPort() {
	return port;
    }

    /**
     * Returns the raw path component of this URI.
     *
     * <p> The path component of a URI, if defined, only contains the slash
     * character (<tt>'/'</tt>), the commercial-at character (<tt>'@'</tt>),
     * and characters in the <i>unreserved</i>, <i>punct</i>, <i>escaped</i>,
     * and <i>other</i> categories. </p>
     *
     * @return  The path component of this URI,
     *          or <tt>null</tt> if the path is undefined
     */
    public String getRawPath() {
	return path;
    }

    /**
     * Returns the decoded path component of this URI.
     *
     * <p> The string returned by this method is equal to that returned by the
     * {@link #getRawPath() getRawPath} method except that all sequences of
     * escaped octets are <a href="#decode">decoded</a>.  </p>
     *
     * @return  The decoded path component of this URI,
     *          or <tt>null</tt> if the path is undefined
     */
    public String getPath() {
	if ((decodedPath == null) && (path != null))
	    decodedPath = decode(path);
	return decodedPath;
    }

    /**
     * Returns the raw query component of this URI.
     *
     * <p> The query component of a URI, if defined, only contains legal URI
     * characters. </p>
     *
     * @return  The raw query component of this URI,
     *          or <tt>null</tt> if the query is undefined
     */
    public String getRawQuery() {
	return query;
    }

    /**
     * Returns the decoded query component of this URI.
     *
     * <p> The string returned by this method is equal to that returned by the
     * {@link #getRawQuery() getRawQuery} method except that all sequences of
     * escaped octets are <a href="#decode">decoded</a>.  </p>
     *
     * @return  The decoded query component of this URI,
     *          or <tt>null</tt> if the query is undefined
     */
    public String getQuery() {
	if ((decodedQuery == null) && (query != null))
	    decodedQuery = decode(query);
	return decodedQuery;
    }

    /**
     * Returns the raw fragment component of this URI.
     *
     * <p> The fragment component of a URI, if defined, only contains legal URI
     * characters. </p>
     *
     * @return  The raw fragment component of this URI,
     *          or <tt>null</tt> if the fragment is undefined
     */
    public String getRawFragment() {
	return fragment;
    }

    /**
     * Returns the decoded fragment component of this URI.
     *
     * <p> The string returned by this method is equal to that returned by the
     * {@link #getRawFragment() getRawFragment} method except that all
     * sequences of escaped octets are <a href="#decode">decoded</a>.  </p>
     *
     * @return  The decoded fragment component of this URI,
     *          or <tt>null</tt> if the fragment is undefined
     */
    public String getFragment() {
	if ((decodedFragment == null) && (fragment != null))
	    decodedFragment = decode(fragment);
	return decodedFragment;
    }


    // -- Equality, comparison, hash code, toString, and serialization --

    /**
     * Tests this URI for equality with another object.
     *
     * <p> If the given object is not a URI then this method immediately
     * returns <tt>false</tt>.
     *
     * <p> For two URIs to be considered equal requires that either both are
     * opaque or both are hierarchical.  Their schemes must either both be
     * undefined or else be equal without regard to case. Their fragments
     * must either both be undefined or else be equal.
     *
     * <p> For two opaque URIs to be considered equal, their scheme-specific
     * parts must be equal.
     *
     * <p> For two hierarchical URIs to be considered equal, their paths must
     * be equal and their queries must either both be undefined or else be
     * equal.  Their authorities must either both be undefined, or both be
     * registry-based, or both be server-based.  If their authorities are
     * defined and are registry-based, then they must be equal.  If their
     * authorities are defined and are server-based, then their hosts must be
     * equal without regard to case, their port numbers must be equal, and
     * their user-information components must be equal.
     *
     * <p> When testing the user-information, path, query, fragment, authority,
     * or scheme-specific parts of two URIs for equality, the raw forms rather
     * than the encoded forms of these components are compared and the
     * hexadecimal digits of escaped octets are compared without regard to
     * case.
     *
     * <p> This method satisfies the general contract of the {@link
     * java.lang.Object#equals(Object) Object.equals} method. </p>
     *
     * @param   ob   The object to which this object is to be compared
     *
     * @return  <tt>true</tt> if, and only if, the given object is a URI that
     *          is identical to this URI
     */
    public boolean equals(Object ob) {
	if (ob == this)
	    return true;
	if (!(ob instanceof URI))
	    return false;
	URI that = (URI)ob;
	if (this.isOpaque() != that.isOpaque()) return false;
	if (!equalIgnoringCase(this.scheme, that.scheme)) return false;
	if (!equal(this.fragment, that.fragment)) return false;

	// Opaque
	if (this.isOpaque())
	    return equal(this.schemeSpecificPart, that.schemeSpecificPart);

	// Hierarchical
	if (!equal(this.path, that.path)) return false;
	if (!equal(this.query, that.query)) return false;

	// Authorities
	if (this.authority == that.authority) return true;
	if (this.host != null) {
	    // Server-based
	    if (!equal(this.userInfo, that.userInfo)) return false;
	    if (!equalIgnoringCase(this.host, that.host)) return false;
	    if (this.port != that.port) return false;
	} else if (this.authority != null) {
	    // Registry-based
	    if (!equal(this.authority, that.authority)) return false;
	} else if (this.authority != that.authority) {
	    return false;
	}

	return true;
    }

    /**
     * Returns a hash-code value for this URI.  The hash code is based upon all
     * of the URI's components, and satisfies the general contract of the
     * {@link java.lang.Object#hashCode() Object.hashCode} method.
     *
     * @return  A hash-code value for this URI
     */
    public int hashCode() {
	if (hash != 0)
	    return hash;
	int h = hashIgnoringCase(0, scheme);
	h = hash(h, fragment);
	if (isOpaque()) {
	    h = hash(h, schemeSpecificPart);
	} else {
	    h = hash(h, path);
	    h = hash(h, query);
	    if (host != null) {
		h = hash(h, userInfo);
		h = hashIgnoringCase(h, host);
		h += 1949 * port;
	    } else {
		h = hash(h, authority);
	    }
	}
	hash = h;
	return h;
    }

    /**
     * Compares this URI to another object, which must be a URI.
     *
     * <p> When comparing corresponding components of two URIs, if one
     * component is undefined but the other is defined then the first is
     * considered to be less than the second.  Unless otherwise noted, string
     * components are ordered according to their natural, case-sensitive
     * ordering as defined by the {@link java.lang.String#compareTo(Object)
     * String.compareTo} method.  String components that are subject to
     * encoding are compared by comparing their raw forms rather than their
     * encoded forms.
     *
     * <p> The ordering of URIs is defined as follows: </p>
     *
     * <ul type=disc>
     *
     *   <li><p> Two URIs with different schemes are ordered according the
     *   ordering of their schemes, without regard to case. </p></li>
     *
     *   <li><p> A hierarchical URI is considered to be less than an opaque URI
     *   with an identical scheme. </p></li>
     *
     *   <li><p> Two opaque URIs with identical schemes are ordered according
     *   to the ordering of their scheme-specific parts. </p></li>
     *
     *   <li><p> Two opaque URIs with identical schemes and scheme-specific
     *   parts are ordered according to the ordering of their
     *   fragments. </p></li>
     *
     *   <li><p> Two hierarchical URIs with identical schemes are ordered
     *   according to the ordering of their authority components: </p></li>
     *
     *   <ul type=disc>
     *
     *     <li><p> If both authority components are server-based then the URIs
     *     are ordered according to their user-information components; if these
     *     components are identical then the URIs are ordered according to the
     *     ordering of their hosts, without regard to case; if the hosts are
     *     identical then the URIs are ordered according to the ordering of
     *     their ports. </p></li>
     *
     *     <li><p> If one or both authority components are registry-based then
     *     the URIs are ordered according to the ordering of their authority
     *     components. </p></li>
     *
     *   </ul>
     *
     *   <li><p> Finally, two hierarchical URIs with identical schemes and
     *   authority components are ordered according to the ordering of their
     *   paths; if their paths are identical then they are ordered according to
     *   the ordering of their queries; if the queries are identical then they
     *   are ordered according to the order of their fragments. </p></li>
     *
     * </ul>
     *
     * <p> This method satisfies the general contract of the {@link
     * java.lang.Comparable#compareTo(Object) Comparable.compareTo}
     * method. </p>
     *
     * @param   that
     *          The object to which this URI is to be compared
     *
     * @return  A negative integer, zero, or a positive integer as this URI is
     *          less than, equal to, or greater than the given URI
     *
     * @throws  ClassCastException
     *          If the given object is not a URI
     */
    public int compareTo(URI that) {
	int c;

	if ((c = compareIgnoringCase(this.scheme, that.scheme)) != 0)
	    return c;

	if (this.isOpaque()) {
	    if (that.isOpaque()) {
		// Both opaque
		if ((c = compare(this.schemeSpecificPart,
				 that.schemeSpecificPart)) != 0)
		    return c;
		return compare(this.fragment, that.fragment);
	    }
	    return +1;			// Opaque > hierarchical
	} else if (that.isOpaque()) {
	    return -1;			// Hierarchical < opaque
	}

	// Hierarchical
	if ((this.host != null) && (that.host != null)) {
	    // Both server-based
	    if ((c = compare(this.userInfo, that.userInfo)) != 0)
		return c;
	    if ((c = compareIgnoringCase(this.host, that.host)) != 0)
		return c;
	    if ((c = this.port - that.port) != 0)
		return c;
	} else {
	    // If one or both authorities are registry-based then we simply
	    // compare them in the usual, case-sensitive way.  If one is
	    // registry-based and one is server-based then the strings are
	    // guaranteed to be unequal, hence the comparison will never return
	    // zero and the compareTo and equals methods will remain
	    // consistent.
	    if ((c = compare(this.authority, that.authority)) != 0) return c;
	}

	if ((c = compare(this.path, that.path)) != 0) return c;
	if ((c = compare(this.query, that.query)) != 0) return c;
	return compare(this.fragment, that.fragment);
    }

    /**
     * Returns the content of this URI as a string.
     *
     * <p> If this URI was created by invoking one of the constructors in this
     * class then a string equivalent to the original input string, or to the
     * string computed from the originally-given components, as appropriate, is
     * returned.  Otherwise this URI was created by normalization, resolution,
     * or relativization, and so a string is constructed from this URI's
     * components according to the rules specified in <a
     * href="http://www.ietf.org/rfc/rfc2396.txt">RFC&nbsp;2396</a>,
     * section&nbsp;5.2, step&nbsp;7. </p>
     *
     * @return  The string form of this URI
     */
    public String toString() {
	defineString();
	return string;
    }

    /**
     * Returns the content of this URI as a US-ASCII string.
     *
     * <p> If this URI does not contain any characters in the <i>other</i>
     * category then an invocation of this method will return the same value as
     * an invocation of the {@link #toString() toString} method.  Otherwise
     * this method works as if by invoking that method and then <a
     * href="#encode">encoding</a> the result.  </p>
     *
     * @return  The string form of this URI, encoded as needed
     *          so that it only contains characters in the US-ASCII
     *          charset
     */
    public String toASCIIString() {
	defineString();
	return encode(string);
    }


    // -- Serialization support --

    /**
     * Saves the content of this URI to the given serial stream.
     *
     * <p> The only serializable field of a URI instance is its <tt>string</tt>
     * field.  That field is given a value, if it does not have one already,
     * and then the {@link java.io.ObjectOutputStream#defaultWriteObject()}
     * method of the given object-output stream is invoked. </p>
     *
     * @param  os  The object-output stream to which this object
     *             is to be written
     */
    private void writeObject(ObjectOutputStream os)
	throws IOException
    {
	defineString();
	os.defaultWriteObject();	// Writes the string field only
    }

    /**
     * Reconstitutes a URI from the given serial stream.
     *
     * <p> The {@link java.io.ObjectInputStream#defaultReadObject()} method is
     * invoked to read the value of the <tt>string</tt> field.  The result is
     * then parsed in the usual way.
     *
     * @param  is  The object-input stream from which this object
     *             is being read
     */
    private void readObject(ObjectInputStream is)
	throws ClassNotFoundException, IOException
    {
	port = -1;			// Argh
	is.defaultReadObject();
	try {
	    new Parser(string).parse(false);
	} catch (URISyntaxException x) {
	    IOException y = new InvalidObjectException("Invalid URI");
	    y.initCause(x);
	    throw y;
	}
    }


    // -- End of public methods --


    // -- Utility methods for string-field comparison and hashing --

    // These methods return appropriate values for null string arguments,
    // thereby simplifying the equals, hashCode, and compareTo methods.
    //
    // The case-ignoring methods should only be applied to strings whose
    // characters are all known to be US-ASCII.  Because of this restriction,
    // these methods are faster than the similar methods in the String class.

    // US-ASCII only
    private static int toLower(char c) {
	if ((c >= 'A') && (c <= 'Z'))
	    return c + ('a' - 'A');
	return c;
    }

    private static boolean equal(String s, String t) {
	if (s == t) return true;
	if ((s != null) && (t != null)) {
	    if (s.length() != t.length())
		return false;
	    if (s.indexOf('%') < 0)
		return s.equals(t);
	    int n = s.length();
	    for (int i = 0; i < n;) {
		char c = s.charAt(i);
		char d = t.charAt(i);
		if (c != '%') {
		    if (c != d)
			return false;
		    i++;
		    continue;
		}
		i++;
		if (toLower(s.charAt(i)) != toLower(t.charAt(i)))
		    return false;
		i++;
		if (toLower(s.charAt(i)) != toLower(t.charAt(i)))
		    return false;
		i++;
	    }
	    return true;
	}
	return false;
    }

    // US-ASCII only
    private static boolean equalIgnoringCase(String s, String t) {
	if (s == t) return true;
	if ((s != null) && (t != null)) {
	    int n = s.length();
	    if (t.length() != n)
		return false;
	    for (int i = 0; i < n; i++) {
		if (toLower(s.charAt(i)) != toLower(t.charAt(i)))
		    return false;
	    }
	    return true;
	}
	return false;
    }

    private static int hash(int hash, String s) {
	if (s == null) return hash;
	return hash * 127 + s.hashCode();
    }

    // US-ASCII only
    private static int hashIgnoringCase(int hash, String s) {
	if (s == null) return hash;
	int h = hash;
	int n = s.length();
	for (int i = 0; i < n; i++)
	    h = 31 * h + toLower(s.charAt(i));
	return h;
    }

    private static int compare(String s, String t) {
	if (s == t) return 0;
	if (s != null) {
	    if (t != null)
		return s.compareTo(t);
	    else
		return +1;
	} else {
	    return -1;
	}
    }

    // US-ASCII only
    private static int compareIgnoringCase(String s, String t) {
	if (s == t) return 0;
	if (s != null) {
	    if (t != null) {
		int sn = s.length();
		int tn = t.length();
		int n = sn < tn ? sn : tn;
		for (int i = 0; i < n; i++) {
		    int c = toLower(s.charAt(i)) - toLower(t.charAt(i));
		    if (c != 0)
			return c;
		}
		return sn - tn;
	    }
	    return +1;
	} else {
	    return -1;
	}
    }


    // -- String construction --

    // If a scheme is given then the path, if given, must be absolute
    //
    private static void checkPath(String s, String scheme, String path)
	throws URISyntaxException
    {
	if (scheme != null) {
	    if ((path != null)
		&& ((path.length() > 0) && (path.charAt(0) != '/')))
		throw new URISyntaxException(s,
					     "Relative path in absolute URI");
	}
    }

    private void appendAuthority(StringBuffer sb,
				 String authority,
				 String userInfo,
				 String host,
				 int port)
    {
	if (host != null) {
	    sb.append("__JOT_PIECE_100__
	    if (userInfo != null) {
		sb.append(quote(userInfo, L_USERINFO, H_USERINFO));
		sb.append('@');
	    }
	    boolean needBrackets = ((host.indexOf(':') >= 0)
				    && !host.startsWith("[")
				    && !host.endsWith("]"));
	    if (needBrackets) sb.append('[');
	    sb.append(host);
	    if (needBrackets) sb.append(']');
	    if (port != -1) {
		sb.append(':');
		sb.append(port);
	    }
	} else if (authority != null) {
	    sb.append("//");
	    if (authority.startsWith("[")) {
		int end = authority.indexOf("]");
		if (end != -1 && authority.indexOf(":")!=-1) {
		    String doquote, dontquote;
		    if (end == authority.length()) {
			dontquote = authority;
			doquote = "";
		    } else {
		    	dontquote = authority.substring(0,end+1);
			doquote = authority.substring(end+1);
		    }
		    sb.append (dontquote);
	    	    sb.append(quote(doquote, 
			    L_REG_NAME | L_SERVER,
			    H_REG_NAME | H_SERVER));
		}
	    } else {
	    	sb.append(quote(authority,
			    L_REG_NAME | L_SERVER,
			    H_REG_NAME | H_SERVER));
	    }
	}
    }

    private void appendSchemeSpecificPart(StringBuffer sb,
					  String opaquePart,
					  String authority,
					  String userInfo,
					  String host,
					  int port,
					  String path,
					  String query)
    {
	if (opaquePart != null) {
	    /* check if SSP begins with an IPv6 address
	     * because we must not quote a literal IPv6 address
	     */
	    if (opaquePart.startsWith("//[")) {
		int end =  opaquePart.indexOf("]");
		if (end != -1 && opaquePart.indexOf(":")!=-1) {
		    String doquote, dontquote;
		    if (end == opaquePart.length()) {
			dontquote = opaquePart;
			doquote = "";
		    } else {
		    	dontquote = opaquePart.substring(0,end+1);
			doquote = opaquePart.substring(end+1);
		    }
		    sb.append (dontquote);
	    	    sb.append(quote(doquote, L_URIC, H_URIC));
		}
	    } else {
	    	sb.append(quote(opaquePart, L_URIC, H_URIC));
	    }
	} else {
	    appendAuthority(sb, authority, userInfo, host, port);
	    if (path != null) 
		sb.append(quote(path, L_PATH, H_PATH));
	    if (query != null) {
		sb.append('?');
		sb.append(quote(query, L_URIC, H_URIC));
	    }
	}
    }

    private void appendFragment(StringBuffer sb, String fragment) {
	if (fragment != null) {
	    sb.append('#');
	    sb.append(quote(fragment, L_URIC, H_URIC));
	}
    }

    private String toString(String scheme,
			    String opaquePart,
			    String authority,
			    String userInfo,
			    String host,
			    int port,
			    String path,
			    String query,
			    String fragment)
    {
	StringBuffer sb = new StringBuffer();
	if (scheme != null) {
	    sb.append(scheme);
	    sb.append(':');
	}
	appendSchemeSpecificPart(sb, opaquePart,
				 authority, userInfo, host, port,
				 path, query);
	appendFragment(sb, fragment);
	return sb.toString();
    }

    private void defineSchemeSpecificPart() {
	if (schemeSpecificPart != null) return;
	StringBuffer sb = new StringBuffer();
	appendSchemeSpecificPart(sb, null, getAuthority(), getUserInfo(),
				 host, port, getPath(), getQuery());
	if (sb.length() == 0) return;
	schemeSpecificPart = sb.toString();
    }

    private void defineString() {
	if (string != null) return;

	StringBuffer sb = new StringBuffer();
        if (scheme != null) {
            sb.append(scheme);
            sb.append(':');
        }
	if (isOpaque()) {
            sb.append(schemeSpecificPart);
        } else {
	    if (host != null) {
                sb.append("__JOT_PIECE_103__
                if (userInfo != null) {
                    sb.append(userInfo);
                    sb.append('@');
                }
                boolean needBrackets = ((host.indexOf(':') >= 0)
                                    && !host.startsWith("[")
                                    && !host.endsWith("]"));
                if (needBrackets) sb.append('[');
                sb.append(host);
                if (needBrackets) sb.append(']');
                if (port != -1) {
                    sb.append(':');
                    sb.append(port);
                }
            } else if (authority != null) {
                sb.append("//");
                sb.append(authority);
	    }
            if (path != null)
                sb.append(path);
            if (query != null) {
                sb.append('?');
                sb.append(query);
            }
        }
	if (fragment != null) {
            sb.append('#');
            sb.append(fragment);
	}
	string = sb.toString();
    }


    // -- Normalization, resolution, and relativization --

    // RFC2396 5.2 (6)
    private static String resolvePath(String base, String child,
				      boolean absolute)
    {
        int i = base.lastIndexOf('/');
	int cn = child.length();
	String path = "";

	if (cn == 0) {
	    // 5.2 (6a)
	    if (i >= 0)
		path = base.substring(0, i + 1);
	} else {
	    StringBuffer sb = new StringBuffer(base.length() + cn);
	    // 5.2 (6a)
	    if (i >= 0)
		sb.append(base.substring(0, i + 1));
	    // 5.2 (6b)
	    sb.append(child);
	    path = sb.toString();
	}

	// 5.2 (6c-f)
	String np = normalize(path);

	// 5.2 (6g): If the result is absolute but the path begins with "../",
	// then we simply leave the path as-is

	return np;
    }

    // RFC2396 5.2
    private static URI resolve(URI base, URI child) {
	// check if child if opaque first so that NPE is thrown 
	// if child is null.
	if (child.isOpaque() || base.isOpaque())
	    return child;

	// 5.2 (2): Reference to current document (lone fragment)
	if ((child.scheme == null) && (child.authority == null)
	    && child.path.equals("") && (child.fragment != null)
	    && (child.query == null)) {
	    if ((base.fragment != null)
		&& child.fragment.equals(base.fragment)) {
		return base;
	    }
	    URI ru = new URI();
	    ru.scheme = base.scheme;
	    ru.authority = base.authority;
	    ru.userInfo = base.userInfo;
	    ru.host = base.host;
	    ru.port = base.port;
	    ru.path = base.path;
	    ru.fragment = child.fragment;
	    ru.query = base.query;
	    return ru;
	}

	// 5.2 (3): Child is absolute
	if (child.scheme != null)
	    return child;

	URI ru = new URI();		// Resolved URI
	ru.scheme = base.scheme;
	ru.query = child.query;
	ru.fragment = child.fragment;

	// 5.2 (4): Authority
	if (child.authority == null) {
	    ru.authority = base.authority;
	    ru.host = base.host;
	    ru.userInfo = base.userInfo;
	    ru.port = base.port;

	    String cp = (child.path == null) ? "" : child.path;
	    if ((cp.length() > 0) && (cp.charAt(0) == '/')) {
		// 5.2 (5): Child path is absolute
		ru.path = child.path;
	    } else {
		// 5.2 (6): Resolve relative path
		ru.path = resolvePath(base.path, cp, base.isAbsolute());
	    }
	} else {
	    ru.authority = child.authority;
	    ru.host = child.host;
	    ru.userInfo = child.userInfo;
	    ru.host = child.host;
	    ru.port = child.port;
	    ru.path = child.path;
	}

	// 5.2 (7): Recombine (nothing to do here)
	return ru;
    }

    // If the given URI's path is normal then return the URI;
    // o.w., return a new URI containing the normalized path.
    //
    private static URI normalize(URI u) {
	if (u.isOpaque() || (u.path == null) || (u.path.length() == 0))
	    return u;

	String np = normalize(u.path);
	if (np == u.path)
	    return u;

	URI v = new URI();
	v.scheme = u.scheme;
	v.fragment = u.fragment;
	v.authority = u.authority;
	v.userInfo = u.userInfo;
	v.host = u.host;
	v.port = u.port;
	v.path = np;
	v.query = u.query;
	return v;
    }

    // If both URIs are hierarchical, their scheme and authority components are
    // identical, and the base path is a prefix of the child's path, then
    // return a relative URI that, when resolved against the base, yields the
    // child; otherwise, return the child.
    //
    private static URI relativize(URI base, URI child) {
	// check if child if opaque first so that NPE is thrown 
        // if child is null.
	if (child.isOpaque() || base.isOpaque())
	    return child;
	if (!equalIgnoringCase(base.scheme, child.scheme)
	    || !equal(base.authority, child.authority))
	    return child;

	String bp = normalize(base.path);
	String cp = normalize(child.path);
	if (!bp.equals(cp)) {
	    if (!bp.endsWith("/"))
		bp = bp + "/";
	    if (!cp.startsWith(bp))
		return child;
	}

	URI v = new URI();
	v.path = cp.substring(bp.length());
	v.query = child.query;
	v.fragment = child.fragment;
	return v;
    }



    // -- Path normalization --

    // The following algorithm for path normalization avoids the creation of a
    // string object for each segment, as well as the use of a string buffer to
    // compute the final result, by using a single char array and editing it in
    // place.  The array is first split into segments, replacing each slash
    // with '\0' and creating a segment-index array, each element of which is
    // the index of the first char in the corresponding segment.  We then walk
    // through both arrays, removing ".", "..", and other segments as necessary
    // by setting their entries in the index array to -1.  Finally, the two
    // arrays are used to rejoin the segments and compute the final result.
    //
    // This code is based upon src/solaris/native/java/io/canonicalize_md.c


    // Check the given path to see if it might need normalization.  A path
    // might need normalization if it contains duplicate slashes, a "."
    // segment, or a ".." segment.  Return -1 if no further normalization is
    // possible, otherwise return the number of segments found.
    //
    // This method takes a string argument rather than a char array so that
    // this test can be performed without invoking path.toCharArray().
    //
    static private int needsNormalization(String path) {
	boolean normal = true;
	int ns = 0;			// Number of segments
	int end = path.length() - 1;	// Index of last char in path
	int p = 0;			// Index of next char in path

	// Skip initial slashes
	while (p <= end) {
	    if (path.charAt(p) != '/') break;
	    p++;
	}
	if (p > 1) normal = false;

	// Scan segments
	while (p <= end) {

	    // Looking at "." or ".." ?
	    if ((path.charAt(p) == '.')
		&& ((p == end)
		    || ((path.charAt(p + 1) == '/')
			|| ((path.charAt(p + 1) == '.')
			    && ((p + 1 == end)
				|| (path.charAt(p + 2) == '/')))))) {
		normal = false;
	    }
	    ns++;

	    // Find beginning of next segment
	    while (p <= end) {
		if (path.charAt(p++) != '/')
		    continue;

		// Skip redundant slashes
		while (p <= end) {
		    if (path.charAt(p) != '/') break;
		    normal = false;
		    p++;
		}

		break;
	    }
	}

	return normal ? -1 : ns;
    }


    // Split the given path into segments, replacing slashes with nulls and
    // filling in the given segment-index array.
    //
    // Preconditions:
    //   segs.length == Number of segments in path
    //
    // Postconditions:
    //   All slashes in path replaced by '\0'
    //   segs[i] == Index of first char in segment i (0 <= i < segs.length)
    //
    static private void split(char[] path, int[] segs) {
	int end = path.length - 1;	// Index of last char in path
	int p = 0;			// Index of next char in path
	int i = 0;			// Index of current segment

	// Skip initial slashes
	while (p <= end) {
	    if (path[p] != '/') break;
	    path[p] = '\0';
	    p++;
	}

	while (p <= end) {

	    // Note start of segment
	    segs[i++] = p++;

	    // Find beginning of next segment
	    while (p <= end) {
		if (path[p++] != '/')
		    continue;
		path[p - 1] = '\0';

		// Skip redundant slashes
		while (p <= end) {
		    if (path[p] != '/') break;
		    path[p++] = '\0';
		}
		break;
	    }
	}

	if (i != segs.length)
	    throw new InternalError();	// ASSERT
    }


    // Join the segments in the given path according to the given segment-index
    // array, ignoring those segments whose index entries have been set to -1,
    // and inserting slashes as needed.  Return the length of the resulting
    // path.
    //
    // Preconditions:
    //   segs[i] == -1 implies segment i is to be ignored
    //   path computed by split, as above, with '\0' having replaced '/'
    //
    // Postconditions:
    //   path[0] .. path[return value] == Resulting path
    //
    static private int join(char[] path, int[] segs) {
	int ns = segs.length;		// Number of segments
	int end = path.length - 1;	// Index of last char in path
	int p = 0;			// Index of next path char to write

	if (path[p] == '\0') {
	    // Restore initial slash for absolute paths
	    path[p++] = '/';
	}

	for (int i = 0; i < ns; i++) {
	    int q = segs[i];		// Current segment
	    if (q == -1)
		// Ignore this segment
		continue;

	    if (p == q) {
		// We're already at this segment, so just skip to its end
		while ((p <= end) && (path[p] != '\0'))
		    p++;
		if (p <= end) {
		    // Preserve trailing slash
		    path[p++] = '/';
		}
	    } else if (p < q) {
		// Copy q down to p
		while ((q <= end) && (path[q] != '\0'))
		    path[p++] = path[q++];
		if (q <= end) {
		    // Preserve trailing slash
		    path[p++] = '/';
		}
	    } else
		throw new InternalError(); // ASSERT false
	}

	return p;
    }


    // Remove "." segments from the given path, and remove segment pairs
    // consisting of a non-".." segment followed by a ".." segment.
    //
    private static void removeDots(char[] path, int[] segs) {
	int ns = segs.length;
	int end = path.length - 1;

	for (int i = 0; i < ns; i++) {
	    int dots = 0;		// Number of dots found (0, 1, or 2)

	    // Find next occurrence of "." or ".."
	    do {
		int p = segs[i];
		if (path[p] == '.') {
		    if (p == end) {
			dots = 1;
			break;
		    } else if (path[p + 1] == '\0') {
			dots = 1;
			break;
		    } else if ((path[p + 1] == '.')
			       && ((p + 1 == end)
				   || (path[p + 2] == '\0'))) {
			dots = 2;
			break;
		    }
		}
		i++;
	    } while (i < ns);
	    if ((i > ns) || (dots == 0))
		break;

	    if (dots == 1) {
		// Remove this occurrence of "."
		segs[i] = -1;
	    } else {
		// If there is a preceding non-".." segment, remove both that
		// segment and this occurrence of ".."; otherwise, leave this
		// ".." segment as-is.
		int j;
		for (j = i - 1; j >= 0; j--) {
		    if (segs[j] != -1) break;
		}
		if (j >= 0) {
		    int q = segs[j];
		    if (!((path[q] == '.')
			  && (path[q + 1] == '.')
			  && (path[q + 2] == '\0'))) {
			segs[i] = -1;
			segs[j] = -1;
		    }
		}
	    }
	}
    }


    // DEVIATION: If the normalized path is relative, and if the first
    // segment could be parsed as a scheme name, then prepend a "." segment
    //
    private static void maybeAddLeadingDot(char[] path, int[] segs) {

	if (path[0] == '\0')
	    // The path is absolute
	    return;

	int ns = segs.length;
	int f = 0;			// Index of first segment
	while (f < ns) {
	    if (segs[f] >= 0)
		break;
	    f++;
	}
	if ((f >= ns) || (f == 0))
	    // The path is empty, or else the original first segment survived,
	    // in which case we already know that no leading "." is needed
	    return;

	int p = segs[f];
	while ((p < path.length) && (path[p] != ':') && (path[p] != '\0')) p++;
	if (p >= path.length || path[p] == '\0')
	    // No colon in first segment, so no "." needed
	    return;

	// At this point we know that the first segment is unused,
	// hence we can insert a "." segment at that position
	path[0] = '.';
	path[1] = '\0';
	segs[0] = 0;
    }


    // Normalize the given path string.  A normal path string has no empty
    // segments (i.e., occurrences of "//"), no segments equal to ".", and no
    // segments equal to ".." that are preceded by a segment not equal to "..".
    // In contrast to Unix-style pathname normalization, for URI paths we
    // always retain trailing slashes.
    //
    private static String normalize(String ps) {

	// Does this path need normalization?
	int ns = needsNormalization(ps);	// Number of segments
	if (ns < 0)
	    // Nope -- just return it
	    return ps;

	char[] path = ps.toCharArray();		// Path in char-array form

	// Split path into segments
	int[] segs = new int[ns];		// Segment-index array
	split(path, segs);

	// Remove dots
	removeDots(path, segs);

	// Prevent scheme-name confusion
	maybeAddLeadingDot(path, segs);

	// Join the remaining segments and return the result
	String s = new String(path, 0, join(path, segs));
	if (s.equals(ps)) {
	    // string was already normalized
	    return ps;
	}
	return s;
    }



    // -- Character classes for parsing --

    // RFC2396 precisely specifies which characters in the US-ASCII charset are
    // permissible in the various components of a URI reference.  We here
    // define a set of mask pairs to aid in enforcing these restrictions.  Each
    // mask pair consists of two longs, a low mask and a high mask.  Taken
    // together they represent a 128-bit mask, where bit i is set iff the
    // character with value i is permitted.
    //
    // This approach is more efficient than sequentially searching arrays of
    // permitted characters.  It could be made still more efficient by
    // precompiling the mask information so that a character's presence in a
    // given mask could be determined by a single table lookup.

    // Compute the low-order mask for the characters in the given string
    private static long lowMask(String chars) {
	int n = chars.length();
	long m = 0;
	for (int i = 0; i < n; i++) {
	    char c = chars.charAt(i);
	    if (c < 64)
		m |= (1L << c);
	}
	return m;
    }

    // Compute the high-order mask for the characters in the given string
    private static long highMask(String chars) {
	int n = chars.length();
	long m = 0;
	for (int i = 0; i < n; i++) {
	    char c = chars.charAt(i);
	    if ((c >= 64) && (c < 128))
		m |= (1L << (c - 64));
	}
	return m;
    }

    // Compute a low-order mask for the characters
    // between first and last, inclusive
    private static long lowMask(char first, char last) {
	long m = 0;
	int f = Math.max(Math.min(first, 63), 0);
	int l = Math.max(Math.min(last, 63), 0);
	for (int i = f; i <= l; i++)
	    m |= 1L << i;
	return m;
    }

    // Compute a high-order mask for the characters
    // between first and last, inclusive
    private static long highMask(char first, char last) {
	long m = 0;
	int f = Math.max(Math.min(first, 127), 64) - 64;
	int l = Math.max(Math.min(last, 127), 64) - 64;
	for (int i = f; i <= l; i++)
	    m |= 1L << i;
	return m;
    }

    // Tell whether the given character is permitted by the given mask pair
    private static boolean match(char c, long lowMask, long highMask) {
	if (c < 64)
	    return ((1L << c) & lowMask) != 0;
	if (c < 128)
	    return ((1L << (c - 64)) & highMask) != 0;
	return false;
    }

    // Character-class masks, in reverse order from RFC2396 because
    // initializers for static fields cannot make forward references.

    // digit    = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" |
    //            "8" | "9"
    private static final long L_DIGIT = lowMask('0', '9');
    private static final long H_DIGIT = 0L;

    // upalpha  = "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" | "I" |
    //            "J" | "K" | "L" | "M" | "N" | "O" | "P" | "Q" | "R" |
    //            "S" | "T" | "U" | "V" | "W" | "X" | "Y" | "Z"
    private static final long L_UPALPHA = 0L;
    private static final long H_UPALPHA = highMask('A', 'Z');

    // lowalpha = "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" |
    //            "j" | "k" | "l" | "m" | "n" | "o" | "p" | "q" | "r" |
    //            "s" | "t" | "u" | "v" | "w" | "x" | "y" | "z"
    private static final long L_LOWALPHA = 0L;
    private static final long H_LOWALPHA = highMask('a', 'z');

    // alpha         = lowalpha | upalpha
    private static final long L_ALPHA = L_LOWALPHA | L_UPALPHA;
    private static final long H_ALPHA = H_LOWALPHA | H_UPALPHA;

    // alphanum      = alpha | digit
    private static final long L_ALPHANUM = L_DIGIT | L_ALPHA;
    private static final long H_ALPHANUM = H_DIGIT | H_ALPHA;

    // hex           = digit | "A" | "B" | "C" | "D" | "E" | "F" |
    //                         "a" | "b" | "c" | "d" | "e" | "f"
    private static final long L_HEX = L_DIGIT;
    private static final long H_HEX = highMask('A', 'F') | highMask('a', 'f');

    // mark          = "-" | "_" | "." | "!" | "~" | "*" | "'" |
    //                 "(" | ")"
    private static final long L_MARK = lowMask("-_.!~*'()");
    private static final long H_MARK = highMask("-_.!~*'()");

    // unreserved    = alphanum | mark
    private static final long L_UNRESERVED = L_ALPHANUM | L_MARK;
    private static final long H_UNRESERVED = H_ALPHANUM | H_MARK;

    // reserved      = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
    //                 "$" | "," | "[" | "]"
    // Added per RFC2732: "[", "]"
    private static final long L_RESERVED = lowMask(";/?:@&=+$,[]");
    private static final long H_RESERVED = highMask(";/?:@&=+$,[]");

    // The zero'th bit is used to indicate that escape pairs and non-US-ASCII
    // characters are allowed; this is handled by the scanEscape method below.
    private static final long L_ESCAPED = 1L;
    private static final long H_ESCAPED = 0L;

    // uric          = reserved | unreserved | escaped
    private static final long L_URIC = L_RESERVED | L_UNRESERVED | L_ESCAPED;
    private static final long H_URIC = H_RESERVED | H_UNRESERVED | H_ESCAPED;

    // pchar         = unreserved | escaped |
    //                 ":" | "@" | "&" | "=" | "+" | "$" | ","
    private static final long L_PCHAR
	= L_UNRESERVED | L_ESCAPED | lowMask(":@&=+$,");
    private static final long H_PCHAR
	= H_UNRESERVED | H_ESCAPED | highMask(":@&=+$,");

    // All valid path characters
    private static final long L_PATH = L_PCHAR | lowMask(";/");
    private static final long H_PATH = H_PCHAR | highMask(";/");

    // Dash, for use in domainlabel and toplabel
    private static final long L_DASH = lowMask("-");
    private static final long H_DASH = highMask("-");

    // Dot, for use in hostnames
    private static final long L_DOT = lowMask(".");
    private static final long H_DOT = highMask(".");

    // userinfo      = *( unreserved | escaped |
    //                    ";" | ":" | "&" | "=" | "+" | "$" | "," )
    private static final long L_USERINFO
	= L_UNRESERVED | L_ESCAPED | lowMask(";:&=+$,");
    private static final long H_USERINFO
	= H_UNRESERVED | H_ESCAPED | highMask(";:&=+$,");

    // reg_name      = 1*( unreserved | escaped | "$" | "," |
    //                     ";" | ":" | "@" | "&" | "=" | "+" )
    private static final long L_REG_NAME
	= L_UNRESERVED | L_ESCAPED | lowMask("$,;:@&=+");
    private static final long H_REG_NAME
	= H_UNRESERVED | H_ESCAPED | highMask("$,;:@&=+");

    // All valid characters for server-based authorities
    private static final long L_SERVER
	= L_USERINFO | L_ALPHANUM | L_DASH | lowMask(".:@[]");
    private static final long H_SERVER
	= H_USERINFO | H_ALPHANUM | H_DASH | highMask(".:@[]");

    // Special case of server authority that represents an IPv6 address
    // In this case, a % does not signify an escape sequence
    private static final long L_SERVER_PERCENT
	= L_SERVER | lowMask("%");
    private static final long H_SERVER_PERCENT
	= H_SERVER | highMask("%");
    private static final long L_LEFT_BRACKET = lowMask("[");
    private static final long H_LEFT_BRACKET = highMask("[");

    // scheme        = alpha *( alpha | digit | "+" | "-" | "." )
    private static final long L_SCHEME = L_ALPHA | L_DIGIT | lowMask("+-.");
    private static final long H_SCHEME = H_ALPHA | H_DIGIT | highMask("+-.");

    // uric_no_slash = unreserved | escaped | ";" | "?" | ":" | "@" |
    //                 "&" | "=" | "+" | "$" | ","
    private static final long L_URIC_NO_SLASH
	= L_UNRESERVED | L_ESCAPED | lowMask(";?:@&=+$,");
    private static final long H_URIC_NO_SLASH
	= H_UNRESERVED | H_ESCAPED | highMask(";?:@&=+$,");


    // -- Escaping and encoding --

    private final static char[] hexDigits = {
	'0', '1', '2', '3', '4', '5', '6', '7',
	'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
    };

    private static void appendEscape(StringBuffer sb, byte b) {
	sb.append('%');
	sb.append(hexDigits[(b >> 4) & 0x0f]);
	sb.append(hexDigits[(b >> 0) & 0x0f]);
    }

    private static void appendEncoded(StringBuffer sb, char c) {
	ByteBuffer bb = null;
	try {
	    bb = ThreadLocalCoders.encoderFor("UTF-8")
		.encode(CharBuffer.wrap("" + c));
	} catch (CharacterCodingException x) {
	    assert false;
	}
	while (bb.hasRemaining()) {
	    int b = bb.get() & 0xff;
	    if (b >= 0x80)
		appendEscape(sb, (byte)b);
	    else
		sb.append((char)b);
	}
    }

    // Quote any characters in s that are not permitted
    // by the given mask pair
    //
    private static String quote(String s, long lowMask, long highMask) {
	int n = s.length();
	StringBuffer sb = null;
	boolean allowNonASCII = ((lowMask & L_ESCAPED) != 0);
	for (int i = 0; i < s.length(); i++) {
	    char c = s.charAt(i);
	    if (c < '\u0080') {
		if (!match(c, lowMask, highMask)) {
		    if (sb == null) {
			sb = new StringBuffer();
			sb.append(s.substring(0, i));
		    }
		    appendEscape(sb, (byte)c);
		} else {
		    if (sb != null)
			sb.append(c);
		}
	    } else if (allowNonASCII
		       && (Character.isSpaceChar(c)
			   || Character.isISOControl(c))) {
		if (sb == null) {
		    sb = new StringBuffer();
		    sb.append(s.substring(0, i));
		}
		appendEncoded(sb, c);
	    } else {
		if (sb != null)
		    sb.append(c);
	    }
	}
	return (sb == null) ? s : sb.toString();
    }

    // Encodes all characters >= \u0080 into escaped, normalized UTF-8 octets,
    // assuming that s is otherwise legal
    //
    private static String encode(String s) {
	int n = s.length();
	if (n == 0)
	    return s;

	// First check whether we actually need to encode
	for (int i = 0;;) {
	    if (s.charAt(i) >= '\u0080')
		break;
	    if (++i >= n)
		return s;
	}

	String ns = Normalizer.normalize(s, Normalizer.Form.NFC);
	ByteBuffer bb = null;
	try {
	    bb = ThreadLocalCoders.encoderFor("UTF-8")
		.encode(CharBuffer.wrap(ns));
	} catch (CharacterCodingException x) {
	    assert false;
	}

	StringBuffer sb = new StringBuffer();
	while (bb.hasRemaining()) {
	    int b = bb.get() & 0xff;
	    if (b >= 0x80)
		appendEscape(sb, (byte)b);
	    else
		sb.append((char)b);
	}
	return sb.toString();
    }

    private static int decode(char c) {
	if ((c >= '0') && (c <= '9'))
	    return c - '0';
	if ((c >= 'a') && (c <= 'f'))
	    return c - 'a' + 10;
	if ((c >= 'A') && (c <= 'F'))
	    return c - 'A' + 10;
	assert false;
	return -1;
    }

    private static byte decode(char c1, char c2) {
	return (byte)(  ((decode(c1) & 0xf) << 4)
		      | ((decode(c2) & 0xf) << 0));
    }

    // Evaluates all escapes in s, applying UTF-8 decoding if needed.  Assumes
    // that escapes are well-formed syntactically, i.e., of the form %XX.  If a
    // sequence of escaped octets is not valid UTF-8 then the erroneous octets
    // are replaced with '\uFFFD'.
    // Exception: any "%" found between "[]" is left alone. It is an IPv6 literal
    //            with a scope_id
    //
    private static String decode(String s) {
	if (s == null)
	    return s;
	int n = s.length();
	if (n == 0)
	    return s;
	if (s.indexOf('%') < 0)
	    return s;

	byte[] ba = new byte[n];
	StringBuffer sb = new StringBuffer(n);
	ByteBuffer bb = ByteBuffer.allocate(n);
	CharBuffer cb = CharBuffer.allocate(n);
	CharsetDecoder dec = ThreadLocalCoders.decoderFor("UTF-8")
	    .onMalformedInput(CodingErrorAction.REPLACE)
	    .onUnmappableCharacter(CodingErrorAction.REPLACE);

	// This is not horribly efficient, but it will do for now
	char c = s.charAt(0);
    	boolean betweenBrackets = false;

	for (int i = 0; i < n;) {
	    assert c == s.charAt(i);	// Loop invariant
	    if (c == '[') {
		betweenBrackets = true;
	    } else if (betweenBrackets && c == ']') {
		betweenBrackets = false;
	    }
	    if (c != '%' || betweenBrackets) {
		sb.append(c);
		if (++i >= n)
		    break;
		c = s.charAt(i);
		continue;
	    }
	    bb.clear();
	    int ui = i;
	    for (;;) {
		assert (n - i >= 2);
		bb.put(decode(s.charAt(++i), s.charAt(++i)));
		if (++i >= n)
		    break;
		c = s.charAt(i);
		if (c != '%')
		    break;
	    }
	    bb.flip();
	    cb.clear();
	    dec.reset();
	    CoderResult cr = dec.decode(bb, cb, true);
	    assert cr.isUnderflow();
	    cr = dec.flush(cb);
	    assert cr.isUnderflow();
	    sb.append(cb.flip().toString());
	}

	return sb.toString();
    }


    // -- Parsing --

    // For convenience we wrap the input URI string in a new instance of the
    // following internal class.  This saves always having to pass the input
    // string as an argument to each internal scan/parse method.

    private class Parser {

	private String input;		// URI input string
	private boolean requireServerAuthority = false;

	Parser(String s) {
	    input = s;
	    string = s;
	}

	// -- Methods for throwing URISyntaxException in various ways --

	private void fail(String reason) throws URISyntaxException {
	    throw new URISyntaxException(input, reason);
	}

	private void fail(String reason, int p) throws URISyntaxException {
	    throw new URISyntaxException(input, reason, p);
	}

	private void failExpecting(String expected, int p)
	    throws URISyntaxException
	{
	    fail("Expected " + expected, p);
	}

	private void failExpecting(String expected, String prior, int p)
	    throws URISyntaxException
	{
	    fail("Expected " + expected + " following " + prior, p);
	}


	// -- Simple access to the input string --

	// Return a substring of the input string
	//
	private String substring(int start, int end) {
	    return input.substring(start, end);
	}

	// Return the char at position p,
	// assuming that p < input.length()
	//
	private char charAt(int p) {
	    return input.charAt(p);
	}

	// Tells whether start < end and, if so, whether charAt(start) == c
	//
	private boolean at(int start, int end, char c) {
	    return (start < end) && (charAt(start) == c);
	}

	// Tells whether start + s.length() < end and, if so,
	// whether the chars at the start position match s exactly
	//
	private boolean at(int start, int end, String s) {
	    int p = start;
	    int sn = s.length();
	    if (sn > end - p)
		return false;
	    int i = 0;
	    while (i < sn) {
		if (charAt(p++) != s.charAt(i)) {
		    break;
		}
		i++;
	    }
	    return (i == sn);
	}


	// -- Scanning --

	// The various scan and parse methods that follow use a uniform
	// convention of taking the current start position and end index as
	// their first two arguments.  The start is inclusive while the end is
	// exclusive, just as in the String class, i.e., a start/end pair
	// denotes the left-open interval [start, end) of the input string.
	//
	// These methods never proceed past the end position.  They may return
	// -1 to indicate outright failure, but more often they simply return
	// the position of the first char after the last char scanned.  Thus
	// a typical idiom is
	//
	//     int p = start;
	//     int q = scan(p, end, ...);
	//     if (q > p)
	//         // We scanned something
	//         ...;
	//     else if (q == p)
	//         // We scanned nothing
	//         ...;
	//     else if (q == -1)
	//         // Something went wrong
	//         ...;


	// Scan a specific char: If the char at the given start position is
	// equal to c, return the index of the next char; otherwise, return the
	// start position.
	//
	private int scan(int start, int end, char c) {
	    if ((start < end) && (charAt(start) == c))
		return start + 1;
	    return start;
	}

	// Scan forward from the given start position.  Stop at the first char
	// in the err string (in which case -1 is returned), or the first char
	// in the stop string (in which case the index of the preceding char is
	// returned), or the end of the input string (in which case the length
	// of the input string is returned).  May return the start position if
	// nothing matches.
	//
	private int scan(int start, int end, String err, String stop) {
	    int p = start;
	    while (p < end) {
		char c = charAt(p);
		if (err.indexOf(c) >= 0)
		    return -1;
		if (stop.indexOf(c) >= 0)
		    break;
		p++;
	    }
	    return p;
	}

	// Scan a potential escape sequence, starting at the given position,
	// with the given first char (i.e., charAt(start) == c).
	//
	// This method assumes that if escapes are allowed then visible
	// non-US-ASCII chars are also allowed.
	//
	private int scanEscape(int start, int n, char first)
	    throws URISyntaxException
	{
	    int p = start;
	    char c = first;
	    if (c == '%') {
		// Process escape pair
		if ((p + 3 <= n)
		    && match(charAt(p + 1), L_HEX, H_HEX)
		    && match(charAt(p + 2), L_HEX, H_HEX)) {
		    return p + 3;
		}
		fail("Malformed escape pair", p);
	    } else if ((c > 128)
		       && !Character.isSpaceChar(c)
		       && !Character.isISOControl(c)) {
		// Allow unescaped but visible non-US-ASCII chars
		return p + 1;
	    }
	    return p;
	}

	// Scan chars that match the given mask pair
	//
	private int scan(int start, int n, long lowMask, long highMask)
	    throws URISyntaxException
	{
	    int p = start;
	    while (p < n) {
		char c = charAt(p);
		if (match(c, lowMask, highMask)) {
		    p++;
		    continue;
		}
		if ((lowMask & L_ESCAPED) != 0) {
		    int q = scanEscape(p, n, c);
		    if (q > p) {
			p = q;
			continue;
		    }
		}
		break;
	    }
	    return p;
	}

	// Check that each of the chars in [start, end) matches the given mask
	//
	private void checkChars(int start, int end,
				long lowMask, long highMask,
				String what)
	    throws URISyntaxException
	{
	    int p = scan(start, end, lowMask, highMask);
	    if (p < end)
		fail("Illegal character in " + what, p);
	}

	// Check that the char at position p matches the given mask
	//
	private void checkChar(int p,
			       long lowMask, long highMask,
			       String what)
	    throws URISyntaxException
	{
	    checkChars(p, p + 1, lowMask, highMask, what);
	}


	// -- Parsing --

	// [<scheme>:]<scheme-specific-part>[#<fragment>]
	//
	void parse(boolean rsa) throws URISyntaxException {
	    requireServerAuthority = rsa;
	    int ssp;			// Start of scheme-specific part
	    int n = input.length();
	    int p = scan(0, n, "/?#", ":");
	    if ((p >= 0) && at(p, n, ':')) {
		if (p == 0)
		    failExpecting("scheme name", 0);
		checkChar(0, L_ALPHA, H_ALPHA, "scheme name");
		checkChars(1, p, L_SCHEME, H_SCHEME, "scheme name");
		scheme = substring(0, p);
		p++;			// Skip ':'
		ssp = p;
		if (at(p, n, '/')) {
		    p = parseHierarchical(p, n);
		} else {
		    int q = scan(p, n, "", "#");
		    if (q <= p)
			failExpecting("scheme-specific part", p);
		    checkChars(p, q, L_URIC, H_URIC, "opaque part");
		    p = q;
		}
	    } else {
		ssp = 0;
		p = parseHierarchical(0, n);
	    }
	    schemeSpecificPart = substring(ssp, p);
	    if (at(p, n, '#')) {
		checkChars(p + 1, n, L_URIC, H_URIC, "fragment");
		fragment = substring(p + 1, n);
		p = n;
	    }
	    if (p < n)
		fail("end of URI", p);
	}

	// [//authority]<path>[?<query>]
	//
	// DEVIATION from RFC2396: We allow an empty authority component as
	// long as it's followed by a non-empty path, query component, or
	// fragment component.  This is so that URIs such as "file:///foo/bar"
	// will parse.  This seems to be the intent of RFC2396, though the
	// grammar does not permit it.  If the authority is empty then the
	// userInfo, host, and port components are undefined.
	//
	// DEVIATION from RFC2396: We allow empty relative paths.  This seems
	// to be the intent of RFC2396, but the grammar does not permit it.
	// The primary consequence of this deviation is that "#f" parses as a
	// relative URI with an empty path.
	//
	private int parseHierarchical(int start, int n)
	    throws URISyntaxException
	{
	    int p = start;
	    if (at(p, n, '/') && at(p + 1, n, '/')) {
		p += 2;
		int q = scan(p, n, "", "/?#");
		if (q > p) {
		    p = parseAuthority(p, q);
		} else if (q < n) {
		    // DEVIATION: Allow empty authority prior to non-empty 
		    // path, query component or fragment identifier
		} else
		    failExpecting("authority", p);
	    }
	    int q = scan(p, n, "", "?#"); // DEVIATION: May be empty
	    checkChars(p, q, L_PATH, H_PATH, "path");
	    path = substring(p, q);
	    p = q;
	    if (at(p, n, '?')) {
		p++;
		q = scan(p, n, "", "#");
		checkChars(p, q, L_URIC, H_URIC, "query");
		query = substring(p, q);
		p = q;
	    }
	    return p;
	}

	// authority     = server | reg_name
	//
	// Ambiguity: An authority that is a registry name rather than a server
	// might have a prefix that parses as a server.  We use the fact that
	// the authority component is always followed by '/' or the end of the
	// input string to resolve this: If the complete authority did not
	// parse as a server then we try to parse it as a registry name.
	//
	private int parseAuthority(int start, int n)
	    throws URISyntaxException
	{
	    int p = start;
	    int q = p;
	    URISyntaxException ex = null;

	    boolean serverChars;
	    boolean regChars;

	    if (scan(p, n, "", "]") > p) {
		// contains a literal IPv6 address, therefore % is allowed
	    	serverChars = (scan(p, n, L_SERVER_PERCENT, H_SERVER_PERCENT) == n);
	    } else {
	    	serverChars = (scan(p, n, L_SERVER, H_SERVER) == n);
	    }
	    regChars = (scan(p, n, L_REG_NAME, H_REG_NAME) == n);

	    if (regChars && !serverChars) {
		// Must be a registry-based authority
		authority = substring(p, n);
		return n;
	    }

	    if (serverChars) {
		// Might be (probably is) a server-based authority, so attempt
		// to parse it as such.  If the attempt fails, try to treat it
		// as a registry-based authority.
		try {
		    q = parseServer(p, n);
		    if (q < n)
			failExpecting("end of authority", q);
		    authority = substring(p, n);
		} catch (URISyntaxException x) {
		    // Undo results of failed parse
		    userInfo = null;
		    host = null;
		    port = -1;
		    if (requireServerAuthority) {
			// If we're insisting upon a server-based authority,
			// then just re-throw the exception
			throw x;
		    } else {
			// Save the exception in case it doesn't parse as a
			// registry either
			ex = x;
			q = p;
		    }
		}
	    }

	    if (q < n) {
		if (regChars) {
		    // Registry-based authority
		    authority = substring(p, n);
		} else if (ex != null) {
		    // Re-throw exception; it was probably due to
		    // a malformed IPv6 address
		    throw ex;
		} else {
		    fail("Illegal character in authority", q);
		}
	    }

	    return n;
	}


	// [<userinfo>@]<host>[:<port>]
	//
	private int parseServer(int start, int n)
	    throws URISyntaxException
	{
	    int p = start;
	    int q;

	    // userinfo
	    q = scan(p, n, "/?#", "@");
	    if ((q >= p) && at(q, n, '@')) {
		checkChars(p, q, L_USERINFO, H_USERINFO, "user info");
		userInfo = substring(p, q);
		p = q + 1;		// Skip '@'
	    }

	    // hostname, IPv4 address, or IPv6 address
	    if (at(p, n, '[')) {
		// DEVIATION from RFC2396: Support IPv6 addresses, per RFC2732
		p++;
		q = scan(p, n, "/?#", "]");
		if ((q > p) && at(q, n, ']')) {
		    // look for a "%" scope id
		    int r = scan (p, q, "", "%");
		    if (r > p) {
		    	parseIPv6Reference(p, r);
			if (r+1 == q) {
			    fail ("scope id expected");
			}
			checkChars (r+1, q, L_ALPHANUM, H_ALPHANUM, 
						"scope id");
		    } else {
		    	parseIPv6Reference(p, q);
		    }
	    	    host = substring(p-1, q+1);
		    p = q + 1;
		} else {
		    failExpecting("closing bracket for IPv6 address", q);
		}
	    } else {
		q = parseIPv4Address(p, n);
		if (q <= p)
		    q = parseHostname(p, n);
		p = q;
	    }

	    // port
	    if (at(p, n, ':')) {
		p++;
		q = scan(p, n, "", "/");
		if (q > p) {
		    checkChars(p, q, L_DIGIT, H_DIGIT, "port number");
		    try {
			port = Integer.parseInt(substring(p, q));
		    } catch (NumberFormatException x) {
			fail("Malformed port number", p);
		    }
		    p = q;
		}
	    }
	    if (p < n)
		failExpecting("port number", p);

	    return p;
	}

	// Scan a string of decimal digits whose value fits in a byte
	//
	private int scanByte(int start, int n)
	    throws URISyntaxException
	{
	    int p = start;
	    int q = scan(p, n, L_DIGIT, H_DIGIT);
	    if (q <= p) return q;
	    if (Integer.parseInt(substring(p, q)) > 255) return p;
	    return q;
	}

	// Scan an IPv4 address.
	//
	// If the strict argument is true then we require that the given
	// interval contain nothing besides an IPv4 address; if it is false
	// then we only require that it start with an IPv4 address.
	//
	// If the interval does not contain or start with (depending upon the
	// strict argument) a legal IPv4 address characters then we return -1
	// immediately; otherwise we insist that these characters parse as a
	// legal IPv4 address and throw an exception on failure.
	//
	// We assume that any string of decimal digits and dots must be an IPv4
	// address.  It won't parse as a hostname anyway, so making that
	// assumption here allows more meaningful exceptions to be thrown.
	//
	private int scanIPv4Address(int start, int n, boolean strict)
	    throws URISyntaxException
	{
	    int p = start;
	    int q;
	    int m = scan(p, n, L_DIGIT | L_DOT, H_DIGIT | H_DOT);
	    if ((m <= p) || (strict && (m != n)))
		return -1;
	    for (;;) {
		// Per RFC2732: At most three digits per byte
		// Further constraint: Each element fits in a byte
		if ((q = scanByte(p, m)) <= p) break;   p = q;
		if ((q = scan(p, m, '.')) <= p) break;  p = q;
		if ((q = scanByte(p, m)) <= p) break;   p = q;
		if ((q = scan(p, m, '.')) <= p) break;  p = q;
		if ((q = scanByte(p, m)) <= p) break;   p = q;
		if ((q = scan(p, m, '.')) <= p) break;  p = q;
		if ((q = scanByte(p, m)) <= p) break;   p = q;
		if (q < m) break;
		return q;
	    }
	    fail("Malformed IPv4 address", q);
	    return -1;
	}

	// Take an IPv4 address: Throw an exception if the given interval
	// contains anything except an IPv4 address
	//
	private int takeIPv4Address(int start, int n, String expected)
	    throws URISyntaxException
	{
	    int p = scanIPv4Address(start, n, true);
	    if (p <= start)
		failExpecting(expected, start);
	    return p;
	}

	// Attempt to parse an IPv4 address, returning -1 on failure but
	// allowing the given interval to contain [:<characters>] after
	// the IPv4 address.
	//
	private int parseIPv4Address(int start, int n) {
	    int p;

	    try {
	        p = scanIPv4Address(start, n, false);
	    } catch (URISyntaxException x) {
		return -1;
            } catch (NumberFormatException nfe) {
		return -1;
            }

	    if (p > start && p < n) {
	        // IPv4 address is followed by something - check that
		// it's a ":" as this is the only valid character to
		// follow an address.
		if (charAt(p) != ':') {
		    p = -1;
		}
	    }

	    if (p > start)
		host = substring(start, p);

	    return p;
	}

	// hostname      = domainlabel [ "." ] | 1*( domainlabel "." ) toplabel [ "." ] 
	// domainlabel   = alphanum | alphanum *( alphanum | "-" ) alphanum
        // toplabel      = alpha | alpha *( alphanum | "-" ) alphanum
	//
	private int parseHostname(int start, int n)
	    throws URISyntaxException
	{
	    int p = start;
	    int q;
	    int l = -1;			// Start of last parsed label

	    do {
		// domainlabel = alphanum [ *( alphanum | "-" ) alphanum ]
		q = scan(p, n, L_ALPHANUM, H_ALPHANUM);
		if (q <= p)
		    break;
		l = p;
		if (q > p) {
		    p = q;
		    q = scan(p, n, L_ALPHANUM | L_DASH, H_ALPHANUM | H_DASH);
		    if (q > p) {
			if (charAt(q - 1) == '-')
			    fail("Illegal character in hostname", q - 1);
			p = q;
		    }
		}
		q = scan(p, n, '.');
		if (q <= p)
		    break;
		p = q;
	    } while (p < n);

	    if ((p < n) && !at(p, n, ':'))
		fail("Illegal character in hostname", p);

	    if (l < 0)
		failExpecting("hostname", start);

	    // for a fully qualified hostname check that the rightmost
	    // label starts with an alpha character.
	    if (l > start && !match(charAt(l), L_ALPHA, H_ALPHA)) {
		fail("Illegal character in hostname", l);
	    }

	    host = substring(start, p);
	    return p;
	}


	// IPv6 address parsing, from RFC2373: IPv6 Addressing Architecture
	//
	// Bug: The grammar in RFC2373 Appendix B does not allow addresses of
	// the form ::12.34.56.78, which are clearly shown in the examples
	// earlier in the document.  Here is the original grammar:
	//
	//   IPv6address = hexpart [ ":" IPv4address ]
	//   hexpart     = hexseq | hexseq "::" [ hexseq ] | "::" [ hexseq ]
	//   hexseq      = hex4 *( ":" hex4)
	//   hex4        = 1*4HEXDIG
	//
	// We therefore use the following revised grammar:
	//
	//   IPv6address = hexseq [ ":" IPv4address ]
	//                 | hexseq [ "::" [ hexpost ] ]
	//                 | "::" [ hexpost ]
	//   hexpost     = hexseq | hexseq ":" IPv4address | IPv4address
	//   hexseq      = hex4 *( ":" hex4)
	//   hex4        = 1*4HEXDIG
	//
	// This covers all and only the following cases:
	//
	//   hexseq
	//   hexseq : IPv4address
	//   hexseq ::
	//   hexseq :: hexseq
	//   hexseq :: hexseq : IPv4address
	//   hexseq :: IPv4address
	//   :: hexseq
	//   :: hexseq : IPv4address
	//   :: IPv4address
	//   ::
	//
	// Additionally we constrain the IPv6 address as follows :-
	//
	//  i.  IPv6 addresses without compressed zeros should contain
	//      exactly 16 bytes.
	//
	//  ii. IPv6 addresses with compressed zeros should contain
	//      less than 16 bytes.

	private int ipv6byteCount = 0;

	private int parseIPv6Reference(int start, int n)
	    throws URISyntaxException
	{
	    int p = start;
	    int q;
	    boolean compressedZeros = false;

	    q = scanHexSeq(p, n);

	    if (q > p) {
		p = q;
		if (at(p, n, "::")) {
		    compressedZeros = true;
		    p = scanHexPost(p + 2, n);
		} else if (at(p, n, ':')) {
		    p = takeIPv4Address(p + 1,  n, "IPv4 address");
		    ipv6byteCount += 4;
		}
	    } else if (at(p, n, "::")) {
		compressedZeros = true;
		p = scanHexPost(p + 2, n);
	    }
	    if (p < n)
		fail("Malformed IPv6 address", start);
	    if (ipv6byteCount > 16)
		fail("IPv6 address too long", start);
	    if (!compressedZeros && ipv6byteCount < 16) 
		fail("IPv6 address too short", start);
	    if (compressedZeros && ipv6byteCount == 16)
		fail("Malformed IPv6 address", start);

	    return p;
	}

	private int scanHexPost(int start, int n)
	    throws URISyntaxException
	{
	    int p = start;
	    int q;

	    if (p == n)
		return p;

	    q = scanHexSeq(p, n);
	    if (q > p) {
		p = q;
		if (at(p, n, ':')) {
		    p++;
		    p = takeIPv4Address(p, n, "hex digits or IPv4 address");
		    ipv6byteCount += 4;
		}
	    } else {
		p = takeIPv4Address(p, n, "hex digits or IPv4 address");
		ipv6byteCount += 4;
	    }
	    return p;
	}

	// Scan a hex sequence; return -1 if one could not be scanned
	//
	private int scanHexSeq(int start, int n)
	    throws URISyntaxException
	{
	    int p = start;
	    int q;

	    q = scan(p, n, L_HEX, H_HEX);
	    if (q <= p)
		return -1;
	    if (at(q, n, '.'))		// Beginning of IPv4 address
		return -1;
	    if (q > p + 4)
                fail("IPv6 hexadecimal digit sequence too long", p);
	    ipv6byteCount += 2;
	    p = q;
	    while (p < n) {
		if (!at(p, n, ':'))
		    break;
		if (at(p + 1, n, ':'))
		    break;		// "::"
		p++;
		q = scan(p, n, L_HEX, H_HEX);
		if (q <= p)
		    failExpecting("digits for an IPv6 address", p);
		if (at(q, n, '.')) {	// Beginning of IPv4 address
		    p--;
		    break;
		}
		if (q > p + 4)
		    fail("IPv6 hexadecimal digit sequence too long", p);
		ipv6byteCount += 2;
		p = q;
	    }

	    return p;
	}

    }

}

Generated By: JavaOnTracks Doclet 0.1.4     ©Thibaut Colar