summaryrefslogtreecommitdiff
path: root/libjava/classpath/gnu/xml/util/XCat.java
blob: ea23ad682fe53284d7283e69fedbf2ea35108c5c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
/* XCat.java --
   Copyright (C) 2001 Free Software Foundation, Inc.

This file is part of GNU Classpath.

GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.

GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */


package gnu.xml.util;

import gnu.java.lang.CPStringBuilder;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.StringTokenizer;
import java.util.Stack;
import java.util.Vector;

import org.xml.sax.Attributes;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;

import org.xml.sax.ext.DefaultHandler2;
import org.xml.sax.ext.EntityResolver2;

import org.xml.sax.helpers.XMLReaderFactory;

/**
 * Packages <a href=
    "http://www.oasis-open.org/committees/entity/spec-2001-08-06.html"
    >OASIS XML Catalogs</a>,
 * primarily for entity resolution by parsers.
 * That specification defines an XML syntax for mappings between
 * identifiers declared in DTDs (particularly PUBLIC identifiers) and
 * locations.  SAX has always supported such mappings, but conventions for
 * an XML file syntax to maintain them have previously been lacking.
 *
 * <p> This has three main operational modes.  The primary intended mode is
 * to create a resolver, then preloading it with one or more site-standard
 * catalogs before using it with one or more SAX parsers: <pre>
 *      XCat    catalog = new XCat ();
 *      catalog.setErrorHandler (diagnosticErrorHandler);
 *      catalog.loadCatalog ("file:/local/catalogs/catalog.cat");
 *      catalog.loadCatalog ("http://shared/catalog.cat");
 *      ...
 *      catalog.disableLoading ();
 *      parser1.setEntityResolver (catalog);
 *      parser2.setEntityResolver (catalog);
 *      ...</pre>
 *
 * <p>A second mode is to arrange that your application uses instances of
 * this class as its entity resolver, and automatically loads catalogs
 * referenced by <em>&lt;?oasis-xml-catalog...?&gt;</em> processing
 * instructions found before the DTD in documents it parses.
 * It would then discard the resolver after each parse.
 *
 * <p> A third mode applies catalogs in contexts other than entity
 * resolution for parsers.
 * The {@link #resolveURI resolveURI()} method supports resolving URIs
 * stored in XML application data, rather than inside DTDs.
 * Catalogs would be loaded as shown above, and the catalog could
 * be used concurrently for parser entity resolution and for
 * application URI resolution.
 * </p>
 *
 * <center><hr width='70%'></center>
 *
 * <p>Errors in catalogs implicitly loaded (during resolution) are ignored
 * beyond being reported through any <em>ErrorHandler</em> assigned using
 * {@link #setErrorHandler setErrorHandler()}.  SAX exceptions
 * thrown from such a handler won't abort resolution, although throwing a
 * <em>RuntimeException</em> or <em>Error</em> will normally abort both
 * resolution and parsing.  Useful diagnostic information is available to
 * any <em>ErrorHandler</em> used to report problems, or from any exception
 * thrown from an explicit {@link #loadCatalog loadCatalog()} invocation.
 * Applications can use that information as troubleshooting aids.
 *
 * <p>While this class requires <em>SAX2 Extensions 1.1</em> classes in
 * its class path, basic functionality does not require using a SAX2
 * parser that supports the extended entity resolution functionality.
 * See the original SAX1
 * {@link #resolveEntity(java.lang.String,java.lang.String) resolveEntity()}
 * method for a list of restrictions which apply when it is used with
 * older SAX parsers.
 *
 * @see EntityResolver2
 *
 * @author David Brownell
 */
public class XCat implements EntityResolver2
{
    private Catalog             catalogs [];
    private boolean             usingPublic = true;
    private boolean             loadingPermitted = true;
    private boolean             unified = true;
    private String              parserClass;
    private ErrorHandler        errorHandler;

    // private EntityResolver   next;   // chain to next if we fail...

    //
    // NOTE:  This is a straightforward implementation, and if
    // there are lots of "nextCatalog" or "delegate*" entries
    // in use, two tweaks would be worth considering:
    //
    //  - Centralize some sort of cache (key by URI) for individual
    //    resolvers.  That'd avoid multiple copies of a given catalog.
    //
    //  - Have resolution track what catalogs (+modes) have been
    //    searched.  This would support loop detection.
    //


    /**
     * Initializes without preloading a catalog.
     * This API is convenient when you may want to arrange that catalogs
     * are automatically loaded when explicitly referenced in documents,
     * using the <em>oasis-xml-catalog</em> processing instruction.
     * In such cases you won't usually be able to preload catalogs.
     */
    public XCat () { }

    /**
     * Initializes, and preloads a catalog using the default SAX parser.
     * This API is convenient when you operate with one or more standard
     * catalogs.
     *
     * <p> This just delegates to {@link #loadCatalog loadCatalog()};
     * see it for exception information.
     *
     * @param uri absolute URI for the catalog file.
     */
    public XCat (String uri)
    throws SAXException, IOException
        { loadCatalog (uri); }


