transformeridentityimpl.java

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

JAVA
1,425
字号
/* * 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.transformer;import java.util.Properties;import java.util.Hashtable;import java.io.IOException;// TRaX Importsimport javax.xml.transform.*;import javax.xml.transform.dom.*;import javax.xml.transform.sax.*;import javax.xml.transform.stream.*;import javax.xml.parsers.*;import org.xml.sax.*;import org.xml.sax.helpers.*;import org.xml.sax.ext.*;import org.apache.xalan.serialize.*;import org.apache.xml.utils.DOMBuilder;import org.apache.xml.utils.TreeWalker;import org.apache.xalan.templates.OutputProperties;import org.apache.xalan.serialize.Method;import org.apache.xalan.res.XSLTErrorResources;import org.apache.xalan.res.XSLMessages;import org.w3c.dom.*;/** * This class implements an identity transformer for * {@link javax.xml.transform.sax.SAXTransformerFactory#newTransformerHandler() * and {@link javax.xml.transform.TransformerFactory#newTransformer()}.  It * simply feeds SAX events directly to a serializer ContentHandler, if the * result is a stream.  If the result is a DOM, it will send the events to * {@link org.apache.xml.utils.DOMBuilder}.  If the result is another * content handler, it will simply pass the events on. */public class TransformerIdentityImpl extends Transformer        implements TransformerHandler, DeclHandler{  /**   * Constructor TransformerIdentityImpl creates an identity transform.   *   */  public TransformerIdentityImpl()  {    m_outputFormat = new OutputProperties(Method.XML);  }  /**   * Enables the user of the TransformerHandler to set the   * to set the Result for the transformation.   *   * @param result A Result instance, should not be null.   *   * @throws IllegalArgumentException if result is invalid for some reason.   */  public void setResult(Result result) throws IllegalArgumentException  {    if(null == result)      throw new IllegalArgumentException(XSLMessages.createMessage(XSLTErrorResources.ER_RESULT_NULL, null)); //"Result should not be null");            m_result = result;  }  /**   * Set the base ID (URI or system ID) from where relative   * URLs will be resolved.   * @param systemID Base URI for the source tree.   */  public void setSystemId(String systemID)  {    m_systemID = systemID;  }  /**   * 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 m_systemID;  }  /**   * Get the Transformer associated with this handler, which   * is needed in order to set parameters and output properties.   *   * @return non-null reference to the transformer.   */  public Transformer getTransformer()  {    return this;  }  /**   * Create a result ContentHandler from a Result object, based   * on the current OutputProperties.   *   * @param outputTarget Where the transform result should go,   * should not be null.   *   * @return A valid ContentHandler that will create the   * result tree when it is fed SAX events.   *   * @throws TransformerException   */  private void createResultContentHandler(Result outputTarget)          throws TransformerException  {    if (outputTarget instanceof SAXResult)    {      SAXResult saxResult = (SAXResult) outputTarget;      m_resultContentHandler = saxResult.getHandler();      m_resultLexicalHandler = saxResult.getLexicalHandler();      if (m_resultContentHandler instanceof Serializer)      {        // Dubious but needed, I think.        m_serializer = (Serializer) m_resultContentHandler;      }    }    else if (outputTarget instanceof DOMResult)    {      DOMResult domResult = (DOMResult) outputTarget;      Node outputNode = domResult.getNode();      Document doc;      short type;      if (null != outputNode)      {        type = outputNode.getNodeType();        doc = (Node.DOCUMENT_NODE == type)              ? (Document) outputNode : outputNode.getOwnerDocument();      }      else      {        try        {          DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();          dbf.setNamespaceAware(true);          DocumentBuilder db = dbf.newDocumentBuilder();          doc = db.newDocument();        }        catch (ParserConfigurationException pce)        {          throw new TransformerException(pce);        }        outputNode = doc;        type = outputNode.getNodeType();        ((DOMResult) outputTarget).setNode(outputNode);      }      m_resultContentHandler =        (Node.DOCUMENT_FRAGMENT_NODE == type)        ? new DOMBuilder(doc, (DocumentFragment) outputNode)        : new DOMBuilder(doc, outputNode);      m_resultLexicalHandler = (LexicalHandler) m_resultContentHandler;    }    else if (outputTarget instanceof StreamResult)    {      StreamResult sresult = (StreamResult) outputTarget;      String method = m_outputFormat.getProperty(OutputKeys.METHOD);      try      {        Serializer serializer =          SerializerFactory.getSerializer(m_outputFormat.getProperties());        m_serializer = serializer;        if (null != sresult.getWriter())          serializer.setWriter(sresult.getWriter());        else if (null != sresult.getOutputStream())          serializer.setOutputStream(sresult.getOutputStream());        else if (null != sresult.getSystemId())        {          String fileURL = sresult.getSystemId();          if (fileURL.startsWith("file:///"))          {            if (fileURL.substring(8).indexOf(":") >0)              fileURL = fileURL.substring(8);            else               fileURL = fileURL.substring(7);          }          m_outputStream = new java.io.FileOutputStream(fileURL);          serializer.setOutputStream(m_outputStream);        }        else          throw new TransformerException(XSLMessages.createMessage(XSLTErrorResources.ER_NO_OUTPUT_SPECIFIED, null)); //"No output specified!");        m_resultContentHandler = serializer.asContentHandler();      }      catch (IOException ioe)      {        throw new TransformerException(ioe);      }    }    else    {      throw new TransformerException(XSLMessages.createMessage(XSLTErrorResources.ER_CANNOT_TRANSFORM_TO_RESULT_TYPE, new Object[]{outputTarget.getClass().getName()})); //"Can't transform to a Result of type "                                    // + outputTarget.getClass().getName()                                    // + "!");    }    if (m_resultContentHandler instanceof DTDHandler)      m_resultDTDHandler = (DTDHandler) m_resultContentHandler;        if (m_resultContentHandler instanceof DeclHandler)      m_resultDeclHandler = (DeclHandler) m_resultContentHandler;    if (m_resultContentHandler instanceof LexicalHandler)      m_resultLexicalHandler = (LexicalHandler) m_resultContentHandler;  }  /**   * Process the source tree to the output result.   * @param source  The input for the source tree.   *   * @param outputTarget The output target.   *   * @throws TransformerException If an unrecoverable error occurs   * during the course of the transformation.   */  public void transform(Source source, Result outputTarget)          throws TransformerException  {    createResultContentHandler(outputTarget);    try    {      if (source instanceof DOMSource)      {        DOMSource dsource = (DOMSource) source;          m_systemID = dsource.getSystemId();          Node dNode = dsource.getNode();          if (null != dNode)        {          try          {            if(dNode.getNodeType() != Node.DOCUMENT_NODE)              this.startDocument();            try            {              if(dNode.getNodeType() == Node.ATTRIBUTE_NODE)              {                String data = dNode.getNodeValue();                char[] chars = data.toCharArray();                characters(chars, 0, chars.length);              }              else              {                TreeWalker walker = new TreeWalker(this, new org.apache.xpath.DOM2Helper(), m_systemID);                walker.traverse(dNode);              }            }            finally            {              if(dNode.getNodeType() != Node.DOCUMENT_NODE)                this.endDocument();            }          }          catch (SAXException se)          {            throw new TransformerException(se);          }            return;        }        else        {          String messageStr = XSLMessages.createMessage(            XSLTErrorResources.ER_ILLEGAL_DOMSOURCE_INPUT, null);            throw new IllegalArgumentException(messageStr);        }      }        InputSource xmlSource = SAXSource.sourceToInputSource(source);        if (null == xmlSource)      {        throw new TransformerException(XSLMessages.createMessage(XSLTErrorResources.ER_CANNOT_TRANSFORM_SOURCE_TYPE, new Object[]{source.getClass().getName()})); //"Can't transform a Source of type "                                       //+ source.getClass().getName() + "!");      }  

⌨️ 快捷键说明

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