stylesheethandler.java

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

JAVA
1,722
字号
/* * 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.processor;import java.net.URL;import java.io.IOException;import javax.xml.transform.sax.TemplatesHandler;import javax.xml.transform.Templates;import javax.xml.transform.TransformerException;import javax.xml.transform.TransformerConfigurationException;import java.util.Stack;import org.apache.xalan.res.XSLMessages;import org.apache.xalan.res.XSLTErrorResources;import org.apache.xalan.templates.Constants;import org.apache.xalan.templates.ElemTemplateElement;import org.apache.xalan.templates.ElemUnknown;import org.apache.xalan.templates.ElemForEach;import org.apache.xalan.templates.StylesheetRoot;import org.apache.xalan.templates.Stylesheet;import org.apache.xml.utils.NodeConsumer;import org.apache.xml.utils.PrefixResolver;import org.apache.xml.utils.XMLCharacterRecognizer;import org.apache.xml.utils.BoolStack;import org.apache.xpath.compiler.FunctionTable;import org.apache.xpath.compiler.XPathParser;import org.apache.xpath.functions.Function;import org.apache.xpath.XPathFactory;import org.apache.xpath.XPath;import org.apache.xpath.functions.FuncExtFunction;import org.apache.xalan.extensions.ExpressionVisitor;import org.w3c.dom.Node;import org.xml.sax.Attributes;import org.xml.sax.ContentHandler;import org.xml.sax.DTDHandler;import org.xml.sax.EntityResolver;import org.xml.sax.InputSource;import org.xml.sax.Locator;import org.xml.sax.helpers.NamespaceSupport;import org.apache.xml.utils.NamespaceSupport2;import org.xml.sax.helpers.DefaultHandler;import javax.xml.transform.SourceLocator;import javax.xml.transform.ErrorListener;import javax.xml.transform.TransformerException;import org.apache.xml.utils.SAXSourceLocator;/** * <meta name="usage" content="advanced"/> * Initializes and processes a stylesheet via SAX events. * This class acts as essentially a state machine, maintaining * a ContentHandler stack, and pushing appropriate content * handlers as parse events occur. */public class StylesheetHandler extends DefaultHandler        implements TemplatesHandler, PrefixResolver, NodeConsumer{  /**   * Create a StylesheetHandler object, creating a root stylesheet   * as the target.   *   * @param processor non-null reference to the transformer factory that owns this handler.   *   * @throws TransformerConfigurationException if a StylesheetRoot   * can not be constructed for some reason.   */  public StylesheetHandler(TransformerFactoryImpl processor)          throws TransformerConfigurationException  {    // m_schema = new XSLTSchema();    init(processor);  }  /**   * Static flag to let us know if the XPath functions table   * has been initialized.   */  private static boolean m_xpathFunctionsInited = false;  /**   * Do common initialization.   *   * @param processor non-null reference to the transformer factory that owns this handler.   */  void init(TransformerFactoryImpl processor)  {    // Not sure about double-check of this flag, but    // it seems safe...    if (false == m_xpathFunctionsInited)    {      synchronized (this)      {        if (false == m_xpathFunctionsInited)        {          m_xpathFunctionsInited = true;          Function func = new org.apache.xalan.templates.FuncDocument();          FunctionTable.installFunction("document", func);          // func = new org.apache.xalan.templates.FuncKey();          // FunctionTable.installFunction("key", func);          func = new org.apache.xalan.templates.FuncFormatNumb();          FunctionTable.installFunction("format-number", func);        }      }    }    m_stylesheetProcessor = processor;    // Set the initial content handler.    m_processors.push(m_schema.getElementProcessor());    this.pushNewNamespaceSupport();    // m_includeStack.push(SystemIDResolver.getAbsoluteURI(this.getBaseIdentifier(), null));    // initXPath(processor, null);  }  /**   * 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);    // Visit the expression, registering namespaces for any extension functions it includes.    xpath.callVisitors(xpath, new ExpressionVisitor(getStylesheetRoot()));    return xpath;  }  /**   * 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);    // Visit the expression, registering namespaces for any extension functions it includes.    xpath.callVisitors(xpath, new ExpressionVisitor(getStylesheetRoot()));    return xpath;      }  /**   * Given a namespace, get the corrisponding prefix from the current   * namespace support context.   *   * @param prefix The prefix to look up, which may be an empty string ("") for the default Namespace.   *   * @return The associated Namespace URI, or null if the prefix   *         is undeclared in this context.   */  public String getNamespaceForPrefix(String prefix)  {    return this.getNamespaceSupport().getURI(prefix);  }  /**   * Given a namespace, get the corrisponding prefix.  This is here only   * to support the {@link org.apache.xml.utils.PrefixResolver} interface,   * and will throw an error if invoked on this object.   *   * @param prefix The prefix to look up, which may be an empty string ("") for the default Namespace.   * @param context The node context from which to look up the URI.   *   * @return The associated Namespace URI, or null if the prefix   *         is undeclared in this context.   */  public String getNamespaceForPrefix(String prefix, org.w3c.dom.Node context)  {    // Don't need to support this here.  Return the current URI for the prefix,    // ignoring the context.    assertion(true, "can't process a context node in StylesheetHandler!");    return null;  }  /**   * Utility function to see if the stack contains the given URL.   *   * @param stack non-null reference to a Stack.   * @param url URL string on which an equality test will be performed.   *   * @return true if the stack contains the url argument.   */  private boolean stackContains(Stack stack, String url)  {    int n = stack.size();    boolean contains = false;    for (int i = 0; i < n; i++)    {      String url2 = (String) stack.elementAt(i);      if (url2.equals(url))      {        contains = true;        break;      }    }    return contains;  }  ////////////////////////////////////////////////////////////////////  // Implementation of the TRAX TemplatesBuilder interface.  ////////////////////////////////////////////////////////////////////  /**   * When this object is used as a ContentHandler or ContentHandler, it will   * create a Templates object, which the caller can get once   * the SAX events have been completed.   * @return The stylesheet object that was created during   * the SAX event process, or null if no stylesheet has   * been created.   *   * @version Alpha   * @author <a href="mailto:scott_boag@lotus.com">Scott Boag</a>   */  public Templates getTemplates()  {    return getStylesheetRoot();  }  /**   * Set the base ID (URL or system ID) for the stylesheet   * created by this builder.  This must be set in order to   * resolve relative URLs in the stylesheet.   *   * @param baseID Base URL for this stylesheet.   */  public void setSystemId(String baseID)  {    pushBaseIndentifier(baseID);  }  /**   * Get the base ID (URI or system ID) from where relative   * URLs will be resolved.   *   * @return The systemID that was set with {@link #setSystemId}.   */  public String getSystemId()  {    return this.getBaseIdentifier();  }  ////////////////////////////////////////////////////////////////////  // Implementation of the EntityResolver interface.  ////////////////////////////////////////////////////////////////////  /**   * Resolve an external entity.   *   * @param publicId The public identifer, or null if none is   *                 available.   * @param systemId The system identifier provided in the XML   *                 document.   * @return The new input source, or null to require the   *         default behaviour.   *   * @throws org.xml.sax.SAXException if the entity can not be resolved.   */  public InputSource resolveEntity(String publicId, String systemId)          throws org.xml.sax.SAXException  {    return getCurrentProcessor().resolveEntity(this, publicId, systemId);  }  ////////////////////////////////////////////////////////////////////  // Implementation of DTDHandler interface.  ////////////////////////////////////////////////////////////////////  /**   * Receive notification of a notation declaration.   *   * <p>By default, do nothing.  Application writers may override this   * method in a subclass if they wish to keep track of the notations   * declared in a document.</p>   *   * @param name The notation name.   * @param publicId The notation public identifier, or null if not   *                 available.   * @param systemId The notation system identifier.   * @see org.xml.sax.DTDHandler#notationDecl   */  public void notationDecl(String name, String publicId, String systemId)  {    getCurrentProcessor().notationDecl(this, name, publicId, systemId);  }  /**   * Receive notification of an unparsed entity declaration.   *   * @param name The entity name.   * @param publicId The entity public identifier, or null if not   *                 available.   * @param systemId The entity system identifier.   * @param notationName The name of the associated notation.   * @see org.xml.sax.DTDHandler#unparsedEntityDecl   */  public void unparsedEntityDecl(String name, String publicId,                                 String systemId, String notationName)  {    getCurrentProcessor().unparsedEntityDecl(this, name, publicId, systemId,                                             notationName);  }  /**   * Given a namespace URI, and a local name or a node type, get the processor   * for the element, or return null if not allowed.   *   * @param uri The Namespace URI, or an empty string.   * @param localName The local name (without prefix), or empty string if not namespace processing.   * @param rawName The qualified name (with prefix).   *   * @return A non-null reference to a element processor.   *   * @throws org.xml.sax.SAXException if the element is not allowed in the   * found position in the stylesheet.   */  XSLTElementProcessor getProcessorFor(          String uri, String localName, String rawName)            throws org.xml.sax.SAXException  {    XSLTElementProcessor currentProcessor = getCurrentProcessor();    XSLTElementDef def = currentProcessor.getElemDef();    XSLTElementProcessor elemProcessor = def.getProcessorFor(uri, localName);    if (null == elemProcessor            && ((null == getStylesheet()                || Double.valueOf(getStylesheet().getVersion()).doubleValue()                   > Constants.XSLTVERSUPPORTED)                 ||(!uri.equals(Constants.S_XSLNAMESPACEURL) &&                            currentProcessor instanceof ProcessorStylesheetElement)                || getElemVersion() > Constants.XSLTVERSUPPORTED        ))    {      elemProcessor = def.getProcessorForUnknown(uri, localName);    }    if (null == elemProcessor)      error(XSLMessages.createMessage(XSLTErrorResources.ER_NOT_ALLOWED_IN_POSITION, new Object[]{rawName}),null);//rawName + " is not allowed in this position in the stylesheet!",                                return elemProcessor;

⌨️ 快捷键说明

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