    /**
     * Loads an OASIS XML Catalog.
     * It is appended to the list of currently active catalogs, or
     * reloaded if a catalog with the same URI was already loaded.
     * Callers have control over what parser is used, how catalog parsing
     * errors are reported, and whether URIs will be resolved consistently.
     *
     * <p> The OASIS specification says that errors detected when loading
     * catalogs "must recover by ignoring the catalog entry file that
     * failed, and proceeding."  In this API, that action can be the
     * responsibility of applications, when they explicitly load any
     * catalog using this method.
     *
     * <p>Note that catalogs referenced by this one will not be loaded
     * at this time.  Catalogs referenced through <em>nextCatalog</em>
     * or <em>delegate*</em> elements are normally loaded only if needed.
     *
     * @see #setErrorHandler
     * @see #setParserClass
     * @see #setUnified
     *
     * @param uri absolute URI for the catalog file.
     *
     * @exception IOException As thrown by the parser, typically to
     *  indicate problems reading data from that URI.
     * @exception SAXException As thrown by the parser, typically to
     *  indicate problems parsing data from that URI.  It may also
     *  be thrown if the parser doesn't support necessary handlers.
     * @exception IllegalStateException When attempting to load a
     *  catalog after loading has been {@link #disableLoading disabled},
     *  such as after any entity or URI lookup has been performed.
     */
    public synchronized void loadCatalog (String uri)
    throws SAXException, IOException
    {
        Catalog         catalog;
        int             index = -1;

        if (!loadingPermitted)
            throw new IllegalStateException ();

        uri = normalizeURI (uri);
        if (catalogs != null) {
            // maybe just reload
            for (index = 0; index < catalogs.length; index++)
                if (uri.equals (catalogs [index].catalogURI))
                    break;
        }
        catalog = loadCatalog (parserClass, errorHandler, uri, unified);

        // add to list of catalogs
        if (catalogs == null) {
            index = 0;
            catalogs = new Catalog [1];
        } else if (index == catalogs.length) {
            Catalog             tmp [];

            tmp = new Catalog [index + 1];
            System.arraycopy (catalogs, 0, tmp, 0, index);
            catalogs = tmp;
        }
        catalogs [index] = catalog;
    }


    /**
     * "New Style" external entity resolution for parsers.
     * Calls to this method prevent explicit loading of additional catalogs
     * using {@link #loadCatalog loadCatalog()}.
     *
     * <p>This supports the full core catalog functionality for locating
     * (and relocating) parsed entities that have been declared in a
     * document's DTD.
     *
     * @param name Entity name, such as "dudley", "%nell", or "[dtd]".
     * @param publicId Either a normalized public ID, or null.
     * @param baseURI Absolute base URI associated with systemId.
     * @param systemId URI found in entity declaration (may be
     *  relative to baseURI).
     *
     * @return Input source for accessing the external entity, or null
     *  if no mapping was found.  The input source may have opened
     *  the stream, and will have a fully resolved URI.
     *
     * @see #getExternalSubset
     */
    public InputSource resolveEntity (
        String name,            // UNUSED ... systemId is always non-null
        String publicId,
        String baseURI,         // UNUSED ... it just lets sysId be relative
        String systemId
    ) throws SAXException, IOException
    {
        if (loadingPermitted)
            disableLoading ();

        try {
            // steps as found in OASIS XML catalog spec 7.1.2
            // steps 1, 8 involve looping over the list of catalogs
            for (int i = 0; i < catalogs.length; i++) {
                InputSource     retval;
                retval = catalogs [i].resolve (usingPublic, publicId, systemId);
                if (retval != null)
                    return retval;
            }
        } catch (DoneDelegation x) {
            // done!
        }
        // step 9 involves returning "no match"
        return null;
    }


    /**
     * "New Style" parser callback to add an external subset.
     * For documents that don't include an external subset, this may
     * return one according to <em>doctype</em> catalog entries.
     * (This functionality is not a core part of the OASIS XML Catalog
     * specification, though it's presented in an appendix.)
     * If no such entry is defined, this returns null to indicate that
     * this document will not be modified to include such a subset.
     * Calls to this method prevent explicit loading of additional catalogs
     * using {@link #loadCatalog loadCatalog()}.
     *
     * <p><em>Warning:</em> That catalog functionality can be dangerous.
     * It can provide definitions of general entities, and thereby mask
     * certain well formedess errors.
     *
     * @param name Name of the document element, either as declared in
     *  a DOCTYPE declaration or as observed in the text.
     * @param baseURI Document's base URI (absolute).
     *
     * @return Input source for accessing the external subset, or null
     *  if no mapping was found.  The input source may have opened
     *  the stream, and will have a fully resolved URI.
     */
    public InputSource getExternalSubset (String name, String baseURI)
    throws SAXException, IOException
    {
        if (loadingPermitted)
            disableLoading ();
        try {
            for (int i = 0; i < catalogs.length; i++) {
                InputSource retval = catalogs [i].getExternalSubset (name);
                if (retval != null)
                    return retval;
            }
        } catch (DoneDelegation x) {
            // done!
        }
        return null;
    }


    /**
     * "Old Style" external entity resolution for parsers.
     * This API provides only core functionality.
     * Calls to this method prevent explicit loading of additional catalogs
     * using {@link #loadCatalog loadCatalog()}.
     *
     * <p>The functional limitations of this interface include:</p><ul>
     *
     *  <li>Since system IDs will be absolutized before the resolver
     *  sees them, matching against relative URIs won't work.
     *  This may affect <em>system</em>, <em>rewriteSystem</em>,
     *  and <em>delegateSystem</em> catalog entries.
     *
     *  <li>Because of that absolutization, documents declaring entities
     *  with system IDs using URI schemes that the JVM does not recognize
     *  may be unparsable.  URI schemes such as <em>file:/</em>,
     *  <em>http://</em>, <em>https://</em>, and <em>ftp://</em>
     *  will usually work reliably.
     *
     *  <li>Because missing external subsets can't be provided, the
     *  <em>doctype</em> catalog entries will be ignored.
     *  (The {@link #getExternalSubset getExternalSubset()} method is
     *  a "New Style" resolution option.)
     *
     *  </ul>
     *
     * <p>Applications can tell whether this limited functionality will be
     * used: if the feature flag associated with the {@link EntityResolver2}
     * interface is not <em>true</em>, the limitations apply.  Applications
     * can't usually know whether a given document and catalog will trigger
     * those limitations.  The issue can only be bypassed by operational
     * procedures such as not using catalogs or documents which involve
     * those features.
     *
     * @param publicId Either a normalized public ID, or null
     * @param systemId Always an absolute URI.
     *
     * @return Input source for accessing the external entity, or null
     *  if no mapping was found.  The input source may have opened
     *  the stream, and will have a fully resolved URI.
     */
    final public InputSource resolveEntity (String publicId, String systemId)
    throws SAXException, IOException
    {
        return resolveEntity (null, publicId, null, systemId);
    }


