KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > webdav > lib > util > DOMWriter


1 /*
2  * $Header: /home/cvs/jakarta-slide/webdavclient/clientlib/src/java/org/apache/webdav/lib/util/DOMWriter.java,v 1.1 2004/08/02 15:45:49 unico Exp $
3  * $Revision: 1.1 $
4  * $Date: 2004/08/02 15:45:49 $
5  *
6  * ====================================================================
7  *
8  * Copyright 1999-2002 The Apache Software Foundation
9  *
10  * Licensed under the Apache License, Version 2.0 (the "License");
11  * you may not use this file except in compliance with the License.
12  * You may obtain a copy of the License at
13  *
14  * http://www.apache.org/licenses/LICENSE-2.0
15  *
16  * Unless required by applicable law or agreed to in writing, software
17  * distributed under the License is distributed on an "AS IS" BASIS,
18  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19  * See the License for the specific language governing permissions and
20  * limitations under the License.
21  *
22  */

23
24 package org.apache.webdav.lib.util;
25
26 import java.io.OutputStreamWriter JavaDoc;
27 import java.io.PrintWriter JavaDoc;
28 import java.io.UnsupportedEncodingException JavaDoc;
29 import java.io.Writer JavaDoc;
30
31 import org.w3c.dom.Attr JavaDoc;
32 import org.w3c.dom.Document JavaDoc;
33 import org.w3c.dom.NamedNodeMap JavaDoc;
34 import org.w3c.dom.Node JavaDoc;
35 import org.w3c.dom.NodeList JavaDoc;
36
37 public class DOMWriter {
38
39    //
40
// Data
41
//
42

43    /** Default Encoding */
44    private static String JavaDoc
45    PRINTWRITER_ENCODING = "UTF8";
46
47    private static String JavaDoc MIME2JAVA_ENCODINGS[] =
48     { "Default", "UTF-8", "US-ASCII", "ISO-8859-1", "ISO-8859-2", "ISO-8859-3", "ISO-8859-4",
49       "ISO-8859-5", "ISO-8859-6", "ISO-8859-7", "ISO-8859-8", "ISO-8859-9", "ISO-2022-JP",
50       "SHIFT_JIS", "EUC-JP","GB2312", "BIG5", "EUC-KR", "ISO-2022-KR", "KOI8-R", "EBCDIC-CP-US",
51       "EBCDIC-CP-CA", "EBCDIC-CP-NL", "EBCDIC-CP-DK", "EBCDIC-CP-NO", "EBCDIC-CP-FI", "EBCDIC-CP-SE",
52       "EBCDIC-CP-IT", "EBCDIC-CP-ES", "EBCDIC-CP-GB", "EBCDIC-CP-FR", "EBCDIC-CP-AR1",
53       "EBCDIC-CP-HE", "EBCDIC-CP-CH", "EBCDIC-CP-ROECE","EBCDIC-CP-YU",
54       "EBCDIC-CP-IS", "EBCDIC-CP-AR2", "UTF-16"
55     };
56
57
58    /** Print writer. */
59    protected PrintWriter JavaDoc out;
60
61    /** Canonical output. */
62    protected boolean canonical;
63
64
65    public DOMWriter(String JavaDoc encoding, boolean canonical)
66    throws UnsupportedEncodingException JavaDoc {
67       out = new PrintWriter JavaDoc(new OutputStreamWriter JavaDoc(System.out, encoding));
68       this.canonical = canonical;
69    } // <init>(String,boolean)
70

71    //
72
// Constructors
73
//
74

75    /** Default constructor. */
76    public DOMWriter(boolean canonical) throws UnsupportedEncodingException JavaDoc {
77       this( getWriterEncoding(), canonical);
78    }
79
80     public DOMWriter(Writer JavaDoc writer, boolean canonical) {
81     out = new PrintWriter JavaDoc(writer);
82     this.canonical = canonical;
83     }
84
85    public static String JavaDoc getWriterEncoding( ) {
86       return (PRINTWRITER_ENCODING);
87    }// getWriterEncoding
88

89    public static void setWriterEncoding( String JavaDoc encoding ) {
90       if( encoding.equalsIgnoreCase( "DEFAULT" ) )
91          PRINTWRITER_ENCODING = "UTF8";
92       else if( encoding.equalsIgnoreCase( "UTF-16" ) )
93          PRINTWRITER_ENCODING = "Unicode";
94       else
95          PRINTWRITER_ENCODING = MIME2Java.convert( encoding );
96    }// setWriterEncoding
97

98
99    public static boolean isValidJavaEncoding( String JavaDoc encoding ) {
100       for ( int i = 0; i < MIME2JAVA_ENCODINGS.length; i++ )
101          if ( encoding.equals( MIME2JAVA_ENCODINGS[i] ) )
102             return (true);
103
104       return (false);
105    }// isValidJavaEncoding
106

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

221    /** Returns a sorted list of attributes. */
222    protected Attr JavaDoc[] sortAttributes(NamedNodeMap JavaDoc attrs) {
223
224       int len = (attrs != null) ? attrs.getLength() : 0;
225       Attr JavaDoc array[] = new Attr JavaDoc[len];
226       for ( int i = 0; i < len; i++ ) {
227          array[i] = (Attr JavaDoc)attrs.item(i);
228       }
229       for ( int i = 0; i < len - 1; i++ ) {
230          String JavaDoc name = array[i].getNodeName();
231          int index = i;
232          for ( int j = i + 1; j < len; j++ ) {
233             String JavaDoc curName = array[j].getNodeName();
234             if ( curName.compareTo(name) < 0 ) {
235                name = curName;
236                index = j;
237             }
238          }
239          if ( index != i ) {
240             Attr JavaDoc temp = array[i];
241             array[i] = array[index];
242             array[index] = temp;
243          }
244       }
245
246       return (array);
247
248    } // sortAttributes(NamedNodeMap):Attr[]
249

250
251    /** Normalizes the given string. */
252    protected String JavaDoc normalize(String JavaDoc s) {
253       StringBuffer JavaDoc str = new StringBuffer JavaDoc();
254
255       int len = (s != null) ? s.length() : 0;
256       for ( int i = 0; i < len; i++ ) {
257          char ch = s.charAt(i);
258          switch ( ch ) {
259             case '<': {
260                   str.append("&lt;");
261                   break;
262                }
263             case '>': {
264                   str.append("&gt;");
265                   break;
266                }
267             case '&': {
268                   str.append("&amp;");
269                   break;
270                }
271             case '"': {
272                   str.append("&quot;");
273                   break;
274                }
275             case '\r':
276             case '\n': {
277                   if ( canonical ) {
278                      str.append("&#");
279                      str.append(Integer.toString(ch));
280                      str.append(';');
281                      break;
282                   }
283                   // else, default append char
284
}
285             default: {
286                   str.append(ch);
287                }
288          }
289       }
290
291       return (str.toString());
292
293    } // normalize(String):String
294

295 }
296
Popular Tags