KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > icesoft > jasper > xmlparser > ParserUtils


1 /*
2  * Copyright 1999,2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package com.icesoft.jasper.xmlparser;
18
19 import com.icesoft.jasper.JasperException;
20 import com.icesoft.jasper.compiler.Localizer;
21 import org.apache.commons.logging.Log;
22 import org.apache.commons.logging.LogFactory;
23 import org.w3c.dom.Comment JavaDoc;
24 import org.w3c.dom.Document JavaDoc;
25 import org.w3c.dom.NamedNodeMap JavaDoc;
26 import org.w3c.dom.Node JavaDoc;
27 import org.w3c.dom.NodeList JavaDoc;
28 import org.w3c.dom.Text JavaDoc;
29 import org.xml.sax.EntityResolver JavaDoc;
30 import org.xml.sax.ErrorHandler JavaDoc;
31 import org.xml.sax.SAXException JavaDoc;
32 import org.xml.sax.SAXParseException JavaDoc;
33
34 import javax.xml.parsers.DocumentBuilder JavaDoc;
35 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
36 import javax.xml.parsers.ParserConfigurationException JavaDoc;
37 import java.io.IOException JavaDoc;
38 import java.io.InputStream JavaDoc;
39
40
41 /**
42  * XML parsing utilities for processing web application deployment descriptor
43  * and tag library descriptor files. FIXME - make these use a separate class
44  * loader for the parser to be used.
45  *
46  * @author Craig R. McClanahan
47  * @version $Revision: 1.10 $ $Date: 2004/03/17 19:23:05 $
48  */

49
50 public class ParserUtils {
51
52     // Logger
53
static Log log = LogFactory.getLog(ParserUtils.class);
54
55     /**
56      * An error handler for use when parsing XML documents.
57      */

58     static ErrorHandler JavaDoc errorHandler = new MyErrorHandler();
59
60     /**
61      * An entity resolver for use when parsing XML documents.
62      */

63     public static EntityResolver JavaDoc entityResolver = new CachedEntityResolver();
64
65     // Turn off for JSP 2.0 until switch over to using xschema.
66
public static boolean validating = false;
67
68     // --------------------------------------------------------- Public Methods
69

70     /**
71      * Parse the specified XML document, and return a <code>TreeNode</code> that
72      * corresponds to the root node of the document tree.
73      *
74      * @param uri URI of the XML document being parsed
75      * @param is Input stream containing the deployment descriptor
76      * @throws JasperException if an input/output error occurs
77      * @throws JasperException if a parsing error occurs
78      */

79     public TreeNode parseXMLDocument(String JavaDoc uri, InputStream JavaDoc is)
80             throws JasperException {
81
82         Document JavaDoc document = null;
83
84         // Perform an XML parse of this document, via JAXP
85
try {
86             DocumentBuilderFactory JavaDoc factory =
87                     DocumentBuilderFactory.newInstance();
88             factory.setNamespaceAware(true);
89             factory.setValidating(validating);
90             DocumentBuilder JavaDoc builder = factory.newDocumentBuilder();
91             builder.setEntityResolver(entityResolver);
92             builder.setErrorHandler(errorHandler);
93             document = builder.parse(is);
94         } catch (ParserConfigurationException JavaDoc ex) {
95             throw new JasperException
96                     (Localizer.getMessage("jsp.error.parse.xml", uri), ex);
97         } catch (SAXParseException JavaDoc ex) {
98             throw new JasperException
99                     (Localizer.getMessage("jsp.error.parse.xml.line",
100                                           uri,
101                                           Integer.toString(ex.getLineNumber()),
102                                           Integer.toString(
103                                                   ex.getColumnNumber())),
104                      ex);
105         } catch (SAXException JavaDoc sx) {
106             throw new JasperException
107                     (Localizer.getMessage("jsp.error.parse.xml", uri), sx);
108         } catch (IOException JavaDoc io) {
109             throw new JasperException
110                     (Localizer.getMessage("jsp.error.parse.xml", uri), io);
111         }
112
113         // Convert the resulting document to a graph of TreeNodes
114
return (convert(null, document.getDocumentElement()));
115     }
116
117     // ------------------------------------------------------ Protected Methods
118

119
120     /**
121      * Create and return a TreeNode that corresponds to the specified Node,
122      * including processing all of the attributes and children nodes.
123      *
124      * @param parent The parent TreeNode (if any) for the new TreeNode
125      * @param node The XML document Node to be converted
126      */

127     protected TreeNode convert(TreeNode parent, Node JavaDoc node) {
128
129         // Construct a new TreeNode for this node
130
TreeNode treeNode = new TreeNode(node.getNodeName(), parent);
131
132         // Convert all attributes of this node
133
NamedNodeMap JavaDoc attributes = node.getAttributes();
134         if (attributes != null) {
135             int n = attributes.getLength();
136             for (int i = 0; i < n; i++) {
137                 Node JavaDoc attribute = attributes.item(i);
138                 treeNode.addAttribute(attribute.getNodeName(),
139                                       attribute.getNodeValue());
140             }
141         }
142
143         // Create and attach all children of this node
144
NodeList JavaDoc children = node.getChildNodes();
145         if (children != null) {
146             int n = children.getLength();
147             for (int i = 0; i < n; i++) {
148                 Node JavaDoc child = children.item(i);
149                 if (child instanceof Comment JavaDoc)
150                     continue;
151                 if (child instanceof Text JavaDoc) {
152                     String JavaDoc body = ((Text JavaDoc) child).getData();
153                     if (body != null) {
154                         body = body.trim();
155                         if (body.length() > 0)
156                             treeNode.setBody(body);
157                     }
158                 } else {
159                     TreeNode treeChild = convert(treeNode, child);
160                 }
161             }
162         }
163
164         // Return the completed TreeNode graph
165
return (treeNode);
166     }
167 }
168
169 // ------------------------------------------------------------ Private Classes
170

171 /*
172 class MyEntityResolver implements EntityResolver {
173     public InputSource resolveEntity(String publicId, String systemId)
174     throws SAXException
175     {
176     for (int i=0; i<Constants.CACHED_DTD_PUBLIC_IDS.length; i++) {
177         String cachedDtdPublicId = Constants.CACHED_DTD_PUBLIC_IDS[i];
178         if (cachedDtdPublicId.equals(publicId)) {
179         String resourcePath = Constants.CACHED_DTD_RESOURCE_PATHS[i];
180         InputStream input =
181             this.getClass().getResourceAsStream(resourcePath);
182         if (input == null) {
183             throw new SAXException(
184                         Localizer.getMessage("jsp.error.internal.filenotfound",
185                          resourcePath));
186         }
187         InputSource isrc = new InputSource(input);
188         return isrc;
189         }
190     }
191         System.out.println("Resolve entity failed" + publicId + " "
192                + systemId );
193     ParserUtils.log.error(Localizer.getMessage("jsp.error.parse.xml.invalidPublicId",
194                            publicId));
195         return null;
196     }
197 }
198 */

199
200 class MyErrorHandler implements ErrorHandler JavaDoc {
201     public void warning(SAXParseException JavaDoc ex)
202             throws SAXException JavaDoc {
203         System.out.println("ParserUtils: warning " + ex);
204         // We ignore warnings
205
}
206
207     public void error(SAXParseException JavaDoc ex)
208             throws SAXException JavaDoc {
209         throw ex;
210     }
211
212     public void fatalError(SAXParseException JavaDoc ex)
213             throws SAXException JavaDoc {
214         throw ex;
215     }
216 }
217
Popular Tags