KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > sapia > util > xml > idefix > XmlScribe


1 package org.sapia.util.xml.idefix;
2
3
4 // Import of Sapia's utility classes
5
// ---------------------------------
6
import org.sapia.util.xml.Attribute;
7
8 // Import of Sun's JDK classes
9
// ---------------------------
10
import java.io.IOException JavaDoc;
11 import java.io.OutputStream JavaDoc;
12
13 import java.util.ArrayList JavaDoc;
14 import java.util.Iterator JavaDoc;
15 import java.util.List JavaDoc;
16
17
18 /**
19  * The <CODE>XmlScribe</CODE> class contain utility methods that generates
20  * XML string. It is usefull to generate string for starting or ending element
21  * with or without namespace prefixes, or to encode a string using the XML
22  * encoding rule that applies to the characters '<', '>', '"', ''' and '&'.
23  *
24  * @author Jean-Cedric Desrochers
25  * <dl>
26  * <dt><b>Copyright:</b><dd>Copyright &#169; 2002-2003 <a HREF="http://www.sapia-oss.org">Sapia Open Source Software</a>. All Rights Reserved.</dd></dt>
27  * <dt><b>License:</b><dd>Read the license.txt file of the jar or visit the
28  * <a HREF="http://www.sapia-oss.org/license.html">license page</a> at the Sapia OSS web site</dd></dt>
29  * </dl>
30  */

