vgritsenko    2003/08/06 14:44:37

  Modified:    xmlutil  build.xml default.properties
  Added:       xmlutil/src/java/org/apache/excalibur/xml/xpath
                        Saxon6ProcessorImpl.java Saxon7ProcessorImpl.java
  Log:
  Add xpath processors based on the Saxon 6.x and 7.x xslt processors
  
  Revision  Changes    Path
  1.49      +37 -31    avalon-excalibur/xmlutil/build.xml
  
  Index: build.xml
  ===================================================================
  RCS file: /home/cvs/avalon-excalibur/xmlutil/build.xml,v
  retrieving revision 1.48
  retrieving revision 1.49
  diff -u -r1.48 -r1.49
  --- build.xml 30 Jul 2003 19:33:42 -0000      1.48
  +++ build.xml 6 Aug 2003 21:44:36 -0000       1.49
  @@ -30,6 +30,8 @@
           <pathelement location="${saxpath.jar}"/>
           <pathelement location="${xml-apis.jar}"/>
           <pathelement location="${jaxen.jar}"/>
  +        <pathelement location="${saxon6.jar}"/>
  +        <pathelement location="${saxon7.jar}"/>
           <pathelement location="${resolver.jar}"/>
           <pathelement location="${jtidy.jar}"/>
           <pathelement path="${java.class.path}"/>
  @@ -55,7 +57,15 @@
   
       <!-- Checks the environment for existing resources -->
       <target name="check-environment">
  -      <available property="jaxen.present" classname="org.jaxen.dom.DOMXPath"/>
  +      <available property="jaxen.present" classname="org.jaxen.dom.DOMXPath">
  +        <classpath refid="project.class.path"/>
  +      </available>
  +      <available property="saxon6.present" 
classname="com.icl.saxon.expr.Expression">
  +        <classpath refid="project.class.path"/>
  +      </available>
  +      <available property="saxon7.present" 
classname="net.sf.saxon.xpath.XPathEvaluator">
  +        <classpath refid="project.class.path"/>
  +      </available>
       </target>
   
       <target name="dependencies" description="Check dependencies" 
unless="skip.dependencies">
  @@ -96,22 +106,23 @@
   
       <!-- Compiles the source code -->
       <target name="compile" depends="dependencies, check-environment" 
description="Compiles the source code">
  -
           <mkdir dir="${build.classes}"/>
   
           <!-- Compile all classes excluding the tests. -->
           <javac srcdir="${java.dir}"
  -            destdir="${build.classes}"
  -            debug="${build.debug}"
  -            optimize="${build.optimize}"
  -            deprecation="${build.deprecation}"
  -            target="1.2">
  +               destdir="${build.classes}"
  +               debug="${build.debug}"
  +               optimize="${build.optimize}"
  +               deprecation="${build.deprecation}"
  +               target="1.2">
               <classpath refid="project.class.path" />
               <exclude name="**/Jaxen*" unless="jaxen.present"/>
  +            <exclude name="**/Saxon6*" unless="saxon6.present"/>
  +            <exclude name="**/Saxon7*" unless="saxon7.present"/>
               <exclude name="**/test/**"/>
           </javac>
   
  -     <!-- generate fortress meta descriptors
  +     <!-- Generate fortress meta descriptors
           <taskdef name="fortress-collect-meta"
                    
