XMLWriter.java 45.6 KB
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
package org.jivesoftware.util;

import org.dom4j.*;
import org.dom4j.io.OutputFormat;
import org.dom4j.tree.NamespaceStack;
import org.xml.sax.*;
import org.xml.sax.ext.LexicalHandler;
import org.xml.sax.helpers.XMLFilterImpl;

import java.io.*;
import java.util.*;

/**
 * Replacement class of the original XMLWriter.java (version: 1.77) since the original is still
 * using StringBuffer which is not fast. 
 */
public class XMLWriter extends XMLFilterImpl implements LexicalHandler {

    private static final String PAD_TEXT = " ";

    protected static final String[] LEXICAL_HANDLER_NAMES = {
        "http://xml.org/sax/properties/lexical-handler",
        "http://xml.org/sax/handlers/LexicalHandler"
    };

    protected static final OutputFormat DEFAULT_FORMAT = new OutputFormat();

    /** Should entityRefs by resolved when writing ? */
    private boolean resolveEntityRefs = true;

    /** Stores the last type of node written so algorithms can refer to the
      * previous node type */
    protected int lastOutputNodeType;

    /** Stores the xml:space attribute value of preserve for whitespace flag */
    protected boolean preserve=false;

    /** The Writer used to output to */
    protected Writer writer;

    /** The Stack of namespaceStack written so far */
    private NamespaceStack namespaceStack = new NamespaceStack();

    /** The format used by this writer */
    private OutputFormat format;

    /** whether we should escape text */
    private boolean escapeText = true;
    /** The initial number of indentations (so you can print a whole
        document indented, if you like) **/
    private int indentLevel = 0;

    /** buffer used when escaping strings */
    private StringBuilder buffer = new StringBuilder();

    /** whether we have added characters before from the same chunk of characters */
    private boolean charactersAdded = false;
    private char lastChar;

    /** Whether a flush should occur after writing a document */
    private boolean autoFlush;

    /** Lexical handler we should delegate to */
    private LexicalHandler lexicalHandler;

    /** Whether comments should appear inside DTD declarations - defaults to false */
    private boolean showCommentsInDTDs;

    /** Is the writer curerntly inside a DTD definition? */
    private boolean inDTD;

    /** The namespaces used for the current element when consuming SAX events */
    private Map namespacesMap;

    /**
     * what is the maximum allowed character code
     * such as 127 in US-ASCII (7 bit) or 255 in ISO-* (8 bit)
     * or -1 to not escape any characters (other than the special XML characters like < > &)
     */
    private int maximumAllowedCharacter;

    public XMLWriter(Writer writer) {
        this( writer, DEFAULT_FORMAT );
    }

    public XMLWriter(Writer writer, OutputFormat format) {
        this.writer = writer;
        this.format = format;
		namespaceStack.push(Namespace.NO_NAMESPACE);
    }

    public XMLWriter() {
        this.format = DEFAULT_FORMAT;
        this.writer = new BufferedWriter( new OutputStreamWriter( System.out ) );
        this.autoFlush = true;
		namespaceStack.push(Namespace.NO_NAMESPACE);
    }

    public XMLWriter(OutputStream out) throws UnsupportedEncodingException {
        this.format = DEFAULT_FORMAT;
        this.writer = createWriter(out, format.getEncoding());
        this.autoFlush = true;
		namespaceStack.push(Namespace.NO_NAMESPACE);
    }

    public XMLWriter(OutputStream out, OutputFormat format) throws UnsupportedEncodingException {
        this.format = format;
        this.writer = createWriter(out, format.getEncoding());
        this.autoFlush = true;
		namespaceStack.push(Namespace.NO_NAMESPACE);
    }

    public XMLWriter(OutputFormat format) throws UnsupportedEncodingException {
        this.format = format;
        this.writer = createWriter( System.out, format.getEncoding() );
        this.autoFlush = true;
		namespaceStack.push(Namespace.NO_NAMESPACE);
    }

    public void setWriter(Writer writer) {
        this.writer = writer;
        this.autoFlush = false;
    }

    public void setOutputStream(OutputStream out) throws UnsupportedEncodingException {
        this.writer = createWriter(out, format.getEncoding());
        this.autoFlush = true;
    }

    /**
     * @return true if text thats output should be escaped.
     * This is enabled by default. It could be disabled if
     * the output format is textual, like in XSLT where we can have
     * xml, html or text output.
     */
    public boolean isEscapeText() {
        return escapeText;
    }

    /**
     * Sets whether text output should be escaped or not.
     * This is enabled by default. It could be disabled if
     * the output format is textual, like in XSLT where we can have
     * xml, html or text output.
     */
    public void setEscapeText(boolean escapeText) {
        this.escapeText = escapeText;
    }


    /** Set the initial indentation level.  This can be used to output
      * a document (or, more likely, an element) starting at a given
      * indent level, so it's not always flush against the left margin.
      * Default: 0
      *
      * @param indentLevel the number of indents to start with
      */
    public void setIndentLevel(int indentLevel) {
        this.indentLevel = indentLevel;
    }

