org.apache.xpath.XPath Java Examples

The following examples show how to use org.apache.xpath.XPath. 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: Variable.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/** 
 * Get the analysis bits for this walker, as defined in the WalkerFactory.
 * @return One of WalkerFactory#BIT_DESCENDANT, etc.
 */
public int getAnalysisBits()
{
	org.apache.xalan.templates.ElemVariable vvar = getElemVariable();
	if(null != vvar)
	{
		XPath xpath = vvar.getSelect();
		if(null != xpath)
		{
 		Expression expr = xpath.getExpression();
 		if(null != expr && expr instanceof PathComponent)
 		{
 			return ((PathComponent)expr).getAnalysisBits();
 		}
		}
	}
  return WalkerFactory.BIT_FILTER;
}
 
Example #2
Source File: ElemNumber.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Get the target node that will be counted..
 *
 * @param xctxt The XPath runtime state for this.
 * @param sourceNode non-null reference to the <a href="http://www.w3.org/TR/xslt#dt-current-node">current source node</a>.
 *
 * @return the target node that will be counted
 *
 * @throws TransformerException
 */
public int getTargetNode(XPathContext xctxt, int sourceNode)
        throws TransformerException
{

  int target = DTM.NULL;
  XPath countMatchPattern = getCountMatchPattern(xctxt, sourceNode);

  if (Constants.NUMBERLEVEL_ANY == m_level)
  {
    target = findPrecedingOrAncestorOrSelf(xctxt, m_fromMatchPattern,
                                           countMatchPattern, sourceNode,
                                           this);
  }
  else
  {
    target = findAncestor(xctxt, m_fromMatchPattern, countMatchPattern,
                          sourceNode, this);
  }

  return target;
}
 
Example #3
Source File: ElemWithParam.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * This function is called after everything else has been
 * recomposed, and allows the template to set remaining
 * values that may be based on some other property that
 * depends on recomposition.
 */
public void compose(StylesheetRoot sroot) throws TransformerException
{
  // See if we can reduce an RTF to a select with a string expression.
  if(null == m_selectPattern  
     && sroot.getOptimizer())
  {
    XPath newSelect = ElemVariable.rewriteChildToExpression(this);
    if(null != newSelect)
      m_selectPattern = newSelect;
  }
  m_qnameID = sroot.getComposeState().getQNameID(m_qname);
  super.compose(sroot);
  
  java.util.Vector vnames = sroot.getComposeState().getVariableNames();
  if(null != m_selectPattern)
    m_selectPattern.fixupVariables(vnames, sroot.getComposeState().getGlobalsSize());
    
  // m_index must be resolved by ElemApplyTemplates and ElemCallTemplate!
}
 
Example #4
Source File: RedundentExprEliminator.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
  * Create a psuedo variable reference that will represent the 
  * shared redundent XPath, for a local reduction.
  * 
  * @param uniquePseudoVarName The name of the new variable.
  * @param stylesheetRoot The broadest scope of where the variable 
  *        should be inserted, which must be a StylesheetRoot element in this case.
  * @param lpi The LocationPathIterator that the variable should represent.
  * @return null if the decl was not created, otherwise the new Pseudo var  
  *              element.
  */
 protected ElemVariable createGlobalPseudoVarDecl(QName uniquePseudoVarName,
                                          StylesheetRoot stylesheetRoot, 
                                          LocPathIterator lpi) 
       throws org.w3c.dom.DOMException 
 {
 	ElemVariable psuedoVar = new ElemVariable();
 	psuedoVar.setIsTopLevel(true);
XPath xpath = new XPath(lpi);
psuedoVar.setSelect(xpath);
psuedoVar.setName(uniquePseudoVarName);

Vector globalVars = stylesheetRoot.getVariablesAndParamsComposed();
psuedoVar.setIndex(globalVars.size());
globalVars.addElement(psuedoVar);
return psuedoVar;
 }
 
Example #5
Source File: RedundentExprEliminator.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Create a psuedo variable reference that will represent the 
 * shared redundent XPath, for a local reduction.
 * 
 * @param uniquePseudoVarName The name of the new variable.
 * @param psuedoVarRecipient The broadest scope of where the variable 
 * should be inserted, usually an xsl:template or xsl:for-each.
 * @param lpi The LocationPathIterator that the variable should represent.
 * @return null if the decl was not created, otherwise the new Pseudo var  
 *              element.
 */
protected ElemVariable createLocalPseudoVarDecl(QName uniquePseudoVarName,
                                         ElemTemplateElement psuedoVarRecipient, 
                                         LocPathIterator lpi) 
      throws org.w3c.dom.DOMException 
{
ElemVariable psuedoVar = new ElemVariablePsuedo();

XPath xpath = new XPath(lpi);
psuedoVar.setSelect(xpath);
psuedoVar.setName(uniquePseudoVarName);

ElemVariable var = addVarDeclToElem(psuedoVarRecipient, lpi, psuedoVar);

lpi.exprSetParent(var);

return var;
}
 