classname="org.apache.avalon.fortress.tools.ComponentMetaInfoCollector">
               <classpath refid="project.class.path"/>
  @@ -119,10 +130,8 @@
   
           <fortress-collect-meta destdir="${build.classes}">
               <fileset dir="${java.dir}"/>
  -    </fortress-collect-meta>
  -
  -    Remove for the time being.
  -    -->
  +        </fortress-collect-meta>
  +        Remove for the time being. -->
   
           <!-- copy resources to same location as .class files -->
           <copy todir="${build.classes}">
  @@ -131,7 +140,6 @@
                   <exclude name="**/package.html"/>
               </fileset>
           </copy>
  -
       </target>
   
       <!-- Compiles the unit test source code -->
  @@ -140,18 +148,22 @@
   
           <!-- Copy over all of the tests applying test filters -->
           <copy todir="${build.testsrc}">
  -            <fileset dir="${test.dir}"/>
  +            <fileset dir="${test.dir}">
  +                <exclude name="**/Jaxen*" unless="jaxen.present"/>
  +                <exclude name="**/Saxon6*" unless="saxon6.present"/>
  +                <exclude name="**/Saxon7*" unless="saxon7.present"/>
  +            </fileset>
           </copy>
   
           <mkdir dir="${build.testclasses}"/>
   
           <!-- Compile all test classes. -->
           <javac srcdir="${build.testsrc}"
  -            destdir="${build.testclasses}"
  -            debug="${build.debug}"
  -            optimize="${build.optimize}"
  -            deprecation="${build.deprecation}"
  -            target="1.2">
  +               destdir="${build.testclasses}"
  +               debug="${build.debug}"
  +               optimize="${build.optimize}"
  +               deprecation="${build.deprecation}"
  +               target="1.2">
               <classpath refid="test.class.path" />
               <include name="**/*.java"/>
           </javac>
  @@ -160,9 +172,11 @@
               <fileset dir="${test.dir}">
                   <exclude name="**/*.java"/>
                   <exclude name="**/package.html"/>
  +                <exclude name="**/Jaxen*" unless="jaxen.present"/>
  +                <exclude name="**/Saxon6*" unless="saxon6.present"/>
  +                <exclude name="**/Saxon7*" unless="saxon7.present"/>
               </fileset>
           </copy>
  -
       </target>
   
       <!-- Copies and filters the license. Used by jar and dist -->
  @@ -178,7 +192,6 @@
   
       <!-- Creates all the .jar file -->
       <target name="jar" depends="compile, prepare-conf" description="Generates the 
jar files">
  -
           <mkdir dir="${build.lib}"/>
   
           <jar jarfile="${build.lib}/${jar.name}"
  @@ -226,15 +239,14 @@
       </target>
   
       <target name="test" depends="compile-test" description="Perform the unit tests" 
unless="skip.tests">
  -
           <echo message="Performing Unit Tests" />
   
           <mkdir dir="${build.tests}"/>
   
           <junit fork="true"
  -            haltonfailure="${junit.failonerror}"
  -            printsummary="yes"
  -            dir="${build.tests}">
  +               haltonfailure="${junit.failonerror}"
  +               printsummary="yes"
  +               dir="${build.tests}">
               <classpath refid="test.class.path"/>
   
               <formatter type="xml"/>    <!-- xml reports for junitreport -->
  @@ -247,11 +259,9 @@
                   </fileset>
               </batchtest>
           </junit>
  -
       </target>
   
       <target name="test-reports" depends="test" description="Generate Reports for 
the unit tests">
  -
           <ant antfile="${depchecker.prefix}/depchecker.xml" target="checkBSF"/>
   
           <mkdir dir="${build.reports}/junit"/>
  @@ -270,7 +280,6 @@
               <fileset dir="${build.tests}" includes="TESTS-*.xml"/>
           </delete>
           -->
  -
       </target>
   
       <target name="checkstyle" if="do.checkstyle" description="Checkstyle">
  @@ -321,7 +330,6 @@
               out="${build.reports}/checkstyle/delete-me.html">
               <param name="pathhack" expression="${checkstyle.pathhack}"/>
           </style>
  -
       </target>
   
       <!-- Creates the distribution -->
  @@ -329,7 +337,6 @@
           depends="dist-jar, test-reports, checkstyle-report, javadocs, docs"
           description="Generates a distribution (jar + javadocs + unit tests + 
checkstyle reports)">
   
  -
           <copy file="${build.conf}/LICENSE.txt" todir="${dist.dir}"/>
   
           <zip zipfile="${dist.dir}/src.zip" compress="false">
  @@ -363,7 +370,6 @@
           description="Generates a minimal distribution (jar + javadocs)">
   
           <copy file="../LICENSE.txt" todir="${dist.dir}"/>
  -
       </target>
   
       <!-- Setup the filters -->
  
  
  
  1.32      +2 -0      avalon-excalibur/xmlutil/default.properties
  
  Index: default.properties
  ===================================================================
  RCS file: /home/cvs/avalon-excalibur/xmlutil/default.properties,v
  retrieving revision 1.31
  retrieving revision 1.32
  diff -u -r1.31 -r1.32
  --- default.properties        2 Jun 2003 14:12:01 -0000       1.31
  +++ default.properties        6 Aug 2003 21:44:36 -0000       1.32
  @@ -97,6 +97,8 @@
   
   saxpath.jar = ${lib.dir}/saxpath.jar
   jaxen.jar = ${lib.dir}/jaxen-full.jar
  +saxon6.jar = ${lib.dir}/saxon-6.5.2.jar
  +saxon7.jar = ${lib.dir}/saxon-7.5.jar
   resolver.jar = ${lib.dir}/resolver-20021114.jar
   jtidy.jar = ${lib.dir}/jtidy-04aug2000r7-dev.jar
   
  
  
  
  1.1                  