    /**
     * Returns the maximum allowed character code that should be allowed
     * unescaped which defaults to 127 in US-ASCII (7 bit) or
     * 255 in ISO-* (8 bit).
     */
    public int getMaximumAllowedCharacter() {
        if (maximumAllowedCharacter == 0) {
            maximumAllowedCharacter = defaultMaximumAllowedCharacter();
        }
        return maximumAllowedCharacter;
    }

    /**
     * Sets the maximum allowed character code that should be allowed
     * unescaped
     * such as 127 in US-ASCII (7 bit) or 255 in ISO-* (8 bit)
     * or -1 to not escape any characters (other than the special XML characters like < > &)
     *
     * If this is not explicitly set then it is defaulted from the encoding.
     *
     * @param maximumAllowedCharacter The maximumAllowedCharacter to set
     */
    public void setMaximumAllowedCharacter(int maximumAllowedCharacter) {
        this.maximumAllowedCharacter = maximumAllowedCharacter;
    }

    /** Flushes the underlying Writer */
    public void flush() throws IOException {
        writer.flush();
    }

    /** Closes the underlying Writer */
    public void close() throws IOException {
        writer.close();
    }

    /** Writes the new line text to the underlying Writer */
    public void println() throws IOException {
        writer.write( format.getLineSeparator() );
    }

    /** Writes the given {@link org.dom4j.Attribute}.
      *
      * @param attribute <code>Attribute</code> to output.
      */
    public void write(Attribute attribute) throws IOException {
        writeAttribute(attribute);

        if ( autoFlush ) {
            flush();
        }
    }


    /** <p>This will print the <code>Document</code> to the current Writer.</p>
     *
     * <p> Warning: using your own Writer may cause the writer's
     * preferred character encoding to be ignored.  If you use
     * encodings other than UTF8, we recommend using the method that
     * takes an OutputStream instead.  </p>
     *
     * <p>Note: as with all Writers, you may need to flush() yours
     * after this method returns.</p>
     *
     * @param doc <code>Document</code> to format.
     * @throws IOException - if there's any problem writing.
     **/
    public void write(Document doc) throws IOException {
        writeDeclaration();

        if (doc.getDocType() != null) {
            indent();
            writeDocType(doc.getDocType());
        }

        for ( int i = 0, size = doc.nodeCount(); i < size; i++ ) {
            Node node = doc.node(i);
            writeNode( node );
        }
        writePrintln();

        if ( autoFlush ) {
            flush();
        }
    }

    /** <p>Writes the <code>{@link org.dom4j.Element}</code>, including
      * its <code>{@link Attribute}</code>s, and its value, and all
      * its content (child nodes) to the current Writer.</p>
      *
      * @param element <code>Element</code> to output.
      */
    public void write(Element element) throws IOException {
        writeElement(element);

        if ( autoFlush ) {
            flush();
        }
    }


    /** Writes the given {@link CDATA}.
      *
      * @param cdata <code>CDATA</code> to output.
      */
    public void write(CDATA cdata) throws IOException {
        writeCDATA( cdata.getText() );

        if ( autoFlush ) {
            flush();
        }
    }

    /** Writes the given {@link Comment}.
      *
      * @param comment <code>Comment</code> to output.
      */
    public void write(Comment comment) throws IOException {
        writeComment( comment.getText() );

        if ( autoFlush ) {
            flush();
        }
    }

    /** Writes the given {@link DocumentType}.
      *
      * @param docType <code>DocumentType</code> to output.
      */
    public void write(DocumentType docType) throws IOException {
        writeDocType(docType);

        if ( autoFlush ) {
            flush();
        }
    }


    /** Writes the given {@link Entity}.
      *
      * @param entity <code>Entity</code> to output.
      */
    public void write(Entity entity) throws IOException {
        writeEntity( entity );

        if ( autoFlush ) {
            flush();
        }
    }


    /** Writes the given {@link Namespace}.
      *
      * @param namespace <code>Namespace</code> to output.
      */
    public void write(Namespace namespace) throws IOException {
        writeNamespace(namespace);

        if ( autoFlush ) {
            flush();
        }
    }

    /** Writes the given {@link ProcessingInstruction}.
      *
      * @param processingInstruction <code>ProcessingInstruction</code> to output.
      */
    public void write(ProcessingInstruction processingInstruction) throws IOException {
        writeProcessingInstruction(processingInstruction);

        if ( autoFlush ) {
            flush();
        }
    }

    /** <p>Print out a {@link String}, Perfoms
      * the necessary entity escaping and whitespace stripping.</p>
      *
      * @param text is the text to output
      */
    public void write(String text) throws IOException {
        writeString(text);

        if ( autoFlush ) {
            flush();
        }
    }

    /** Writes the given {@link Text}.
      *
      * @param text <code>Text</code> to output.
      */
    public void write(Text text) throws IOException {
        writeString(text.getText());

        if ( autoFlush ) {
            flush();
        }
    }

