Java Code Examples for org.apache.xpath.objects.XObject#getType()

The following examples show how to use org.apache.xpath.objects.XObject#getType() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: VariableStack.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Get a local variable or parameter in the current stack frame.
 *
 *
 * @param xctxt The XPath context, which must be passed in order to
 * lazy evaluate variables.
 *
 * @param index Local variable index relative to the current stack
 * frame bottom.
 *
 * @return The value of the variable.
 *
 * @throws TransformerException
 */
public XObject getLocalVariable(XPathContext xctxt, int index)
        throws TransformerException
{

  index += _currentFrameBottom;

  XObject val = _stackFrames[index];
  
  if(null == val)
    throw new TransformerException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_VARIABLE_ACCESSED_BEFORE_BIND, null),
                   xctxt.getSAXLocator());
    // "Variable accessed before it is bound!", xctxt.getSAXLocator());

  // Lazy execution of variables.
  if (val.getType() == XObject.CLASS_UNRESOLVEDVARIABLE)
    return (_stackFrames[index] = val.execute(xctxt));

  return val;
}
 
Example 2
Source File: VariableStack.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Get a local variable or parameter in the current stack frame.
 *
 *
 * @param xctxt The XPath context, which must be passed in order to
 * lazy evaluate variables.
 *
 * @param index Local variable index relative to the current stack
 * frame bottom.
 *
 * @return The value of the variable.
 *
 * @throws TransformerException
 */
public XObject getLocalVariable(XPathContext xctxt, int index, boolean destructiveOK)
        throws TransformerException
{

  index += _currentFrameBottom;

  XObject val = _stackFrames[index];
  
  if(null == val)
    throw new TransformerException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_VARIABLE_ACCESSED_BEFORE_BIND, null),
                   xctxt.getSAXLocator());
    // "Variable accessed before it is bound!", xctxt.getSAXLocator());

  // Lazy execution of variables.
  if (val.getType() == XObject.CLASS_UNRESOLVEDVARIABLE)
    return (_stackFrames[index] = val.execute(xctxt));

  return destructiveOK ? val : val.getFresh();
}
 
Example 3
Source File: XalanXPathExecuter.java    From jasperreports with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public Object selectObject(Node contextNode, String expression) throws JRException {
	try {
		Object value;
		XObject object = xpathAPI.eval(contextNode, expression);
		switch (object.getType()) {
			case XObject.CLASS_NODESET:
				value = object.nodeset().nextNode();
				break;
			case XObject.CLASS_BOOLEAN:
				value = object.bool();
				break;
			case XObject.CLASS_NUMBER:
				value = object.num();
				break;
			default:
				value = object.str();
				break;
		}
		return value;
	} catch (TransformerException e) {
		throw 
			new JRException(
				EXCEPTION_MESSAGE_KEY_XPATH_SELECTION_FAILURE,
				new Object[]{expression},
				e);
	}
}
 
Example 4
Source File: XalanNsAwareXPathExecuter.java    From jasperreports with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public Object selectObject(Node contextNode, String expression)
		throws JRException {
	try {
		createNamespaceElement(contextNode, expression);
		Object value;
		XObject object = null; 
		if (namespaceElement != null) {	
			object = xpathAPI.eval(contextNode, expression, namespaceElement);
		} else {
			object = xpathAPI.eval(contextNode, expression);
		}
		switch (object.getType()) {
		case XObject.CLASS_NODESET:
			value = object.nodeset().nextNode();
			break;
		case XObject.CLASS_BOOLEAN:
			value = object.bool();
			break;
		case XObject.CLASS_NUMBER:
			value = object.num();
			break;
		default:
			value = object.str();
			break;
		}
		return value;
	} catch (TransformerException e) {
		throw 
			new JRException(
				EXCEPTION_MESSAGE_KEY_XPATH_SELECTION_FAILURE,
				new Object[]{expression},
				e);
	}
}
 
Example 5
Source File: ElemCopyOf.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * The xsl:copy-of element can be used to insert a result tree
 * fragment into the result tree, without first converting it to
 * a string as xsl:value-of does (see [7.6.1 Generating Text with
 * xsl:value-of]).
 *
 * @param transformer non-null reference to the the current transform-time state.
 *
 * @throws TransformerException
 */