avalon-excalibur/xmlutil/src/java/org/apache/excalibur/xml/xpath/Saxon6ProcessorImpl.java
  
  Index: Saxon6ProcessorImpl.java
  ===================================================================
  /* ====================================================================
   * The Apache Software License, Version 1.1
   *
   * Copyright (c) 2002 The Apache Software Foundation. All rights
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *
   * 1. Redistributions of source code must retain the above copyright
   *    notice, this list of conditions and the following disclaimer.
   *
   * 2. Redistributions in binary form must reproduce the above copyright
   *    notice, this list of conditions and the following disclaimer in
   *    the documentation and/or other materials provided with the
   *    distribution.
   *
   * 3. The end-user documentation included with the redistribution,
   *    if any, must include the following acknowledgment:
   *    "This product includes software developed by the
   *    Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowledgment may appear in the software
   *    itself, if and wherever such third-party acknowledgments
   *    normally appear.
   *
   * 4. The names "Jakarta", "Avalon", and "Apache Software Foundation"
   *    must not be used to endorse or promote products derived from this
   *    software without prior written permission. For written
   *    permission, please contact [EMAIL PROTECTED]
   *
   * 5. Products derived from this software may not be called "Apache",
   *    nor may "Apache" appear in their name, without prior written
   *    permission of the Apache Software Foundation.
   *
   * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
   * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   * SUCH DAMAGE.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation. For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.excalibur.xml.xpath;
  
  import javax.xml.transform.dom.DOMSource;
  import javax.xml.transform.TransformerFactory;
  
  import org.apache.avalon.framework.component.Component;
  import org.apache.avalon.framework.thread.ThreadSafe;
  
  import com.icl.saxon.Context;
  import com.icl.saxon.TransformerFactoryImpl;
  import com.icl.saxon.tinytree.TinyBuilder;
  import com.icl.saxon.expr.Expression;
  import com.icl.saxon.expr.StandaloneContext;
  import com.icl.saxon.expr.Value;
  import com.icl.saxon.expr.XPathException;
  import com.icl.saxon.expr.NodeSetValue;
  import com.icl.saxon.om.DocumentInfo;
  import com.icl.saxon.om.NamePool;
  import com.icl.saxon.om.NodeInfo;
  import com.icl.saxon.om.NodeEnumeration;
  import org.w3c.dom.Node;
  import org.w3c.dom.NodeList;
  
  /**
   * This class defines the implementation of the [EMAIL PROTECTED] XPathProcessor}
   * component. This implementation depends on Saxon 6.X XSLT processor.
   * This implementation was tested with Saxon 6.5.2 release.
   *
   * To configure it, add the following lines in the
   * <file>cocoon.xconf</file> file:
   *
   * <pre>
   * &lt;xpath-processor 
class="org.apache.cocoon.components.xpath.Saxon6ProcessorImpl"&gt;
   * &lt;/xpath-processor&gt;
   * </pre>
   *
   * @author <a href="mailto:[EMAIL PROTECTED]">Vadim Gritsenko</a>
   * @version CVS $Revision: 1.1 $ $Date: 2003/08/06 21:44:37 $ $Author: vgritsenko $
   */
  public class Saxon6ProcessorImpl
          extends AbstractProcessorImpl
          implements XPathProcessor, Component, ThreadSafe
  {
      private static final TransformerFactory factory = new TransformerFactoryImpl();
  
      /**
       * Evaluate XPath expression within a context.
       *
       * @param contextNode The context node.
       * @param str A valid XPath string.
       * @param resolver a PrefixResolver, used for resolving namespace prefixes
       * @return expression result as boolean.
       */
      public boolean evaluateAsBoolean(Node contextNode, String str, PrefixResolver 
resolver)
      {
          try
          {
              Value value = evaluate(contextNode, str, resolver);
              if (value == null)
              {
                  return false;
              }
  
              return value.asBoolean();
          }
          catch (final Exception e)
          {
              if (getLogger().isDebugEnabled()) {
                  getLogger().debug("Failed to evaluate '" + str + "'", e);
              }
  
              // ignore it
              return false;
          }
      }
  
      /**
       * Evaluate XPath expression within a context.
       *
       * @param contextNode The context node.
       * @param str A valid XPath string.
       * @param resolver a PrefixResolver, used for resolving namespace prefixes
       * @return expression result as number.
       */
      public Number evaluateAsNumber(Node contextNode, String str, PrefixResolver 
resolver)
      {
          try
          {
              Value value = evaluate(contextNode, str, resolver);
              if (value == null)
              {
                  return null;
              }
  
              return new Double(value.asNumber());
          }
          catch (final Exception e)
          {
              if (getLogger().isDebugEnabled()) {
                  getLogger().debug("Failed to evaluate '" + str + "'", e);
              }
  
              // ignore it
              return null;
          }
      }
  
      /**
       * Evaluate XPath expression within a context.
       *
       * @param contextNode The context node.
       * @param str A valid XPath string.
       * @param resolver a PrefixResolver, used for resolving namespace prefixes
       * @return expression result as string.
       */
      public String evaluateAsString(Node contextNode, String str, PrefixResolver 
resolver) {
          try
          {
              Value value = evaluate(contextNode, str, resolver);
              if (value == null)
              {
                  return null;
              }
  
              return value.asString();
          }
          catch (final Exception e)
          {
              if (getLogger().isDebugEnabled()) {
                  getLogger().debug("Failed to evaluate '" + str + "'", e);
              }
  
              // ignore it
              return null;
          }
      }
  
      public Node selectSingleNode(Node contextNode, String str, PrefixResolver 
resolver)
      {
          try
          {
              Value value = evaluate(contextNode, str, resolver);
              if (value == null || value.getDataType() != Value.NODESET)
              {
                  return null;
              }
  
              return (Node)((NodeSetValue)value).getFirst();
          }
          catch (final Exception e)
          {
              if (getLogger().isDebugEnabled()) {
                  getLogger().debug("Failed to evaluate '" + str + "'", e);
              }
  
              // ignore it
              return null;
          }
      }
  
      public NodeList selectNodeList(Node contextNode, String str, PrefixResolver 
resolver)
      {
          try
          {
              Value value = evaluate(contextNode, str, resolver);
              if (value.getDataType() != Value.NODESET)
              {
                  return null;
              }
  
              NodeSetValue nodeset = (NodeSetValue)value;
              NodeEnumeration enumeration = nodeset.enumerate();
              Node[] nodes = new Node[nodeset.getCount()];
              for (int i = 0; i < nodes.length; i++)
              {
                  nodes[i] = (Node)enumeration.nextElement();
              }
  
              return new NodeListImpl(nodes);
          } catch (final Exception e) {
              if (getLogger().isDebugEnabled()) {
                  getLogger().debug("Failed to evaluate '" + str + "'", e);
              }
  
              // ignore it
              return null;
          }
      }
  
      private Value evaluate(Node contextNode, String str, PrefixResolver resolver)
      {
          try
          {
              if (!(contextNode instanceof NodeInfo))
              {
                  getLogger().debug("Input tree is not SAXON TinyTree, converting");
  
                  DOMSource source = new DOMSource(contextNode);
                  TinyBuilder result = new TinyBuilder();
                  factory.newTransformer().transform(source, result);
                  contextNode = (Node)result.getCurrentDocument();
              }
  
              DocumentInfo doc = ((NodeInfo)contextNode).getDocumentRoot();
              NamePool pool = doc.getNamePool();
              if (pool == null)
              {
                  pool = NamePool.getDefaultNamePool();
                  doc.setNamePool(pool);
              }
              Expression expression = Expression.make(str, new Saxon6Context(pool, 
resolver));
  
              Context context = new Context();
              context.setContextNode((NodeInfo)contextNode);
              context.setPosition(1);
              context.setLast(1);
  
              return expression.evaluate(context);
          }
          catch (final Exception e)
          {
              if (getLogger().isDebugEnabled()) {
                  getLogger().debug("Failed to evaluate '" + str + "'", e);
              }
  
              // ignore it
              return null;
          }
      }
  
      private class Saxon6Context extends StandaloneContext
      {
          private final PrefixResolver resolver;
  
          public Saxon6Context(NamePool namePool, PrefixResolver resolver)
          {
              super(namePool);
              this.resolver = resolver;
          }
  
          public String getURIForPrefix(String prefix) throws XPathException
          {
              return resolver.prefixToNamespace(prefix);
          }
      }
  }
  
  
  
  1.1                  