    /**
     * Resolves a URI reference that's not defined to the DTD.
     * This is intended for use with URIs found in document text, such as
     * <em>xml-stylesheet</em> processing instructions and in attribute
     * values, where they are not recognized as URIs by XML parsers.
     * Calls to this method prevent explicit loading of additional catalogs
     * using {@link #loadCatalog loadCatalog()}.
     *
     * <p>This functionality is supported by the OASIS XML Catalog
     * specification, but will never be invoked by an XML parser.
     * It corresponds closely to functionality for mapping system
     * identifiers for entities declared in DTDs; closely enough that
     * this implementation's default behavior is that they be
     * identical, to minimize potential confusion.
     *
     * <p>This method could be useful when implementing the
     * {@link javax.xml.transform.URIResolver} interface, wrapping the
     * input source in a {@link javax.xml.transform.sax.SAXSource}.
     *
     * @see #isUnified
     * @see #setUnified
     *
     * @param baseURI The relevant base URI as specified by the XML Base
     *  specification.  This recognizes <em>xml:base</em> attributes
     *  as overriding the actual (physical) base URI.
     * @param uri Either an absolute URI, or one relative to baseURI
     *
     * @return Input source for accessing the mapped URI, or null
     *  if no mapping was found.  The input source may have opened
     *  the stream, and will have a fully resolved URI.
     */
    public InputSource resolveURI (String baseURI, String uri)
    throws SAXException, IOException
    {
        if (loadingPermitted)
            disableLoading ();

        // NOTE:  baseURI isn't used here, but caller MUST have it,
        // and heuristics _might_ use it in the future ... plus,
        // it's symmetric with resolveEntity ().

        // steps 1, 6 involve looping
        try {
            for (int i = 0; i < catalogs.length; i++) {
                InputSource     tmp = catalogs [i].resolveURI (uri);
                if (tmp != null)
                    return tmp;
            }
        } catch (DoneDelegation x) {
            // done
        }
        // step 7 reports no match
        return null;
    }


    /**
     * Records that catalog loading is no longer permitted.
     * Loading is automatically disabled when lookups are performed,
     * and should be manually disabled when <em>startDTD()</em> (or
     * any other DTD declaration callback) is invoked, or at the latest
     * when the document root element is seen.
     */
    public synchronized void disableLoading ()
    {
        // NOTE:  this method and loadCatalog() are synchronized
        // so that it's impossible to load (top level) catalogs
        // after lookups start.  Likewise, deferred loading is also
        // synchronized (for "next" and delegated catalogs) to
        // ensure that parsers can share resolvers.
        loadingPermitted = false;
    }


    /**
     * Returns the error handler used to report catalog errors.
     * Null is returned if the parser's default error handling
     * will be used.
     *
     * @see #setErrorHandler
     */
    public ErrorHandler getErrorHandler ()
        { return errorHandler; }

    /**
     * Assigns the error handler used to report catalog errors.
     * These errors may come either from the SAX2 parser or
     * from the catalog parsing code driven by the parser.
     *
     * <p> If you're sharing the resolver between parsers, don't
     * change this once lookups have begun.
     *
     * @see #getErrorHandler
     *
     * @param parser The error handler, or null saying to use the default
     *  (no diagnostics, and only fatal errors terminate loading).
     */
    public void setErrorHandler (ErrorHandler handler)
        { errorHandler = handler; }


    /**
     * Returns the name of the SAX2 parser class used to parse catalogs.
     * Null is returned if the system default is used.
     * @see #setParserClass
     */
    public String getParserClass ()
        { return parserClass; }

    /**
     * Names the SAX2 parser class used to parse catalogs.
     *
     * <p> If you're sharing the resolver between parsers, don't change
     * this once lookups have begun.
     *
     * <p> Note that in order to properly support the <em>xml:base</em>
     * attribute and relative URI resolution, the SAX parser used to parse
     * the catalog must provide a {@link Locator} and support the optional
     * declaration and lexical handlers.
     *
     * @see #getParserClass
     *
     * @param parser The parser class name, or null saying to use the
     *  system default SAX2 parser.
     */
    public void setParserClass (String parser)
        { parserClass = parser; }


    /**
     * Returns true (the default) if all methods resolve
     * a given URI in the same way.
     * Returns false if calls resolving URIs as entities (such as
     * {@link #resolveEntity resolveEntity()}) use different catalog entries
     * than those resolving them as URIs ({@link #resolveURI resolveURI()}),
     * which will generally produce different results.
     *
     * <p>The OASIS XML Catalog specification defines two related schemes
     * to map URIs "as URIs" or "as system IDs".
     * URIs use <em>uri</em>, <em>rewriteURI</em>, and <em>delegateURI</em>
     * elements.  System IDs do the same things with <em>systemId</em>,
     * <em>rewriteSystemId</em>, and <em>delegateSystemId</em>.
     * It's confusing and error prone to maintain two parallel copies of
     * such data.  Accordingly, this class makes that behavior optional.
     * The <em>unified</em> interpretation of URI mappings is preferred,
     * since it prevents surprises where one URI gets mapped to different
     * contents depending on whether the reference happens to have come
     * from a DTD (or not).
     *
     * @see #setUnified
     */
    public boolean isUnified ()
        { return unified; }

    /**
     * Assigns the value of the flag returned by {@link #isUnified}.
     * Set it to false to be strictly conformant with the OASIS XML Catalog
     * specification.  Set it to true to make all mappings for a given URI
     * give the same result, regardless of the reason for the mapping.
     *
     * <p>Don't change this once you've loaded the first catalog.
     *
     * @param value new flag setting
     */
    public void setUnified (boolean value)
        { unified = value; }