public void execute(
        TransformerImpl transformer)
          throws TransformerException
{
  try
  {
    XPathContext xctxt = transformer.getXPathContext();
    int sourceNode = xctxt.getCurrentNode();
    XObject value = m_selectExpression.execute(xctxt, sourceNode, this);

    SerializationHandler handler = transformer.getSerializationHandler();

    if (null != value)
                      {
      int type = value.getType();
      String s;

      switch (type)
      {
      case XObject.CLASS_BOOLEAN :
      case XObject.CLASS_NUMBER :
      case XObject.CLASS_STRING :
        s = value.str();

        handler.characters(s.toCharArray(), 0, s.length());
        break;
      case XObject.CLASS_NODESET :

        // System.out.println(value);
        DTMIterator nl = value.iter();

        // Copy the tree.
        DTMTreeWalker tw = new TreeWalker2Result(transformer, handler);
        int pos;

        while (DTM.NULL != (pos = nl.nextNode()))
        {
          DTM dtm = xctxt.getDTMManager().getDTM(pos);
          short t = dtm.getNodeType(pos);

          // If we just copy the whole document, a startDoc and endDoc get 
          // generated, so we need to only walk the child nodes.
          if (t == DTM.DOCUMENT_NODE)
          {
            for (int child = dtm.getFirstChild(pos); child != DTM.NULL;
                 child = dtm.getNextSibling(child))
            {
              tw.traverse(child);
            }
          }
          else if (t == DTM.ATTRIBUTE_NODE)
          {
            SerializerUtils.addAttribute(handler, pos);
          }
          else
          {
            tw.traverse(pos);
          }
        }
        // nl.detach();
        break;
      case XObject.CLASS_RTREEFRAG :
        SerializerUtils.outputResultTreeFragment(
          handler, value, transformer.getXPathContext());
        break;
      default :
        
        s = value.str();

        handler.characters(s.toCharArray(), 0, s.length());
        break;
      }
    }
                      
    // I don't think we want this.  -sb
    //  if (transformer.getDebug())
    //  transformer.getTraceManager().fireSelectedEvent(sourceNode, this,
    //  "endSelect", m_selectExpression, value);

  }
  catch(org.xml.sax.SAXException se)
  {
    throw new TransformerException(se);
  }

}
 
Example 6
Source File: NodeSorter.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * Constructor NodeCompareElem
 *
 *
 * @param node Current node
 *
 * @throws javax.xml.transform.TransformerException
 */
NodeCompareElem(int node) throws javax.xml.transform.TransformerException
{
  m_node = node;

  if (!m_keys.isEmpty())
  {
    NodeSortKey k1 = (NodeSortKey) m_keys.elementAt(0);
    XObject r = k1.m_selectPat.execute(m_execContext, node,
                                       k1.m_namespaceContext);

    double d;

    if (k1.m_treatAsNumbers)
    {
      d = r.num();

      // Can't use NaN for compare. They are never equal. Use zero instead.  
      m_key1Value = new Double(d);
    }
    else
    {
      m_key1Value = k1.m_col.getCollationKey(r.str());
    }

    if (r.getType() == XObject.CLASS_NODESET)
    {
      // %REVIEW%
      DTMIterator ni = ((XNodeSet)r).iterRaw();
      int current = ni.getCurrentNode();
      if(DTM.NULL == current)
        current = ni.nextNode();

      // if (ni instanceof ContextNodeList) // %REVIEW%
      // tryNextKey = (DTM.NULL != current);

      // else abdicate... should never happen, but... -sb
    }

    if (m_keys.size() > 1)
    {
      NodeSortKey k2 = (NodeSortKey) m_keys.elementAt(1);

      XObject r2 = k2.m_selectPat.execute(m_execContext, node,
                                          k2.m_namespaceContext);

      if (k2.m_treatAsNumbers) {
        d = r2.num();
        m_key2Value = new Double(d);
      } else {
        m_key2Value = k2.m_col.getCollationKey(r2.str());
      }
    }

    /* Leave this in case we decide to use an array later
    while (kIndex <= m_keys.size() && kIndex < maxkey)
    {
      NodeSortKey k = (NodeSortKey)m_keys.elementAt(kIndex);
      XObject r = k.m_selectPat.execute(m_execContext, node, k.m_namespaceContext);
      if(k.m_treatAsNumbers)
        m_KeyValue[kIndex] = r.num();
      else
        m_KeyValue[kIndex] = r.str();
    } */
  }  // end if not empty    
}
 
Example 7
Source File: StepPattern.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * New Method to check whether the current node satisfies a position predicate
 *
 * @param xctxt The XPath runtime context.
 * @param predPos Which predicate we're evaluating of foo[1][2][3].
 * @param dtm The DTM of the current node.
 * @param context The currentNode.
 * @param pos The position being requested, i.e. the value returned by 
 *            m_predicates[predPos].execute(xctxt).
 *
 * @return true of the position of the context matches pos, false otherwise.
 */
