Esempio n. 1
0
  /**
   * Get the match score of the given node.
   *
   * @param xctxt XPath runtime context.
   * @param context The current source tree context node.
   * @return score, one of {@link #MATCH_SCORE_NODETEST}, {@link #MATCH_SCORE_NONE}, {@link
   *     #MATCH_SCORE_OTHER}, or {@link #MATCH_SCORE_QNAME}.
   * @throws javax.xml.transform.TransformerException
   */
  public double getMatchScore(XPathContext xctxt, int context)
      throws javax.xml.transform.TransformerException {

    xctxt.pushCurrentNode(context);
    xctxt.pushCurrentExpressionNode(context);

    try {
      XObject score = m_mainExp.execute(xctxt);

      if (DEBUG_MATCHES) {
        DTM dtm = xctxt.getDTM(context);
        System.out.println(
            "score: "
                + score.num()
                + " for "
                + dtm.getNodeName(context)
                + " for xpath "
                + this.getPatternString());
      }

      return score.num();
    } finally {
      xctxt.popCurrentNode();
      xctxt.popCurrentExpressionNode();
    }

    // return XPath.MATCH_SCORE_NONE;
  }
  /**
   * Test whether a specified node is visible in the logical view of a TreeWalker or NodeIterator.
   * This function will be called by the implementation of TreeWalker and NodeIterator; it is not
   * intended to be called directly from user code.
   *
   * @param n The node to check to see if it passes the filter or not.
   * @return a constant to determine whether the node is accepted, rejected, or skipped, as defined
   *     above .
   */
  public short acceptNode(int n, XPathContext xctxt) {

    try {
      xctxt.pushCurrentNode(n);
      xctxt.pushIteratorRoot(m_context);
      if (DEBUG) {
        System.out.println("traverser: " + m_traverser);
        System.out.print("node: " + n);
        System.out.println(", " + m_cdtm.getNodeName(n));
        // if(m_cdtm.getNodeName(n).equals("near-east"))
        System.out.println("pattern: " + m_pattern.toString());
        m_pattern.debugWhatToShow(m_pattern.getWhatToShow());
      }

      XObject score = m_pattern.execute(xctxt);

      if (DEBUG) {
        // System.out.println("analysis: "+Integer.toBinaryString(m_analysis));
        System.out.println("score: " + score);
        System.out.println("skip: " + (score == NodeTest.SCORE_NONE));
      }

      // System.out.println("\n::acceptNode - score: "+score.num()+"::");
      return (score == NodeTest.SCORE_NONE) ? DTMIterator.FILTER_SKIP : DTMIterator.FILTER_ACCEPT;
    } catch (javax.xml.transform.TransformerException se) {

      // TODO: Fix this.
      throw new RuntimeException(se.getMessage());
    } finally {
      xctxt.popCurrentNode();
      xctxt.popIteratorRoot();
    }
  }
  /**
   * Return the first node out of the nodeset, if this expression is a nodeset expression. This is
   * the default implementation for nodesets.
   *
   * <p>WARNING: Do not mutate this class from this function!
   *
   * @param xctxt The XPath runtime context.
   * @return the first node out of the nodeset, or DTM.NULL.
   */
  public int asNode(XPathContext xctxt) throws javax.xml.transform.TransformerException {
    int current = xctxt.getCurrentNode();

    DTM dtm = xctxt.getDTM(current);

    return dtm.getFirstChild(current);
  }
Esempio n. 4
0
 /**
  * Dereference the variable, and return the reference value. Note that lazy evaluation will occur.
  * If a variable within scope is not found, a warning will be sent to the error listener, and an
  * empty nodeset will be returned.
  *
  * @param xctxt The runtime execution context.
  * @return The evaluated variable, or an empty nodeset if not found.
  * @throws javax.xml.transform.TransformerException
  */
 public XObject execute(XPathContext xctxt, boolean destructiveOK)
     throws javax.xml.transform.TransformerException {
   XNodeSet xns = (XNodeSet) super.execute(xctxt, destructiveOK);
   DTMManager dtmMgr = xctxt.getDTMManager();
   int context = xctxt.getContextNode();
   if (dtmMgr.getDTM(xns.getRoot()).getDocument() != dtmMgr.getDTM(context).getDocument()) {
     Expression expr = (Expression) xns.getContainedIter();
     xns = (XNodeSet) expr.asIterator(xctxt, context);
   }
   return xns;
 }
  /**
   * Execute the first argument expression that is expected to return a string. If the argument is
   * null, then get the string value from the current context node.
   *
   * @param xctxt Runtime XPath context.
   * @return The string value of the first argument, or the string value of the current context node
   *     if the first argument is null.
   * @throws javax.xml.transform.TransformerException if an error occurs while executing the
   *     argument expression.
   */
  protected XMLString getArg0AsString(XPathContext xctxt)
      throws javax.xml.transform.TransformerException {
    if (null == m_arg0) {
      int currentNode = xctxt.getCurrentNode();
      if (DTM.NULL == currentNode) return XString.EMPTYSTRING;
      else {
        DTM dtm = xctxt.getDTM(currentNode);
        return dtm.getStringValue(currentNode);
      }

    } else return m_arg0.execute(xctxt).xstr();
  }