    /** Writes the given {@link Node}.
      *
      * @param node <code>Node</code> to output.
      */
    public void write(Node node) throws IOException {
        writeNode(node);

        if ( autoFlush ) {
            flush();
        }
    }

    /** Writes the given object which should be a String, a Node or a List
      * of Nodes.
      *
      * @param object is the object to output.
      */
    public void write(Object object) throws IOException {
        if (object instanceof Node) {
            write((Node) object);
        }
        else if (object instanceof String) {
            write((String) object);
        }
        else if (object instanceof List) {
            List list = (List) object;
            for ( int i = 0, size = list.size(); i < size; i++ ) {
                write( list.get(i) );
            }
        }
        else if (object != null) {
            throw new IOException( "Invalid object: " + object );
        }
    }


    /** <p>Writes the opening tag of an {@link Element},
      * including its {@link Attribute}s
      * but without its content.</p>
      *
      * @param element <code>Element</code> to output.
      */
    public void writeOpen(Element element) throws IOException {
        writer.write("<");
        writer.write( element.getQualifiedName() );
        writeAttributes(element);
        writer.write(">");
    }

    /** <p>Writes the closing tag of an {@link Element}</p>
      *
      * @param element <code>Element</code> to output.
      */
    public void writeClose(Element element) throws IOException {
        writeClose( element.getQualifiedName() );
    }


    // XMLFilterImpl methods
    //-------------------------------------------------------------------------
    public void parse(InputSource source) throws IOException, SAXException {
        installLexicalHandler();
        super.parse(source);
    }


    public void setProperty(String name, Object value) throws SAXNotRecognizedException, SAXNotSupportedException {
        for (int i = 0; i < LEXICAL_HANDLER_NAMES.length; i++) {
            if (LEXICAL_HANDLER_NAMES[i].equals(name)) {
                setLexicalHandler((LexicalHandler) value);
                return;
            }
        }
        super.setProperty(name, value);
    }

    public Object getProperty(String name) throws SAXNotRecognizedException, SAXNotSupportedException {
        for (int i = 0; i < LEXICAL_HANDLER_NAMES.length; i++) {
            if (LEXICAL_HANDLER_NAMES[i].equals(name)) {
                return getLexicalHandler();
            }
        }
        return super.getProperty(name);
    }

    public void setLexicalHandler (LexicalHandler handler) {
        if (handler == null) {
            throw new NullPointerException("Null lexical handler");
        }
        else {
            this.lexicalHandler = handler;
        }
    }

    public LexicalHandler getLexicalHandler(){
        return lexicalHandler;
    }


    // ContentHandler interface
    //-------------------------------------------------------------------------
    public void setDocumentLocator(Locator locator) {
        super.setDocumentLocator(locator);
    }

    public void startDocument() throws SAXException {
        try {
            writeDeclaration();
            super.startDocument();
        }
        catch (IOException e) {
            handleException(e);
        }
    }

    public void endDocument() throws SAXException {
        super.endDocument();

        if ( autoFlush ) {
            try {
                flush();
            } catch ( IOException e) {}
        }
    }

    public void startPrefixMapping(String prefix, String uri) throws SAXException {
        if ( namespacesMap == null ) {
            namespacesMap = new HashMap();
        }
        namespacesMap.put(prefix, uri);
        super.startPrefixMapping(prefix, uri);
    }

    public void endPrefixMapping(String prefix) throws SAXException {
        super.endPrefixMapping(prefix);
    }

    public void startElement(String namespaceURI, String localName, String qName, Attributes attributes) throws SAXException {
        try {
            charactersAdded = false;

            writePrintln();
            indent();
            writer.write("<");
            writer.write(qName);
            writeNamespaces();
            writeAttributes( attributes );
            writer.write(">");
            ++indentLevel;
            lastOutputNodeType = Node.ELEMENT_NODE;

            super.startElement( namespaceURI, localName, qName, attributes );
        }
        catch (IOException e) {
            handleException(e);
        }
    }