Example #6
Source File: ProcessorPreserveSpace.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
  * Receive notification of the start of an preserve-space element.
  *
  * @param handler The calling StylesheetHandler/TemplatesBuilder.
  * @param uri The Namespace URI, or the empty string if the
  *        element has no Namespace URI or if Namespace
  *        processing is not being performed.
  * @param localName The local name (without prefix), or the
  *        empty string if Namespace processing is not being
  *        performed.
  * @param rawName The raw XML 1.0 name (with prefix), or the
  *        empty string if raw names are not available.
  * @param attributes The attributes attached to the element.  If
  *        there are no attributes, it shall be an empty
  *        Attributes object.
  */
 public void startElement(
         StylesheetHandler handler, String uri, String localName, String rawName, 
         Attributes attributes)
           throws org.xml.sax.SAXException
 {
   Stylesheet thisSheet = handler.getStylesheet();
WhitespaceInfoPaths paths = new WhitespaceInfoPaths(thisSheet);
   setPropertiesFromAttributes(handler, rawName, attributes, paths);

   Vector xpaths = paths.getElements();

   for (int i = 0; i < xpaths.size(); i++)
   {
     WhiteSpaceInfo wsi = new WhiteSpaceInfo((XPath) xpaths.elementAt(i), false, thisSheet);
     wsi.setUid(handler.nextUid());

     thisSheet.setPreserveSpaces(wsi);
   }
   paths.clearElements();
 }
 
Example #7
Source File: StylesheetRoot.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Uses an XSL stylesheet document.
 * @throws TransformerConfigurationException if the baseIdentifier can not be resolved to a URL.
 */
public StylesheetRoot(ErrorListener errorListener) throws TransformerConfigurationException
{

  super(null);

  setStylesheetRoot(this);

  try
  {
    m_selectDefault = new XPath("node()", this, this, XPath.SELECT, errorListener);

    initDefaultRule(errorListener);
  }
  catch (TransformerException se)
  {
    throw new TransformerConfigurationException(XSLMessages.createMessage(XSLTErrorResources.ER_CANNOT_INIT_DEFAULT_TEMPLATES, null), se); //"Can't init default templates!", se);
  }
}
 
Example #8
Source File: XSLTAttributeDef.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Process an attribute string of type T_EXPR into
 * an XPath value.
 *
 * @param handler non-null reference to current StylesheetHandler that is constructing the Templates.
 * @param uri The Namespace URI, or an empty string.
 * @param name The local name (without prefix), or empty string if not namespace processing.
 * @param rawName The qualified name (with prefix).
 * @param value An XSLT expression string.
 *
 * @return an XPath object that may be used for evaluation.
 *
 * @throws org.xml.sax.SAXException that wraps a
 * {@link javax.xml.transform.TransformerException} if the expression
 * string contains a syntax error.
 */
Object processEXPR(
        StylesheetHandler handler, String uri, String name, String rawName, String value,
        ElemTemplateElement owner)
          throws org.xml.sax.SAXException
{

  try
  {
    XPath expr = handler.createXPath(value, owner);

    return expr;
  }
  catch (TransformerException te)
  {
    throw new org.xml.sax.SAXException(te);
  }
}
 
Example #9
Source File: XSLTAttributeDef.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Process an attribute string of type T_PATTERN into
 * an XPath match pattern value.
 *
 * @param handler non-null reference to current StylesheetHandler that is constructing the Templates.
 * @param uri The Namespace URI, or an empty string.
 * @param name The local name (without prefix), or empty string if not namespace processing.
 * @param rawName The qualified name (with prefix).
 * @param value A match pattern string.
 *
 * @return An XPath pattern that may be used to evaluate the XPath.
 *
 * @throws org.xml.sax.SAXException that wraps a
 * {@link javax.xml.transform.TransformerException} if the match pattern
 * string contains a syntax error.
 */
Object processPATTERN(
        StylesheetHandler handler, String uri, String name, String rawName, String value,
        ElemTemplateElement owner)
          throws org.xml.sax.SAXException
{

  try
  {
    XPath pattern = handler.createMatchPatternXPath(value, owner);

    return pattern;
  }
  catch (TransformerException te)
  {
    throw new org.xml.sax.SAXException(te);
  }
}
 