Esempio n. 6
0
  /**
   * Warn the user of an problem.
   *
   * @param xctxt The XPath runtime context.
   * @param sourceNode Not used.
   * @param msg An error msgkey that corresponds to one of the constants found in {@link
   *     com.sun.org.apache.xpath.internal.res.XPATHErrorResources}, which is a key for a format
   *     string.
   * @param args An array of arguments represented in the format string, which may be null.
   * @throws TransformerException if the current ErrorListoner determines to throw an exception.
   */
  public void warn(XPathContext xctxt, int sourceNode, String msg, Object[] args)
      throws javax.xml.transform.TransformerException {

    String fmsg = XSLMessages.createXPATHWarning(msg, args);
    ErrorListener ehandler = xctxt.getErrorListener();

    if (null != ehandler) {

      // TO DO: Need to get stylesheet Locator from here.
      ehandler.warning(new TransformerException(fmsg, (SAXSourceLocator) xctxt.getSAXLocator()));
    }
  }
  /**
   * Execute the first argument expression that is expected to return a number. If the argument is
   * null, then get the number value from the current context node.
   *
   * @param xctxt Runtime XPath context.
   * @return The number value of the first argument, or the number value of the current context node
   *     if the first argument is null.
   * @throws javax.xml.transform.TransformerException if an error occurs while executing the
   *     argument expression.
   */
  protected double getArg0AsNumber(XPathContext xctxt)
      throws javax.xml.transform.TransformerException {

    if (null == m_arg0) {
      int currentNode = xctxt.getCurrentNode();
      if (DTM.NULL == currentNode) return 0;
      else {
        DTM dtm = xctxt.getDTM(currentNode);
        XMLString str = dtm.getStringValue(currentNode);
        return str.toDouble();
      }

    } else return m_arg0.execute(xctxt).num();
  }
 public synchronized TemplateModel executeQuery(Object context, String xpathQuery)
     throws TemplateModelException {
   if (!(context instanceof Node)) {
     if (context != null) {
       if (isNodeList(context)) {
         int cnt = ((List) context).size();
         if (cnt != 0) {
           throw new TemplateModelException(
               "Cannot perform an XPath query against a node set of "
                   + cnt
                   + " nodes. Expecting a single node."
                   + ERRMSG_RECOMMEND_JAXEN);
         } else {
           throw new TemplateModelException(ERRMSG_EMPTY_NODE_SET);
         }
       } else {
         throw new TemplateModelException(
             "Cannot perform an XPath query against a "
                 + context.getClass().getName()
                 + ". Expecting a single org.w3c.dom.Node.");
       }
     } else {
       throw new TemplateModelException(ERRMSG_EMPTY_NODE_SET);
     }
   }
   Node node = (Node) context;
   try {
     XPath xpath = new XPath(xpathQuery, null, customPrefixResolver, XPath.SELECT, null);
     int ctxtNode = xpathContext.getDTMHandleFromNode(node);
     XObject xresult = xpath.execute(xpathContext, ctxtNode, customPrefixResolver);
     if (xresult instanceof XNodeSet) {
       NodeListModel result = new NodeListModel(node);
       result.xpathSupport = this;
       NodeIterator nodeIterator = xresult.nodeset();
       Node n;
       do {
         n = nodeIterator.nextNode();
         if (n != null) {
           result.add(n);
         }
       } while (n != null);
       return result.size() == 1 ? result.get(0) : result;
     }
     if (xresult instanceof XBoolean) {
       return ((XBoolean) xresult).bool() ? TemplateBooleanModel.TRUE : TemplateBooleanModel.FALSE;
     }
     if (xresult instanceof XNull) {
       return null;
     }
     if (xresult instanceof XString) {
       return new SimpleScalar(xresult.toString());
     }
     if (xresult instanceof XNumber) {
       return new SimpleNumber(new Double(((XNumber) xresult).num()));
     }
     throw new TemplateModelException("Cannot deal with type: " + xresult.getClass().getName());
   } catch (TransformerException te) {
     throw new TemplateModelException(te);
   }
 }
