KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > dom > DOMAddLines


1 /*
2  * The Apache Software License, Version 1.1
3  *
4  *
5  * Copyright (c) 1999 The Apache Software Foundation. All rights
6  * reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  * notice, this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  * notice, this list of conditions and the following disclaimer in
17  * the documentation and/or other materials provided with the
18  * distribution.
19  *
20  * 3. The end-user documentation included with the redistribution,
21  * if any, must include the following acknowledgment:
22  * "This product includes software developed by the
23  * Apache Software Foundation (http://www.apache.org/)."
24  * Alternately, this acknowledgment may appear in the software itself,
25  * if and wherever such third-party acknowledgments normally appear.
26  *
27  * 4. The names "Xerces" and "Apache Software Foundation" must
28  * not be used to endorse or promote products derived from this
29  * software without prior written permission. For written
30  * permission, please contact apache@apache.org.
31  *
32  * 5. Products derived from this software may not be called "Apache",
33  * nor may "Apache" appear in their name, without prior written
34  * permission of the Apache Software Foundation.
35  *
36  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
37  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
38  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
39  * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
40  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
41  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
42  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
43  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
44  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
45  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
46  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47  * SUCH DAMAGE.
48  * ====================================================================
49  *
50  * This software consists of voluntary contributions made by many
51  * individuals on behalf of the Apache Software Foundation and was
52  * originally based on software copyright (c) 1999, International
53  * Business Machines, Inc., http://www.apache.org. For more
54  * information on the Apache Software Foundation, please see
55  * <http://www.apache.org/>.
56  */

57
58 package dom;
59
60 import java.io.IOException JavaDoc;
61 import java.io.OutputStreamWriter JavaDoc;
62 import java.io.PrintWriter JavaDoc;
63
64 import org.enhydra.apache.xerces.dom.NodeImpl;
65 import org.enhydra.apache.xerces.framework.XMLAttrList;
66 import org.enhydra.apache.xerces.parsers.DOMParser;
67 import org.enhydra.apache.xerces.utils.QName;
68 import org.w3c.dom.Attr JavaDoc;
69 import org.w3c.dom.Document JavaDoc;
70 import org.w3c.dom.NamedNodeMap JavaDoc;
71 import org.w3c.dom.Node JavaDoc;
72 import org.w3c.dom.NodeList JavaDoc;
73
74 /**
75  * A sample of Adding lines to the DOM Node. This sample program illustrates:
76  * - How to override methods from DocumentHandler ( XMLDocumentHandler)
77  * - How to turn off ignorable white spaces by overriding ignorableWhiteSpace
78  * - How to use the SAX Locator to return row position ( line number of DOM element).
79  * - How to attach user defined Objects to Nodes using method setUserData
80  * This example relies on the following:
81  * - Turning off the "fast" DOM so we can use set expansion to FULL
82  * @version
83  */