Example #10
Source File: TemplateList.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Given a match pattern and template association, return the 
 * score of that match.  This score or priority can always be 
 * statically calculated.
 *
 * @param matchPat The match pattern to template association.
 *
 * @return {@link org.apache.xpath.patterns.NodeTest#SCORE_NODETEST}, 
 *         {@link org.apache.xpath.patterns.NodeTest#SCORE_NONE}, 
 *         {@link org.apache.xpath.patterns.NodeTest#SCORE_NSWILD}, 
 *         {@link org.apache.xpath.patterns.NodeTest#SCORE_QNAME}, or
 *         {@link org.apache.xpath.patterns.NodeTest#SCORE_OTHER}, or 
 *         the value defined by the priority attribute of the template.
 *
 */
private double getPriorityOrScore(TemplateSubPatternAssociation matchPat)
{

  double priority = matchPat.getTemplate().getPriority();

  if (priority == XPath.MATCH_SCORE_NONE)
  {
    Expression ex = matchPat.getStepPattern();

    if (ex instanceof NodeTest)
    {
      return ((NodeTest) ex).getDefaultScore();
    }
  }

  return priority;
}
 
Example #11
Source File: ProcessorStripSpace.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
  * Receive notification of the start of an strip-space element.
  *
  * @param handler The calling StylesheetHandler/TemplatesBuilder.
  * @param uri The Namespace URI, or the empty string if the
  *        element has no Namespace URI or if Namespace
  *        processing is not being performed.
  * @param localName The local name (without prefix), or the
  *        empty string if Namespace processing is not being
  *        performed.
  * @param rawName The raw XML 1.0 name (with prefix), or the
  *        empty string if raw names are not available.
  * @param attributes The attributes attached to the element.  If
  *        there are no attributes, it shall be an empty
  *        Attributes object.
  */
 public void startElement(
         StylesheetHandler handler, String uri, String localName, String rawName, Attributes attributes)
           throws org.xml.sax.SAXException
 {
   Stylesheet thisSheet = handler.getStylesheet();
WhitespaceInfoPaths paths = new WhitespaceInfoPaths(thisSheet);
   setPropertiesFromAttributes(handler, rawName, attributes, paths);

   Vector xpaths = paths.getElements();

   for (int i = 0; i < xpaths.size(); i++)
   {
     WhiteSpaceInfo wsi = new WhiteSpaceInfo((XPath) xpaths.elementAt(i), true, thisSheet);
     wsi.setUid(handler.nextUid());

     thisSheet.setStripSpaces(wsi);
   }
   paths.clearElements();

 }
 
Example #12
Source File: StylesheetHandler.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Process an expression string into an XPath.
 *
 * @param str A non-null reference to a valid or invalid match pattern string.
 *
 * @return A non-null reference to an XPath object that represents the string argument.
 *
 * @throws javax.xml.transform.TransformerException if the pattern can not be processed.
 * @see <a href="http://www.w3.org/TR/xslt#patterns">Section 5.2 Patterns in XSLT Specification</a>
 */
XPath createMatchPatternXPath(String str, ElemTemplateElement owningTemplate)
        throws javax.xml.transform.TransformerException
{
  ErrorListener handler = m_stylesheetProcessor.getErrorListener();
  XPath xpath = new XPath(str, owningTemplate, this, XPath.MATCH, handler, 
      m_funcTable);
  // Visit the expression, registering namespaces for any extension functions it includes.
  xpath.callVisitors(xpath, new ExpressionVisitor(getStylesheetRoot()));
  return xpath;    
}
 
Example #13
Source File: ElemVariable.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * This function is called after everything else has been
 * recomposed, and allows the template to set remaining
 * values that may be based on some other property that
 * depends on recomposition.
 */
public void compose(StylesheetRoot sroot) throws TransformerException
{
  // See if we can reduce an RTF to a select with a string expression.
  if(null == m_selectPattern  
     && sroot.getOptimizer())
  {
    XPath newSelect = rewriteChildToExpression(this);
    if(null != newSelect)
      m_selectPattern = newSelect;
  }
  
  StylesheetRoot.ComposeState cstate = sroot.getComposeState();
  
  // This should be done before addVariableName, so we don't have visibility 
  // to the variable now being defined.
  java.util.Vector vnames = cstate.getVariableNames();
  if(null != m_selectPattern)
    m_selectPattern.fixupVariables(vnames, cstate.getGlobalsSize());
    
  // Only add the variable if this is not a global.  If it is a global, 
  // it was already added by stylesheet root.
  if(!(m_parentNode instanceof Stylesheet) && m_qname != null)
  {
    m_index = cstate.addVariableName(m_qname) - cstate.getGlobalsSize();
  }
  else if (m_parentNode instanceof Stylesheet)
  {
  	// If this is a global, then we need to treat it as if it's a xsl:template, 
  	// and count the number of variables it contains.  So we set the count to 
  	// zero here.
cstate.resetStackFrameSize();
  }
  
  // This has to be done after the addVariableName, so that the variable 
  // pushed won't be immediately popped again in endCompose.
  super.compose(sroot);
}
 
Example #14
Source File: XSLTAttributeDef.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Process an attribute string of type T_SIMPLEPATTERNLIST into
 * a vector of XPath match patterns.
 *
 * @param handler non-null reference to current StylesheetHandler that is constructing the Templates.
 * @param uri The Namespace URI, or an empty string.
 * @param name The local name (without prefix), or empty string if not namespace processing.
 * @param rawName The qualified name (with prefix).
 * @param value A whitespace delimited list of simple match patterns.
 *
 * @return A Vector of XPath objects.
 *
 * @throws org.xml.sax.SAXException that wraps a
 * {@link javax.xml.transform.TransformerException} if one of the match pattern
 * strings contains a syntax error.
 */
Vector processSIMPLEPATTERNLIST(
        StylesheetHandler handler, String uri, String name, String rawName, String value,
        ElemTemplateElement owner)
          throws org.xml.sax.SAXException
{

  try
  {
    StringTokenizer tokenizer = new StringTokenizer(value, " \t\n\r\f");
    int nPatterns = tokenizer.countTokens();
    Vector patterns = new Vector(nPatterns);

    for (int i = 0; i < nPatterns; i++)
    {
      XPath pattern =
        handler.createMatchPatternXPath(tokenizer.nextToken(), owner);

      patterns.addElement(pattern);
    }

    return patterns;
  }
  catch (TransformerException te)
  {
    throw new org.xml.sax.SAXException(te);
  }
}
 
Example #15
Source File: ElemValueOf.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Set the "select" attribute.
 * The required select attribute is an expression; this expression
 * is evaluated and the resulting object is converted to a
 * string as if by a call to the string function.
 *
 * @param v The value to set for the "select" attribute.
 */
public void setSelect(XPath v)
{

  if (null != v)
  {
    String s = v.getPatternString();

    m_isDot = (null != s) && s.equals(".");
  }

  m_selectExpression = v;
}
 
Example #16
Source File: SqlXmlHelperXalan.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Take the received string, which is an XML query expression, compile it, and
 * store the compiled query locally. Note that for now, we only support XPath
 * because that's what Xalan supports.
 * 
 * @param queryExpr
 *          The XPath expression to compile
 */
public void compileXQExpr(final String queryExpr, final String opName,
    final DocumentBuilder dBuilder) throws StandardException {
  try {

    /* The following XPath constructor compiles the expression
     * as part of the construction process.  We have to pass
     * in a PrefixResolver object in order to avoid NPEs when
     * invalid/unknown functions are used, so we just create
     * a dummy one, which means prefixes will not be resolved
     * in the query (Xalan will just throw an error if a prefix
     * is used).  In the future we may want to revisit this
     * to make it easier for users to query based on namespaces.
     */
    query = new XPath(queryExpr, null, new PrefixResolverDefault(
        dBuilder.newDocument()), XPath.SELECT);

  } catch (Throwable te) {

    /* Something went wrong during compilation of the
     * expression; wrap the error and re-throw it.
     * Note: we catch "Throwable" here to catch as many
     * Xalan-produced errors as possible in order to
     * minimize the chance of an uncaught Xalan error
     * (such as a NullPointerException) causing Derby
     * to fail in a more serious way.  In particular, an
     * uncaught Java exception like NPE can result in
     * Derby throwing "ERROR 40XT0: An internal error was
     * identified by RawStore module" for all statements on
     * the connection after the failure--which we clearly
     * don't want.  If we catch the error and wrap it,
     * though, the statement will fail but Derby will
     * continue to run as normal. 
     */
    throw StandardException.newException(SQLState.LANG_XML_QUERY_ERROR, te,
        opName, te.getMessage());

  }
}
 
Example #17
Source File: ElemNumber.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Given a 'from' pattern (ala xsl:number), a match pattern
 * and a context, find the first ancestor that matches the
 * pattern (including the context handed in).
 *
 * @param xctxt The XPath runtime state for this.
 * @param fromMatchPattern The ancestor must match this pattern.
 * @param countMatchPattern The ancestor must also match this pattern.
 * @param context The node that "." expresses.
 * @param namespaceContext The context in which namespaces in the
 * queries are supposed to be expanded.
 *
 * @return the first ancestor that matches the given pattern
 *
 * @throws javax.xml.transform.TransformerException
 */
int findAncestor(
        XPathContext xctxt, XPath fromMatchPattern, XPath countMatchPattern, 
        int context, ElemNumber namespaceContext)
          throws javax.xml.transform.TransformerException
{
  DTM dtm = xctxt.getDTM(context);
  while (DTM.NULL != context)
  {
    if (null != fromMatchPattern)
    {
      if (fromMatchPattern.getMatchScore(xctxt, context)
              != XPath.MATCH_SCORE_NONE)
      {

        //context = null;
        break;
      }
    }

    if (null != countMatchPattern)
    {
      if (countMatchPattern.getMatchScore(xctxt, context)
              != XPath.MATCH_SCORE_NONE)
      {
        break;
      }
    }

    context = dtm.getParent(context);
  }

  return context;
}
 
Example #18
Source File: SqlXmlHelperXalan.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Take the received string, which is an XML query expression, compile it, and
 * store the compiled query locally. Note that for now, we only support XPath
 * because that's what Xalan supports.
 * 
 * @param queryExpr
 *          The XPath expression to compile
 */
public void compileXQExpr(final String queryExpr, final String opName,
    final DocumentBuilder dBuilder) throws StandardException {
  try {

    /* The following XPath constructor compiles the expression
     * as part of the construction process.  We have to pass
     * in a PrefixResolver object in order to avoid NPEs when
     * invalid/unknown functions are used, so we just create
     * a dummy one, which means prefixes will not be resolved
     * in the query (Xalan will just throw an error if a prefix
     * is used).  In the future we may want to revisit this
     * to make it easier for users to query based on namespaces.
     */
    query = new XPath(queryExpr, null, new PrefixResolverDefault(
        dBuilder.newDocument()), XPath.SELECT);

  } catch (Throwable te) {

    /* Something went wrong during compilation of the
     * expression; wrap the error and re-throw it.
     * Note: we catch "Throwable" here to catch as many
     * Xalan-produced errors as possible in order to
     * minimize the chance of an uncaught Xalan error
     * (such as a NullPointerException) causing Derby
     * to fail in a more serious way.  In particular, an
     * uncaught Java exception like NPE can result in
     * Derby throwing "ERROR 40XT0: An internal error was
     * identified by RawStore module" for all statements on
     * the connection after the failure--which we clearly
     * don't want.  If we catch the error and wrap it,
     * though, the statement will fail but Derby will
     * continue to run as normal. 
     */
    throw StandardException.newException(SQLState.LANG_XML_QUERY_ERROR, te,
        opName, te.getMessage());

  }
}
 
Example #19
Source File: ElemForEach.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Set the "select" attribute.
 *
 * @param xpath The XPath expression for the "select" attribute.
 */
public void setSelect(XPath xpath)
{
  m_selectExpression = xpath.getExpression();
  
  // The following line is part of the codes added to fix bug#16889
  // Store xpath which will be needed when firing Selected Event
  m_xpath = xpath;    
}
 
Example #20
Source File: KeyIterator.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 *  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 testNode  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 testNode)
{
  boolean foundKey = false;
  KeyIterator ki = (KeyIterator) m_lpi;
  org.apache.xpath.XPathContext xctxt = ki.getXPathContext();
  Vector keys = ki.getKeyDeclarations();

  QName name = ki.getName();
  try
  {
    // System.out.println("lookupKey: "+lookupKey);
    int nDeclarations = keys.size();

    // Walk through each of the declarations made with xsl:key
    for (int i = 0; i < nDeclarations; i++)
    {
      KeyDeclaration kd = (KeyDeclaration) keys.elementAt(i);

      // Only continue if the name on this key declaration
      // matches the name on the iterator for this walker. 
      if (!kd.getName().equals(name))
        continue;

      foundKey = true;
      // xctxt.setNamespaceContext(ki.getPrefixResolver());

      // See if our node matches the given key declaration according to 
      // the match attribute on xsl:key.
      XPath matchExpr = kd.getMatch();
      double score = matchExpr.getMatchScore(xctxt, testNode);

      if (score == kd.getMatch().MATCH_SCORE_NONE)
        continue;

      return DTMIterator.FILTER_ACCEPT;

    } // end for(int i = 0; i < nDeclarations; i++)
  }
  catch (TransformerException se)
  {

    // TODO: What to do?
  }

  if (!foundKey)
    throw new RuntimeException(
      XSLMessages.createMessage(
        XSLTErrorResources.ER_NO_XSLKEY_DECLARATION,
        new Object[] { name.getLocalName()}));
        
  return DTMIterator.FILTER_REJECT;
}
 
Example #21
Source File: NodeSortKey.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * Constructor NodeSortKey
 *
 *
 * @param transformer non null transformer instance
 * @param selectPat Select pattern for this key 
 * @param treatAsNumbers Flag indicating whether the result will be a number
 * @param descending Flag indicating whether to sort in descending order
 * @param langValue Lang value to use to get locale
 * @param caseOrderUpper Flag indicating whether case is relevant
 * @param namespaceContext Prefix resolver
 *
 * @throws javax.xml.transform.TransformerException
 */
NodeSortKey(
        TransformerImpl transformer, XPath selectPat, boolean treatAsNumbers, 
        boolean descending, String langValue, boolean caseOrderUpper, 
        org.apache.xml.utils.PrefixResolver namespaceContext)
          throws javax.xml.transform.TransformerException
{

  m_processor = transformer;
  m_namespaceContext = namespaceContext;
  m_selectPat = selectPat;
  m_treatAsNumbers = treatAsNumbers;
  m_descending = descending;
  m_caseOrderUpper = caseOrderUpper;

  if (null != langValue && m_treatAsNumbers == false)
  {
    // See http://nagoya.apache.org/bugzilla/show_bug.cgi?id=2851
    // The constructor of Locale is defined as 
    //   public Locale(String language, String country)
    // with
    //   language - lowercase two-letter ISO-639 code
    //   country - uppercase two-letter ISO-3166 code
    // a) language must be provided as a lower-case ISO-code 
    //    instead of an upper-case code
    // b) country must be provided as an ISO-code 
    //    instead of a full localized country name (e.g. "France")
    m_locale = new Locale(langValue.toLowerCase(), 
                Locale.getDefault().getCountry());
                
    // (old, before bug report 2851).
    //  m_locale = new Locale(langValue.toUpperCase(),
    //                        Locale.getDefault().getDisplayCountry());                    

    if (null == m_locale)
    {

      // m_processor.warn("Could not find locale for <sort xml:lang="+langValue);
      m_locale = Locale.getDefault();
    }
  }
  else
  {
    m_locale = Locale.getDefault();
  }

  m_col = Collator.getInstance(m_locale);

  if (null == m_col)
  {
    m_processor.getMsgMgr().warn(null, XSLTErrorResources.WG_CANNOT_FIND_COLLATOR,
                                 new Object[]{ langValue });  //"Could not find Collator for <sort xml:lang="+langValue);

    m_col = Collator.getInstance();
  }
}
 
Example #22
Source File: TemplateList.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * Add a template to the table of named templates and/or the table of templates
 * with match patterns.  This routine should
 * be called in decreasing order of precedence but it checks nonetheless.
 *
 * @param template
 */
public void setTemplate(ElemTemplate template)
{
  XPath matchXPath = template.getMatch();
  
  if (null == template.getName() && null == matchXPath)
  {  
    template.error(XSLTErrorResources.ER_NEED_NAME_OR_MATCH_ATTRIB,
        new Object[]{ "xsl:template" });
  }
  
  if (null != template.getName())
  {
    ElemTemplate existingTemplate = (ElemTemplate) m_namedTemplates.get(template.getName());
    if (null == existingTemplate)
    {
      m_namedTemplates.put(template.getName(), template);
    }
    else
    {
      int existingPrecedence =
                      existingTemplate.getStylesheetComposed().getImportCountComposed();
      int newPrecedence = template.getStylesheetComposed().getImportCountComposed();
      if (newPrecedence > existingPrecedence)
      {
        // This should never happen
        m_namedTemplates.put(template.getName(), template);
      }
      else if (newPrecedence == existingPrecedence)
        template.error(XSLTErrorResources.ER_DUPLICATE_NAMED_TEMPLATE,
                     new Object[]{ template.getName() });
    }
  }

  

  if (null != matchXPath)
  {
    Expression matchExpr = matchXPath.getExpression();

    if (matchExpr instanceof StepPattern)
    {
      insertPatternInTable((StepPattern) matchExpr, template);
    }
    else if (matchExpr instanceof UnionPattern)
    {
      UnionPattern upat = (UnionPattern) matchExpr;
      StepPattern[] pats = upat.getPatterns();
      int n = pats.length;

      for (int i = 0; i < n; i++)
      {
        insertPatternInTable(pats[i], template);
      }
    }
    else
    {

      // TODO: assert error
    }
  }
}
 
Example #23
Source File: XSLTAttributeDef.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * Get the primative type for the class, if there
 * is one.  If the class is a Double, for instance,
 * this will return double.class.  If the class is not one
 * of the 9 primative types, it will return the same
 * class that was passed in.
 *
 * @param obj The object which will be resolved to a primative class object if possible.
 *
 * @return The most primative class representation possible for the object, never null.
 */
private Class getPrimativeClass(Object obj)
{

  if (obj instanceof XPath)
    return XPath.class;

  Class cl = obj.getClass();

  if (cl == Double.class)
  {
    cl = double.class;
  }

  if (cl == Float.class)
  {
    cl = float.class;
  }
  else if (cl == Boolean.class)
  {
    cl = boolean.class;
  }
  else if (cl == Byte.class)
  {
    cl = byte.class;
  }
  else if (cl == Character.class)
  {
    cl = char.class;
  }
  else if (cl == Short.class)
  {
    cl = short.class;
  }
  else if (cl == Integer.class)
  {
    cl = int.class;
  }
  else if (cl == Long.class)
  {
    cl = long.class;
  }

  return cl;
}
 
Example #24
Source File: ElemNumber.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * Given a 'from' pattern (ala xsl:number), a match pattern
 * and a context, find the first ancestor that matches the
 * pattern (including the context handed in).
 * @param xctxt The XPath runtime state for this.
 * @param fromMatchPattern The ancestor must match this pattern.
 * @param countMatchPattern The ancestor must also match this pattern.
 * @param context The node that "." expresses.
 * @param namespaceContext The context in which namespaces in the
 * queries are supposed to be expanded.
 *
 * @return the first preceding, ancestor or self node that 
 * matches the given pattern
 *
 * @throws javax.xml.transform.TransformerException
 */
private int findPrecedingOrAncestorOrSelf(
        XPathContext xctxt, XPath fromMatchPattern, XPath countMatchPattern, 
        int context, ElemNumber namespaceContext)
          throws javax.xml.transform.TransformerException
{
  DTM dtm = xctxt.getDTM(context);
  while (DTM.NULL != context)
  {
    if (null != fromMatchPattern)
    {
      if (fromMatchPattern.getMatchScore(xctxt, context)
              != XPath.MATCH_SCORE_NONE)
      {
        context = DTM.NULL;

        break;
      }
    }

    if (null != countMatchPattern)
    {
      if (countMatchPattern.getMatchScore(xctxt, context)
              != XPath.MATCH_SCORE_NONE)
      {
        break;
      }
    }

    int prevSibling = dtm.getPreviousSibling(context);

    if (DTM.NULL == prevSibling)
    {
      context = dtm.getParent(context);
    }
    else
    {

      // Now go down the chain of children of this sibling 
      context = dtm.getLastChild(prevSibling);

      if (context == DTM.NULL)
        context = prevSibling;
    }
  }

  return context;
}
 
Example #25
Source File: ElemNumber.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * Get the previous node to be counted.
 *
 * @param xctxt The XPath runtime state for this.
 * @param pos The current node
 *
 * @return the previous node to be counted.
 *
 * @throws TransformerException
 */
public int getPreviousNode(XPathContext xctxt, int pos)
        throws TransformerException
{

  XPath countMatchPattern = getCountMatchPattern(xctxt, pos);
  DTM dtm = xctxt.getDTM(pos);

  if (Constants.NUMBERLEVEL_ANY == m_level)
  {
    XPath fromMatchPattern = m_fromMatchPattern;

    // Do a backwards document-order walk 'till a node is found that matches 
    // the 'from' pattern, or a node is found that matches the 'count' pattern, 
    // or the top of the tree is found.
    while (DTM.NULL != pos)
    {

      // Get the previous sibling, if there is no previous sibling, 
      // then count the parent, but if there is a previous sibling, 
      // dive down to the lowest right-hand (last) child of that sibling.
      int next = dtm.getPreviousSibling(pos);

      if (DTM.NULL == next)
      {
        next = dtm.getParent(pos);

        if ((DTM.NULL != next) && ((((null != fromMatchPattern) && (fromMatchPattern.getMatchScore(
                xctxt, next) != XPath.MATCH_SCORE_NONE))) 
            || (dtm.getNodeType(next) == DTM.DOCUMENT_NODE)))
        {
          pos = DTM.NULL;  // return null from function.

          break;  // from while loop
        }
      }
      else
      {

        // dive down to the lowest right child.
        int child = next;

        while (DTM.NULL != child)
        {
          child = dtm.getLastChild(next);

          if (DTM.NULL != child)
            next = child;
        }
      }

      pos = next;

      if ((DTM.NULL != pos)
              && ((null == countMatchPattern)
                  || (countMatchPattern.getMatchScore(xctxt, pos)
                      != XPath.MATCH_SCORE_NONE)))
      {
        break;
      }
    }
  }
  else  // NUMBERLEVEL_MULTI or NUMBERLEVEL_SINGLE
  {
    while (DTM.NULL != pos)
    {
      pos = dtm.getPreviousSibling(pos);

      if ((DTM.NULL != pos)
              && ((null == countMatchPattern)
                  || (countMatchPattern.getMatchScore(xctxt, pos)
                      != XPath.MATCH_SCORE_NONE)))
      {
        break;
      }
    }
  }

  return pos;
}
 
Example #26
Source File: ElemVariable.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * If the children of a variable is a single xsl:value-of or text literal, 
 * it is cheaper to evaluate this as an expression, so try and adapt the 
 * child an an expression.
 *
 * @param varElem Should be a ElemParam, ElemVariable, or ElemWithParam.
 *
 * @return An XPath if rewrite is possible, else null.
 *
 * @throws TransformerException
 */
static XPath rewriteChildToExpression(ElemTemplateElement varElem)
        throws TransformerException
{

  ElemTemplateElement t = varElem.getFirstChildElem();

  // Down the line this can be done with multiple string objects using 
  // the concat function.
  if (null != t && null == t.getNextSiblingElem())
  {
    int etype = t.getXSLToken();

    if (Constants.ELEMNAME_VALUEOF == etype)
    {
      ElemValueOf valueof = (ElemValueOf) t;

      // %TBD% I'm worried about extended attributes here.
      if (valueof.getDisableOutputEscaping() == false
              && valueof.getDOMBackPointer() == null)
      {
        varElem.m_firstChild = null;

        return new XPath(new XRTreeFragSelectWrapper(valueof.getSelect().getExpression()));
      }
    }
    else if (Constants.ELEMNAME_TEXTLITERALRESULT == etype)
    {
      ElemTextLiteral lit = (ElemTextLiteral) t;

      if (lit.getDisableOutputEscaping() == false
              && lit.getDOMBackPointer() == null)
      {
        String str = lit.getNodeValue();
        XString xstr = new XString(str);

        varElem.m_firstChild = null;

        return new XPath(new XRTreeFragSelectWrapper(xstr));
      }
    }
  }

  return null;
}
 
Example #27
Source File: ElemNumber.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * Get the ancestors, up to the root, that match the
 * pattern.
 * 
 * @param xctxt The XPath runtime state for this.
 * @param node Count this node and it's ancestors.
 * @param stopAtFirstFound Flag indicating to stop after the
 * first node is found (difference between level = single
 * or multiple)
 * @return The number of ancestors that match the pattern.
 *
 * @throws javax.xml.transform.TransformerException
 */
NodeVector getMatchingAncestors(
        XPathContext xctxt, int node, boolean stopAtFirstFound)
          throws javax.xml.transform.TransformerException
{

  NodeSetDTM ancestors = new NodeSetDTM(xctxt.getDTMManager());
  XPath countMatchPattern = getCountMatchPattern(xctxt, node);
  DTM dtm = xctxt.getDTM(node);

  while (DTM.NULL != node)
  {
    if ((null != m_fromMatchPattern)
            && (m_fromMatchPattern.getMatchScore(xctxt, node)
                != XPath.MATCH_SCORE_NONE))
    {

      // The following if statement gives level="single" different 
      // behavior from level="multiple", which seems incorrect according 
      // to the XSLT spec.  For now we are leaving this in to replicate 
      // the same behavior in XT, but, for all intents and purposes we 
      // think this is a bug, or there is something about level="single" 
      // that we still don't understand.
      if (!stopAtFirstFound)
        break;
    }

    if (null == countMatchPattern)
      System.out.println(
        "Programmers error! countMatchPattern should never be null!");

    if (countMatchPattern.getMatchScore(xctxt, node)
            != XPath.MATCH_SCORE_NONE)
    {
      ancestors.addElement(node);

      if (stopAtFirstFound)
        break;
    }

    node = dtm.getParent(node);
  }

  return ancestors;
}
 
Example #28
Source File: WhiteSpaceInfo.java    From j2objc with Apache License 2.0 3 votes vote down vote up
/**
 * Constructor WhiteSpaceInfo
 *
 *
 * @param matchPattern Match pattern
 * @param shouldStripSpace Flag indicating whether or not
 * to strip whitespaces
 * @param thisSheet The current stylesheet
 */
public WhiteSpaceInfo(XPath matchPattern, boolean shouldStripSpace, Stylesheet thisSheet)
{

  m_shouldStripSpace = shouldStripSpace;

  setMatch(matchPattern);

  setStylesheet(thisSheet);
}
 
Example #29
Source File: ElemSort.java    From j2objc with Apache License 2.0 3 votes vote down vote up
/**
 * Set the "select" attribute.
 * xsl:sort has a select attribute whose value is an expression.
 * For each node to be processed, the expression is evaluated
 * with that node as the current node and with the complete
 * list of nodes being processed in unsorted order as the current
 * node list. The resulting object is converted to a string as if
 * by a call to the string function; this string is used as the
 * sort key for that node. The default value of the select attribute
 * is ., which will cause the string-value of the current node to
 * be used as the sort key.
 *
 * @param v Value to set for the "select" attribute
 */
public void setSelect(XPath v)
{

  if (v.getPatternString().indexOf("{") < 0)
    m_selectExpression = v;
  else
    error(XSLTErrorResources.ER_NO_CURLYBRACE, null);
}
 
Example #30
Source File: StylesheetHandler.java    From j2objc with Apache License 2.0 3 votes vote down vote up
/**
 * Process an expression string into an XPath.
 * Must be public for access by the AVT class.
 *
 * @param str A non-null reference to a valid or invalid XPath expression string.
 *
 * @return A non-null reference to an XPath object that represents the string argument.
 *
 * @throws javax.xml.transform.TransformerException if the expression can not be processed.
 * @see <a href="http://www.w3.org/TR/xslt#section-Expressions">Section 4 Expressions in XSLT Specification</a>
 */
public XPath createXPath(String str, ElemTemplateElement owningTemplate)
        throws javax.xml.transform.TransformerException
{
  ErrorListener handler = m_stylesheetProcessor.getErrorListener();
  XPath xpath = new XPath(str, owningTemplate, this, XPath.SELECT, handler, 
          m_funcTable);
  // Visit the expression, registering namespaces for any extension functions it includes.
  xpath.callVisitors(xpath, new ExpressionVisitor(getStylesheetRoot()));
  return xpath;
}