Esempio n. 9
0
  /**
   * Cast result object to a result tree fragment.
   *
   * @param support Xpath context to use for the conversion
   * @return A document fragment with this string as a child node
   */
  public int rtf(XPathContext support) {

    DTM frag = support.createDocumentFragment();

    frag.appendTextChild(str());

    return frag.getDocument();
  }
  /**
   * Execute the function. The function must return a valid object.
   *
   * @param xctxt The current execution context.
   * @return A valid XObject.
   * @throws javax.xml.transform.TransformerException
   */
  public XObject execute(XPathContext xctxt) throws javax.xml.transform.TransformerException {

    int context = getArg0AsNode(xctxt);
    if (DTM.NULL == context) return XString.EMPTYSTRING;
    DTM dtm = xctxt.getDTM(context);
    String s = (context != DTM.NULL) ? dtm.getLocalName(context) : "";
    if (s.startsWith("#") || s.equals("xmlns")) return XString.EMPTYSTRING;

    return new XString(s);
  }
Esempio n. 11
0
  /**
   * Set the root node of the TreeWalker. (Not part of the DOM2 TreeWalker interface).
   *
   * @param root The context node of this step.
   */
  public void setRoot(int root) {
    // %OPT% Get this directly from the lpi.
    XPathContext xctxt = wi().getXPathContext();
    m_dtm = xctxt.getDTM(root);
    m_traverser = m_dtm.getAxisTraverser(m_axis);
    m_isFresh = true;
    m_foundLast = false;
    m_root = root;
    m_currentNode = root;

    if (DTM.NULL == root) {
      throw new RuntimeException(
          XSLMessages.createXPATHMessage(
              XPATHErrorResources.ER_SETTING_WALKER_ROOT_TO_NULL,
              null)); // "\n !!!! Error! Setting the root of a walker to null!!!");
    }

    resetProximityPositions();
  }
Esempio n. 12
0
  /**
   * Tell the user of an error, and probably throw an exception.
   *
   * @param xctxt The XPath runtime context.
   * @param sourceNode Not used.
   * @param msg An error msgkey that corresponds to one of the constants found in {@link
   *     com.sun.org.apache.xpath.internal.res.XPATHErrorResources}, which is a key for a format
   *     string.
   * @param args An array of arguments represented in the format string, which may be null.
   * @throws TransformerException if the current ErrorListoner determines to throw an exception.
   */
  public void error(XPathContext xctxt, int sourceNode, String msg, Object[] args)
      throws javax.xml.transform.TransformerException {

    String fmsg = XSLMessages.createXPATHMessage(msg, args);
    ErrorListener ehandler = xctxt.getErrorListener();

    if (null != ehandler) {
      ehandler.fatalError(new TransformerException(fmsg, (SAXSourceLocator) xctxt.getSAXLocator()));
    } else {
      SourceLocator slocator = xctxt.getSAXLocator();
      System.out.println(
          fmsg
              + "; file "
              + slocator.getSystemId()
              + "; line "
              + slocator.getLineNumber()
              + "; column "
              + slocator.getColumnNumber());
    }
  }
Esempio n. 13
0
  /**
   * The number of nodes in the list. The range of valid child node indices is 0 to <code>length-1
   * </code> inclusive.
   *
   * @return The number of nodes in the list, always greater or equal to zero.
   */
  public int getLength() {
    if (!isReverseAxes()) return super.getLength();

    // Tell if this is being called from within a predicate.
    boolean isPredicateTest = (this == m_execContext.getSubContextList());

    // And get how many total predicates are part of this step.
    int predCount = getPredicateCount();

    // If we have already calculated the length, and the current predicate
    // is the first predicate, then return the length.  We don't cache
    // the anything but the length of the list to the first predicate.
    if (-1 != m_length && isPredicateTest && m_predicateIndex < 1) return m_length;

    int count = 0;

    XPathContext xctxt = getXPathContext();
    try {
      OneStepIterator clone = (OneStepIterator) this.cloneWithReset();

      int root = getRoot();
      xctxt.pushCurrentNode(root);
      clone.setRoot(root, xctxt);

      clone.m_predCount = m_predicateIndex;

      int next;

      while (DTM.NULL != (next = clone.nextNode())) {
        count++;
      }
    } catch (CloneNotSupportedException cnse) {
      // can't happen
    } finally {
      xctxt.popCurrentNode();
    }
    if (isPredicateTest && m_predicateIndex < 1) m_length = count;

    return count;
  }