    /**
     * Returns true (the default) if a catalog's public identifier
     * mappings will be used.
     * When false is returned, such mappings are ignored except when
     * system IDs are discarded, such as for
     * entities using the <em>urn:publicid:</em> URI scheme in their
     * system identifiers.  (See RFC 3151 for information about that
     * URI scheme.  Using it in system identifiers may not work well
     * with many SAX parsers unless the <em>resolve-dtd-uris</em>
     * feature flag is set to false.)
     * @see #setUsingPublic
     */
    public boolean isUsingPublic ()
        { return usingPublic; }

    /**
     * Specifies which catalog search mode is used.
     * By default, public identifier mappings are able to override system
     * identifiers when both are available.
     * Applications may choose to ignore public
     * identifier mappings in such cases, so that system identifiers
     * declared in DTDs will only be overridden by an explicit catalog
     * match for that system ID.
     *
     * <p> If you're sharing the resolver between parsers, don't
     * change this once lookups have begun.
     * @see #isUsingPublic
     *
     * @param value true to always use public identifier mappings,
     *  false to only use them for system ids using the <em>urn:publicid:</em>
     *  URI scheme.
     */
    public void setUsingPublic (boolean value)
        { usingPublic = value; }



    // hmm, what's this do? :)
    private static Catalog loadCatalog (
        String          parserClass,
        ErrorHandler    eh,
        String          uri,
        boolean         unified
    ) throws SAXException, IOException
    {
        XMLReader       parser;
        Loader          loader;
        boolean         doesIntern = false;

        if (parserClass == null)
            parser = XMLReaderFactory.createXMLReader ();
        else
            parser = XMLReaderFactory.createXMLReader (parserClass);
        if (eh != null)
            parser.setErrorHandler (eh);
        // resolve-dtd-entities is at default value (unrecognized == true)

        try {
            doesIntern = parser.getFeature (
                "http://xml.org/sax/features/string-interning");
        } catch (SAXNotRecognizedException e) { }

        loader = new Loader (doesIntern, eh, unified);
        loader.cat.parserClass = parserClass;
        loader.cat.catalogURI = uri;

        parser.setContentHandler (loader);
        parser.setProperty (
            "http://xml.org/sax/properties/declaration-handler",
            loader);
        parser.setProperty (
            "http://xml.org/sax/properties/lexical-handler",
            loader);
        parser.parse (uri);

        return loader.cat;
    }

    // perform one or both the normalizations for public ids
    private static String normalizePublicId (boolean full, String publicId)
    {
        if (publicId.startsWith ("urn:publicid:")) {
            CPStringBuilder     buf = new CPStringBuilder ();
            char                chars [] = publicId.toCharArray ();
boolean hasbug = false;

            for (int i = 13; i < chars.length; i++) {
                switch (chars [i]) {
                case '+':       buf.append (' '); continue;
                case ':':       buf.append ("//"); continue;
                case ';':       buf.append ("::"); continue;
                case '%':
// FIXME unhex that char!  meanwhile, warn and fallthrough ...
                    hasbug = true;
                default:        buf.append (chars [i]); continue;
                }
            }
            publicId = buf.toString ();
if (hasbug)
System.err.println ("nyet unhexing public id: " + publicId);
            full = true;
        }

        // SAX parsers do everything except that URN mapping, but
        // we can't trust other sources to normalize correctly
        if (full) {
            StringTokenizer     tokens;
            String              token;

            tokens = new StringTokenizer (publicId, " \r\n");
            publicId = null;
            while (tokens.hasMoreTokens ()) {
                if (publicId == null)
                    publicId = tokens.nextToken ();
                else
                    publicId += " " + tokens.nextToken ();
            }
        }
        return publicId;
    }

    private static boolean isUriExcluded (int c)
        { return c <= 0x20 || c >= 0x7f || "\"<>^`{|}".indexOf (c) != -1; }

    private static int hexNibble (int c)
    {
        if (c < 10)
            return c + '0';
        return ('a' - 10) + c;
    }

    // handles URIs with "excluded" characters
    private static String normalizeURI (String systemId)
    {
        int                     length = systemId.length ();

        for (int i = 0; i < length; i++) {
            char        c = systemId.charAt (i);

            // escape non-ASCII plus "excluded" characters
            if (isUriExcluded (c)) {
                byte                    buf [];
                ByteArrayOutputStream   out;
                int                             b;

                // a JVM that doesn't know UTF8 and 8859_1 is unusable!
                try {
                    buf = systemId.getBytes ("UTF8");
                    out = new ByteArrayOutputStream (buf.length + 10);

                    for (i = 0; i < buf.length; i++) {
                        b = buf [i] & 0x0ff;
                        if (isUriExcluded (b)) {
                            out.write ((int) '%');
                            out.write (hexNibble (b >> 4));
                            out.write (hexNibble (b & 0x0f));
                        } else
                            out.write (b);
                    }
                    return out.toString ("8859_1");
                } catch (IOException e) {
                    throw new RuntimeException (
                        "can't normalize URI: " + e.getMessage ());
                }
            }
        }
        return systemId;
    }

    // thrown to mark authoritative end of a search
    private static class DoneDelegation extends SAXException
    {
        DoneDelegation () { }
    }


    /**
     * Represents a OASIS XML Catalog, and encapsulates much of
     * the catalog functionality.
     */
    private static class Catalog
    {
        // loading infrastructure
        String          catalogURI;
        ErrorHandler    eh;
        boolean         unified;
        String          parserClass;

        // catalog data
        boolean         hasPreference;
        boolean         usingPublic;

        Hashtable       publicIds;
        Hashtable       publicDelegations;

        Hashtable       systemIds;
        Hashtable       systemRewrites;
        Hashtable       systemDelegations;

        Hashtable       uris;
        Hashtable       uriRewrites;
        Hashtable       uriDelegations;

