1 /*
   2  * Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 //@@3RD PARTY CODE@@
  27 
  28 // DataWriter.java - XML writer for data-oriented files.
  29 
  30 package com.sun.xml.internal.txw2.output;
  31 
  32 import org.xml.sax.Attributes;
  33 import org.xml.sax.SAXException;
  34 
  35 import java.io.Writer;
  36 import java.util.Stack;
  37 
  38 
  39 /**
  40  * Write data- or field-oriented XML.
  41  *
  42  * <p>This filter pretty-prints field-oriented XML without mixed content.
  43  * all added indentation and newlines will be passed on down
  44  * the filter chain (if any).</p>
  45  *
  46  * <p>In general, all whitespace in an XML document is potentially
  47  * significant, so a general-purpose XML writing tool like the
  48  * {@link XMLWriter} class cannot
  49  * add newlines or indentation.</p>
  50  *
  51  * <p>There is, however, a large class of XML documents where information
  52  * is strictly fielded: each element contains either character data
  53  * or other elements, but not both.  For this special case, it is possible
  54  * for a writing tool to provide automatic indentation and newlines
  55  * without requiring extra work from the user.  Note that this class
  56  * will likely not yield appropriate results for document-oriented
  57  * XML like XHTML pages, which mix character data and elements together.</p>
  58  *
  59  * <p>This writer will automatically place each start tag on a new line,
  60  * optionally indented if an indent step is provided (by default, there
  61  * is no indentation).  If an element contains other elements, the end
  62  * tag will also appear on a new line with leading indentation.  Consider,
  63  * for example, the following code:</p>
  64  *
  65  * <pre>
  66  * DataWriter w = new DataWriter();
  67  *
  68  * w.setIndentStep(2);
  69  * w.startDocument();
  70  * w.startElement("Person");
  71  * w.dataElement("name", "Jane Smith");
  72  * w.dataElement("date-of-birth", "1965-05-23");
  73  * w.dataElement("citizenship", "US");
  74  * w.endElement("Person");
  75  * w.endDocument();
  76  * </pre>
  77  *
  78  * <p>This code will produce the following document:</p>
  79  *
  80  * <pre>
  81  * &lt;?xml version="1.0" standalone="yes"?>
  82  *
  83  * &lt;Person>
  84  *   &lt;name>Jane Smith&lt;/name>
  85  *   &lt;date-of-birth>1965-05-23&lt;/date-of-birth>
  86  *   &lt;citizenship>US&lt;/citizenship>
  87  * &lt;/Person>
  88  * </pre>
  89  *
  90  * <p>This class inherits from {@link XMLWriter},
  91  * and provides all of the same support for Namespaces.</p>
  92  *
  93  * @since 1.0
  94  * @author David Megginson, david@megginson.com
  95  * @version 0.2
  96  * @see XMLWriter
  97  */
  98 public class DataWriter extends XMLWriter
  99 {
 100 
 101 
 102 
 103     ////////////////////////////////////////////////////////////////////
 104     // Constructors.
 105     ////////////////////////////////////////////////////////////////////
 106 
 107 
 108     /**
 109      * Create a new data writer for the specified output.
 110      *
 111      * @param writer The character stream where the XML document
 112      *        will be written.
 113      * @param encoding
 114      *      If non-null string is specified, it is written as a part
 115      *      of the XML declaration.
 116      */
 117     public DataWriter ( Writer writer, String encoding, CharacterEscapeHandler _escapeHandler )
 118     {
 119         super(writer,encoding,_escapeHandler);
 120     }
 121 
 122 
 123     public DataWriter (Writer writer, String encoding ) {
 124         this( writer, encoding, DumbEscapeHandler.theInstance );
 125     }
 126 
 127     public DataWriter (Writer writer) {
 128         this( writer, null, DumbEscapeHandler.theInstance );
 129     }
 130 
 131 
 132 
 133     ////////////////////////////////////////////////////////////////////
 134     // Accessors and setters.
 135     ////////////////////////////////////////////////////////////////////
 136 
 137 
 138     /**
 139      * Return the current indent step.
 140      *
 141      * <p>Return the current indent step: each start tag will be
 142      * indented by this number of spaces times the number of
 143      * ancestors that the element has.</p>
 144      *
 145      * @return The number of spaces in each indentation step,
 146      *         or 0 or less for no indentation.
 147      * @see #setIndentStep(int)
 148      *
 149      * @deprecated
 150      *      Only return the length of the indent string.
 151      */
 152     public int getIndentStep ()
 153     {
 154         return indentStep.length();
 155     }
 156 
 157 
 158     /**
 159      * Set the current indent step.
 160      *
 161      * @param indentStep The new indent step (0 or less for no
 162      *        indentation).
 163      * @see #getIndentStep()
 164      *
 165      * @deprecated
 166      *      Should use the version that takes string.
 167      */
 168     public void setIndentStep (int indentStep)
 169     {
 170         StringBuilder s = new StringBuilder();
 171         for( ; indentStep>0; indentStep-- )   s.append(' ');
 172         setIndentStep(s.toString());
 173     }
 174 
 175     public void setIndentStep(String s) {
 176         this.indentStep = s;
 177     }
 178 
 179 
 180 
 181     ////////////////////////////////////////////////////////////////////
 182     // Override methods from XMLWriter.
 183     ////////////////////////////////////////////////////////////////////
 184 
 185 
 186     /**
 187      * Reset the writer so that it can be reused.
 188      *
 189      * <p>This method is especially useful if the writer failed
 190      * with an exception the last time through.</p>
 191      *
 192      * @see XMLWriter#reset()
 193      */
 194     public void reset ()
 195     {
 196         depth = 0;
 197         state = SEEN_NOTHING;
 198         stateStack = new Stack();
 199         super.reset();
 200     }
 201 
 202 
 203     /**
 204      * Write a start tag.
 205      *
 206      * <p>Each tag will begin on a new line, and will be
 207      * indented by the current indent step times the number
 208      * of ancestors that the element has.</p>
 209      *
 210      * <p>The newline and indentation will be passed on down
 211      * the filter chain through regular characters events.</p>
 212      *
 213      * @param uri The element's Namespace URI.
 214      * @param localName The element's local name.
 215      * @param qName The element's qualified (prefixed) name.
 216      * @param atts The element's attribute list.
 217      * @exception org.xml.sax.SAXException If there is an error
 218      *            writing the start tag, or if a filter further
 219      *            down the chain raises an exception.
 220      * @see XMLWriter#startElement(String, String, String, Attributes)
 221      */
 222     public void startElement (String uri, String localName,
 223                               String qName, Attributes atts)
 224         throws SAXException
 225     {
 226         stateStack.push(SEEN_ELEMENT);
 227         state = SEEN_NOTHING;
 228         if (depth > 0) {
 229             super.characters("\n");
 230         }
 231         doIndent();
 232         super.startElement(uri, localName, qName, atts);
 233         depth++;
 234     }
 235 
 236 
 237     /**
 238      * Write an end tag.
 239      *
 240      * <p>If the element has contained other elements, the tag
 241      * will appear indented on a new line; otherwise, it will
 242      * appear immediately following whatever came before.</p>
 243      *
 244      * <p>The newline and indentation will be passed on down
 245      * the filter chain through regular characters events.</p>
 246      *
 247      * @param uri The element's Namespace URI.
 248      * @param localName The element's local name.
 249      * @param qName The element's qualified (prefixed) name.
 250      * @exception org.xml.sax.SAXException If there is an error
 251      *            writing the end tag, or if a filter further
 252      *            down the chain raises an exception.
 253      * @see XMLWriter#endElement(String, String, String)
 254      */
 255     public void endElement (String uri, String localName, String qName)
 256         throws SAXException
 257     {
 258         depth--;
 259         if (state == SEEN_ELEMENT) {
 260             super.characters("\n");
 261             doIndent();
 262         }
 263         super.endElement(uri, localName, qName);
 264         state = stateStack.pop();
 265     }
 266 
 267 
 268 //    /**
 269 //     * Write a empty element tag.
 270 //     *
 271 //     * <p>Each tag will appear on a new line, and will be
 272 //     * indented by the current indent step times the number
 273 //     * of ancestors that the element has.</p>
 274 //     *
 275 //     * <p>The newline and indentation will be passed on down
 276 //     * the filter chain through regular characters events.</p>
 277 //     *
 278 //     * @param uri The element's Namespace URI.
 279 //     * @param localName The element's local name.
 280 //     * @param qName The element's qualified (prefixed) name.
 281 //     * @param atts The element's attribute list.
 282 //     * @exception org.xml.sax.SAXException If there is an error
 283 //     *            writing the empty tag, or if a filter further
 284 //     *            down the chain raises an exception.
 285 //     * @see XMLWriter#emptyElement(String, String, String, Attributes)
 286 //     */
 287 //    public void emptyElement (String uri, String localName,
 288 //                              String qName, Attributes atts)
 289 //        throws SAXException
 290 //    {
 291 //        state = SEEN_ELEMENT;
 292 //        if (depth > 0) {
 293 //            super.characters("\n");
 294 //        }
 295 //        doIndent();
 296 //        super.emptyElement(uri, localName, qName, atts);
 297 //    }
 298 
 299 
 300     /**
 301      * Write a sequence of characters.
 302      *
 303      * @param ch The characters to write.
 304      * @param start The starting position in the array.
 305      * @param length The number of characters to use.
 306      * @exception org.xml.sax.SAXException If there is an error
 307      *            writing the characters, or if a filter further
 308      *            down the chain raises an exception.
 309      * @see XMLWriter#characters(char[], int, int)
 310      */
 311     public void characters (char ch[], int start, int length)
 312         throws SAXException
 313     {
 314         state = SEEN_DATA;
 315         super.characters(ch, start, length);
 316     }
 317 
 318     public void comment(char ch[], int start, int length) throws SAXException {
 319         if (depth > 0) {
 320             super.characters("\n");
 321         }
 322         doIndent();
 323         super.comment(ch,start,length);
 324     }
 325 
 326 
 327 
 328     ////////////////////////////////////////////////////////////////////
 329     // Internal methods.
 330     ////////////////////////////////////////////////////////////////////
 331 
 332 
 333     /**
 334      * Print indentation for the current level.
 335      *
 336      * @exception org.xml.sax.SAXException If there is an error
 337      *            writing the indentation characters, or if a filter
 338      *            further down the chain raises an exception.
 339      */
 340     private void doIndent ()
 341         throws SAXException
 342     {
 343         if (depth > 0) {
 344             char[] ch = indentStep.toCharArray();
 345             for( int i=0; i<depth; i++ )
 346                 characters(ch, 0, ch.length);
 347         }
 348     }
 349 
 350 
 351 
 352     ////////////////////////////////////////////////////////////////////
 353     // Constants.
 354     ////////////////////////////////////////////////////////////////////
 355 
 356     private final static Object SEEN_NOTHING = new Object();
 357     private final static Object SEEN_ELEMENT = new Object();
 358     private final static Object SEEN_DATA = new Object();
 359 
 360 
 361 
 362     ////////////////////////////////////////////////////////////////////
 363     // Internal state.
 364     ////////////////////////////////////////////////////////////////////
 365 
 366     private Object state = SEEN_NOTHING;
 367     private Stack stateStack = new Stack();
 368 
 369     private String indentStep = "";
 370     private int depth = 0;
 371 
 372 }
 373 
 374 // end of DataWriter.java