private final boolean checkProximityPosition(XPathContext xctxt,
        int predPos, DTM dtm, int context, int pos)
{

  try
  {
    DTMAxisTraverser traverser =
      dtm.getAxisTraverser(Axis.PRECEDINGSIBLING);

    for (int child = traverser.first(context); DTM.NULL != child;
            child = traverser.next(context, child))
    {
      try
      {
        xctxt.pushCurrentNode(child);

        if (NodeTest.SCORE_NONE != super.execute(xctxt, child))
        {
          boolean pass = true;

          try
          {
            xctxt.pushSubContextList(this);

            for (int i = 0; i < predPos; i++)
            {
              xctxt.pushPredicatePos(i);
              try
              {
                XObject pred = m_predicates[i].execute(xctxt);
                
                try
                {
                  if (XObject.CLASS_NUMBER == pred.getType())
                  {
                    throw new Error("Why: Should never have been called");
                  }
                  else if (!pred.boolWithSideEffects())
                  {
                    pass = false;
  
                    break;
                  }
                }
                finally
                {
                  pred.detach();
                }
              }
              finally
              {
                xctxt.popPredicatePos();
              }
            }
          }
          finally
          {
            xctxt.popSubContextList();
          }

          if (pass)
            pos--;

          if (pos < 1)
            return false;
        }
      }
      finally
      {
        xctxt.popCurrentNode();
      }
    }
  }
  catch (javax.xml.transform.TransformerException se)
  {

    // TODO: should keep throw sax exception...
    throw new java.lang.RuntimeException(se.getMessage());
  }

  return (pos == 1);
}
 
Example 8
Source File: StepPattern.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * Execute the predicates on this step to determine if the current node 
 * should be filtered or accepted.
 *
 * @param xctxt The XPath runtime context.
 * @param dtm The DTM of the current node.
 * @param currentNode The current node context.
 *
 * @return true if the node should be accepted, false otherwise.
 *
 * @throws javax.xml.transform.TransformerException
 */
protected final boolean executePredicates(
        XPathContext xctxt, DTM dtm, int currentNode)
          throws javax.xml.transform.TransformerException
{

  boolean result = true;
  boolean positionAlreadySeen = false;
  int n = getPredicateCount();

  try
  {
    xctxt.pushSubContextList(this);

    for (int i = 0; i < n; i++)
    {
      xctxt.pushPredicatePos(i);

      try
      {
        XObject pred = m_predicates[i].execute(xctxt);

        try
        {
          if (XObject.CLASS_NUMBER == pred.getType())
          {
            int pos = (int) pred.num();

            if (positionAlreadySeen)
            {
              result = (pos == 1);

              break;
            }
            else
            {
              positionAlreadySeen = true;

              if (!checkProximityPosition(xctxt, i, dtm, currentNode, pos))
              {
                result = false;

                break;
              }
            }
          
          }
          else if (!pred.boolWithSideEffects())
          {
            result = false;

            break;
          }
        }
        finally
        {
          pred.detach();
        }
      }
      finally
      {
        xctxt.popPredicatePos();
      }
    }
  }
  finally
  {
    xctxt.popSubContextList();
  }

  return result;
}
 
Example 9
Source File: PredicatedNodeTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * Process the predicates.
 *
 * @param context The current context node.
 * @param xctxt The XPath runtime context.
 *
 * @return the result of executing the predicate expressions.
 *
 * @throws javax.xml.transform.TransformerException
 */
