Docjar: A Java Source and Docuemnt Enginecom.*    java.*    javax.*    org.*    all    new    plug-in

Quick Search    Search Deep

Source code: org/jdom/xpath/XPath.java


1   /*--
2   
3    $Id: XPath.java,v 1.15 2004/02/06 09:28:32 jhunter Exp $
4   
5    Copyright (C) 2000-2004 Jason Hunter & Brett McLaughlin.
6    All rights reserved.
7   
8    Redistribution and use in source and binary forms, with or without
9    modification, are permitted provided that the following conditions
10   are met:
11  
12   1. Redistributions of source code must retain the above copyright
13      notice, this list of conditions, and the following disclaimer.
14  
15   2. Redistributions in binary form must reproduce the above copyright
16      notice, this list of conditions, and the disclaimer that follows
17      these conditions in the documentation and/or other materials
18      provided with the distribution.
19  
20   3. The name "JDOM" must not be used to endorse or promote products
21      derived from this software without prior written permission.  For
22      written permission, please contact <request_AT_jdom_DOT_org>.
23  
24   4. Products derived from this software may not be called "JDOM", nor
25      may "JDOM" appear in their name, without prior written permission
26      from the JDOM Project Management <request_AT_jdom_DOT_org>.
27  
28   In addition, we request (but do not require) that you include in the
29   end-user documentation provided with the redistribution and/or in the
30   software itself an acknowledgement equivalent to the following:
31       "This product includes software developed by the
32        JDOM Project (http://www.jdom.org/)."
33   Alternatively, the acknowledgment may be graphical using the logos
34   available at http://www.jdom.org/images/logos.
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 THE JDOM AUTHORS OR THE PROJECT
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   This software consists of voluntary contributions made by many
50   individuals on behalf of the JDOM Project and was originally
51   created by Jason Hunter <jhunter_AT_jdom_DOT_org> and
52   Brett McLaughlin <brett_AT_jdom_DOT_org>.  For more information
53   on the JDOM Project, please see <http://www.jdom.org/>.
54  
55   */
56  
57  package org.jdom.xpath;
58  
59  
60  import java.io.*;
61  import java.lang.reflect.*;
62  import java.util.*;
63  
64  import org.jdom.*;
65  
66  
67  /**
68   * A utility class for performing XPath calls on JDOM nodes, with a factory
69   * interface for obtaining a first XPath instance. Users operate against this
70   * class while XPath vendors can plug-in implementations underneath.  Users
71   * can choose an implementation using either {@link #setXPathClass} or
72   * the system property "org.jdom.xpath.class".
73   *
74   * @version $Revision: 1.15 $, $Date: 2004/02/06 09:28:32 $
75   * @author  Laurent Bihanic
76   */
77  public abstract class XPath implements Serializable {
78  
79      private static final String CVS_ID =
80      "@(#) $RCSfile: XPath.java,v $ $Revision: 1.15 $ $Date: 2004/02/06 09:28:32 $ $Name: jdom_1_0 $";
81  
82     /**
83      * The name of the system property from which to retrieve the
84      * name of the implementation class to use.
85      * <p>
86      * The property name is:
87      * "<code>org.jdom.xpath.class</code>".</p>
88      */
89     private final static String  XPATH_CLASS_PROPERTY = "org.jdom.xpath.class";
90  
91     /**
92      * The default implementation class to use if none was configured.
93      */
94     private final static String  DEFAULT_XPATH_CLASS  =
95                                                  "org.jdom.xpath.JaxenXPath";
96  
97     /**
98      * The constructor to instanciate a new XPath concrete
99      * implementation.
100     *
101     * @see    #newInstance
102     */
103    private static Constructor constructor = null;
104 
105    /**
106     * Creates a new XPath wrapper object, compiling the specified
107     * XPath expression.
108     *
109     * @param  path   the XPath expression to wrap.
110     *
111     * @throws JDOMException   if the XPath expression is invalid.
112     */
113    public static XPath newInstance(String path) throws JDOMException {
114       try {
115          if (constructor == null) {
116             // First call => Determine implementation.
117             String className;
118             try {
119                className = System.getProperty(XPATH_CLASS_PROPERTY,
120                                               DEFAULT_XPATH_CLASS);
121             }
122             catch (SecurityException ex1) {
123                // Access to system property denied. => Use default impl.
124                className = DEFAULT_XPATH_CLASS;
125             }
126             setXPathClass(Class.forName(className));
127          }
128          // Allocate and return new implementation instance.
129          return (XPath)constructor.newInstance(new Object[] { path });
130       }
131       catch (JDOMException ex1) {
132          throw ex1;
133       }
134       catch (InvocationTargetException ex2) {
135          // Constructor threw an error on invocation.
136          Throwable t = ex2.getTargetException();
137 
138          throw (t instanceof JDOMException)? (JDOMException)t:
139                                         new JDOMException(t.toString(), t);
140       }
141       catch (Exception ex3) {
142          // Any reflection error (probably due to a configuration mistake).
143          throw new JDOMException(ex3.toString(), ex3);
144       }
145    }
146 
147    /**
148     * Sets the concrete XPath subclass to use when allocating XPath
149     * instances.
150     *
151     * @param  aClass   the concrete subclass of XPath.
152     *
153     * @throws IllegalArgumentException   if <code>aClass</code> is
154     *                                    <code>null</code>.
155     * @throws JDOMException              if <code>aClass</code> is
156     *                                    not a concrete subclass
157     *                                    of XPath.
158     */
159    public static void setXPathClass(Class aClass) throws JDOMException {
160       if (aClass == null) {
161          throw new IllegalArgumentException("aClass");
162       }
163 
164       try {
165          if ((XPath.class.isAssignableFrom(aClass)) &&
166              (Modifier.isAbstract(aClass.getModifiers()) == false)) {
167             // Concrete subclass of XPath => Get constructor
168             constructor = aClass.getConstructor(new Class[] { String.class });
169          }
170          else {
171             throw new JDOMException(aClass.getName() +
172                         " is not a concrete JDOM XPath implementation");
173          }
174       }
175       catch (JDOMException ex1) {
176          throw ex1;
177       }
178       catch (Exception ex2) {
179          // Any reflection error (probably due to a configuration mistake).
180          throw new JDOMException(ex2.toString(), ex2);
181       }
182    }
183 
184     /**
185      * Evaluates the wrapped XPath expression and returns the list
186      * of selected items.
187      *
188      * @param  context   the node to use as context for evaluating
189      *                   the XPath expression.
190      *
191      * @return the list of selected items, which may be of types: {@link Element},
192      *         {@link Attribute}, {@link Text}, {@link CDATA},
193      *         {@link Comment}, {@link ProcessingInstruction}, Boolean,
194      *         Double, or String.
195      *
196      * @throws JDOMException   if the evaluation of the XPath
197      *                         expression on the specified context
198      *                         failed.
199      */
200    abstract public List selectNodes(Object context) throws JDOMException;
201 
202     /**
203      * Evaluates the wrapped XPath expression and returns the first
204      * entry in the list of selected nodes (or atomics).
205      *
206      * @param  context   the node to use as context for evaluating
207      *                   the XPath expression.
208      *
209      * @return the first selected item, which may be of types: {@link Element},
210      *         {@link Attribute}, {@link Text}, {@link CDATA},
211      *         {@link Comment}, {@link ProcessingInstruction}, Boolean,
212      *         Double, String, or <code>null</code> if no item was selected.
213      *
214      * @throws JDOMException   if the evaluation of the XPath
215      *                         expression on the specified context
216      *                         failed.
217      */
218    abstract public Object selectSingleNode(Object context) throws JDOMException;
219 
220    /**
221     * Returns the string value of the first node selected by applying
222     * the wrapped XPath expression to the given context.
223     *
224     * @param  context   the element to use as context for evaluating
225     *                   the XPath expression.
226     *
227     * @return the string value of the first node selected by applying
228     *         the wrapped XPath expression to the given context.
229     *
230     * @throws JDOMException   if the XPath expression is invalid or
231     *                         its evaluation on the specified context
232     *                         failed.
233     */
234    abstract public String valueOf(Object context) throws JDOMException;
235 
236    /**
237     * Returns the number value of the first node selected by applying
238     * the wrapped XPath expression to the given context.
239     *
240     * @param  context   the element to use as context for evaluating
241     *                   the XPath expression.
242     *
243     * @return the number value of the first node selected by applying
244     *         the wrapped XPath expression to the given context,
245     *         <code>null</code> if no node was selected or the
246     *         special value {@link java.lang.Double#NaN}
247     *         (Not-a-Number) if the selected value can not be
248     *         converted into a number value.
249     *
250     * @throws JDOMException   if the XPath expression is invalid or
251     *                         its evaluation on the specified context
252     *                         failed.
253     */
254    abstract public Number numberValueOf(Object context) throws JDOMException;
255 
256    /**
257     * Defines an XPath variable and sets its value.
258     *
259     * @param  name    the variable name.
260     * @param  value   the variable value.
261     *
262     * @throws IllegalArgumentException   if <code>name</code> is not
263     *                                    a valid XPath variable name
264     *                                    or if the value type is not
265     *                                    supported by the underlying
266     *                                    implementation
267     */
268    abstract public void setVariable(String name, Object value);
269 
270    /**
271     * Adds a namespace definition to the list of namespaces known of
272     * this XPath expression.
273     * <p>
274     * <strong>Note</strong>: In XPath, there is no such thing as a
275     * 'default namespace'.  The empty prefix <b>always</b> resolves
276     * to the empty namespace URI.</p>
277     *
278     * @param  namespace   the namespace.
279     */
280    abstract public void addNamespace(Namespace namespace);
281 
282    /**
283     * Adds a namespace definition (prefix and URI) to the list of
284     * namespaces known of this XPath expression.
285     * <p>
286     * <strong>Note</strong>: In XPath, there is no such thing as a
287     * 'default namespace'.  The empty prefix <b>always</b> resolves
288     * to the empty namespace URI.</p>
289     *
290     * @param  prefix   the namespace prefix.
291     * @param  uri      the namespace URI.
292     *
293     * @throws IllegalNameException   if the prefix or uri are null or
294     *                                empty strings or if they contain
295     *                                illegal characters.
296     */
297    public void addNamespace(String prefix, String uri) {
298       addNamespace(Namespace.getNamespace(prefix, uri));
299    }
300 
301    /**
302     * Returns the wrapped XPath expression as a string.
303     *
304     * @return the wrapped XPath expression as a string.
305     */
306    abstract public String getXPath();
307 
308 
309    /**
310     * Evaluates an XPath expression and returns the list of selected
311     * items.
312     * <p>
313     * <strong>Note</strong>: This method should not be used when the
314     * same XPath expression needs to be applied several times (on the
315     * same or different contexts) as it requires the expression to be
316     * compiled before being evaluated.  In such cases,
317     * {@link #newInstance allocating} an XPath wrapper instance and
318     * {@link #selectNodes(java.lang.Object) evaluating} it several
319     * times is way more efficient.
320     * </p>
321     *
322     * @param  context   the node to use as context for evaluating
323     *                   the XPath expression.
324     * @param  path      the XPath expression to evaluate.
325     *
326     * @return the list of selected items, which may be of types: {@link Element},
327     *         {@link Attribute}, {@link Text}, {@link CDATA},
328     *         {@link Comment}, {@link ProcessingInstruction}, Boolean,
329     *         Double, or String.
330     *
331     * @throws JDOMException   if the XPath expression is invalid or
332     *                         its evaluation on the specified context
333     *                         failed.
334     */
335    public static List selectNodes(Object context, String path)
336                                                         throws JDOMException {
337       return newInstance(path).selectNodes(context);
338    }
339 
340    /**
341     * Evaluates the wrapped XPath expression and returns the first
342     * entry in the list of selected nodes (or atomics).
343     * <p>
344     * <strong>Note</strong>: This method should not be used when the
345     * same XPath expression needs to be applied several times (on the
346     * same or different contexts) as it requires the expression to be
347     * compiled before being evaluated.  In such cases,
348     * {@link #newInstance allocating} an XPath wrapper instance and
349     * {@link #selectSingleNode(java.lang.Object) evaluating} it
350     * several times is way more efficient.
351     * </p>
352     *
353     * @param  context   the element to use as context for evaluating
354     *                   the XPath expression.
355     * @param  path      the XPath expression to evaluate.
356     *
357     * @return the first selected item, which may be of types: {@link Element},
358     *         {@link Attribute}, {@link Text}, {@link CDATA},
359     *         {@link Comment}, {@link ProcessingInstruction}, Boolean,
360     *         Double, String, or <code>null</code> if no item was selected.
361     *
362     * @throws JDOMException   if the XPath expression is invalid or
363     *                         its evaluation on the specified context
364     *                         failed.
365     */
366    public static Object selectSingleNode(Object context, String path)
367                                                         throws JDOMException {
368       return newInstance(path).selectSingleNode(context);
369    }
370 
371 
372    //-------------------------------------------------------------------------
373    // Serialization support
374    //-------------------------------------------------------------------------
375 
376    /**
377     * <i>[Serialization support]</i> Returns the alternative object
378     * to write to the stream when serializing this object.  This
379     * method returns an instance of a dedicated nested class to
380     * serialize XPath expressions independently of the concrete
381     * implementation being used.
382     * <p>
383     * <strong>Note</strong>: Subclasses are not allowed to override
384     * this method to ensure valid serialization of all
385     * implementations.</p>
386     *
387     * @return an XPathString instance configured with the wrapped
388     *         XPath expression.
389     *
390     * @throws ObjectStreamException   never.
391     */
392    protected final Object writeReplace() throws ObjectStreamException {
393       return new XPathString(this.getXPath());
394    }
395 
396    /**
397     * The XPathString is dedicated to serialize instances of
398     * XPath subclasses in a implementation-independent manner.
399     * <p>
400     * XPathString ensures that only string data are serialized.  Upon
401     * deserialization, XPathString relies on XPath factory method to
402     * to create instances of the concrete XPath wrapper currently
403     * configured.</p>
404     */
405    private final static class XPathString implements Serializable {
406       /**
407        * The XPath expression as a string.
408        */
409       private String xPath = null;
410 
411       /**
412        * Creates a new XPathString instance from the specified
413        * XPath expression.
414        *
415        * @param  xpath   the XPath expression.
416        */
417       public XPathString(String xpath) {
418          super();
419 
420          this.xPath = xpath;
421       }
422 
423       /**
424        * <i>[Serialization support]</i> Resolves the read XPathString
425        * objects into XPath implementations.
426        *
427        * @return an instance of a concrete implementation of
428        *         XPath.
429        *
430        * @throws ObjectStreamException   if no XPath could be built
431        *                                 from the read object.
432        */
433       private Object readResolve() throws ObjectStreamException {
434          try {
435             return XPath.newInstance(this.xPath);
436          }
437          catch (JDOMException ex1) {
438             throw new InvalidObjectException(
439                         "Can't create XPath object for expression \"" +
440                         this.xPath + "\": " + ex1.toString());
441          }
442       }
443    }
444 }
445