001package org.hl7.fhir.utilities.xml;
002
003/*
004  Copyright (c) 2011+, HL7, Inc.
005  All rights reserved.
006  
007  Redistribution and use in source and binary forms, with or without modification, 
008  are permitted provided that the following conditions are met:
009    
010   * Redistributions of source code must retain the above copyright notice, this 
011     list of conditions and the following disclaimer.
012   * Redistributions in binary form must reproduce the above copyright notice, 
013     this list of conditions and the following disclaimer in the documentation 
014     and/or other materials provided with the distribution.
015   * Neither the name of HL7 nor the names of its contributors may be used to 
016     endorse or promote products derived from this software without specific 
017     prior written permission.
018  
019  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
020  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
021  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
022  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
023  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 
024  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
025  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
026  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
027  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
028  POSSIBILITY OF SUCH DAMAGE.
029  
030 */
031
032
033
034import java.io.IOException;
035import java.io.OutputStream;
036import java.io.OutputStreamWriter;
037import java.io.UnsupportedEncodingException;
038
039import org.hl7.fhir.utilities.ElementDecoration;
040
041/**
042 * XML Writer class.
043 */
044public class XMLWriter extends OutputStreamWriter implements IXMLWriter {
045
046        private boolean xmlHeader = true;
047        private String charset;
048        private boolean prettyBase;
049        private boolean prettyHeader;
050        private boolean pendingClose;
051        private boolean pendingOpen;
052        private String pendingComment;
053        private int lineType = LINE_UNIX;
054        private OutputStream stream;
055        private boolean started = false;
056        private String[] specialAttributeNames = new String[] {"id", "name" };
057        private boolean canonical;
058        private int attributeLineWrap;
059  private boolean xml1_1;
060  private boolean ignoreComments;
061        
062        public final static int LINE_UNIX = 0;
063        public final static int LINE_WINDOWS = 1;
064
065  public XMLWriter(OutputStream stream, String charset, boolean xml1_1) throws UnsupportedEncodingException {    
066    super(stream, charset);
067    this.stream = stream;
068    this.charset = charset;
069    this.xml1_1 = xml1_1;
070  }
071        public XMLWriter(OutputStream stream, String charset) throws UnsupportedEncodingException {
072                super(stream, charset);
073                this.stream = stream;
074                this.charset = charset;
075    this.xml1_1 = false;
076        }
077
078        protected boolean condition(boolean bTest, String message) throws IOException {
079                if (!bTest)
080                        throw new IOException(message);
081                return bTest;
082        }
083
084        // -- writing context ------------------------------------------------
085
086
087        
088        /**
089         * Returns the encoding.
090         * 
091         * @param charset
092         * @return encoding
093         * @throws IOException
094         */
095        public static String getXMLCharsetName(String charset) throws IOException {
096                if (charset == null || charset.equals(""))
097                        return "UTF-8";
098                else if (charset.equals("US-ASCII"))
099                        return "UTF-8";
100                else if (XMLUtil.charSetImpliesAscii(charset))
101                        return "ISO-8859-1";
102                else if (charset.equals("UTF-8"))
103                        return "UTF-8";
104                else if (charset.equals("UTF-16") || charset.equals("UTF-16BE") || charset.equals("UTF-16LE"))
105                        return "UTF-16";
106                else 
107                        throw new IOException("Unknown charset encoding "+charset);
108        }
109
110        /* (non-Javadoc)
111         * @see org.eclipse.ohf.utilities.xml.IXMLWriter#start()
112         */
113        @Override
114        public void start() throws IOException {
115                condition(!started, "attempt to start after starting");
116                levels.clear();
117                attributes = null;
118                try {
119                        if (xmlHeader) {
120                                write("<?xml version=\""+(xml1_1 ? "1.1" : "1.0")+"\" encoding=\""+getXMLCharsetName(charset)+"\"?>");
121                                if (prettyBase || prettyHeader)
122                                        write(lineType == LINE_UNIX ? "\n" : "\r\n");
123                        }
124                } catch (UnsupportedEncodingException e) {
125                        // TODO Auto-generated catch block
126                        throw new IOException(e.getMessage());
127                }
128                started = true;
129        }
130
131        private void checkStarted () throws IOException {
132                condition(started, "not started");
133        }
134
135        private void checkInElement() throws IOException {
136                condition(levels.size() > 0, "not in an element");
137        }
138
139        // -- attributes ----------------------------------------------------
140
141        private String[][] attributes;
142        
143        private void addAttribute(String name, String value) throws IOException {
144                addAttribute(name, value, false);
145        }
146
147        private void addAttribute(String name, String value, boolean noLines) throws IOException {
148                if (!XMLUtil.isNMToken(name))
149                        throw new IOException("XML name "+name+" is not valid for value '"+value+"'");
150
151                newLevelIfRequired();
152                value = XMLUtil.escapeXML(value, charset, noLines);
153
154                if (attributes == null) 
155                        attributes = new String[][] {{name, value}};
156                else {
157                        String[][] newattr = new String[attributes.length+1][];
158                        for (int i = 0; i < attributes.length; i++) {
159                                condition(!attributes[i][0].equals(name), "attempt to define attribute with name "+name+" more than once for value '"+value+"'");
160                                newattr[i] = attributes[i];
161                        }
162                        attributes = newattr;
163                        attributes[attributes.length-1] = new String[] {name, value};
164                }
165        }
166
167        protected String getAttribute(String name) {
168                if (attributes != null) {
169                        for (int i = 0; i < attributes.length; i++) {
170                                if (attributes[i][0].equals(name)) {
171                                        return attributes[i][1];
172                                }
173                        }                       
174                }
175                return null;
176        }
177        
178        protected void setAttribute(String name, String value) throws IOException {
179                newLevelIfRequired();
180                if (attributes == null) 
181                        addAttribute(name, value, false);
182                else {
183                        for (int i = 0; i < attributes.length; i++) {
184                                if (attributes[i][0].equals(name)) {
185                                        attributes[i][1] = XMLUtil.escapeXML(value, charset, false);
186                                        return;
187                                }
188                        }
189                        addAttribute(name, value);
190                }
191        }
192
193        protected void commitAttributes() throws IOException {
194                
195        }
196
197        
198        private boolean nameIsSpecial(String name) {
199                for (int i = 0; i < specialAttributeNames.length; i++) {
200                        String n = specialAttributeNames[i];
201                        if (n.equalsIgnoreCase(name))
202                                return true;
203                }
204                return false;
205        }
206        
207        private void writeAttributes(int col) throws IOException {
208                commitAttributes();
209                if (attributes != null && canonical)
210                        sortAttributes();       
211                int c = col;
212                c = writeAttributeSet(true, c, col);
213                writeAttributeSet(false, c, col);
214                attributes = null;
215        }
216
217
218        private void sortAttributes() {
219                // bubble sort - look, it's easy
220                for (int i = 0; i < attributes.length - 1; i++) {
221                        for (int j = 0; j < attributes.length - 1; j++) {
222                                if (String.CASE_INSENSITIVE_ORDER.compare(attributes[j][0], attributes[j+1][0]) < 0) {
223                                        String[] t = attributes[j];
224                                        attributes[j] = attributes[j+1];
225                                        attributes[j+1] = t;
226                                }
227                        }
228                }
229                
230        }
231
232
233        private int writeAttributeSet(boolean special, int col, int wrap) throws IOException {
234                // first pass: name, id
235                if (attributes != null) {
236                        for (int i=0; i < attributes.length; i++) {
237                                String[] element = attributes[i];
238                                if (nameIsSpecial(element[0]) == special) {
239                                        col = col + element[0].length()+element[1].length() + 4;
240                                        if (isPretty() && attributeLineWrap > 0 && col > attributeLineWrap && col > wrap) {
241                                                write(lineType == LINE_UNIX ? "\n" : "\r\n");
242                                                for (int j = 0; j < wrap; j++)
243                                                        write(" ");
244                                                col = wrap;
245                                        }
246                                        write(' ');
247                                        write(element[0]);
248                                        write("=\"");
249                                        if (element[1] != null)
250                                                write(xmlEscape(element[1]));
251                                        write("\"");
252                                }
253                        }
254                }
255                return col;
256        }
257
258         protected String xmlEscape(String s) {
259     StringBuilder b = new StringBuilder();
260     for (char c : s.toCharArray()) {
261       if (c < ' ') {
262         b.append("&#x");
263         b.append(Integer.toHexString(c).toUpperCase());
264         b.append(";");
265       } else
266         b.append(c);
267     }
268     return b.toString();
269   }
270
271         /* (non-Javadoc)
272         * @see org.eclipse.ohf.utilities.xml.IXMLWriter#attribute(java.lang.String, java.lang.String, java.lang.String, boolean)
273         */
274        @Override
275        public void attribute(String namespace, String name, String value, boolean onlyIfNotEmpty) throws IOException {
276                if (!onlyIfNotEmpty || value != null && !value.equals(""))
277                        attribute(namespace, name, value);
278        }
279        
280        /* (non-Javadoc)
281         * @see org.eclipse.ohf.utilities.xml.IXMLWriter#attribute(java.lang.String, java.lang.String, java.lang.String)
282         */
283        @Override
284        public void attribute(String namespace, String name, String value) throws IOException {
285
286                checkStarted();
287                if (namespace == null || namespace.equals("")) 
288                        addAttribute(name, value);
289                else
290                        addAttribute(getNSAbbreviation(namespace)+name, value);
291        }
292
293        /* (non-Javadoc)
294         * @see org.eclipse.ohf.utilities.xml.IXMLWriter#attribute(java.lang.String, java.lang.String, boolean)
295         */
296        @Override
297        public void attribute(String name, String value, boolean onlyIfNotEmpty) throws IOException {
298                if (!onlyIfNotEmpty || value != null && !value.equals(""))
299                        attribute(name, value);
300        }
301
302        /* (non-Javadoc)
303         * @see org.eclipse.ohf.utilities.xml.IXMLWriter#attribute(java.lang.String, java.lang.String)
304         */
305        @Override
306        public void attribute(String name, String value) throws IOException {
307                checkStarted();
308                addAttribute(name, value);
309        }
310
311        /* (non-Javadoc)
312         * @see org.eclipse.ohf.utilities.xml.IXMLWriter#attributeNoLines(java.lang.String, java.lang.String)
313         */
314        @Override
315        public void attributeNoLines(String name, String value) throws IOException {
316                checkStarted();
317                addAttribute(name, value, true);
318        }
319
320        // -- levels -------------------------------------------------
321
322        private XMLWriterStateStack levels = new XMLWriterStateStack();
323
324        private void newLevelIfRequired() throws IOException {
325                if (!pendingOpen) {
326                        if (!levels.empty())
327                                levels.current().seeChild();
328                        XMLWriterState level = new XMLWriterState();
329                        level.setPretty(isPretty());
330                        levels.push(level);
331                        pendingOpen = true;
332                }
333        }
334
335        // -- namespaces ---------------------------------------------
336
337
338        private void defineNamespace(String namespace, String abbrev) throws IOException {
339                checkStarted();
340                if (namespace != null && !namespace.equals("")) {
341                        if ("".equals(abbrev))
342                                abbrev = null;
343
344                        newLevelIfRequired();
345
346                        levels.current().addNamespaceDefn(namespace, abbrev);
347                        if (abbrev == null)
348                                addAttribute("xmlns", namespace);
349                        else
350                                addAttribute("xmlns:"+abbrev, namespace);
351                }
352        }
353
354        /* (non-Javadoc)
355         * @see org.eclipse.ohf.utilities.xml.IXMLWriter#findByNamespace(java.lang.String)
356         */
357        public XMLNamespace findByNamespace(String namespace) {
358                for (int i = levels.size() - 1; i >= 0; i--) {
359                        XMLNamespace ns = levels.item(i).getDefnByNamespace(namespace);
360                        if (ns != null)
361                                return ns;
362                }
363                return null;
364        }
365
366        /* (non-Javadoc)
367         * @see org.eclipse.ohf.utilities.xml.IXMLWriter#namespaceDefined(java.lang.String)
368         */
369        @Override
370        public boolean namespaceDefined(String namespace) {
371                return namespace == null || namespace.equals("") || findByNamespace(namespace) != null;
372        }
373
374        /* (non-Javadoc)
375         * @see org.eclipse.ohf.utilities.xml.IXMLWriter#findByAbbreviation(java.lang.String)
376         */
377        public XMLNamespace findByAbbreviation(String abbreviation) {
378                for (int i = levels.size() - 1; i >= 0; i--) {
379                        XMLNamespace ns = levels.item(i).getDefnByAbbreviation(abbreviation);
380                        if (ns != null)
381                                return ns;
382                }
383                return null;
384        }
385
386        /* (non-Javadoc)
387         * @see org.eclipse.ohf.utilities.xml.IXMLWriter#abbreviationDefined(java.lang.String)
388         */
389        @Override
390        public boolean abbreviationDefined(String abbreviation) {
391                return findByAbbreviation(abbreviation) != null;
392        }
393
394        protected XMLNamespace findDefaultNamespace() {
395                for (int i = levels.size() - 1; i >= 0; i--) {
396                        XMLNamespace ns = levels.item(i).getDefaultNamespace();
397                        if (ns != null)
398                                return ns;
399                }
400                return null;
401        }
402
403        /* (non-Javadoc)
404         * @see org.eclipse.ohf.utilities.xml.IXMLWriter#getDefaultNamespace()
405         */
406        @Override
407        public String getDefaultNamespace() {
408                XMLNamespace ns = findDefaultNamespace();
409                if (ns == null)
410                        return null;
411                else
412                        return ns.getNamespace();
413        }
414
415        /* (non-Javadoc)
416         * @see org.eclipse.ohf.utilities.xml.IXMLWriter#namespace(java.lang.String)
417         */
418        @Override
419        public void namespace(String namespace) throws IOException {
420                if (!namespaceDefined(namespace)) {
421                        int index = 0;
422                        while (abbreviationDefined("ns"+Integer.toString(index))) 
423                                index++;
424                        defineNamespace(namespace, "ns"+Integer.toString(index));
425                }
426        }
427
428        /* (non-Javadoc)
429         * @see org.eclipse.ohf.utilities.xml.IXMLWriter#defaultNamespace(java.lang.String)
430         * 
431         * Replace defaultNamespace()
432         */
433        @Override
434        public void setDefaultNamespace(String namespace) throws IOException {
435                if ((namespace == null && getDefaultNamespace() != null) ||
436                                (namespace != null && !namespace.equals(getDefaultNamespace())))
437                        defineNamespace(namespace, "");                 
438        }
439
440        /* (non-Javadoc)
441         * @see org.eclipse.ohf.utilities.xml.IXMLWriter#namespace(java.lang.String, java.lang.String)
442         */
443        @Override
444        public void namespace(String namespace, String abbreviation) throws IOException {
445                XMLNamespace ns = findByAbbreviation(abbreviation);
446                if (ns == null || !ns.getNamespace().equals(namespace))
447                        defineNamespace(namespace, abbreviation);
448        }
449
450
451        private String getNSAbbreviation(String namespace) throws IOException {
452                if ("http://www.w3.org/XML/1998/namespace".equals(namespace))
453                        return "xml:";
454                
455                if (namespace == null || "".equals(namespace) || "noNamespace".equals(namespace))
456                        return "";
457                
458                XMLNamespace ns = findByNamespace(namespace);
459                if (ns == null)
460                        throw new IOException("Namespace "+namespace+" is not defined");
461                else if (ns.getAbbreviation() == null)
462                        return "";
463                else
464                        return ns.getAbbreviation()+":";
465        }
466
467        // -- public API -----------------------------------------------------------
468
469        /* (non-Javadoc)
470         * @see org.eclipse.ohf.utilities.xml.IXMLWriter#comment(java.lang.String, boolean)
471         */
472        @Override
473        public void comment(String comment, boolean doPretty) throws IOException {
474          if (ignoreComments) {
475            return;
476          }
477                checkStarted();
478                if (pendingClose) { 
479                        write('>');
480                        writePendingComment();
481                        pendingClose = false;
482                }
483                if (doPretty) {
484                        writePretty();
485                }
486                if (levels.inComment())
487                        write("  <!-- "+comment+" -- >");
488                else
489                        write("  <!-- "+comment+" -->");
490                if (doPretty && !isPretty())
491                        writePretty();
492        }
493
494
495        private void writePendingComment() throws IOException {
496                if (pendingComment != null) {
497                        if (isPretty())
498                                write("   ");
499                        if (levels.inComment())
500                                write("<!-- "+pendingComment+" -- >");
501                        else
502                                write("<!-- "+pendingComment+" -->");
503                }
504        }
505        
506        /* (non-Javadoc)
507         * @see org.eclipse.ohf.utilities.xml.IXMLWriter#open(java.lang.String, java.lang.String)
508         */
509        @Override
510        public void enter(String namespace, String name) throws IOException {
511                enter(namespace, name, null);
512        }
513
514
515        /* (non-Javadoc)
516         * @see org.eclipse.ohf.utilities.xml.IXMLWriter#open(java.lang.String, java.lang.String, java.lang.String)
517         */
518        @Override
519        public void enter(String namespace, String name, String comment) throws IOException {
520                if (name == null)
521                        throw new Error("name == null");
522                if (!XMLUtil.isNMToken(name))
523                        throw new IOException("XML name "+name+" is not valid");
524                checkStarted();
525                if (pendingClose) { 
526                        write('>');
527                        writePendingComment();
528                        pendingClose = false;
529                }
530
531                if (name == null) {
532                        throw new IOException("name is null");
533                }
534                newLevelIfRequired();
535                levels.current().setName(name);
536                levels.current().setNamespace(namespace);
537                int col = writePretty();
538                write('<');
539                if (namespace == null) {
540                        write(name);
541                        col = col + name.length()+1;
542                } else {
543                        String n = getNSAbbreviation(namespace)+name;
544                        write(n);
545                        col = col + n.length()+1;
546                }
547                writeAttributes(col);
548                pendingOpen = false;
549                pendingClose = true;
550                pendingComment = comment;
551        }
552
553
554        /* (non-Javadoc)
555         * @see org.eclipse.ohf.utilities.xml.IXMLWriter#close(java.lang.String)
556         */
557        @Override
558        public void exit(String name) throws IOException {
559                checkStarted();
560                if (levels.empty())
561                        throw new IOException("Unable to close null|"+name+", nothing to close");
562                if (levels.current().getNamespace() != null || !name.equals(levels.current().getName()))
563                        throw new IOException("Unable to close null|"+name+", found "+levels.current().getNamespace()+"|"+levels.current().getName());
564                exit();
565        }
566
567        /* (non-Javadoc)
568         * @see org.eclipse.ohf.utilities.xml.IXMLWriter#close(java.lang.String, java.lang.String)
569         */
570        @Override
571        public void exit(String namespace, String name) throws IOException {
572                checkStarted();
573                if (levels.empty())
574                        throw new IOException("Unable to close "+namespace+"|"+name+", nothing to close");
575                if (levels == null)
576                        throw new Error("levels = null");
577                if (levels.current() == null)
578                        throw new Error("levels.current() = null");
579                if (levels.current().getName() == null)
580                        throw new Error("levels.current().getName() = null");
581                if (levels.current().getNamespace() == null)
582                        throw new Error("levels.current().getNamespace() = null");
583                if (name == null)
584                        throw new Error("name = null");
585                if (namespace == null)
586                        throw new Error("namespace = null");
587                if (!levels.current().getNamespace().equals(namespace) || !levels.current().getName().equals(name))
588                        throw new IOException("Unable to close "+namespace+"|"+name+", found "+levels.current().getNamespace()+"|"+levels.current().getName());
589                exit();
590        }
591
592        /* (non-Javadoc)
593         * @see org.eclipse.ohf.utilities.xml.IXMLWriter#closeToLevel(int)
594         */
595        @Override
596        public void exitToLevel(int count) throws IOException {
597    checkStarted();
598                while (levels.size() > count)
599                        exit();         
600        }
601
602
603        /* (non-Javadoc)
604         * @see org.eclipse.ohf.utilities.xml.IXMLWriter#close()
605         */
606  @Override
607  public void close() throws IOException {
608    checkStarted();
609    if (!levels.empty()) 
610      throw new IOException("Called close before exiting all opened elements");
611     super.close();
612  }
613    
614  @Override
615  public void end() throws IOException {
616    checkStarted();
617    if (!levels.empty()) 
618      throw new IOException("Called end() before exiting all opened elements");
619     flush();
620  }
621        @Override
622        public void exit() throws IOException {
623                checkStarted();
624                if (levels.empty()) {
625                        throw new IOException("Called exit one too many times");
626                } else {
627                        if (pendingClose) { 
628                                write("/>");
629                                writePendingComment();
630                                pendingClose = false;
631                        } else {
632                                if (levels.current().hasChildren())
633                                        writePretty();
634                                write("</");
635                                if (levels.current().getNamespace() == null)
636                                        write(levels.current().getName());
637                                else
638                                        write(getNSAbbreviation(levels.current().getNamespace())+levels.current().getName());
639                                write('>');
640                        }
641                        levels.pop();
642                }
643        }
644
645        /* (non-Javadoc)
646         * @see org.eclipse.ohf.utilities.xml.IXMLWriter#open(java.lang.String)
647         */
648        @Override
649        public void enter(String name) throws IOException {
650                enter(null, name);
651        }
652
653
654        /* (non-Javadoc)
655         * @see org.eclipse.ohf.utilities.xml.IXMLWriter#element(java.lang.String, java.lang.String, java.lang.String, boolean)
656         */
657        @Override
658        public void element(String namespace, String name, String content, boolean onlyIfNotEmpty) throws IOException {
659                if (!onlyIfNotEmpty || content != null && !content.equals(""))
660                        element(namespace, name, content);
661        }
662
663        /* (non-Javadoc)
664         * @see org.eclipse.ohf.utilities.xml.IXMLWriter#element(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
665         */
666        @Override
667        public void element(String namespace, String name, String content, String comment) throws IOException {
668                if (!XMLUtil.isNMToken(name))
669                        throw new IOException("XML name "+name+" is not valid");
670                enter(namespace, name, comment);
671                text(content);
672                exit();
673        }
674        
675        /* (non-Javadoc)
676         * @see org.eclipse.ohf.utilities.xml.IXMLWriter#element(java.lang.String, java.lang.String, java.lang.String)
677         */
678        @Override
679        public void element(String namespace, String name, String content) throws IOException {
680                if (!XMLUtil.isNMToken(name))
681                        throw new IOException("XML name "+name+" is not valid");
682                enter(namespace, name);
683                text(content);
684                exit();
685        }
686
687        /* (non-Javadoc)
688         * @see org.eclipse.ohf.utilities.xml.IXMLWriter#element(java.lang.String, java.lang.String, boolean)
689         */
690        @Override
691        public void element(String name, String content, boolean onlyIfNotEmpty) throws IOException {
692                if (!onlyIfNotEmpty || content != null && !content.equals(""))
693                        element(null, name, content);
694        }
695
696        /* (non-Javadoc)
697         * @see org.eclipse.ohf.utilities.xml.IXMLWriter#element(java.lang.String, java.lang.String)
698         */
699        @Override
700        public void element(String name, String content) throws IOException {
701                element(null, name, content);
702        }
703
704  @Override
705  public void element(String name) throws IOException {
706    element(null, name, null);
707  }
708
709        /* (non-Javadoc)
710         * @see org.eclipse.ohf.utilities.xml.IXMLWriter#text(java.lang.String)
711         */
712        @Override
713        public void text(String content) throws IOException {
714                text(content, false);
715        }
716
717        /* (non-Javadoc)
718         * @see org.eclipse.ohf.utilities.xml.IXMLWriter#text(java.lang.String, boolean)
719         * 
720         * Replace escapeText()
721         */
722        @Override
723        public void text(String content, boolean dontEscape) throws IOException {
724                checkInElement();
725                if (content != null) {
726                        if (pendingClose) { 
727                                write(">");
728                                writePendingComment();
729                                pendingClose = false;
730                        }
731                        if (dontEscape)
732                                write(content);
733                        else
734                                write(XMLUtil.escapeXML(content, charset, false));
735                }
736        }
737
738        /* (non-Javadoc)
739         * @see org.eclipse.ohf.utilities.xml.IXMLWriter#cData(java.lang.String)
740         */
741        @Override
742        public void cData(String text) throws IOException {
743                text("<![CDATA["+text+"]]>");           
744        }
745        
746        /* (non-Javadoc)
747         * @see org.eclipse.ohf.utilities.xml.IXMLWriter#writeBytes(byte[])
748         */
749        @Override
750        public void writeBytes(byte[] bytes) throws IOException {
751                checkInElement();
752                if (pendingClose) { 
753                        write(">");
754                        writePendingComment();
755                        pendingClose = false;
756                }
757                flush();
758                stream.write(bytes);
759        }
760
761
762        /* (non-Javadoc)
763         * @see org.eclipse.ohf.utilities.xml.IXMLWriter#isPretty()
764         */
765        @Override
766        public boolean isPretty() throws IOException {
767                return (levels == null || levels.empty()) ? prettyBase : levels.current().isPretty();
768        }
769
770        /* (non-Javadoc)
771         * @see org.eclipse.ohf.utilities.xml.IXMLWriter#setPretty(boolean)
772         */
773        @Override
774        public void setPretty(boolean pretty) throws IOException {
775                if (levels == null || levels.empty())
776                        this.prettyBase = pretty;
777                else 
778                        levels.current().setPretty(pretty);
779        }
780
781        /* (non-Javadoc)
782         * @see org.eclipse.ohf.utilities.xml.IXMLWriter#startCommentBlock()
783         */
784        @Override
785        public void startCommentBlock() throws IOException {
786                if (levels.inComment())
787                        throw new IOException("cannot nest comments");
788                levels.current().setInComment(true);
789                if (isPretty())
790                        writePretty();
791                write("<!--");
792                if (isPretty())
793                        writePretty();          
794        }
795
796        /* (non-Javadoc)
797         * @see org.eclipse.ohf.utilities.xml.IXMLWriter#endCommentBlock()
798         */
799        @Override
800        public void endCommentBlock() throws IOException {
801                if (!levels.inComment())
802                        throw new IOException("cannot close a comment block when it is open");
803                if (!levels.current().isInComment())
804                        throw new IOException("cannot close a comment block when it is open");
805                if (isPretty())
806                        writePretty();
807                write("-->");
808                if (isPretty())
809                        writePretty();          
810                levels.current().setInComment(false);
811        }
812
813
814
815        public void setCanonical(boolean canonical) {
816    this.canonical = canonical;
817  }
818  public boolean isPrettyHeader() {
819                return prettyHeader;
820        }
821
822        public void setPrettyHeader(boolean pretty) {
823                this.prettyHeader = pretty;
824        }
825
826        public int writePretty() throws IOException {
827                return writePretty(true);
828        }
829        
830        public int writePretty(boolean eoln) throws IOException {
831                if (isPretty()) {
832                        if (eoln)
833                                write(lineType == LINE_UNIX ? "\n" : "\r\n");
834                        for (int i = 0; i < levels.size() - 1; i++)
835                                write("  ");
836                        return (levels.size() - 1) * 2;
837                } else
838                        return 0;
839        }
840
841        public int getLineType() {
842                return lineType;
843        }
844
845        public void setLineType(int lineType) {
846                this.lineType = lineType;
847        }
848
849        public boolean isXmlHeader() {
850                return xmlHeader;
851        }
852
853        public void setXmlHeader(boolean xmlHeader) {
854                this.xmlHeader = xmlHeader;
855        }
856
857        public String[] getSpecialAttributeNames() {
858                return specialAttributeNames;
859        }
860
861        public void setSpecialAttributeNames(String[] specialAttributeNames) {
862                this.specialAttributeNames = specialAttributeNames;
863        }
864
865        public int getAttributeLineWrap() {
866                return attributeLineWrap;
867        }
868
869        public void setAttributeLineWrap(int attributeLineWrap) {
870                this.attributeLineWrap = attributeLineWrap;
871        }
872
873        @Override
874        public void escapedText(String content) throws IOException {
875                text("");
876                int i = content.length();
877                if (isPretty())
878                  while (i > 0 && (content.charAt(i-1) == '\r' || content.charAt(i-1) == '\n'))
879                         i--;
880                write(content.substring(0, i));
881        }
882
883  public void processingInstruction(String value) throws IOException {
884    write("<?"+value+"?>");
885    if (isPrettyHeader())
886      write("\r\n");
887  }
888
889  @Override
890  public void link(String href) {
891    // ignore this
892    
893  }
894
895  @Override
896  public void anchor(String name) {
897    // ignore this    
898  }
899
900  @Override
901  public void decorate(ElementDecoration element) throws IOException {
902    // nothing...
903  }
904  @Override
905  public void setSchemaLocation(String ns, String loc) throws IOException {
906    namespace("http://www.w3.org/2001/XMLSchema-instance", "xsi");
907    attribute("http://www.w3.org/2001/XMLSchema-instance", "schemaLocation", ns+" "+loc);
908    
909  }
910  @Override
911  public void externalLink(String ref) {
912    // ignore this    
913  }
914
915  @Override
916  public boolean canElide() { return false; }
917
918  @Override
919  public void attributeElide() {
920    // ignore this
921  }
922
923  @Override
924  public void elide() throws IOException {
925    // ignore this
926  }
927  public boolean isIgnoreComments() {
928    return ignoreComments;
929  }
930  public void setIgnoreComments(boolean ignoreComments) {
931    this.ignoreComments = ignoreComments;
932  }
933  @Override
934  public boolean isCanonical() throws IOException {
935    // TODO Auto-generated method stub
936    return false;
937  }
938
939}