KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openlaszlo > xml > internal > XMLUtils


1 /* *****************************************************************************
2  * XMLUtils.java
3  * ****************************************************************************/

4
5 /* J_LZ_COPYRIGHT_BEGIN *******************************************************
6 * Copyright 2001-2004 Laszlo Systems, Inc. All Rights Reserved. *
7 * Use is subject to license terms. *
8 * J_LZ_COPYRIGHT_END *********************************************************/

9
10 package org.openlaszlo.xml.internal;
11 import org.openlaszlo.utils.ChainedException;
12 import org.jdom.Document;
13 import org.jdom.Element;
14 import org.xml.sax.SAXException JavaDoc;
15 import java.io.*;
16 import java.util.*;
17
18 /**
19  * XMLUtils
20  *
21  * @author Oliver Steele
22  */

23 abstract public class XMLUtils {
24     /** Returns an element's attribute value, as a String. Same as
25      * Element.getAttributeValue, except that it takes a default value
26      * to return if the attribute is missing.
27      *
28      * @param e an Element
29      * @param aname the attribute name
30      * @param defaultValue default value
31      * @return a String
32      */

33     public static String JavaDoc getAttributeValue(Element e, String JavaDoc aname,
34                                            String JavaDoc defaultValue)
35     {
36         String JavaDoc value = e.getAttributeValue(aname);
37         if (value == null) {
38             value = defaultValue;
39         }
40         return value;
41     }
42
43     /** Returns an element's attribute value, as a String. Same as
44      * Element.getAttributeValue, except guarantees not to return
45      * void.
46      *
47      * @param e an Element
48      * @param aname the attribute name
49      * @return a String
50      */

51     public static String JavaDoc requireAttributeValue(Element e, String JavaDoc aname) {
52         String JavaDoc value = e.getAttributeValue(aname);
53         if (value == null) {
54             throw new MissingAttributeException(e, aname);
55         }
56         return value;
57     }
58     
59     /**
60      * Escape the 5 entities defined by XML.
61      * These are: '<', '>', '\', '&', '"'.
62      *
63      * @param s an xml string
64      * @return an escaped xml string
65      */

66     public static String JavaDoc escapeXml(String JavaDoc s) {
67         if (s == null) return null;
68         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
69         for(int i=0; i<s.length(); i++) {
70             char c = s.charAt(i);
71             if (c == '<') {
72                 sb.append("&lt;");
73             } else if (c == '>') {
74                 sb.append("&gt;");
75             } else if (c == '\'') {
76                 sb.append("&apos;");
77             } else if (c == '&') {
78                 sb.append("&amp;");
79             } else if (c == '"') {
80                 sb.append("&quot;");
81             } else {
82                 sb.append(c);
83             }
84         }
85         return sb.toString();
86     }
87
88     /**
89      * Escape 3 entities understood by HTML text.
90      * These are: '<', '>', '&'
91      *
92      * TODO: [2003-05-05 bloch] move to LZHttpUtils and rename
93      * to escapeHTML
94      *
95      * @param s an xml string
96      * @return an escaped xml string
97      */

98     public static String JavaDoc escapeXmlForSWFHTML(String JavaDoc s) {
99         if (s == null) return null;
100         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
101         for(int i=0; i<s.length(); i++) {
102             char c = s.charAt(i);
103             if (c == '<') {
104                 sb.append("&lt;");
105             } else if (c == '>') {
106                 sb.append("&gt;");
107             } else if (c == '&') {
108                 sb.append("&amp;");
109             } else {
110                 sb.append(c);
111             }
112         }
113         return sb.toString();
114     }
115
116     /**
117      * Make sure all the following sequences
118      * &lt; &gt; &apos; &quot; and &amp;
119      *
120      * have their ampersands escaped
121      *
122      * @param s an xml string
123      * @return an escaped xml string
124      */

125     public static String JavaDoc escapeAmpersands(String JavaDoc s) {
126         if (s == null) return null;
127         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
128         for(int i=0; i<s.length(); i++) {
129             char c = s.charAt(i);
130             if (c == '&') {
131                 int j = i+1;
132                 if (s.regionMatches(j, "lt;", 0, 3)) {
133                     sb.append("&amp;lt;");
134                     i += 3;
135                 } else if (s.regionMatches(j, "gt;", 0, 3)) {
136                     sb.append("&amp;gt;");
137                     i += 3;
138                 } else if (s.regionMatches(j, "apos;", 0, 5)) {
139                     sb.append("&amp;apos;");
140                     i += 5;
141                 } else if (s.regionMatches(j, "quot;", 0, 5)) {
142                     sb.append("&amp;quot;");
143                     i += 5;
144                 } else if (s.regionMatches(j, "amp;", 0, 4)) {
145                     sb.append("&amp;amp;");
146                     i += 4;
147                 } else {
148                     sb.append(c);
149                 }
150             } else {
151                 sb.append(c);
152             }
153         }
154
155         return sb.toString();
156     }
157
158     public static boolean isURL(String JavaDoc str) {
159         // when running in ant, some of these protocols (https and soap, at
160
// least) throw MalformedURLException
161
if (str.startsWith("http:") ||
162             str.startsWith("https:") ||
163             str.startsWith("file:") ||
164             str.startsWith("ftp:") ||
165             str.startsWith("soap:")) {
166             return true;
167         }
168         try {
169             new java.net.URL JavaDoc(str); // for effect
170
return true;
171         } catch (java.net.MalformedURLException JavaDoc e) {
172             return false;
173         }
174     }
175
176     public static Element parse(String JavaDoc source) {
177         try {
178             org.jdom.input.SAXHandler handler = new org.jdom.input.SAXHandler();
179             org.xml.sax.XMLReader JavaDoc reader =
180                 org.xml.sax.helpers.XMLReaderFactory.createXMLReader(
181                     "org.apache.xerces.parsers.SAXParser");
182             reader.setContentHandler(handler);
183             reader.parse(new org.xml.sax.InputSource JavaDoc(new StringReader(source)));
184             Document doc = handler.getDocument();
185             return doc.getRootElement();
186         } catch (IOException e) {
187             throw new ChainedException(e);
188         } catch (SAXException JavaDoc e) {
189             throw new ChainedException(e);
190         }
191     }
192
193     /**
194      * Returns xml from first non-declaration element.
195      *
196      * @param xml xml string buffer.
197      * @return xml string with no declarations.
198      */

199     public static String JavaDoc getNoDeclarationXML(StringBuffer JavaDoc xml)
200     {
201         int len = xml.length();
202         for (int i=0; i < len; i++)
203             if ( xml.charAt(i) == '<' && ( i+1 < len) )
204                 if (xml.charAt(i+1) != '?' && xml.charAt(i+1) != '!')
205                     return xml.substring(i);
206         return xml.toString();
207     }
208
209
210     public static String JavaDoc toString(Element element) {
211         org.jdom.output.XMLOutputter outputter =
212             new org.jdom.output.XMLOutputter();
213         outputter.setTextNormalize(true);
214         return outputter.outputString(element);
215     }
216
217     /**
218      * Helper function for getXPathTo
219      */

220     private static StringBuffer JavaDoc getXPathToInternal(Element elt) {
221         Element parent = elt.getParent();
222         if (parent == null) {
223             return new StringBuffer JavaDoc("/*[1]");
224         }
225         int i = parent.getChildren().indexOf(elt);
226         if (i == -1) {
227             throw new RuntimeException JavaDoc("Element " + elt + " not in parent " + parent + " .getChildren()?");
228         }
229         StringBuffer JavaDoc sb = getXPathToInternal(parent);
230         sb.append("/*[");
231         // DOM is 1-based
232
sb.append(i + 1);
233         sb.append("]");
234         return sb;
235     }
236
237     /**
238      * Returns an xpath for the element
239      *
240      * @param elt the element
241      * @return the xpath
242      */

243     public static String JavaDoc getXPathTo(Element elt) {
244         return getXPathToInternal(elt).toString();
245     }
246 }
247
Popular Tags