    public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
        try {
            charactersAdded = false;
            --indentLevel;
            if ( lastOutputNodeType == Node.ELEMENT_NODE ) {
                writePrintln();
                indent();
            }

            // XXXX: need to determine this using a stack and checking for
            // content / children
            boolean hadContent = true;
            if ( hadContent ) {
                writeClose(qName);
            }
            else {
                writeEmptyElementClose(qName);
            }
            lastOutputNodeType = Node.ELEMENT_NODE;

            super.endElement( namespaceURI, localName, qName );
        }
        catch (IOException e) {
            handleException(e);
        }
    }

    public void characters(char[] ch, int start, int length) throws SAXException {
        if (ch == null || ch.length == 0 || length <= 0) {
            return;
        }

        try {
            /*
             * we can't use the writeString method here because it's possible
             * we don't receive all characters at once and calling writeString
             * would cause unwanted spaces to be added in between these chunks
             * of character arrays.
             */
            String string = new String(ch, start, length);

            if (escapeText) {
            	string = escapeElementEntities(string);
            }

            if (format.isTrimText()) {
                if ((lastOutputNodeType == Node.TEXT_NODE) && !charactersAdded) {
                    writer.write(" ");
                } else if (charactersAdded && Character.isWhitespace(lastChar)) {
                    writer.write(lastChar);
                }

                String delim = "";
                StringTokenizer tokens = new StringTokenizer(string);
                while (tokens.hasMoreTokens()) {
                    writer.write(delim);
                    writer.write(tokens.nextToken());
                    delim = " ";
                }
            } else {
                writer.write(string);
            }

            charactersAdded = true;
            lastChar = ch[start + length - 1];
            lastOutputNodeType = Node.TEXT_NODE;

            super.characters(ch, start, length);
        }
        catch (IOException e) {
            handleException(e);
        }
    }

    public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {
        super.ignorableWhitespace(ch, start, length);
    }

    public void processingInstruction(String target, String data) throws SAXException {
        try {
            indent();
            writer.write("<?");
            writer.write(target);
            writer.write(" ");
            writer.write(data);
            writer.write("?>");
            writePrintln();
            lastOutputNodeType = Node.PROCESSING_INSTRUCTION_NODE;

            super.processingInstruction(target, data);
        }
        catch (IOException e) {
            handleException(e);
        }
    }



    // DTDHandler interface
    //-------------------------------------------------------------------------
    public void notationDecl(String name, String publicID, String systemID) throws SAXException {
        super.notationDecl(name, publicID, systemID);
    }

    public void unparsedEntityDecl(String name, String publicID, String systemID, String notationName) throws SAXException {
        super.unparsedEntityDecl(name, publicID, systemID, notationName);
    }


    // LexicalHandler interface
    //-------------------------------------------------------------------------
    public void startDTD(String name, String publicID, String systemID) throws SAXException {
        inDTD = true;
        try {
            writeDocType(name, publicID, systemID);
        }
        catch (IOException e) {
            handleException(e);
        }

        if (lexicalHandler != null) {
            lexicalHandler.startDTD(name, publicID, systemID);
        }
    }

    public void endDTD() throws SAXException {
        inDTD = false;
        if (lexicalHandler != null) {
            lexicalHandler.endDTD();
        }
    }

    public void startCDATA() throws SAXException {
        try {
            writer.write( "<![CDATA[" );
        }
        catch (IOException e) {
            handleException(e);
        }

        if (lexicalHandler != null) {
            lexicalHandler.startCDATA();
        }
    }

    public void endCDATA() throws SAXException {
        try {
            writer.write( "]]>" );
        }
        catch (IOException e) {
            handleException(e);
        }

        if (lexicalHandler != null) {
            lexicalHandler.endCDATA();
        }
    }

    public void startEntity(String name) throws SAXException {
        try {
            writeEntityRef(name);
        }
        catch (IOException e) {
            handleException(e);
        }

        if (lexicalHandler != null) {
            lexicalHandler.startEntity(name);
        }
    }

    public void endEntity(String name) throws SAXException {
        if (lexicalHandler != null) {
            lexicalHandler.endEntity(name);
        }
    }

    public void comment(char[] ch, int start, int length) throws SAXException {
        if ( showCommentsInDTDs || ! inDTD ) {
            try {
                charactersAdded = false;
                writeComment( new String(ch, start, length) );
            }
            catch (IOException e) {
                handleException(e);
            }
        }

        if (lexicalHandler != null) {
            lexicalHandler.comment(ch, start, length);
        }
    }



    // Implementation methods
    //-------------------------------------------------------------------------
    protected void writeElement(Element element) throws IOException {
        int size = element.nodeCount();
        String qualifiedName = element.getQualifiedName();

        writePrintln();
        indent();

        writer.write("<");
        writer.write(qualifiedName);

        int previouslyDeclaredNamespaces = namespaceStack.size();
        Namespace ns = element.getNamespace();
        if (isNamespaceDeclaration( ns ) ) {
            namespaceStack.push(ns);
            writeNamespace(ns);
        }

        // Print out additional namespace declarations
        boolean textOnly = true;
        for ( int i = 0; i < size; i++ ) {
            Node node = element.node(i);
            if ( node instanceof Namespace ) {
                Namespace additional = (Namespace) node;
                if (isNamespaceDeclaration( additional ) ) {
                    namespaceStack.push(additional);
                    writeNamespace(additional);
                }
            }
            else if ( node instanceof Element) {
                textOnly = false;
            }
            else if ( node instanceof Comment) {
                textOnly = false;
            }
        }

        writeAttributes(element);

        lastOutputNodeType = Node.ELEMENT_NODE;

        if ( size <= 0 ) {
            writeEmptyElementClose(qualifiedName);
        }
        else {
            writer.write(">");
            if ( textOnly ) {
                // we have at least one text node so lets assume
                // that its non-empty
                writeElementContent(element);
            }
            else {
                // we know it's not null or empty from above
                ++indentLevel;

                writeElementContent(element);

                --indentLevel;

                writePrintln();
                indent();
            }
            writer.write("</");
            writer.write(qualifiedName);
            writer.write(">");
        }

        // remove declared namespaceStack from stack
        while (namespaceStack.size() > previouslyDeclaredNamespaces) {
            namespaceStack.pop();
        }

        lastOutputNodeType = Node.ELEMENT_NODE;
    }

    /**
     * Determines if element is a special case of XML elements
     * where it contains an xml:space attribute of "preserve".
     * If it does, then retain whitespace.
     */
    protected final boolean isElementSpacePreserved(Element element) {
      final Attribute attr = (Attribute)element.attribute("space");
      boolean preserveFound=preserve; //default to global state
      if (attr!=null) {
        if ("xml".equals(attr.getNamespacePrefix()) &&
            "preserve".equals(attr.getText())) {
          preserveFound = true;
        }
        else {
          preserveFound = false;
        }
      }
      return preserveFound;
    }
    /** Outputs the content of the given element. If whitespace trimming is
     * enabled then all adjacent text nodes are appended together before
     * the whitespace trimming occurs to avoid problems with multiple
     * text nodes being created due to text content that spans parser buffers
     * in a SAX parser.
     */
    protected void writeElementContent(Element element) throws IOException {
        boolean trim = format.isTrimText();
        boolean oldPreserve=preserve;
        if (trim) { //verify we have to before more expensive test
          preserve=isElementSpacePreserved(element);
          trim = !preserve;
        }
        if (trim) {
            // concatenate adjacent text nodes together
            // so that whitespace trimming works properly
            Text lastTextNode = null;
            StringBuilder buffer = null;
            boolean textOnly = true;
            for ( int i = 0, size = element.nodeCount(); i < size; i++ ) {
                Node node = element.node(i);
                if ( node instanceof Text ) {
                    if ( lastTextNode == null ) {
                        lastTextNode = (Text) node;
                    }
                    else {
                        if (buffer == null) {
                            buffer = new StringBuilder( lastTextNode.getText() );
                        }
                      buffer.append( ((Text) node).getText() );
                    }
                }
                else {
                    if (!textOnly && format.isPadText()) {
                        writer.write(PAD_TEXT);
                    }

                    textOnly = false;

                    if ( lastTextNode != null ) {
                        if ( buffer != null ) {
                            writeString( buffer.toString() );
                            buffer = null;
                        }
                        else {
                            writeString( lastTextNode.getText() );
                        }
                        lastTextNode = null;

                        if (format.isPadText()) {
                            writer.write(PAD_TEXT);
                        }
                    }
                    writeNode(node);
                }
            }
            if ( lastTextNode != null ) {
                if (!textOnly && format.isPadText()) {
                    writer.write(PAD_TEXT);
                }
                if ( buffer != null ) {
                    writeString( buffer.toString() );
                    buffer = null;
                }
                else {
                    writeString( lastTextNode.getText() );
                }
                lastTextNode = null;
            }
        }
        else {
            Node lastTextNode = null;
            for ( int i = 0, size = element.nodeCount(); i < size; i++ ) {
                Node node = element.node(i);
                if (node instanceof Text) {
                    writeNode(node);
                    lastTextNode = node;
                } else {
                    if ((lastTextNode != null) && format.isPadText()) {
                        writer.write(PAD_TEXT);
                    }
                    writeNode(node);
                    if ((lastTextNode != null) && format.isPadText()) {
                        writer.write(PAD_TEXT);
                    }
                    lastTextNode = null;
                }
            }
        }
        preserve=oldPreserve;
    }
    protected void writeCDATA(String text) throws IOException {
        writer.write( "<![CDATA[" );
        if (text != null) {
        	writer.write( text );
        }
        writer.write( "]]>" );

        lastOutputNodeType = Node.CDATA_SECTION_NODE;
    }

    protected void writeDocType(DocumentType docType) throws IOException {
        if (docType != null) {
            docType.write( writer );
            //writeDocType( docType.getElementName(), docType.getPublicID(), docType.getSystemID() );
            writePrintln();
        }
    }


    protected void writeNamespace(Namespace namespace) throws IOException {
        if ( namespace != null ) {
            writeNamespace(namespace.getPrefix(), namespace.getURI());
        }
    }

    /**
     * Writes the SAX namepsaces
     */
    protected void writeNamespaces() throws IOException {
        if ( namespacesMap != null ) {
            for ( Iterator iter = namespacesMap.entrySet().iterator(); iter.hasNext(); ) {
                Map.Entry entry = (Map.Entry) iter.next();
                String prefix = (String) entry.getKey();
                String uri = (String) entry.getValue();
                writeNamespace(prefix, uri);
            }
            namespacesMap = null;
        }
    }

    /**
     * Writes the SAX namepsaces
     */
    protected void writeNamespace(String prefix, String uri) throws IOException {
        if ( prefix != null && prefix.length() > 0 ) {
            writer.write(" xmlns:");
            writer.write(prefix);
            writer.write("=\"");
        }
        else {
            writer.write(" xmlns=\"");
        }
        writer.write(uri);
        writer.write("\"");
    }

    protected void writeProcessingInstruction(ProcessingInstruction processingInstruction) throws IOException {
        //indent();
        writer.write( "<?" );
        writer.write( processingInstruction.getName() );
        writer.write( " " );
        writer.write( processingInstruction.getText() );
        writer.write( "?>" );
        writePrintln();

        lastOutputNodeType = Node.PROCESSING_INSTRUCTION_NODE;
    }

    protected void writeString(String text) throws IOException {
        if ( text != null && text.length() > 0 ) {
            if ( escapeText ) {
                text = escapeElementEntities(text);
            }

//            if (format.isPadText()) {
//                if (lastOutputNodeType == Node.ELEMENT_NODE) {
//                    writer.write(PAD_TEXT);
//                }
//            }

            if (format.isTrimText()) {
                boolean first = true;
                StringTokenizer tokenizer = new StringTokenizer(text);
                while (tokenizer.hasMoreTokens()) {
                    String token = tokenizer.nextToken();
                    if ( first ) {
                        first = false;
                        if ( lastOutputNodeType == Node.TEXT_NODE ) {
                            writer.write(" ");
                        }
                    }
                    else {
                        writer.write(" ");
                    }
                    writer.write(token);
                    lastOutputNodeType = Node.TEXT_NODE;
                }
            }
            else {
                lastOutputNodeType = Node.TEXT_NODE;
                writer.write(text);
            }
        }
    }

    /**
     * This method is used to write out Nodes that contain text
     * and still allow for xml:space to be handled properly.
     *
     */
    protected void writeNodeText(Node node) throws IOException {
        String text = node.getText();
        if (text != null && text.length() > 0) {
            if (escapeText) {
                text = escapeElementEntities(text);
            }

            lastOutputNodeType = Node.TEXT_NODE;
            writer.write(text);
        }
    }

    protected void writeNode(Node node) throws IOException {
        int nodeType = node.getNodeType();
        switch (nodeType) {
            case Node.ELEMENT_NODE:
                writeElement((Element) node);
                break;
            case Node.ATTRIBUTE_NODE:
                writeAttribute((Attribute) node);
                break;
            case Node.TEXT_NODE:
                writeNodeText(node);
                //write((Text) node);
                break;
            case Node.CDATA_SECTION_NODE:
                writeCDATA(node.getText());
                break;
            case Node.ENTITY_REFERENCE_NODE:
                writeEntity((Entity) node);
                break;
            case Node.PROCESSING_INSTRUCTION_NODE:
                writeProcessingInstruction((ProcessingInstruction) node);
                break;
            case Node.COMMENT_NODE:
                writeComment(node.getText());
                break;
            case Node.DOCUMENT_NODE:
                write((Document) node);
                break;
            case Node.DOCUMENT_TYPE_NODE:
                writeDocType((DocumentType) node);
                break;
            case Node.NAMESPACE_NODE:
                // Will be output with attributes
                //write((Namespace) node);
                break;
            default:
                throw new IOException( "Invalid node type: " + node );
        }
    }




    protected void installLexicalHandler() {
        XMLReader parent = getParent();
        if (parent == null) {
            throw new NullPointerException("No parent for filter");
        }
        // try to register for lexical events
        for (int i = 0; i < LEXICAL_HANDLER_NAMES.length; i++) {
            try {
                parent.setProperty(LEXICAL_HANDLER_NAMES[i], this);
                break;
            }
            catch (SAXNotRecognizedException ex) {
                // ignore
            }
            catch (SAXNotSupportedException ex) {
                // ignore
            }
        }
    }

    protected void writeDocType(String name, String publicID, String systemID) throws IOException {
        boolean hasPublic = false;

        writer.write("<!DOCTYPE ");
        writer.write(name);
        if ((publicID != null) && (!publicID.equals(""))) {
            writer.write(" PUBLIC \"");
            writer.write(publicID);
            writer.write("\"");
            hasPublic = true;
        }
        if ((systemID != null) && (!systemID.equals(""))) {
            if (!hasPublic) {
                writer.write(" SYSTEM");
            }
            writer.write(" \"");
            writer.write(systemID);
            writer.write("\"");
        }
        writer.write(">");
        writePrintln();
    }

    protected void writeEntity(Entity entity) throws IOException {
        if (!resolveEntityRefs()) {
            writeEntityRef( entity.getName() );
        } else {
            writer.write(entity.getText());
        }
    }

    protected void writeEntityRef(String name) throws IOException {
        writer.write( "&" );
        writer.write( name );
        writer.write( ";" );

        lastOutputNodeType = Node.ENTITY_REFERENCE_NODE;
    }

    protected void writeComment(String text) throws IOException {
        if (format.isNewlines()) {
            println();
            indent();
        }
        writer.write( "<!--" );
        writer.write( text );
        writer.write( "-->" );

        lastOutputNodeType = Node.COMMENT_NODE;
    }

    /** Writes the attributes of the given element
      *
      */
    protected void writeAttributes( Element element ) throws IOException {

        // I do not yet handle the case where the same prefix maps to
        // two different URIs. For attributes on the same element
        // this is illegal; but as yet we don't throw an exception
        // if someone tries to do this
        for ( int i = 0, size = element.attributeCount(); i < size; i++ ) {
            Attribute attribute = element.attribute(i);
            Namespace ns = attribute.getNamespace();
            if (ns != null && ns != Namespace.NO_NAMESPACE && ns != Namespace.XML_NAMESPACE) {
                String prefix = ns.getPrefix();
                String uri = namespaceStack.getURI(prefix);
                if (!ns.getURI().equals(uri)) { // output a new namespace declaration
                    writeNamespace(ns);
                    namespaceStack.push(ns);
                }
            }

            // If the attribute is a namespace declaration, check if we have already
            // written that declaration elsewhere (if that's the case, it must be
            // in the namespace stack
            String attName = attribute.getName();
            if (attName.startsWith("xmlns:")) {
                String prefix = attName.substring(6);
                if (namespaceStack.getNamespaceForPrefix(prefix) == null) {
                    String uri = attribute.getValue();
                    namespaceStack.push(prefix, uri);
                    writeNamespace(prefix, uri);
                }
            } else if (attName.equals("xmlns")) {
                if (namespaceStack.getDefaultNamespace() == null) {
                    String uri = attribute.getValue();
                    namespaceStack.push(null, uri);
                    writeNamespace(null, uri);
                }
            } else {
                char quote = format.getAttributeQuoteCharacter();
                writer.write(" ");
                writer.write(attribute.getQualifiedName());
                writer.write("=");
                writer.write(quote);
                writeEscapeAttributeEntities(attribute.getValue());
                writer.write(quote);
            }
        }
    }

    protected void writeAttribute(Attribute attribute) throws IOException {
        writer.write(" ");
        writer.write(attribute.getQualifiedName());
        writer.write("=");

        char quote = format.getAttributeQuoteCharacter();
        writer.write(quote);

        writeEscapeAttributeEntities(attribute.getValue());

        writer.write(quote);
        lastOutputNodeType = Node.ATTRIBUTE_NODE;
    }

    protected void writeAttributes(Attributes attributes) throws IOException {
        for (int i = 0, size = attributes.getLength(); i < size; i++) {
            writeAttribute( attributes, i );
        }
    }

    protected void writeAttribute(Attributes attributes, int index) throws IOException {
        char quote = format.getAttributeQuoteCharacter();
        writer.write(" ");
        writer.write(attributes.getQName(index));
        writer.write("=");
        writer.write(quote);
        writeEscapeAttributeEntities(attributes.getValue(index));
        writer.write(quote);
    }



    protected void indent() throws IOException {
        String indent = format.getIndent();
        if ( indent != null && indent.length() > 0 ) {
            for ( int i = 0; i < indentLevel; i++ ) {
                writer.write(indent);
            }
        }
    }

    /**
     * <p>
     * This will print a new line only if the newlines flag was set to true
     * </p>
     */
    protected void writePrintln() throws IOException  {
        if (format.isNewlines()) {
            writer.write( format.getLineSeparator() );
        }
    }

    /**
     * Get an OutputStreamWriter, use preferred encoding.
     */
    protected Writer createWriter(OutputStream outStream, String encoding) throws UnsupportedEncodingException {
        return new BufferedWriter(
            new OutputStreamWriter( outStream, encoding )
        );
    }

    /**
     * <p>
     * This will write the declaration to the given Writer.
     *   Assumes XML version 1.0 since we don't directly know.
     * </p>
     */
    protected void writeDeclaration() throws IOException {
        String encoding = format.getEncoding();

        // Only print of declaration is not suppressed
        if (! format.isSuppressDeclaration()) {
            // Assume 1.0 version
            if (encoding.equals("UTF8")) {
                writer.write("<?xml version=\"1.0\"");
                if (!format.isOmitEncoding()) {
                    writer.write(" encoding=\"UTF-8\"");
                }
                writer.write("?>");
            } else {
                writer.write("<?xml version=\"1.0\"");
                if (! format.isOmitEncoding()) {
                    writer.write(" encoding=\"" + encoding + "\"");
                }
                writer.write("?>");
            }
            if (format.isNewLineAfterDeclaration()) {
                println();
            }
        }
    }

    protected void writeClose(String qualifiedName) throws IOException {
        writer.write("</");
        writer.write(qualifiedName);
        writer.write(">");
    }

    protected void writeEmptyElementClose(String qualifiedName) throws IOException {
        // Simply close up
        if (! format.isExpandEmptyElements()) {
            writer.write("/>");
        } else {
            writer.write("></");
            writer.write(qualifiedName);
            writer.write(">");
        }
    }

    protected boolean isExpandEmptyElements() {
        return format.isExpandEmptyElements();
    }


    /** This will take the pre-defined entities in XML 1.0 and
      * convert their character representation to the appropriate
      * entity reference, suitable for XML attributes.
      */
    protected String escapeElementEntities(String text) {
        char[] block = null;
        int i, last = 0, size = text.length();
        for ( i = 0; i < size; i++ ) {
            String entity = null;
            char c = text.charAt(i);
            switch( c ) {
                case '<' :
                    entity = "&lt;";
                    break;
                case '>' :
                    entity = "&gt;";
                    break;
                case '&' :
                    entity = "&amp;";
                    break;
                case '\t': case '\n': case '\r':
                    // don't encode standard whitespace characters
                    if (preserve) {
                      entity=String.valueOf(c);
                    }
                    break;
                default:
                	if (c < 32 || shouldEncodeChar(c)) {
                        entity = "&#" + (int) c + ";";
                	}
                    break;
            }
            if (entity != null) {
                if ( block == null ) {
                    block = text.toCharArray();
                }
                buffer.append(block, last, i - last);
                buffer.append(entity);
                last = i + 1;
            }
        }
        if ( last == 0 ) {
            return text;
        }
        if ( last < size ) {
            if ( block == null ) {
                block = text.toCharArray();
            }
            buffer.append(block, last, i - last);
        }
        String answer = buffer.toString();
        buffer.setLength(0);
        return answer;
    }


    protected void writeEscapeAttributeEntities(String text) throws IOException {
        if ( text != null ) {
            String escapedText = escapeAttributeEntities( text );
            writer.write( escapedText );
        }
    }
    /** This will take the pre-defined entities in XML 1.0 and
      * convert their character representation to the appropriate
      * entity reference, suitable for XML attributes.
      */
    protected String escapeAttributeEntities(String text) {
        char quote = format.getAttributeQuoteCharacter();

        char[] block = null;
        int i, last = 0, size = text.length();
        for ( i = 0; i < size; i++ ) {
            String entity = null;
            char c = text.charAt(i);
            switch( c ) {
                case '<' :
                    entity = "&lt;";
                    break;
                case '>' :
                    entity = "&gt;";
                    break;
                case '\'' :
                    if (quote == '\'') {
                        entity = "&apos;";
                    }
                    break;
                case '\"' :
                    if (quote == '\"') {
                        entity = "&quot;";
                    }
                    break;
                case '&' :
                    entity = "&amp;";
                    break;
                case '\t': case '\n': case '\r':
                    // don't encode standard whitespace characters
                    break;
                default:
                	if (c < 32 || shouldEncodeChar(c)) {
                        entity = "&#" + (int) c + ";";
                	}
                    break;
            }
            if (entity != null) {
                if ( block == null ) {
                    block = text.toCharArray();
                }
                buffer.append(block, last, i - last);
                buffer.append(entity);
                last = i + 1;
            }
        }
        if ( last == 0 ) {
            return text;
        }
        if ( last < size ) {
            if ( block == null ) {
                block = text.toCharArray();
            }
            buffer.append(block, last, i - last);
        }
        String answer = buffer.toString();
        buffer.setLength(0);
        return answer;
    }

	/**
	 * Should the given character be escaped. This depends on the
	 * encoding of the document.
	 *
	 * @return boolean
	 */
	protected boolean shouldEncodeChar(char c) {
		int max = getMaximumAllowedCharacter();
		return max > 0 && c > max;
	}

	/**
	 * Returns the maximum allowed character code that should be allowed
	 * unescaped which defaults to 127 in US-ASCII (7 bit) or
	 * 255 in ISO-* (8 bit).
	 */
	protected int defaultMaximumAllowedCharacter() {
		String encoding = format.getEncoding();
		if (encoding != null) {
			if (encoding.equals("US-ASCII")) {
				return 127;
			}
		}
		// no encoding for things like ISO-*, UTF-8 or UTF-16
		return -1;
	}

    protected boolean isNamespaceDeclaration( Namespace ns ) {
        if (ns != null && ns != Namespace.XML_NAMESPACE) {
            String uri = ns.getURI();
            if ( uri != null ) {
                if ( ! namespaceStack.contains( ns ) ) {
                    return true;

                }
            }
        }
        return false;

    }

    protected void handleException(IOException e) throws SAXException {
        throw new SAXException(e);
    }

    //Laramie Crocker 4/8/2002 10:38AM
    /** Lets subclasses get at the current format object, so they can call setTrimText, setNewLines, etc.
      * Put in to support the HTMLWriter, in the way
      *  that it pushes the current newline/trim state onto a stack and overrides
      *  the state within preformatted tags.
      */
    protected OutputFormat getOutputFormat() {
        return format;
    }

    public boolean resolveEntityRefs() {
        return resolveEntityRefs;
    }

    public void setResolveEntityRefs(boolean resolve) {
        this.resolveEntityRefs = resolve;
    }
}