        Hashtable       doctypes;

        Vector          next;

        // nonpublic!
        Catalog () { }


        // steps as found in OASIS XML catalog spec 7.1.2
        private InputSource locatePublicId (String publicId)
        throws SAXException, IOException
        {
            // 5. return (first) 'public' entry
            if (publicIds != null) {
                String  retval = (String) publicIds.get (publicId);
                if (retval != null) {
                    // IF the URI is accessible ...
                    return new InputSource (retval);
                }
            }

            // 6. return delegatePublic catalog match [complex]
            if (publicDelegations != null)
                return checkDelegations (publicDelegations, publicId,
                                publicId, null);

            return null;
        }

        // steps as found in OASIS XML catalog spec 7.1.2 or 7.2.2
        private InputSource mapURI (
            String      uri,
            Hashtable   ids,
            Hashtable   rewrites,
            Hashtable   delegations
        ) throws SAXException, IOException
        {
            // 7.1.2: 2. return (first) 'system' entry
            // 7.2.2: 2. return (first) 'uri' entry
            if (ids != null) {
                String  retval = (String) ids.get (uri);
                if (retval != null) {
                    // IF the URI is accessible ...
                    return new InputSource (retval);
                }
            }

            // 7.1.2: 3. return 'rewriteSystem' entries
            // 7.2.2: 3. return 'rewriteURI' entries
            if (rewrites != null) {
                String  prefix = null;
                String  replace = null;
                int     prefixLen = -1;

                for (Enumeration e = rewrites.keys ();
                        e.hasMoreElements ();
                        /* NOP */) {
                    String      temp = (String) e.nextElement ();
                    int         len = -1;

                    if (!uri.startsWith (temp))
                        continue;
                    if (prefix != null
                            && (len = temp.length ()) < prefixLen)
                        continue;
                    prefix = temp;
                    prefixLen = len;
                    replace = (String) rewrites.get (temp);
                }
                if (prefix != null) {
                    CPStringBuilder     buf = new CPStringBuilder (replace);
                    buf.append (uri.substring (prefixLen));
                    // IF the URI is accessible ...
                    return new InputSource (buf.toString ());
                }
            }

            // 7.1.2: 4. return 'delegateSystem' catalog match [complex]
            // 7.2.2: 4. return 'delegateURI' catalog match [complex]
            if (delegations != null)
                return checkDelegations (delegations, uri, null, uri);

            return null;
        }


        /**
         * Returns a URI for an external entity.
         */
        public InputSource resolve (
            boolean     usingPublic,
            String      publicId,
            String      systemId
        ) throws SAXException, IOException
        {
            boolean     preferSystem;
            InputSource retval;

            if (hasPreference)
                preferSystem = !this.usingPublic;
            else
                preferSystem = !usingPublic;

            if (publicId != null)
                publicId = normalizePublicId (false, publicId);

            // behavior here matches section 7.1.1 of the oasis spec
            if (systemId != null) {
                if (systemId.startsWith ("urn:publicid:")) {
                    String      temp = normalizePublicId (true, systemId);
                    if (publicId == null) {
                        publicId = temp;
                        systemId = null;
                    } else if (!publicId.equals (temp)) {
                        // error; ok to recover by:
                        systemId = null;
                    }
                } else
                    systemId = normalizeURI (systemId);
            }

            if (systemId == null && publicId == null)
                return null;

            if (systemId != null) {
                retval = mapURI (systemId, systemIds, systemRewrites,
                                        systemDelegations);
                if (retval != null) {
                    retval.setPublicId (publicId);
                    return retval;
                }
            }

            if (publicId != null
                    && !(systemId != null && preferSystem)) {
                retval = locatePublicId (publicId);
                if (retval != null) {
                    retval.setPublicId (publicId);
                    return retval;
                }
            }

            // 7. apply nextCatalog entries
            if (next != null) {
                int     length = next.size ();
                for (int i = 0; i < length; i++) {
                    Catalog     n = getNext (i);
                    retval = n.resolve (usingPublic, publicId, systemId);
                    if (retval != null)
                        return retval;
                }
            }

            return null;
        }

        /**
         * Maps one URI into another, for resources that are not defined
         * using XML external entity or notation syntax.
         */
        public InputSource resolveURI (String uri)
        throws SAXException, IOException
        {
            if (uri.startsWith ("urn:publicid:"))
                return resolve (true, normalizePublicId (true, uri), null);

            InputSource retval;

            uri = normalizeURI (uri);

            // 7.2.2 steps 2-4
            retval = mapURI (uri, uris, uriRewrites, uriDelegations);
            if (retval != null)
                return retval;

            // 7.2.2 step 5. apply nextCatalog entries
            if (next != null) {
                int     length = next.size ();
                for (int i = 0; i < length; i++) {
                    Catalog     n = getNext (i);
                    retval = n.resolveURI (uri);
                    if (retval != null)
                        return retval;
                }
            }

            return null;
        }


        /**
         * Finds the external subset associated with a given root element.
         */
        public InputSource getExternalSubset (String name)
        throws SAXException, IOException
        {
            if (doctypes != null) {
                String  value = (String) doctypes.get (name);
                if (value != null) {
                    // IF the URI is accessible ...
                    return new InputSource (value);
                }
            }
            if (next != null) {
                int     length = next.size ();
                for (int i = 0; i < length; i++) {
                    Catalog     n = getNext (i);
                    if (n == null)
                        continue;
                    InputSource retval = n.getExternalSubset (name);
                    if (retval != null)
                        return retval;
                }
            }
            return null;
        }

        private synchronized Catalog getNext (int i)
        throws SAXException, IOException
        {
            Object      obj;

            if (next == null || i < 0 || i >= next.size ())
                return null;
            obj = next.elementAt (i);
            if (obj instanceof Catalog)
                return (Catalog) obj;

            // ok, we deferred reading that catalog till now.
            // load and cache it.
            Catalog     cat = null;

            try {
                cat = loadCatalog (parserClass, eh, (String) obj, unified);
                next.setElementAt (cat, i);
            } catch (SAXException e) {
                // must fail quietly, says the OASIS spec
            } catch (IOException e) {
                // same applies here
            }
            return cat;
        }