Esempio n. 14
0
  /**
   * Get the current sub-context position. In order to do the reverse axes count, for the moment
   * this re-searches the axes up to the predicate. An optimization on this is to cache the nodes
   * searched, but, for the moment, this case is probably rare enough that the added complexity
   * isn't worth it.
   *
   * @param predicateIndex The predicate index of the proximity position.
   * @return The pridicate index, or -1.
   */
  protected int getProximityPosition(int predicateIndex) {
    if (!isReverseAxes()) return super.getProximityPosition(predicateIndex);

    // A negative predicate index seems to occur with
    // (preceding-sibling::*|following-sibling::*)/ancestor::*[position()]/*[position()]
    // -sb
    if (predicateIndex < 0) return -1;

    if (m_proximityPositions[predicateIndex] <= 0) {
      XPathContext xctxt = getXPathContext();
      try {
        OneStepIterator clone = (OneStepIterator) this.clone();

        int root = getRoot();
        xctxt.pushCurrentNode(root);
        clone.setRoot(root, xctxt);

        // clone.setPredicateCount(predicateIndex);
        clone.m_predCount = predicateIndex;

        // Count 'em all
        int count = 1;
        int next;

        while (DTM.NULL != (next = clone.nextNode())) {
          count++;
        }

        m_proximityPositions[predicateIndex] += count;
      } catch (CloneNotSupportedException cnse) {

        // can't happen
      } finally {
        xctxt.popCurrentNode();
      }
    }

    return m_proximityPositions[predicateIndex];
  }
  /**
   * Try to create a DOM source tree from the input source.
   *
   * @param source The Source object that identifies the source node.
   * @param locator The location of the caller, for diagnostic purposes.
   * @return non-null reference to node identified by the source argument.
   * @throws TransformerException if the source argument can not be resolved to a source node.
   */
  public int parseToNode(Source source, SourceLocator locator, XPathContext xctxt)
      throws TransformerException {

    try {
      Object xowner = xctxt.getOwnerObject();
      DTM dtm;
      if (null != xowner && xowner instanceof com.sun.org.apache.xml.internal.dtm.DTMWSFilter) {
        dtm =
            xctxt.getDTM(
                source,
                false,
                (com.sun.org.apache.xml.internal.dtm.DTMWSFilter) xowner,
                false,
                true);
      } else {
        dtm = xctxt.getDTM(source, false, null, false, true);
      }
      return dtm.getDocument();
    } catch (Exception e) {
      // e.printStackTrace();
      throw new TransformerException(e.getMessage(), locator, e);
    }
  }
Esempio n. 16
0
  /**
   * Test whether a specified node is visible in the logical view of a TreeWalker or NodeIterator.
   * This function will be called by the implementation of TreeWalker and NodeIterator; it is not
   * intended to be called directly from user code.
   *
   * @param n The node to check to see if it passes the filter or not.
   * @return a constant to determine whether the node is accepted, rejected, or skipped, as defined
   *     above .
   */
  public short acceptNode(int n) {
    XPathContext xctxt = getXPathContext();
    try {
      xctxt.pushCurrentNode(n);
      for (int i = 0; i < m_nodeTests.length; i++) {
        PredicatedNodeTest pnt = m_nodeTests[i];
        XObject score = pnt.execute(xctxt, n);
        if (score != NodeTest.SCORE_NONE) {
          // Note that we are assuming there are no positional predicates!
          if (pnt.getPredicateCount() > 0) {
            if (pnt.executePredicates(n, xctxt)) return DTMIterator.FILTER_ACCEPT;
          } else return DTMIterator.FILTER_ACCEPT;
        }
      }
    } catch (javax.xml.transform.TransformerException se) {

      // TODO: Fix this.
      throw new RuntimeException(se.getMessage());
    } finally {
      xctxt.popCurrentNode();
    }
    return DTMIterator.FILTER_SKIP;
  }
