stylesheetroot.java

来自「java jdk 1.4的源码」· Java 代码 · 共 1,336 行 · 第 1/3 页

JAVA
1,336
字号
/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 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 "Xalan" 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 apache@apache.org. * * 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 and was * originally based on software copyright (c) 1999, Lotus * Development Corporation., http://www.lotus.com.  For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */package org.apache.xalan.templates;// import org.w3c.dom.*;import org.apache.xml.dtm.DTM;import java.util.*;import java.net.MalformedURLException;import java.text.DecimalFormat;import java.text.DecimalFormatSymbols;import java.io.*;import org.xml.sax.*;import org.xml.sax.helpers.*;import org.apache.xalan.serialize.*;import org.apache.xml.utils.*;import org.apache.xpath.*;import org.apache.xpath.compiler.XPathParser;import org.apache.xalan.trace.*;import org.apache.xalan.res.XSLTErrorResources;import org.apache.xalan.res.XSLMessages;import org.apache.xalan.processor.XSLTSchema;import org.apache.xalan.transformer.TransformerImpl;import javax.xml.transform.Transformer;import javax.xml.transform.TransformerException;import javax.xml.transform.TransformerConfigurationException;import javax.xml.transform.Templates;import javax.xml.transform.OutputKeys;import javax.xml.transform.ErrorListener;import org.apache.xml.dtm.ref.ExpandedNameTable;//dmlimport org.apache.xml.utils.StringVector;import org.apache.xalan.extensions.ExtensionNamespaceSupport;import org.apache.xalan.extensions.ExtensionHandler;import org.apache.xalan.extensions.ExtensionNamespacesManager;/** * <meta name="usage" content="general"/> * This class represents the root object of the stylesheet tree. */public class StylesheetRoot extends StylesheetComposed        implements java.io.Serializable, Templates{  /**   * 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);    }  }  /**   * The schema used when creating this StylesheetRoot   * @serial   */  private Hashtable m_availElems;    /**   * Creates a StylesheetRoot and retains a pointer to the schema used to create this   * StylesheetRoot.  The schema may be needed later for an element-available() function call.   *    * @param schema The schema used to create this stylesheet   * @throws TransformerConfigurationException if the baseIdentifier can not be resolved to a URL.   */  public StylesheetRoot(XSLTSchema schema, ErrorListener listener) throws TransformerConfigurationException  {    this(listener);    m_availElems = schema.getElemsAvailable();  }  /**   * Tell if this is the root of the stylesheet tree.   *   * @return True since this is the root of the stylesheet tree.   */  public boolean isRoot()  {    return true;  }  /**   * Get the hashtable of available elements.   *   * @return table of available elements, keyed by qualified names, and with    * values of the same qualified names.   */  public Hashtable getAvailableElements()  {    return m_availElems;  }    private ExtensionNamespacesManager m_extNsMgr = null;    /**   * Only instantiate an ExtensionNamespacesManager if one is called for   * (i.e., if the stylesheet contains  extension functions and/or elements).   */  public ExtensionNamespacesManager getExtensionNamespacesManager()  {     if (m_extNsMgr == null)       m_extNsMgr = new ExtensionNamespacesManager();     return m_extNsMgr;  }    /**   * Get the vector of extension namespaces. Used to provide   * the extensions table access to a list of extension   * namespaces encountered during composition of a stylesheet.   */  public Vector getExtensions()  {    return m_extNsMgr != null ? m_extNsMgr.getExtensions() : null;  }  /*  public void runtimeInit(TransformerImpl transformer) throws TransformerException  {    System.out.println("StylesheetRoot.runtimeInit()");        //    try{throw new Exception("StylesheetRoot.runtimeInit()");} catch(Exception e){e.printStackTrace();}    }*/    //============== Templates Interface ================  /**   * Create a new transformation context for this Templates object.   *   * @return A Transformer instance, never null.   */  public Transformer newTransformer()  {    return new TransformerImpl(this);  }    public Properties getDefaultOutputProps()  {    return m_outputProperties.getProperties();  }    /**   * Get the static properties for xsl:output.  The object returned will   * be a clone of the internal values, and thus it can be mutated   * without mutating the Templates object, and then handed in to   * the process method.   *   * <p>For XSLT, Attribute Value Templates attribute values will   * be returned unexpanded (since there is no context at this point).</p>   *   * @return A Properties object, not null.   */  public Properties getOutputProperties()  {        return (Properties)getDefaultOutputProps().clone();  }  //============== End Templates Interface ================  /**   * Recompose the values of all "composed" properties, meaning   * properties that need to be combined or calculated from   * the combination of imported and included stylesheets.  This   * method determines the proper import precedence of all imported   * stylesheets.  It then iterates through all of the elements and    * properties in the proper order and triggers the individual recompose   * methods.   *   * @throws TransformerException   */  public void recompose() throws TransformerException  {    // Now we make a Vector that is going to hold all of the recomposable elements      Vector recomposableElements = new Vector();    // First, we build the global import tree.    if (null == m_globalImportList)    {      Vector importList = new Vector();      addImports(this, true, importList);                  // Now we create an array and reverse the order of the importList vector.      // We built the importList vector backwards so that we could use addElement      // to append to the end of the vector instead of constantly pushing new      // stylesheets onto the front of the vector and having to shift the rest      // of the vector each time.      m_globalImportList = new StylesheetComposed[importList.size()];      for (int i =  0, j= importList.size() -1; i < importList.size(); i++)      {          m_globalImportList[j] = (StylesheetComposed) importList.elementAt(i);        // Build the global include list for this stylesheet.        // This needs to be done ahead of the recomposeImports        // because we need the info from the composed includes.         m_globalImportList[j].recomposeIncludes(m_globalImportList[j]);        // Calculate the number of this import.            m_globalImportList[j--].recomposeImports();              }    }        // Next, we walk the import tree and add all of the recomposable elements to the vector.    int n = getGlobalImportCount();    for (int i = 0; i < n; i++)    {      StylesheetComposed imported = getGlobalImport(i);      imported.recompose(recomposableElements);    }    // We sort the elements into ascending order.    QuickSort2(recomposableElements, 0, recomposableElements.size() - 1);    // We set up the global variables that will hold the recomposed information.    m_outputProperties = new OutputProperties(Method.XML);        m_attrSets = new Hashtable();    m_decimalFormatSymbols = new Hashtable();    m_keyDecls = new Vector();    m_namespaceAliasComposed = new Hashtable();    m_templateList = new TemplateList();    m_variables = new Vector();    // Now we sequence through the sorted elements,     // calling the recompose() function on each one.  This will call back into the    // appropriate routine here to actually do the recomposition.    // Note that we're going backwards, encountering the highest precedence items first.    for (int i = recomposableElements.size() - 1; i >= 0; i--)      ((ElemTemplateElement) recomposableElements.elementAt(i)).recompose(this);        initComposeState();    // Need final composition of TemplateList.  This adds the wild cards onto the chains.    m_templateList.compose(this);        // Need to clear check for properties at the same import level.    m_outputProperties.compose(this);    m_outputProperties.endCompose(this);        // Now call the compose() method on every element to give it a chance to adjust    // based on composed values.        n = getGlobalImportCount();    for (int i = 0; i < n; i++)    {      StylesheetComposed imported = this.getGlobalImport(i);      int includedCount = imported.getIncludeCountComposed();      for (int j = -1; j < includedCount; j++)      {        Stylesheet included = imported.getIncludeComposed(j);        composeTemplates(included);      }    }    // Attempt to register any remaining unregistered extension namespaces.    if (m_extNsMgr != null)      m_extNsMgr.registerUnregisteredNamespaces();    clearComposeState();  }  /**   * Call the compose function for each ElemTemplateElement.   *   * @param templ non-null reference to template element that will have    * the composed method called on it, and will have it's children's composed    * methods called.   */  void composeTemplates(ElemTemplateElement templ) throws TransformerException  {    templ.compose(this);    for (ElemTemplateElement child = templ.getFirstChildElem();            child != null; child = child.getNextSiblingElem())    {      composeTemplates(child);    }        templ.endCompose(this);  }  /**   * The combined list of imports.  The stylesheet with the highest   * import precedence will be at element 0.  The one with the lowest   * import precedence will be at element length - 1.   * @serial   */  private StylesheetComposed[] m_globalImportList;  /**   * Add the imports in the given sheet to the working importList vector.   * The will be added from highest import precedence to   * least import precedence.  This is a post-order traversal of the   * import tree as described in <a href="http://www.w3.org/TR/xslt.html#import">the   * XSLT Recommendation</a>.   * <p>For example, suppose</p>   * <p>stylesheet A imports stylesheets B and C in that order;</p>   * <p>stylesheet B imports stylesheet D;</p>   * <p>stylesheet C imports stylesheet E.</p>   * <p>Then the order of import precedence (highest first) is   * A, C, E, B, D.</p>   *   * @param stylesheet Stylesheet to examine for imports.   * @param addToList  <code>true</code> if this template should be added to the import list   * @param importList The working import list.  Templates are added here in the reverse   *        order of priority.  When we're all done, we'll reverse this to the correct   *        priority in an array.   */  protected void addImports(Stylesheet stylesheet, boolean addToList, Vector importList)  {    // Get the direct imports of this sheet.    int n = stylesheet.getImportCount();    if (n > 0)    {      for (int i = 0; i < n; i++)      {        Stylesheet imported = stylesheet.getImport(i);        addImports(imported, true, importList);      }    }    n = stylesheet.getIncludeCount();    if (n > 0)    {      for (int i = 0; i < n; i++)      {        Stylesheet included = stylesheet.getInclude(i);        addImports(included, false, importList);      }    }    if (addToList)      importList.addElement(stylesheet);  }  /**   * Get a stylesheet from the global import list.    * TODO: JKESS PROPOSES SPECIAL-CASE FOR NO IMPORT LIST, TO MATCH COUNT.   *    * @param i Index of stylesheet to get from global import list    *   * @return The stylesheet at the given index    */  public StylesheetComposed getGlobalImport(int i)  {    return m_globalImportList[i];  }  /**   * Get the total number of imports in the global import list.   *    * @return The total number of imported stylesheets, including   * the root stylesheet, thus the number will always be 1 or   * greater.

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?