        private InputSource checkDelegations (
            Hashtable   delegations,
            String      id,
            String      publicId,       // only one of public/system
            String      systemId        // will be non-null...
        ) throws SAXException, IOException
        {
            Vector      matches = null;
            int         length = 0;

            // first, see if any prefixes match.
            for (Enumeration e = delegations.keys ();
                    e.hasMoreElements ();
                    /* NOP */) {
                String  prefix = (String) e.nextElement ();

                if (!id.startsWith (prefix))
                    continue;
                if (matches == null)
                    matches = new Vector ();

                // maintain in longer->shorter sorted order
                // NOTE:  assumes not many matches will fire!
                int     index;

                for (index = 0; index < length; index++) {
                    String      temp = (String) matches.elementAt (index);
                    if (prefix.length () > temp.length ()) {
                        matches.insertElementAt (prefix, index);
                        break;
                    }
                }
                if (index == length)
                    matches.addElement (prefix);
                length++;
            }
            if (matches == null)
                return null;

            // now we know the list of catalogs to replace our "top level"
            // list ... we use it here, rather than somehow going back and
            // restarting, since this helps avoid reading most catalogs.
            // this assumes stackspace won't be a problem.
            for (int i = 0; i < length; i++) {
                Catalog         catalog = null;
                InputSource     result;

                // get this catalog.  we may not have read it yet.
                synchronized (delegations) {
                    Object      prefix = matches.elementAt (i);
                    Object      cat = delegations.get (prefix);

                    if (cat instanceof Catalog)
                        catalog = (Catalog) cat;
                    else {
                        try {
                            // load and cache that catalog
                            catalog = loadCatalog (parserClass, eh,
                                    (String) cat, unified);
                            delegations.put (prefix, catalog);
                        } catch (SAXException e) {
                            // must ignore, says the OASIS spec
                        } catch (IOException e) {
                            // same applies here
                        }
                    }
                }

                // ignore failed loads, and proceed
                if (catalog == null)
                    continue;

                // we have a catalog ... resolve!
                // usingPublic value can't matter, there's no choice
                result = catalog.resolve (true, publicId, systemId);
                if (result != null)
                    return result;
            }

            // if there were no successes, the entire
            // lookup failed (all the way to top level)
            throw new DoneDelegation ();
        }
    }


    /** This is the namespace URI used for OASIS XML Catalogs.  */
    private static final String catalogNamespace =
        "urn:oasis:names:tc:entity:xmlns:xml:catalog";


    /**
     * Loads/unmarshals one catalog.
     */
    private static class Loader extends DefaultHandler2
    {
        private boolean         preInterned;
        private ErrorHandler    handler;
        private boolean         unified;
        private int             ignoreDepth;
        private Locator         locator;
        private boolean         started;
        private Hashtable       externals;
        private Stack           bases;

        Catalog                 cat = new Catalog ();


        /**
         * Constructor.
         * @param flag true iff the parser already interns strings.
         * @param eh Errors and warnings are delegated to this.
         * @param unified true keeps one table for URI mappings;
         *      false matches OASIS spec, storing mappings
         *      for URIs and SYSTEM ids in parallel tables.
         */
        Loader (boolean flag, ErrorHandler eh, boolean unified)
        {
            preInterned = flag;
            handler = eh;
            this.unified = unified;
            cat.unified = unified;
            cat.eh = eh;
        }


        // strips out fragments
        private String nofrag (String uri)
        throws SAXException
        {
            if (uri.indexOf ('#') != -1) {
                warn ("URI with fragment: " + uri);
                uri = uri.substring (0, uri.indexOf ('#'));
            }
            return uri;
        }

        // absolutizes relative URIs
        private String absolutize (String uri)
        throws SAXException
        {
            // avoid creating URLs if they're already absolutized,
            // or if the URI is already using a known scheme
            if (uri.startsWith ("file:/")
                    || uri.startsWith ("http:/")
                    || uri.startsWith ("https:/")
                    || uri.startsWith ("ftp:/")
                    || uri.startsWith ("urn:")
                    )
                return uri;

            // otherwise, let's hope the JDK handles this URI scheme.
            try {
                URL     base = (URL) bases.peek ();
                return new URL (base, uri).toString ();
            } catch (Exception e) {
                fatal ("can't absolutize URI: " + uri);
                return null;
            }
        }

        // recoverable error
        private void error (String message)
        throws SAXException
        {
            if (handler == null)
                return;
            handler.error (new SAXParseException (message, locator));
        }

        // nonrecoverable error
        private void fatal (String message)
        throws SAXException
        {
            SAXParseException   spe;

            spe = new SAXParseException (message, locator);
            if (handler != null)
                handler.fatalError (spe);
            throw spe;
        }

        // low severity problem
        private void warn (String message)
        throws SAXException
        {
            if (handler == null)
                return;
            handler.warning (new SAXParseException (message, locator));
        }

        // callbacks:

        public void setDocumentLocator (Locator l)
            { locator = l; }

        public void startDocument ()
        throws SAXException
        {
            if (locator == null)
                error ("no locator!");
            bases = new Stack ();
            String      uri = locator.getSystemId ();
            try {
                bases.push (new URL (uri));
            } catch (IOException e) {
                fatal ("bad document base URI: " + uri);
            }
        }

        public void endDocument ()
        throws SAXException
        {
            try {
                if (!started)
                    error ("not a catalog!");
            } finally {
                locator = null;
                handler = null;
                externals = null;
                bases = null;
            }
        }

        // XML Base support for external entities.