Esempio n. 17
0
  /**
   * Execute the function. The function must return a valid object.
   *
   * @param xctxt The current execution context.
   * @return A valid XObject.
   * @throws javax.xml.transform.TransformerException
   */
  public XObject execute(XPathContext xctxt) throws javax.xml.transform.TransformerException {

    int whereNode = getArg0AsNode(xctxt);
    String fileLocation = null;

    if (DTM.NULL != whereNode) {
      DTM dtm = xctxt.getDTM(whereNode);

      // %REVIEW%
      if (DTM.DOCUMENT_FRAGMENT_NODE == dtm.getNodeType(whereNode)) {
        whereNode = dtm.getFirstChild(whereNode);
      }

      if (DTM.NULL != whereNode) {
        fileLocation = dtm.getDocumentBaseURI();
        //        int owner = dtm.getDocument();
        //        fileLocation = xctxt.getSourceTreeManager().findURIFromDoc(owner);
      }
    }

    return new XString((null != fileLocation) ? fileLocation : "");
  }
Esempio n. 18
0
  /**
   * Given an expression and a context, evaluate the XPath and return the result.
   *
   * @param xctxt The execution context.
   * @param contextNode The node that "." expresses.
   * @param namespaceContext The context in which namespaces in the XPath are supposed to be
   *     expanded.
   * @throws TransformerException thrown if the active ProblemListener decides the error condition
   *     is severe enough to halt processing.
   * @throws javax.xml.transform.TransformerException
   * @xsl.usage experimental
   */
  public XObject execute(XPathContext xctxt, int contextNode, PrefixResolver namespaceContext)
      throws javax.xml.transform.TransformerException {

    xctxt.pushNamespaceContext(namespaceContext);

    xctxt.pushCurrentNodeAndExpression(contextNode, contextNode);

    XObject xobj = null;

    try {
      xobj = m_mainExp.execute(xctxt);
    } catch (TransformerException te) {
      te.setLocator(this.getLocator());
      ErrorListener el = xctxt.getErrorListener();
      if (null != el) // defensive, should never happen.
      {
        el.error(te);
      } else throw te;
    } catch (Exception e) {
      while (e instanceof com.sun.org.apache.xml.internal.utils.WrappedRuntimeException) {
        e = ((com.sun.org.apache.xml.internal.utils.WrappedRuntimeException) e).getException();
      }
      // e.printStackTrace();

      String msg = e.getMessage();

      if (msg == null || msg.length() == 0) {
        msg = XSLMessages.createXPATHMessage(XPATHErrorResources.ER_XPATH_ERROR, null);
      }
      TransformerException te = new TransformerException(msg, getLocator(), e);
      ErrorListener el = xctxt.getErrorListener();
      // te.printStackTrace();
      if (null != el) // defensive, should never happen.
      {
        el.fatalError(te);
      } else throw te;
    } finally {
      xctxt.popNamespaceContext();

      xctxt.popCurrentNodeAndExpression();
    }

    return xobj;
  }
  /**
   * Execute the first argument expression that is expected to return a nodeset. If the argument is
   * null, then return the current context node.
   *
   * @param xctxt Runtime XPath context.
   * @return The first node of the executed nodeset, or the current context node if the first
   *     argument is null.
   * @throws javax.xml.transform.TransformerException if an error occurs while executing the
   *     argument expression.
   */
  protected int getArg0AsNode(XPathContext xctxt) throws javax.xml.transform.TransformerException {

    return (null == m_arg0) ? xctxt.getCurrentNode() : m_arg0.asNode(xctxt);
  }
Esempio n. 20
0
 /**
  * Given an expression and a context, evaluate the XPath and return the result.
  *
  * @param xctxt The execution context.
  * @param contextNode The node that "." expresses.
  * @param namespaceContext The context in which namespaces in the XPath are supposed to be
  *     expanded.
  * @return The result of the XPath or null if callbacks are used.
  * @throws TransformerException thrown if the error condition is severe enough to halt processing.
  * @throws javax.xml.transform.TransformerException
  * @xsl.usage experimental
  */
 public XObject execute(
     XPathContext xctxt, org.w3c.dom.Node contextNode, PrefixResolver namespaceContext)
     throws javax.xml.transform.TransformerException {
   return execute(xctxt, xctxt.getDTMHandleFromNode(contextNode), namespaceContext);
 }