boolean executePredicates(int context, XPathContext xctxt)
        throws javax.xml.transform.TransformerException
{
  
  int nPredicates = getPredicateCount();
  // System.out.println("nPredicates: "+nPredicates);
  if (nPredicates == 0)
    return true;

  PrefixResolver savedResolver = xctxt.getNamespaceContext();

  try
  {
    m_predicateIndex = 0;
    xctxt.pushSubContextList(this);
    xctxt.pushNamespaceContext(m_lpi.getPrefixResolver());
    xctxt.pushCurrentNode(context);

    for (int i = 0; i < nPredicates; i++)
    {
      // System.out.println("Executing predicate expression - waiting count: "+m_lpi.getWaitingCount());
      XObject pred = m_predicates[i].execute(xctxt);
      // System.out.println("\nBack from executing predicate expression - waiting count: "+m_lpi.getWaitingCount());
      // System.out.println("pred.getType(): "+pred.getType());
      if (XObject.CLASS_NUMBER == pred.getType())
      {
        if (DEBUG_PREDICATECOUNTING)
        {
          System.out.flush();
          System.out.println("\n===== start predicate count ========");
          System.out.println("m_predicateIndex: " + m_predicateIndex);
          // System.out.println("getProximityPosition(m_predicateIndex): "
          //                   + getProximityPosition(m_predicateIndex));
          System.out.println("pred.num(): " + pred.num());
        }

        int proxPos = this.getProximityPosition(m_predicateIndex);
        int predIndex = (int) pred.num();
        if (proxPos != predIndex)
        {
          if (DEBUG_PREDICATECOUNTING)
          {
            System.out.println("\nnode context: "+nodeToString(context));
            System.out.println("index predicate is false: "+proxPos);
            System.out.println("\n===== end predicate count ========");
          }
          return false;
        }
        else if (DEBUG_PREDICATECOUNTING)
        {
          System.out.println("\nnode context: "+nodeToString(context));
          System.out.println("index predicate is true: "+proxPos);
          System.out.println("\n===== end predicate count ========");
        }
        
        // If there is a proximity index that will not change during the 
        // course of itteration, then we know there can be no more true 
        // occurances of this predicate, so flag that we're done after 
        // this.
        //
        // bugzilla 14365
        // We can't set m_foundLast = true unless we're sure that -all-
        // remaining parameters are stable, or else last() fails. Fixed so
        // only sets m_foundLast if on the last predicate
        if(m_predicates[i].isStableNumber() && i == nPredicates - 1)
        {
          m_foundLast = true;
        }
      }
      else if (!pred.bool())
        return false;

      countProximityPosition(++m_predicateIndex);
    }
  }
  finally
  {
    xctxt.popCurrentNode();
    xctxt.popNamespaceContext();
    xctxt.popSubContextList();
    m_predicateIndex = -1;
  }

  return true;
}
 
Example 10
Source File: Bool.java    From j2objc with Apache License 2.0 3 votes vote down vote up
/**
 * Apply the operation to two operands, and return the result.
 *
 *
 * @param right non-null reference to the evaluated right operand.
 *
 * @return non-null reference to the XObject that represents the result of the operation.
 *
 * @throws javax.xml.transform.TransformerException
 */
public XObject operate(XObject right) throws javax.xml.transform.TransformerException
{

  if (XObject.CLASS_BOOLEAN == right.getType())
    return right;
  else
    return right.bool() ? XBoolean.S_TRUE : XBoolean.S_FALSE;
}
 
Example 11
Source File: Number.java    From j2objc with Apache License 2.0 3 votes vote down vote up
/**
 * Apply the operation to two operands, and return the result.
 *
 *
 * @param right non-null reference to the evaluated right operand.
 *
 * @return non-null reference to the XObject that represents the result of the operation.
 *
 * @throws javax.xml.transform.TransformerException
 */
public XObject operate(XObject right) throws javax.xml.transform.TransformerException
{

  if (XObject.CLASS_NUMBER == right.getType())
    return right;
  else
    return new XNumber(right.num());
}
 
Example 12
Source File: VariableStack.java    From j2objc with Apache License 2.0 3 votes vote down vote up
/**
 * Get a global variable or parameter from the global stack frame.
 *
 *
 * @param xctxt The XPath context, which must be passed in order to
 * lazy evaluate variables.
 *
 * @param index Global variable index relative to the global stack
 * frame bottom.
 *
 * @return The value of the variable.
 *
 * @throws TransformerException
 */
public XObject getGlobalVariable(XPathContext xctxt, final int index)
        throws TransformerException
{

  XObject val = _stackFrames[index];

  // Lazy execution of variables.
  if (val.getType() == XObject.CLASS_UNRESOLVEDVARIABLE)
    return (_stackFrames[index] = val.execute(xctxt));

  return val;
}
 
Example 13
Source File: VariableStack.java    From j2objc with Apache License 2.0 3 votes vote down vote up
/**
 * Get a global variable or parameter from the global stack frame.
 *
 *
 * @param xctxt The XPath context, which must be passed in order to
 * lazy evaluate variables.
 *
 * @param index Global variable index relative to the global stack
 * frame bottom.
 *
 * @return The value of the variable.
 *
 * @throws TransformerException
 */
public XObject getGlobalVariable(XPathContext xctxt, final int index, boolean destructiveOK)
        throws TransformerException
{

  XObject val = _stackFrames[index];

  // Lazy execution of variables.
  if (val.getType() == XObject.CLASS_UNRESOLVEDVARIABLE)
    return (_stackFrames[index] = val.execute(xctxt));

  return destructiveOK ? val : val.getFresh();
}