KickJava   Java API By Example, From Geeks To Geeks.

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


1 /*
2  * $Header: /home/cvs/jakarta-slide/webdavclient/clientlib/src/java/org/apache/webdav/lib/util/PropertyWriter.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 PropertyWriter {
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 PropertyWriter(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 PropertyWriter(boolean canonical) throws UnsupportedEncodingException JavaDoc {
77       this( getWriterEncoding(), canonical);
78    }
79
80     public PropertyWriter(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.getLocalName());
141                out.print(' ');
142                out.print("xmlns=\"");
143                if (node.getNamespaceURI() != null) {
144                    out.print(node.getNamespaceURI());
145                }
146                out.print("\"");
147                Attr JavaDoc attrs[] = sortAttributes(node.getAttributes());
148                for ( int i = 0; i < attrs.length; i++ ) {
149                   Attr JavaDoc attr = attrs[i];
150                   if (!attr.getNodeName().equals("xmlns")) {
151                       out.print(' ');
152                       out.print(attr.getNodeName());
153                       out.print("=\"");
154                       out.print(normalize(attr.getNodeValue()));
155                       out.print('"');
156                   }
157                }
158                out.print('>');
159                NodeList JavaDoc children = node.getChildNodes();
160                if ( children != null ) {
161                   int len = children.getLength();
162                   for ( int i = 0; i < len; i++ ) {
163                      print(children.item(i));
164                   }
165                }
166                break;
167             }
168
169             // handle entity reference nodes
170
case Node.ENTITY_REFERENCE_NODE: {
171                if ( canonical ) {
172                   NodeList JavaDoc children = node.getChildNodes();
173                   if ( children != null ) {
174                      int len = children.getLength();
175                      for ( int i = 0; i < len; i++ ) {
176                         print(children.item(i));
177                      }
178                   }
179                } else {
180                   out.print('&');
181                   out.print(node.getNodeName());
182                   out.print(';');
183                }
184                break;
185             }
186
187             // print cdata sections
188
case Node.CDATA_SECTION_NODE: {
189                if ( canonical ) {
190                   out.print(normalize(node.getNodeValue()));
191                } else {
192                   out.print("<![CDATA[");
193                   out.print(node.getNodeValue());
194                   out.print("]]>");
195                }
196                break;
197             }
198
199             // print text
200
case Node.TEXT_NODE: {
201                out.print(normalize(node.getNodeValue()));
202                break;
203             }
204
205             // print processing instruction
206
case Node.PROCESSING_INSTRUCTION_NODE: {
207                out.print("<?");
208                out.print(node.getNodeName());
209                String JavaDoc data = node.getNodeValue();
210                if ( data != null && data.length() > 0 ) {
211                   out.print(' ');
212                   out.print(data);
213                }
214                out.print("?>");
215                break;
216             }
217       }
218
219       if ( type == Node.ELEMENT_NODE ) {
220          out.print("</");
221          out.print(node.getLocalName());
222          out.print('>');
223       }
224
225       out.flush();
226
227    } // print(Node)
228

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

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

303 }
304
Popular Tags