KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openlaszlo > iv > flash > xml > apache > XPathHelper


1 /*
2  * $Id: XPathHelper.java,v 1.5 2002/07/18 06:02:22 skavish Exp $
3  *
4  * ===========================================================================
5  *
6  * The JGenerator Software License, Version 1.0
7  *
8  * Copyright (c) 2000 Dmitry Skavish (skavish@usa.net). All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  * notice, this list of conditions and the following disclaimer.
15  *
16  * 2. Redistributions in binary form must reproduce the above copyright
17  * notice, this list of conditions and the following disclaimer in
18  * the documentation and/or other materials provided with the
19  * distribution.
20  *
21  * 3. The end-user documentation included with the redistribution, if
22  * any, must include the following acknowlegement:
23  * "This product includes software developed by Dmitry Skavish
24  * (skavish@usa.net, http://www.flashgap.com/)."
25  * Alternately, this acknowlegement may appear in the software itself,
26  * if and wherever such third-party acknowlegements normally appear.
27  *
28  * 4. The name "The JGenerator" must not be used to endorse or promote
29  * products derived from this software without prior written permission.
30  * For written permission, please contact skavish@usa.net.
31  *
32  * 5. Products derived from this software may not be called "The JGenerator"
33  * nor may "The JGenerator" appear in their names without prior written
34  * permission of Dmitry Skavish.
35  *
36  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
37  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
38  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
39  * DISCLAIMED. IN NO EVENT SHALL DMITRY SKAVISH OR THE OTHER
40  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
41  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
42  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
43  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
44  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
45  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
46  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47  * SUCH DAMAGE.
48  *
49  */

50
51 package org.openlaszlo.iv.flash.xml.apache;
52
53 import java.io.*;
54 import java.net.*;
55 import java.util.*;
56
57 import java.io.FileInputStream JavaDoc;
58 import java.io.FileNotFoundException JavaDoc;
59 import java.util.Properties JavaDoc;
60
61 import org.apache.xerces.parsers.DOMParser;
62 import org.apache.xpath.*;
63 import org.apache.xml.utils.*;
64 import org.apache.xpath.objects.*;
65 import org.w3c.dom.*;
66 import org.w3c.dom.traversal.*;
67 import org.xml.sax.SAXException JavaDoc;
68 import org.xml.sax.InputSource JavaDoc;
69
70 import javax.xml.parsers.*;
71 import javax.xml.transform.*;
72
73 import org.openlaszlo.iv.flash.api.*;
74 import org.openlaszlo.iv.flash.url.*;
75
76 import org.openlaszlo.iv.flash.cache.*;
77
78 import org.xml.sax.EntityResolver JavaDoc;
79 import org.xml.sax.InputSource JavaDoc;
80
81 /**
82  * XML Helper class for apache implementation
83  * <P>
84  * Provides various methods for XML stuff
85  *
86  * @author Dmitry Skavish
87  */