avalon-excalibur/xmlutil/src/java/org/apache/excalibur/xml/xpath/Saxon7ProcessorImpl.java
  
  Index: Saxon7ProcessorImpl.java
  ===================================================================
  /* ====================================================================
   * The Apache Software License, Version 1.1
   *
   * Copyright (c) 2002 The Apache Software Foundation. All rights
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *
   * 1. Redistributions of source code must retain the above copyright
   *    notice, this list of conditions and the following disclaimer.
   *
   * 2. Redistributions in binary form must reproduce the above copyright
   *    notice, this list of conditions and the following disclaimer in
   *    the documentation and/or other materials provided with the
   *    distribution.
   *
   * 3. The end-user documentation included with the redistribution,
   *    if any, must include the following acknowledgment:
   *    "This product includes software developed by the
   *    Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowledgment may appear in the software
   *    itself, if and wherever such third-party acknowledgments
   *    normally appear.
   *
   * 4. The names "Jakarta", "Avalon", and "Apache Software Foundation"
   *    must not be used to endorse or promote products derived from this
   *    software without prior written permission. For written
   *    permission, please contact [EMAIL PROTECTED]
   *
   * 5. Products derived from this software may not be called "Apache",
   *    nor may "Apache" appear in their name, without prior written
   *    permission of the Apache Software Foundation.
   *
   * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
   * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   * SUCH DAMAGE.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation. For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.excalibur.xml.xpath;
  
  import org.apache.avalon.framework.thread.ThreadSafe;
  import org.apache.avalon.framework.component.Component;
  
  import org.w3c.dom.Node;
  import org.w3c.dom.NodeList;
  import net.sf.saxon.om.NodeInfo;
  import net.sf.saxon.om.SequenceIterator;
  import net.sf.saxon.om.Item;
  import net.sf.saxon.xpath.XPathException;
  import net.sf.saxon.xpath.StandaloneContext;
  import net.sf.saxon.TransformerFactoryImpl;
  import net.sf.saxon.expr.Expression;
  import net.sf.saxon.expr.XPathContext;
  import net.sf.saxon.tinytree.TinyBuilder;
  import net.sf.saxon.value.Type;
  import net.sf.saxon.value.BooleanValue;
  import net.sf.saxon.value.DoubleValue;
  
  import javax.xml.transform.TransformerFactory;
  import javax.xml.transform.dom.DOMSource;
  import java.util.ArrayList;
  
  /**
   * This class defines the implementation of the [EMAIL PROTECTED] XPathProcessor}
   * component. This implementation depends on Saxon 7.X XSLT processor.
   * This implementation was tested with Saxon 7.5 release.
   *
   * To configure it, add the following lines in the
   * <file>cocoon.xconf</file> file:
   *
   * <pre>
   * &lt;xslt-processor 
class="org.apache.cocoon.components.xpath.Saxon7ProcessorImpl"&gt;
   * &lt;/xslt-processor&gt;
   * </pre>
   *
   * @author <a href="mailto:[EMAIL PROTECTED]">Vadim Gritsenko</a>
   * @version CVS $Id: Saxon7ProcessorImpl.java,v 1.1 2003/08/06 21:44:37 vgritsenko 
Exp $
   */
  public class Saxon7ProcessorImpl
          extends AbstractProcessorImpl
          implements XPathProcessor, Component, ThreadSafe
  {
      private static final TransformerFactory factory = new TransformerFactoryImpl();
  
      /**
       * Evaluate XPath expression within a context.
       *
       * @param contextNode The context node.
       * @param str A valid XPath string.
       * @param resolver a PrefixResolver, used for resolving namespace prefixes
       * @return expression result as boolean.
       */
      public boolean evaluateAsBoolean(Node contextNode, String str, PrefixResolver 
resolver)
      {
          try
          {
              Item item = evaluateSingle(contextNode, str, resolver);
              if (item == null)
              {
                  return false;
              }
  
              if (item.getItemType() == Type.BOOLEAN)
              {
                  return ((BooleanValue)item).getValue();
              }
  
              return Boolean.valueOf(item.getStringValue()).booleanValue();
          }
          catch (final Exception e)
          {
              if (getLogger().isDebugEnabled()) {
                  getLogger().debug("Failed to evaluate '" + str + "'", e);
              }
  
              // ignore it
              return false;
          }
      }
  
      /**
       * Evaluate XPath expression within a context.
       *
       * @param contextNode The context node.
       * @param str A valid XPath string.
       * @param resolver a PrefixResolver, used for resolving namespace prefixes
       * @return expression result as number.
       */
      public Number evaluateAsNumber(Node contextNode, String str, PrefixResolver 
resolver)
      {
          try
          {
              Item item = evaluateSingle(contextNode, str, resolver);
              if (item == null)
              {
                  return null;
              }
  
              if (item.getItemType() == Type.NUMBER)
              {
                  return new Double(((DoubleValue)item).getValue());
              }
  
              return Double.valueOf(item.getStringValue());
          }
          catch (final Exception e)
          {
              if (getLogger().isDebugEnabled()) {
                  getLogger().debug("Failed to evaluate '" + str + "'", e);
              }
  
              // ignore it
              return null;
          }
      }
  
      /**
       * Evaluate XPath expression within a context.
       *
       * @param contextNode The context node.
       * @param str A valid XPath string.
       * @param resolver a PrefixResolver, used for resolving namespace prefixes
       * @return expression result as string.
       */
      public String evaluateAsString(Node contextNode, String str, PrefixResolver 
resolver) {
          try
          {
              Item item = evaluateSingle(contextNode, str, resolver);
              if (item == null)
              {
                  return null;
              }
  
              return item.getStringValue();
          }
          catch (final Exception e)
          {
              if (getLogger().isDebugEnabled()) {
                  getLogger().debug("Failed to evaluate '" + str + "'", e);
              }
  
              // ignore it
              return null;
          }
      }
  
      public Node selectSingleNode(Node contextNode, String str, PrefixResolver 
resolver)
      {
          try
          {
              Item item = evaluateSingle(contextNode, str, resolver);
  
              return (Node)item;
          }
          catch (final Exception e)
          {
              if (getLogger().isDebugEnabled()) {
                  getLogger().debug("Failed to evaluate '" + str + "'", e);
              }
  
              // ignore it
              return null;
          }
      }
  
      public NodeList selectNodeList(Node contextNode, String str, PrefixResolver 
resolver)
      {
          try
          {
              SequenceIterator iterator = evaluate(contextNode, str, resolver);
              ArrayList nodes = new ArrayList();
              while (iterator.hasNext())
              {
                  Node node = (Node)iterator.current();
                  nodes.add(node);
              }
  
              return new NodeListImpl((Node[])nodes.toArray());
          } catch (final Exception e) {
              if (getLogger().isDebugEnabled()) {
                  getLogger().debug("Failed to evaluate '" + str + "'", e);
              }
  
              // ignore it
              return null;
          }
      }
  
      private Item evaluateSingle(Node contextNode, String str, PrefixResolver 
resolver)
      {
          try
          {
              SequenceIterator iterator = evaluate(contextNode, str, resolver);
              if (iterator == null)
              {
                  return null;
              }
  
              return iterator.current();
          }
          catch (final Exception e)
          {
              if (getLogger().isDebugEnabled()) {
                  getLogger().debug("Failed to evaluate '" + str + "'", e);
              }
  
              // ignore it
              return null;
          }
      }
  
      private SequenceIterator evaluate(Node contextNode, String str, PrefixResolver 
resolver)
      {
          try
          {
              if (!(contextNode instanceof NodeInfo))
              {
                  getLogger().debug("Input tree is not SAXON TinyTree, converting");
                  DOMSource source = new DOMSource(contextNode);
                  TinyBuilder result = new TinyBuilder();
                  factory.newTransformer().transform(source, result);
                  contextNode = (Node)result.getCurrentDocument();
              }
  
              Expression expression = Expression.make(str, new 
Saxon7Context((NodeInfo)contextNode, resolver));
              XPathContext context = new XPathContext((NodeInfo)contextNode);
              return expression.iterate(context);
          }
          catch (final Exception e)
          {
              if (getLogger().isDebugEnabled()) {
                  getLogger().debug("Failed to evaluate '" + str + "'", e);
              }
  
              // ignore it
              return null;
          }
      }
  
  
      private class Saxon7Context extends StandaloneContext
      {
          private final PrefixResolver resolver;
  
          public Saxon7Context(NodeInfo node, PrefixResolver resolver)
          {
              super(node);
              this.resolver = resolver;
          }
  
          public String getURIForPrefix(String prefix) throws XPathException
          {
              return resolver.prefixToNamespace(prefix);
          }
      }
  }
  
  
  

---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to