84
85 public class DOMAddLines extends DOMParser {
86
87    /** Print writer. */
88    private PrintWriter JavaDoc out;
89    static private boolean NotIncludeIgnorableWhiteSpaces = false;
90
91
92    public DOMAddLines( String JavaDoc inputName ) {
93       //fNodeExpansion = FULL; // faster than: this.setFeature("http://apache.org/xml/features/defer-node-expansion", false);
94

95       try {
96          this.setFeature( "http://apache.org/xml/features/dom/defer-node-expansion", false );
97          this.parse( inputName );
98          out = new PrintWriter JavaDoc(new OutputStreamWriter JavaDoc(System.out, "UTF8"));
99       } catch ( IOException JavaDoc e ) {
100          System.err.println( "except" + e );
101       } catch ( org.xml.sax.SAXException JavaDoc e ) {
102          System.err.println( "except" + e );
103       }
104    } // constructor
105

106    /** Prints the specified node, recursively. */
107    public void print(Node JavaDoc node) {
108       // is there anything to do?
109
if ( node == null ) {
110          return;
111       }
112
113       String JavaDoc lineRowColumn = (String JavaDoc ) ((NodeImpl) node).getUserData();
114
115       int type = node.getNodeType();
116       switch ( type ) {
117          // print document
118
case Node.DOCUMENT_NODE: {
119                out.println( lineRowColumn + ":" + "<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
120                print( ((Document JavaDoc)node).getDocumentElement());
121                out.flush();
122                break;
123             }
124
125             // print element with attributes
126
case Node.ELEMENT_NODE: {
127                out.print( lineRowColumn + ":" + '<');
128                out.print(node.getNodeName());
129                Attr JavaDoc attrs[] = sortAttributes(node.getAttributes());
130                for ( int i = 0; i < attrs.length; i++ ) {
131                   Attr JavaDoc attr = attrs[i];
132                   out.print(' ');
133                   out.print(attr.getNodeName());
134                   out.print("=\"");
135                   out.print( attr.getNodeValue());
136                   out.print('"');
137                }
138                out.print('>');
139                NodeList JavaDoc children = node.getChildNodes();
140                if ( children != null ) {
141                   int len = children.getLength();
142                   for ( int i = 0; i < len; i++ ) {
143                      print(children.item(i));
144                   }
145                }
146                break;
147             }
148
149             // handle entity reference nodes
150
case Node.ENTITY_REFERENCE_NODE: {
151                out.print('&');
152                out.print(node.getNodeName());
153                out.print(';');
154                break;
155             }
156
157             // print cdata sections
158
case Node.CDATA_SECTION_NODE: {
159                out.print("<![CDATA[");
160                out.print(node.getNodeValue());
161                out.print("]]>");
162                break;
163             }
164
165             // print text
166
case Node.TEXT_NODE: {
167                out.print( node.getNodeValue());
168                break;
169             }
170
171             // print processing instruction
172
case Node.PROCESSING_INSTRUCTION_NODE: {
173                out.print("<?");
174                out.print(node.getNodeName());
175                String JavaDoc data = node.getNodeValue();
176                if ( data != null && data.length() > 0 ) {
177                   out.print(' ');
178                   out.print(data);
179                }
180                out.print("?>");
181                break;
182             }
183       }
184
185       if ( type == Node.ELEMENT_NODE ) {
186          out.print("</");
187          out.print(node.getNodeName());
188          out.print('>');
189       }
190
191       out.flush();
192
193    } // print(Node)
194

195
196    /** Returns a sorted list of attributes. */
197    private Attr JavaDoc[] sortAttributes(NamedNodeMap JavaDoc attrs) {
198
199       int len = (attrs != null) ? attrs.getLength() : 0;
200       Attr JavaDoc array[] = new Attr JavaDoc[len];
201       for ( int i = 0; i < len; i++ ) {
202          array[i] = (Attr JavaDoc)attrs.item(i);
203       }
204       for ( int i = 0; i < len - 1; i++ ) {
205          String JavaDoc name = array[i].getNodeName();
206          int index = i;
207          for ( int j = i + 1; j < len; j++ ) {
208             String JavaDoc curName = array[j].getNodeName();
209             if ( curName.compareTo(name) < 0 ) {
210                name = curName;
211                index = j;
212             }
213          }
214          if ( index != i ) {
215             Attr JavaDoc temp = array[i];
216             array[i] = array[index];
217             array[index] = temp;
218          }
219       }
220
221       return (array);
222
223    } // sortAttributes(NamedNodeMap):Attr[]
224

225    /* Methods that we override */
226
227    /* We override startElement callback from DocumentHandler */
228
229    public void startElement(QName elementQName, XMLAttrList attrList, int attrListIndex) throws Exception JavaDoc
230    {
231       super.startElement(elementQName, attrList, attrListIndex);
232
233       NodeImpl node = null;
234       try {
235       node = (NodeImpl) this.getProperty( "http://apache.org/xml/properties/dom/current-element-node" );
236       //System.out.println( "The node = " + node ); TODO JEFF
237
}
238       catch( org.xml.sax.SAXException JavaDoc ex )
239       {
240           System.err.println( "except" + ex );;
241       }
242       //NodeImpl node = (NodeImpl)getCurrentNode(); // Get current node
243
if( node != null )
244           node.setUserData( String.valueOf( getLocator().getLineNumber() ) ); // Save location String into node
245
} //startElement
246

247    /* We override startDocument callback from DocumentHandler */
248
249    public void startDocument(int versionIndex, int encodingIndex,
250                                    int standAloneIndex)
251    {
252      //super.startDocument( versionIndex, encodingIndex,
253
// standAloneIndex);
254
super.startDocument();
255      NodeImpl node = null ;
256       try {
257       node = (NodeImpl) this.getProperty( "http://apache.org/xml/properties/dom/current-element-node" );
258       //System.out.println( "The node = " + node );
259
}
260      catch( org.xml.sax.SAXException JavaDoc ex )
261       {
262         System.err.println( "except" + ex );;
263       }
264      
265 // NodeImpl node = (NodeImpl)getCurrentNode(); // Get current node
266
if( node != null )
267           node.setUserData( String.valueOf( getLocator().getLineNumber() ) ); // Save location String into node
268
} //startDocument
269

270
271    public void ignorableWhitespace(int dataIndex) throws Exception JavaDoc
272     {
273     if(! NotIncludeIgnorableWhiteSpaces )
274        super.ignorableWhitespace( dataIndex);
275     else
276        ;// Ignore ignorable white spaces
277
}// ignorableWhitespace
278

279
280
281    //
282
// Main
283
//
284

285    /** Main program entry point. */
286    public static void main(String JavaDoc argv[]) {
287       // is there anything to do?
288
if ( argv.length == 0 ) {
289          printUsage();
290          System.exit(1);
291       }
292       // check parameters
293

294       for ( int i = 0; i < argv.length; i++ ) {
295          String JavaDoc arg = argv[i];
296
297          // options
298
if ( arg.startsWith("-") ) {
299             if ( arg.equals("-h") ) {
300                printUsage();
301                System.exit(1);
302             }
303             if (arg.equals("-i")) {
304                    NotIncludeIgnorableWhiteSpaces = true;
305                    continue;
306                }
307             
308          }
309       // DOMAddLine parse and print
310

311       DOMAddLines domAddExample = new DOMAddLines( arg );
312       Document JavaDoc doc = domAddExample.getDocument();
313       domAddExample.print( doc );
314
315      }
316    } // main(String[])
317

318    /** Prints the usage. */
319    private static void printUsage() {
320       System.err.println("usage: jre dom.DOMAddLines uri ...");
321       System.err.println();
322       System.err.println(" -h This help screen.");
323       System.err.println(" -i don't print ignorable white spaces");
324
325    } // printUsage()
326

327 }
328
Popular Tags