        // NOTE: expects parser is in default "resolve-dtd-uris" mode.
        public void externalEntityDecl (String name, String pub, String sys)
        throws SAXException
        {
            if (externals == null)
                externals = new Hashtable ();
            if (externals.get (name) == null)
                externals.put (name, pub);
        }

        public void startEntity (String name)
        throws SAXException
        {
            if (externals == null)
                return;
            String uri = (String) externals.get (name);

            // NOTE: breaks if an EntityResolver substitutes these URIs.
            // If toplevel loader supports one, must intercept calls...
            if (uri != null) {
                try {
                    bases.push (new URL (uri));
                } catch (IOException e) {
                    fatal ("entity '" + name + "', bad URI: " + uri);
                }
            }
        }

        public void endEntity (String name)
        {
            if (externals == null)
                return;
            String value = (String) externals.get (name);

            if (value != null)
                bases.pop ();
        }

        /**
         * Processes catalog elements, saving their data.
         */
        public void startElement (String namespace, String local,
            String qName, Attributes atts)
        throws SAXException
        {
            // must ignore non-catalog elements, and their contents
            if (ignoreDepth != 0 || !catalogNamespace.equals (namespace)) {
                ignoreDepth++;
                return;
            }

            // basic sanity checks
            if (!preInterned)
                local = local.intern ();
            if (!started) {
                started = true;
                if ("catalog" != local)
                    fatal ("root element not 'catalog': " + local);
            }

            // Handle any xml:base attribute
            String      xmlbase = atts.getValue ("xml:base");

            if (xmlbase != null) {
                URL     base = (URL) bases.peek ();
                try {
                    base = new URL (base, xmlbase);
                } catch (IOException e) {
                    fatal ("can't resolve xml:base attribute: " + xmlbase);
                }
                bases.push (base);
            } else
                bases.push (bases.peek ());

            // fetch multi-element attributes, apply standard tweaks
            // values (uri, catalog, rewritePrefix) get normalized too,
            // as a precaution and since we may compare the values
            String      catalog = atts.getValue ("catalog");
            if (catalog != null)
                catalog = normalizeURI (absolutize (catalog));

            String      rewritePrefix = atts.getValue ("rewritePrefix");
            if (rewritePrefix != null)
                rewritePrefix = normalizeURI (absolutize (rewritePrefix));

            String      systemIdStartString;
            systemIdStartString = atts.getValue ("systemIdStartString");
            if (systemIdStartString != null) {
                systemIdStartString = normalizeURI (systemIdStartString);
                // unmatchable <rewriteSystemId>, <delegateSystemId> elements
                if (systemIdStartString.startsWith ("urn:publicid:")) {
                    error ("systemIdStartString is really a publicId!!");
                    return;
                }
            }

            String      uri = atts.getValue ("uri");
            if (uri != null)
                uri = normalizeURI (absolutize (uri));

            String      uriStartString;
            uriStartString = atts.getValue ("uriStartString");
            if (uriStartString != null) {
                uriStartString = normalizeURI (uriStartString);
                // unmatchable <rewriteURI>, <delegateURI> elements
                if (uriStartString.startsWith ("urn:publicid:")) {
                    error ("uriStartString is really a publicId!!");
                    return;
                }
            }

            // strictly speaking "group" and "catalog" shouldn't nest
            // ... arbitrary restriction, no evident motivation

// FIXME stack "prefer" settings (two elements only!) and use
// them to populate different public mapping/delegation tables

            if ("catalog" == local || "group" == local) {
                String  prefer = atts.getValue ("prefer");

                if (prefer != null && !"public".equals (prefer)) {
                    if (!"system".equals (prefer)) {
                        error ("in <" + local + " ... prefer='...'>, "
                            + "assuming 'public'");
                        prefer = "public";
                    }
                }
                if (prefer != null) {
                    if ("catalog" == local) {
                        cat.hasPreference = true;
                        cat.usingPublic = "public".equals (prefer);
                    } else {
                        if (!cat.hasPreference || cat.usingPublic
                                    != "public".equals (prefer)) {
fatal ("<group prefer=...> case not handled");
                        }
                    }
                } else if ("group" == local && cat.hasPreference) {
fatal ("<group prefer=...> case not handled");
                }

            //
            // PUBLIC ids:  cleanly set up for id substitution
            //
            } else if ("public" == local) {
                String  publicId = atts.getValue ("publicId");
                String  value = null;

                if (publicId == null || uri == null) {
                    error ("expecting <public publicId=... uri=.../>");
                    return;
                }
                publicId = normalizePublicId (true, publicId);
                uri = nofrag (uri);
                if (cat.publicIds == null)
                    cat.publicIds = new Hashtable ();
                else
                    value = (String) cat.publicIds.get (publicId);
                if (value != null) {
                    if (!value.equals (uri))
                        warn ("ignoring <public...> entry for " + publicId);
                } else
                    cat.publicIds.put (publicId, uri);

            } else if ("delegatePublic" == local) {
                String  publicIdStartString;
                Object  value = null;

                publicIdStartString = atts.getValue ("publicIdStartString");
                if (publicIdStartString == null || catalog == null) {
                    error ("expecting <delegatePublic "
                        + "publicIdStartString=... catalog=.../>");
                    return;
                }
                publicIdStartString = normalizePublicId (true,
                        publicIdStartString);
                if (cat.publicDelegations == null)
                    cat.publicDelegations = new Hashtable ();
                else
                    value = cat.publicDelegations.get (publicIdStartString);
                if (value != null) {
                    if (!value.equals (catalog))
                        warn ("ignoring <delegatePublic...> entry for "
                            + uriStartString);
                } else
                    cat.publicDelegations.put (publicIdStartString, catalog);


            //
            // SYSTEM ids:  need substitution due to operational issues
            //
            } else if ("system" == local) {
                String  systemId = atts.getValue ("systemId");
                String  value = null;

                if (systemId == null || uri == null) {
                    error ("expecting <system systemId=... uri=.../>");
                    return;
                }
                systemId = normalizeURI (systemId);
                uri = nofrag (uri);
                if (systemId.startsWith ("urn:publicid:")) {
                    error ("systemId is really a publicId!!");
                    return;
                }
                if (cat.systemIds == null) {
                    cat.systemIds = new Hashtable ();
                    if (unified)
                        cat.uris = cat.systemIds;
                } else
                    value = (String) cat.systemIds.get (systemId);
                if (value != null) {
                    if (!value.equals (uri))
                        warn ("ignoring <system...> entry for " + systemId);
                } else
                    cat.systemIds.put (systemId, uri);

            } else if ("rewriteSystem" == local) {
                String  value = null;

                if (systemIdStartString == null || rewritePrefix == null
                        || systemIdStartString.length () == 0
                        || rewritePrefix.length () == 0
                        ) {
                    error ("expecting <rewriteSystem "
                        + "systemIdStartString=... rewritePrefix=.../>");
                    return;
                }
                if (cat.systemRewrites == null) {
                    cat.systemRewrites = new Hashtable ();
                    if (unified)
                        cat.uriRewrites = cat.systemRewrites;
                } else
                    value = (String) cat.systemRewrites.get (
                                                systemIdStartString);
                if (value != null) {
                    if (!value.equals (rewritePrefix))
                        warn ("ignoring <rewriteSystem...> entry for "
                            + systemIdStartString);
                } else
                    cat.systemRewrites.put (systemIdStartString,
                                rewritePrefix);

            } else if ("delegateSystem" == local) {
                Object  value = null;

                if (systemIdStartString == null || catalog == null) {
                    error ("expecting <delegateSystem "
                        + "systemIdStartString=... catalog=.../>");
                    return;
                }
                if (cat.systemDelegations == null) {
                    cat.systemDelegations = new Hashtable ();
                    if (unified)
                        cat.uriDelegations = cat.systemDelegations;
                } else
                    value = cat.systemDelegations.get (systemIdStartString);
                if (value != null) {
                    if (!value.equals (catalog))
                        warn ("ignoring <delegateSystem...> entry for "
                            + uriStartString);
                } else
                    cat.systemDelegations.put (systemIdStartString, catalog);


            //
            // URI:  just like "system" ID support, except that
            // fragment IDs are disallowed in "system" elements.
            //
            } else if ("uri" == local) {
                String  name = atts.getValue ("name");
                String  value = null;

                if (name == null || uri == null) {
                    error ("expecting <uri name=... uri=.../>");
                    return;
                }
                if (name.startsWith ("urn:publicid:")) {
                    error ("name is really a publicId!!");
                    return;
                }
                name = normalizeURI (name);
                if (cat.uris == null) {
                    cat.uris = new Hashtable ();
                    if (unified)
                        cat.systemIds = cat.uris;
                } else
                    value = (String) cat.uris.get (name);
                if (value != null) {
                    if (!value.equals (uri))
                        warn ("ignoring <uri...> entry for " + name);
                } else
                    cat.uris.put (name, uri);

            } else if ("rewriteURI" == local) {
                String value = null;

                if (uriStartString == null || rewritePrefix == null
                        || uriStartString.length () == 0
                        || rewritePrefix.length () == 0
                        ) {
                    error ("expecting <rewriteURI "
                        + "uriStartString=... rewritePrefix=.../>");
                    return;
                }
                if (cat.uriRewrites == null) {
                    cat.uriRewrites = new Hashtable ();
                    if (unified)
                        cat.systemRewrites = cat.uriRewrites;
                } else
                    value = (String) cat.uriRewrites.get (uriStartString);
                if (value != null) {
                    if (!value.equals (rewritePrefix))
                        warn ("ignoring <rewriteURI...> entry for "
                            + uriStartString);
                } else
                    cat.uriRewrites.put (uriStartString, rewritePrefix);

            } else if ("delegateURI" == local) {
                Object  value = null;

                if (uriStartString == null || catalog == null) {
                    error ("expecting <delegateURI "
                        + "uriStartString=... catalog=.../>");
                    return;
                }
                if (cat.uriDelegations == null) {
                    cat.uriDelegations = new Hashtable ();
                    if (unified)
                        cat.systemDelegations = cat.uriDelegations;
                } else
                    value = cat.uriDelegations.get (uriStartString);
                if (value != null) {
                    if (!value.equals (catalog))
                        warn ("ignoring <delegateURI...> entry for "
                            + uriStartString);
                } else
                    cat.uriDelegations.put (uriStartString, catalog);

            //
            // NON-DELEGATING approach to modularity
            //
            } else if ("nextCatalog" == local) {
                if (catalog == null) {
                    error ("expecting <nextCatalog catalog=.../>");
                    return;
                }
                if (cat.next == null)
                    cat.next = new Vector ();
                cat.next.addElement (catalog);

            //
            // EXTENSIONS from appendix E
            //
            } else if ("doctype" == local) {
                String  name = atts.getValue ("name");
                String  value = null;

                if (name == null || uri == null) {
                    error ("expecting <doctype name=... uri=.../>");
                    return;
                }
                name = normalizeURI (name);
                if (cat.doctypes == null)
                    cat.doctypes = new Hashtable ();
                else
                    value = (String) cat.doctypes.get (name);
                if (value != null) {
                    if (!value.equals (uri))
                        warn ("ignoring <doctype...> entry for "
                            + uriStartString);
                } else
                    cat.doctypes.put (name, uri);


            //
            // RESERVED ... ignore (like reserved attributes) but warn
            //
            } else {
                warn ("ignoring unknown catalog element: " + local);
                ignoreDepth++;
            }
        }

        public void endElement (String uri, String local, String qName)
        throws SAXException
        {
            if (ignoreDepth != 0)
                ignoreDepth--;
            else
                bases.pop ();
        }
    }
}