31 public class XmlScribe {
32   /** Defines an empty map. */
33   private static final List JavaDoc EMPTY_LIST = new ArrayList JavaDoc(0);
34
35   /** Defines the character encoding to use to generate the streaming methods. */
36   private String JavaDoc _theStreamEncoding;
37
38   /**
39    * Creates a new XmlScribe instance using the default UTF-8 as character encoding
40    * for the streaming methods.
41    */

42   public XmlScribe() {
43     _theStreamEncoding = "UTF-8";
44   }
45
46   /**
47    * Creates a new XmlScribe instance with the passed in parameter.
48    *
49    * @param aStreamEncoding The character encoding of the streaming methods.
50    */

51   public XmlScribe(String JavaDoc aStreamEncoding) {
52     _theStreamEncoding = aStreamEncoding;
53   }
54
55   /**
56    * Changes the character encoding used in the streaming methods of the XMl scribe.
57    *
58    * @param anEncoding The new character encofing.
59    */

60   public void setStreamEncoding(String JavaDoc anEncoding) {
61     _theStreamEncoding = anEncoding;
62   }
63
64   /**
65    * Returns the character encoding used in the streaming methods of the XMl scribe.
66    *
67    * @return The character encoding used in the streaming methods of the XMl scribe.
68    */

69   public String JavaDoc getStreamEncoding() {
70     return _theStreamEncoding;
71   }
72
73   /**
74    * Builds the XML declaration and appends it into the buffer.
75    *
76    * @param aCharacterEncoding The character encoding of the xml declaration or
77    * null if it's not defined.
78    * @param aBuffer The string buffer to which add the created string.
79    */

80   public void composeXmlDeclaration(String JavaDoc aCharacterEncoding,
81     StringBuffer JavaDoc aBuffer) {
82     if ((aCharacterEncoding != null) && (aCharacterEncoding.length() > 0)) {
83       aBuffer.append("<?xml version=\"1.0\" encoding=\"")
84              .append(aCharacterEncoding).append("\" ?>");
85     } else {
86       aBuffer.append("<?xml version=\"1.0\" ?>");
87     }
88   }
89
90   /**
91    * Builds the XML declaration and appends it into the output stream.
92    *
93    * @param aCharacterEncoding The character encoding of the xml declaration or
94    * null if it's not defined.
95    * @param aStream The output stream to which add the created string.
96    * @exception IOException If an error occurs while writing to the outpt stream.
97    */

98   public void composeXmlDeclaration(String JavaDoc aCharacterEncoding,
99     OutputStream JavaDoc aStream) throws IOException JavaDoc {
100     StringBuffer JavaDoc aBuffer = new StringBuffer JavaDoc();
101     composeXmlDeclaration(aCharacterEncoding, aBuffer);
102     aStream.write(aBuffer.toString().getBytes(_theStreamEncoding));
103   }
104
105   /**
106    * Builds an XML starting element with the arguments passed in and appends the string to the buffer.
107    *
108    * @param aNamespacePrefix The namespace prefix of the element.
109    * @param anElementName The name of the element to create.
110    * @param someAttributes A list of the attribtues of the element.
111    * @param isEmptyElement Tells wether to create an empty element or not.
112    * @param aBuffer The string buffer to which add the created string.
113    */

114   public void composeStartingElement(String JavaDoc aNamespacePrefix,
115     String JavaDoc anElementName, List JavaDoc someAttributes, boolean isEmptyElement,
116     StringBuffer JavaDoc aBuffer) {
117     // Starting the element
118
aBuffer.append("<");
119     composeQualifiedName(aNamespacePrefix, anElementName, aBuffer);
120
121     // Adding any attributes
122
for (Iterator JavaDoc it = someAttributes.iterator(); it.hasNext();) {
123       Attribute anAttribute = (Attribute) it.next();
124
125       // Add the attribute only if there's a value
126
if ((anAttribute.getValue() != null) &&
127             (anAttribute.getValue().length() > 0)) {
128         aBuffer.append(" ");
129         composeQualifiedName(anAttribute.getNamespacePrefix(),
130           anAttribute.getName(), aBuffer);
131         aBuffer.append("=\"");
132         xmlEncode(anAttribute.getValue(), aBuffer);
133         aBuffer.append("\"");
134       }
135     }
136
137     // Closing the element
138
if (isEmptyElement) {
139       aBuffer.append(" />");
140     } else {
141       aBuffer.append(">");
142     }
143   }
144
145   /**
146    * Builds an XML starting element with the arguments passed in and appends the string to the output stream.
147    *
148    * @param aNamespacePrefix The namespace prefix of the element.
149    * @param anElementName The name of the element to create.
150    * @param someAttributes A list of the attribtues of the element.
151    * @param isEmptyElement Tells wether to create an empty element or not.
152    * @param aStream The output stream to which add the created string.
153    * @exception IOException If an error occurs while writing to the output stream.
154    */

155   public void composeStartingElement(String JavaDoc aNamespacePrefix,
156     String JavaDoc anElementName, List JavaDoc someAttributes, boolean isEmptyElement,
157     OutputStream JavaDoc aStream) throws IOException JavaDoc {
158     StringBuffer JavaDoc aBuffer = new StringBuffer JavaDoc();
159     composeStartingElement(aNamespacePrefix, anElementName, someAttributes,
160       isEmptyElement, aBuffer);
161     aStream.write(aBuffer.toString().getBytes(_theStreamEncoding));
162   }
163
164   /**
165    * Builds and returns a string of an XML starting element with the arguments passed in without
166    * any attributes and appends the string to the buffer.
167    *
168    * @param aNamespacePrefix The namespace prefix of the element.
169    * @param anElementName The name of the element to create.
170    * @param isEmptyElement Tells wether to create an empty element or not.
171    * @param aBuffer The string buffer to which add the created string.
172    */

173   public void composeStartingElement(String JavaDoc aNamespacePrefix,
174     String JavaDoc anElementName, boolean isEmptyElement, StringBuffer JavaDoc aBuffer) {
175     composeStartingElement(aNamespacePrefix, anElementName, EMPTY_LIST,
176       isEmptyElement, aBuffer);
177   }
178
179   /**
180    * Builds and returns a string of an XML starting element with the arguments passed in without
181    * any attributes and appends the string to the output stream.
182    *
183    * @param aNamespacePrefix The namespace prefix of the element.
184    * @param anElementName The name of the element to create.
185    * @param isEmptyElement Tells wether to create an empty element or not.
186    * @param aStream The output stream to which add the created string.
187    * @exception IOException If an error occurs while writing to the output stream.
188    */

189   public void composeStartingElement(String JavaDoc aNamespacePrefix,
190     String JavaDoc anElementName, boolean isEmptyElement, OutputStream JavaDoc aStream)
191     throws IOException JavaDoc {
192     StringBuffer JavaDoc aBuffer = new StringBuffer JavaDoc();
193     composeStartingElement(aNamespacePrefix, anElementName, EMPTY_LIST,
194       isEmptyElement, aBuffer);
195     aStream.write(aBuffer.toString().getBytes(_theStreamEncoding));
196   }
197
198   /**
199    * Builds an XML ending element with the arguments passed in and appends the string to the buffer.
200    *
201    * @param aNamespacePrefix The namespace prefix of the element.
202    * @param anElementName The name of the element to create.
203    * @param aBuffer The string buffer to which add the created string.
204    */

205   public void composeEndingElement(String JavaDoc aNamespacePrefix,
206     String JavaDoc anElementName, StringBuffer JavaDoc aBuffer) {
207     aBuffer.append("</");
208     composeQualifiedName(aNamespacePrefix, anElementName, aBuffer);
209     aBuffer.append(">");
210   }
211
212   /**
213    * Builds an XML ending element with the arguments passed in and appends the string to the buffer.
214    *
215    * @param aNamespacePrefix The namespace prefix of the element.
216    * @param anElementName The name of the element to create.
217    * @param aStream The output stream to which add the created string.
218    * @exception IOException If an error occurs while writing ti the output stream.
219    */

220   public void composeEndingElement(String JavaDoc aNamespacePrefix,
221     String JavaDoc anElementName, OutputStream JavaDoc aStream) throws IOException JavaDoc {
222     StringBuffer JavaDoc aBuffer = new StringBuffer JavaDoc();
223     composeEndingElement(aNamespacePrefix, anElementName, aBuffer);
224     aStream.write(aBuffer.toString().getBytes(_theStreamEncoding));
225   }
226
227   /**
228    * Builds a CData section with the content passed in.
229    *
230    * @param aContent the content of the CData.
231    * @param aBuffer The buffer into which to add the generated CData.
232    */

233   public void composeCData(String JavaDoc aContent, StringBuffer JavaDoc aBuffer) {
234     aBuffer.append("<![CDATA[").append(aContent).append("]]>");
235   }
236
237   /**
238    * Builds a CData section with the content passed in and add it to the output stream.
239    *
240    * @param aContent the content of the CData.
241    * @param aStream The output stream into which to add the generated CData.
242    * @exception IOException If an error occurs while writing to the output stream.
243    */

244   public void composeCData(String JavaDoc aContent, OutputStream JavaDoc aStream)
245     throws IOException JavaDoc {
246     StringBuffer JavaDoc aBuffer = new StringBuffer JavaDoc();
247     composeCData(aContent, aBuffer);
248     aStream.write(aBuffer.toString().getBytes(_theStreamEncoding));
249   }
250
251   /**
252    * Parses the passed in string and replaces the predefined entity of the XML spec.
253    *
254    * @param aString The string to encode.
255    * @return The XML encoded string.
256    */

257   public String JavaDoc xmlEncode(String JavaDoc aString) {
258     StringBuffer JavaDoc anXmlString = new StringBuffer JavaDoc();
259     xmlEncode(aString, anXmlString);
260
261     return anXmlString.toString();
262   }
263
264   /**
265    * Parses the passed in string and replaces the predefined entity of the XML spec.
266    *
267    * @param aString The string to encode.
268    * @param aStream The output stream into which add the XML encoded string.
269    * @exception IOException If an error occurs while writing to the output stream.
270    */

271   public void xmlEncode(String JavaDoc aString, OutputStream JavaDoc aStream)
272     throws IOException JavaDoc {
273     StringBuffer JavaDoc aBuffer = new StringBuffer JavaDoc();
274     xmlEncode(aString, aBuffer);
275     aStream.write(aBuffer.toString().getBytes(_theStreamEncoding));
276   }
277
278   /**
279    * Parses the passed in string and replaces the predefined entity of the XML spec.
280    *
281    * @param aString The string to encode.
282    * @param anXmlString The string buffer into which to add the XML encoded string.
283    */

284   public void xmlEncode(String JavaDoc aString, StringBuffer JavaDoc anXmlString) {
285     for (int i = 0; i < aString.length(); ++i) {
286       int aChar = (int) aString.charAt(i);
287
288       if (((aChar & 0xfc00) == 0xd800) && ((i + 1) < aString.length())) {
289         int lowch = (int) aString.charAt(i + 1);
290
291         if ((lowch & 0xfc00) == 0xdc00) {
292           aChar = (0x10000 + ((aChar - 0xd800) << 10) + lowch) - 0xdc00;
293           i++;
294         }
295       }
296
297       String JavaDoc anEntityRef = getEntityReference(aChar);
298
299       if (anEntityRef != null) {
300         anXmlString.append('&').append(anEntityRef).append(';');
301       } else if (((aChar >= ' ') && (aChar <= 0xF7)) || (aChar == '\n') ||
302             (aChar == '\r') || (aChar == '\t')) {
303         // If the character is not printable, print as character reference.
304
// Non printables are below ASCII space but not tab or line
305
// terminator, ASCII delete, or above a certain Unicode threshold.
306
if (aChar < 0x10000) {
307           anXmlString.append((char) aChar);
308         } else {
309           anXmlString.append((char) (((aChar - 0x10000) >> 10) + 0xd800));
310           anXmlString.append((char) (((aChar - 0x10000) & 0x3ff) + 0xdc00));
311         }
312       } else {
313         anXmlString.append("&#x").append(Integer.toHexString(aChar)).append(';');
314       }
315     }
316   }
317
318   /**
319    * Builds a qualified name of the name passed in with the namspace prefix.
320    *
321    * @param aNamespacePrefix The namespace prefix of the qualification
322    * @param aName The name to qualify.
323    * @param aBuffer The buffer into which to add the generated name.
324    */

325   protected void composeQualifiedName(String JavaDoc aNamespacePrefix, String JavaDoc aName,
326     StringBuffer JavaDoc aBuffer) {
327     if ((aNamespacePrefix != null) && (aNamespacePrefix.length() > 0)) {
328       aBuffer.append(aNamespacePrefix).append(":");
329     }
330
331     aBuffer.append(aName);
332   }
333
334   /**
335    * Returns the entity reference defined in the XML specification for the character passed in,
336    * or null if the character passed in is not one of the five defined characters (<, >, ", ', &)
337    * in the XML spec.
338    *
339    * @param aChar The character for which to return the entity
340    * @return The entity reference associated or null.
341    */

342   protected String JavaDoc getEntityReference(int aChar) {
343     switch (aChar) {
344     case '<':
345       return "lt";
346
347     case '>':
348       return "gt";
349
350     case '"':
351       return "quot";
352
353     case '\'':
354       return "apos";
355
356     case '&':
357       return "amp";
358     }
359
360     return null;
361   }
362 }
363
Popular Tags