88 public class XPathHelper {
89
90     private static Hashtable xpaths = new Hashtable();
91     private static Hashtable prefix_resolvers = new Hashtable();
92
93     public synchronized static PrefixResolver getPrefixResolver( Node node ) {
94         if( prefix_resolvers.size() > 300 ) prefix_resolvers.clear();
95
96         PrefixResolver pr = (PrefixResolver) prefix_resolvers.get(node);
97         if( pr == null ) {
98             // Create an object to resolve namespace prefixes.
99
// XPath namespaces are resolved from the input context node's document element
100
// if it is a root node, or else the current context node (for lack of a better
101
// resolution space, given the simplicity of this sample code).
102
pr = new PrefixResolverDefault(
103                         (node.getNodeType() == Node.DOCUMENT_NODE)?
104                             ((Document) node).getDocumentElement() :
105                             node
106                 );
107             prefix_resolvers.put(node, pr);
108         }
109
110         return pr;
111     }
112
113     /**
114      * Compiles specified string into XPath.
115      * <P>
116      * Tries to retrieve compiled XPath expression from cache,
117      * if it's not in the cache then compiles give string into XPath
118      * and caches in the cache.
119      *
120      * @param expr string representing XPath expression
121      * @return compiled XPath expression
122      * @exception TransformerException
123      */

124     public synchronized static XPath getXPath( Node node, String JavaDoc expr ) throws TransformerException {
125         if( xpaths.size() > 300 ) xpaths.clear();
126
127         XPath xpath = (XPath) xpaths.get( expr );
128         if( xpath == null ) {
129             xpath = new XPath(expr, null, getPrefixResolver(node), XPath.SELECT, null);
130             xpaths.put( expr, xpath );
131         }
132         return xpath;
133     }
134
135     /**
136      * Evaluates specified XPath expression in the specified xml node.
137      *
138      * @param xpathContext
139      * @param node xml node to evaluated on
140      * @param expr xpath expression
141      * @return result of xpath execution
142      * @exception TransformerException
143      */

144     public static XObject evalXPath( XPathContext xpathContext, Node node, String JavaDoc expr )
145         throws TransformerException
146     {
147         return evalXPath( xpathContext, node, getXPath(node, expr) );
148     }
149
150     /**
151      * Evaluates specified XPath expression in the specified xml node.
152      *
153      * @param xpathContext
154      * @param node xml node to evaluated on
155      * @param xpath xpath expression
156      * @return result of xpath execution
157      * @exception TransformerException
158      */

159     public static XObject evalXPath( XPathContext xpathContext, Node node, XPath xpath )
160         throws TransformerException
161     {
162         // Execute the XPath, and have it return the result
163
// return xpath.execute(xpathSupport, contextNode, prefixResolver);
164
int ctxtNode = xpathContext.getDTMHandleFromNode(node);
165
166         return xpath.execute(xpathContext, ctxtNode, getPrefixResolver(node));
167     }
168
169     /**
170      * Evaluates XPath to list of nodes.
171      *
172      * @param xpathContext
173      * @param node xml node to evaluated on
174      * @param expr XPath expression
175      * @return result of xpath execution - list of nodes
176      * @exception TransformerException
177      */

178     public static NodeList selectNodeList( XPathContext xpathContext, Node node, String JavaDoc expr )
179         throws TransformerException
180     {
181         return getNodeList( evalXPath(xpathContext, node, expr) );
182     }
183
184     /**
185      * Evaluates XPath to list of nodes.
186      *
187      * @param xpathContext
188      * @param node xml node to evaluated on
189      * @param xpath XPath expression
190      * @return result of xpath execution - list of nodes
191      * @exception TransformerException
192      */

193     public static NodeList selectNodeList( XPathContext xpathContext, Node node, XPath xpath )
194         throws TransformerException
195     {
196         return getNodeList( evalXPath(xpathContext, node, xpath) );
197     }
198
199     /**
200      * Evaluates XPath to one node.
201      *
202      * @param xpathContext
203      * @param node xml node to be evaluated on
204      * @param expr XPath expression
205      * @return xml node
206      * @exception TransformerException
207      */

208     public static Node selectSingleNode( XPathContext xpathContext, Node node, String JavaDoc expr )
209         throws TransformerException
210     {
211         NodeList nl = selectNodeList(xpathContext, node, expr);
212         if( nl.getLength() > 0 ) return nl.item(0);
213         return null;
214     }
215
216     /**
217      * Evaluates XPath to one node.
218      *
219      * @param xpathContext
220      * @param node xml node to be evaluated on
221      * @param xpath XPath expression
222      * @return xml node
223      * @exception TransformerException
224      */

225     public static Node selectSingleNode( XPathContext xpathContext, Node node, XPath xpath )
226         throws TransformerException
227     {
228         NodeList nl = selectNodeList(xpathContext, node, xpath);
229         if( nl.getLength() > 0 ) return nl.item(0);
230         return null;
231     }
232
233     /**
234      * Converts result of XPath evaluation to nodelist.
235      *
236      * @param xo result of xpath evaluation
237      * @return nodelist
238      * @exception TransformerException
239      */

240     public static NodeList getNodeList( XObject xo ) throws TransformerException {
241         return xo.nodelist();
242     }
243
244     /**
245      * Returns String representation of specified xml node.
246      *
247      * @param node the specified xml node
248      * @return string representation of the node
249      */

250     public static String JavaDoc getNodeData( Node node ) {
251         switch( node.getNodeType() ) {
252             case Node.DOCUMENT_FRAGMENT_NODE:
253             case Node.DOCUMENT_NODE:
254             case Node.ELEMENT_NODE: {
255               /*for (Node child = node.getFirstChild(); null != child;
256                     child = child.getNextSibling())*/

257                 Node child = node.getFirstChild();
258                 if( child != null ) return getNodeData( child );
259             }
260             break;
261             case Node.TEXT_NODE:
262             case Node.CDATA_SECTION_NODE:
263                 return node.getNodeValue();
264             case Node.ATTRIBUTE_NODE:
265                 return node.getNodeValue();
266             case Node.PROCESSING_INSTRUCTION_NODE :
267                 break;
268             default:
269                 break;
270         }
271         return "";
272     }
273
274     public static String JavaDoc getXObjectData( XObject xo ) {
275         switch( xo.getType() ) {
276             case XObject.CLASS_UNKNOWN:
277                 return null;
278             case XObject.CLASS_BOOLEAN:
279             case XObject.CLASS_STRING:
280             case XObject.CLASS_NULL:
281             case XObject.CLASS_NUMBER:
282             case XObject.CLASS_UNRESOLVEDVARIABLE:
283             case XObject.CLASS_RTREEFRAG:
284                 return xo.toString();
285                 //break;
286
case XObject.CLASS_NODESET:
287                 try {
288                     NodeList nl = xo.nodelist();
289                     StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
290                     int l = nl.getLength();
291                     if( l == 0 ) return null;
292                     for( int i=0; i<l; i++ ) {
293                         Node node = nl.item(i);
294                         sb.append(getNodeData(node));
295                     }
296                     return sb.toString();
297                 } catch( javax.xml.transform.TransformerException JavaDoc e ) {
298                 }
299         }
300         return null;
301         //return xo.toString();
302
}
303
304     public static void getNodeData(Node node, StringBuffer JavaDoc buf) {
305         switch( node.getNodeType() ) {
306             case Node.DOCUMENT_FRAGMENT_NODE:
307             case Node.DOCUMENT_NODE:
308             case Node.ELEMENT_NODE:
309                 {
310                     for( Node child = node.getFirstChild(); null != child;
311                        child = child.getNextSibling() ) {
312                         buf.append('<');
313                         buf.append(node.getNodeName());
314                         buf.append('>');
315                         getNodeData(child, buf);
316                         buf.append("</");
317                         buf.append(node.getNodeName());
318                         buf.append('>');
319                     }
320                 }
321                 break;
322             case Node.TEXT_NODE :
323             case Node.CDATA_SECTION_NODE :
324                 buf.append(node.getNodeValue());
325                 break;
326             case Node.ATTRIBUTE_NODE :
327                 buf.append(node.getNodeValue());
328                 break;
329             case Node.PROCESSING_INSTRUCTION_NODE :
330                 // warning(XPATHErrorResources.WG_PARSING_AND_PREPARING);
331
break;
332             default :
333                 // ignore
334
break;
335         }
336     }
337 }
338
339
Popular Tags