transformerimpl.java

来自「JAVA的一些源码 JAVA2 STANDARD EDITION DEVELO」· Java 代码 · 共 1,308 行 · 第 1/3 页

JAVA
1,308
字号
		    _tohFactory.setOutputStream(connection.getOutputStream());		    return _tohFactory.getSerializationHandler();                }                else {                    // system id is just a filename                    url = new File(systemId).toURL();		    _tohFactory.setOutputStream(		        new FileOutputStream(url.getFile()));		    return _tohFactory.getSerializationHandler();                }	    }	}        // If we cannot write to the location specified by the SystemId        catch (UnknownServiceException e) {            throw new TransformerException(e);        }        catch (ParserConfigurationException e) {            throw new TransformerException(e);        }        // If we cannot create the file specified by the SystemId        catch (IOException e) {            throw new TransformerException(e);        }	return null;    }    /**     * Set the internal DOM that will be used for the next transformation     */    protected void setDOM(DOM dom) {	_dom = dom;    }    /**     * Builds an internal DOM from a TrAX Source object     */    private DOM getDOM(Source source) throws TransformerException {        try {            DOM dom = null;            if (source != null) {                DTMWSFilter wsfilter;                if (_translet != null && _translet instanceof StripFilter) {                    wsfilter = new DOMWSFilter(_translet);                 } else {                    wsfilter = null;                 }                             boolean hasIdCall = (_translet != null) ? _translet.hasIdCall()                                                         : false;                 if (_dtmManager == null) {                     _dtmManager =                         (XSLTCDTMManager)_tfactory.getDTMManagerClass()                                                   .newInstance();                 }                 dom = (DOM)_dtmManager.getDTM(source, false, wsfilter, true,                                              false, false, 0, hasIdCall);            } else if (_dom != null) {                 dom = _dom;                 _dom = null;  // use only once, so reset to 'null'            } else {                 return null;            }            if (!_isIdentity) {                // Give the translet the opportunity to make a prepass of                // the document, in case it can extract useful information early                _translet.prepassDocument(dom);            }            return dom;        }        catch (Exception e) {            if (_errorListener != null) {                postErrorToListener(e.getMessage());            }            throw new TransformerException(e);        }    }     /**     * Returns the {@link com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl}     * object that create this <code>Transformer</code>.     */    protected TransformerFactoryImpl getTransformerFactory() {        return _tfactory;    }    /**     * Returns the {@link com.sun.org.apache.xalan.internal.xsltc.runtime.output.TransletOutputHandlerFactory}     * object that create the <code>TransletOutputHandler</code>.     */    protected TransletOutputHandlerFactory getTransletOutputHandlerFactory() {        return _tohFactory;    }    private void transformIdentity(Source source, SerializationHandler handler)	throws Exception     {        // Get systemId from source        if (source != null) {            _sourceSystemId = source.getSystemId();        }        if (source instanceof StreamSource) {            final StreamSource stream = (StreamSource) source;            final InputStream streamInput = stream.getInputStream();            final Reader streamReader = stream.getReader();            final XMLReader reader = _readerManager.getXMLReader();            try {                // Hook up reader and output handler                 try {                    reader.setProperty(LEXICAL_HANDLER_PROPERTY, handler);		    reader.setFeature(NAMESPACE_PREFIXES_FEATURE, true);                }                catch (SAXException e) {                    // Falls through                }                reader.setContentHandler(handler);                // Create input source from source                InputSource input;                if (streamInput != null) {                    input = new InputSource(streamInput);                    input.setSystemId(_sourceSystemId);                 }                 else if (streamReader != null) {                    input = new InputSource(streamReader);                    input.setSystemId(_sourceSystemId);                 }                 else if (_sourceSystemId != null) {                    input = new InputSource(_sourceSystemId);                }                 else {                    ErrorMsg err = new ErrorMsg(ErrorMsg.JAXP_NO_SOURCE_ERR);                    throw new TransformerException(err.toString());                }                // Start pushing SAX events                reader.parse(input);            } finally {                _readerManager.releaseXMLReader(reader);            }        } else if (source instanceof SAXSource) {            final SAXSource sax = (SAXSource) source;            XMLReader reader = sax.getXMLReader();            final InputSource input = sax.getInputSource();            boolean userReader = true;            try {                // Create a reader if not set by user                if (reader == null) {                    reader = _readerManager.getXMLReader();                    userReader = false;                }                // Hook up reader and output handler                 try {                    reader.setProperty(LEXICAL_HANDLER_PROPERTY, handler);		    reader.setFeature(NAMESPACE_PREFIXES_FEATURE, true);                }                catch (SAXException e) {                    // Falls through                }                reader.setContentHandler(handler);                // Start pushing SAX events                reader.parse(input);            } finally {                if (!userReader) {                    _readerManager.releaseXMLReader(reader);                }            }        } else if (source instanceof DOMSource) {            final DOMSource domsrc = (DOMSource) source;            new DOM2TO(domsrc.getNode(), handler).parse();        } else if (source instanceof XSLTCSource) {            final DOM dom = ((XSLTCSource) source).getDOM(null, _translet);            ((SAXImpl)dom).copy(handler);        } else {            ErrorMsg err = new ErrorMsg(ErrorMsg.JAXP_NO_SOURCE_ERR);            throw new TransformerException(err.toString());        }    }    /**     * Internal transformation method - uses the internal APIs of XSLTC     */    private void transform(Source source, SerializationHandler handler, 	String encoding) throws TransformerException     {	try {            /*             * According to JAXP1.2, new SAXSource()/StreamSource()             * should create an empty input tree, with a default root node.              * new DOMSource()creates an empty document using DocumentBuilder.             * newDocument(); Use DocumentBuilder.newDocument() for all 3              * situations, since there is no clear spec. how to create              * an empty tree when both SAXSource() and StreamSource() are used.             */            if ((source instanceof StreamSource && source.getSystemId()==null                 && ((StreamSource)source).getInputStream()==null &&                ((StreamSource)source).getReader()==null)||                (source instanceof SAXSource &&                ((SAXSource)source).getInputSource()==null &&                ((SAXSource)source).getXMLReader()==null )||                (source instanceof DOMSource &&                 ((DOMSource)source).getNode()==null)){                        DocumentBuilderFactory builderF =                                 DocumentBuilderFactory.newInstance();                        DocumentBuilder builder =                                 builderF.newDocumentBuilder();                        String systemID = source.getSystemId();                        source = new DOMSource(builder.newDocument());                        // Copy system ID from original, empty Source to new                        if (systemID != null) {                          source.setSystemId(systemID);                        }            }           	    if (_isIdentity) {		transformIdentity(source, handler);	    } else {		_translet.transform(getDOM(source), handler);	    }	} catch (TransletException e) {	    if (_errorListener != null)	postErrorToListener(e.getMessage());	    throw new TransformerException(e);	} catch (RuntimeException e) {	    if (_errorListener != null)	postErrorToListener(e.getMessage());	    throw new TransformerException(e);	} catch (Exception e) {	    if (_errorListener != null)	postErrorToListener(e.getMessage());	    throw new TransformerException(e);	} finally {            _dtmManager = null;        }    }    /**     * Implements JAXP's Transformer.getErrorListener()     * Get the error event handler in effect for the transformation.     *     * @return The error event handler currently in effect     */    public ErrorListener getErrorListener() {  	return _errorListener;     }    /**     * Implements JAXP's Transformer.setErrorListener()     * Set the error event listener in effect for the transformation.     * Register a message handler in the translet in order to forward     * xsl:messages to error listener.     *     * @param listener The error event listener to use     * @throws IllegalArgumentException     */    public void setErrorListener(ErrorListener listener)	throws IllegalArgumentException {        if (listener == null) {	    ErrorMsg err = new ErrorMsg(ErrorMsg.ERROR_LISTENER_NULL_ERR,					"Transformer");            throw new IllegalArgumentException(err.toString());	}        _errorListener = listener;        	// Register a message handler to report xsl:messages    if (_translet != null)    	_translet.setMessageHandler(new MessageHandler(_errorListener));    }    /**     * Inform TrAX error listener of an error     */    private void postErrorToListener(String message) {        try {            _errorListener.error(new TransformerException(message));	}	catch (TransformerException e) {            // ignored - transformation cannot be continued        }    }    /**     * Inform TrAX error listener of a warning     */    private void postWarningToListener(String message) {        try {            _errorListener.warning(new TransformerException(message));        }	catch (TransformerException e) {            // ignored - transformation cannot be continued        }    }    /**     * The translet stores all CDATA sections set in the <xsl:output> element     * in a Hashtable. This method will re-construct the whitespace separated     * list of elements given in the <xsl:output> element.     */    private String makeCDATAString(Hashtable cdata) {	// Return a 'null' string if no CDATA section elements were specified	if (cdata == null) return null;	StringBuffer result = new StringBuffer();	// Get an enumeration of all the elements in the hashtable	Enumeration elements = cdata.keys();	if (elements.hasMoreElements()) {	    result.append((String)elements.nextElement());	    while (elements.hasMoreElements()) {		String element = (String)elements.nextElement();		result.append(' ');		result.append(element);	    }	}		return(result.toString());    }    /**     * Implements JAXP's Transformer.getOutputProperties().     * Returns a copy of the output properties for the transformation. This is     * a set of layered properties. The first layer contains properties set by     * calls to setOutputProperty() and setOutputProperties() on this class,     * and the output settings defined in the stylesheet's <xsl:output>     * element makes up the second level, while the default XSLT output     * settings are returned on the third level.     *     * @return Properties in effect for this Transformer     */    public Properties getOutputProperties() { 	return (Properties) _properties.clone();    }    /**     * Implements JAXP's Transformer.getOutputProperty().     * Get an output property that is in effect for the transformation. The     * property specified may be a property that was set with setOutputProperty,     * or it may be a property specified in the stylesheet.     *     * @param name A non-null string that contains the name of the property     * @throws IllegalArgumentException if the property name is not known     */    public String getOutputProperty(String name)	throws IllegalArgumentException     {	if (!validOutputProperty(name)) {	    ErrorMsg err = new ErrorMsg(ErrorMsg.JAXP_UNKNOWN_PROP_ERR, name);	    throw new IllegalArgumentException(err.toString());	}	return _properties.getProperty(name);    }    /**     * Implements JAXP's Transformer.setOutputProperties().     * Set the output properties for the transformation. These properties     * will override properties set in the Templates with xsl:output.     * Unrecognised properties will be quitely ignored.     *     * @param properties The properties to use for the Transformer     * @throws IllegalArgumentException Never, errors are ignored     */    public void setOutputProperties(Properties properties) 	throws IllegalArgumentException     {	if (properties != null) {	    final Enumeration names = properties.propertyNames();	    while (names.hasMoreElements()) {		final String name = (String) names.nextElement();		// Ignore lower layer properties		if (isDefaultProperty(name, properties)) continue;		if (validOutputProperty(name)) {		    _properties.setProperty(name, properties.getProperty(name));		}		else {		    ErrorMsg err = new ErrorMsg(ErrorMsg.JAXP_UNKNOWN_PROP_ERR, name);		    throw new IllegalArgumentException(err.toString());		}	    }	}	else {	    _properties = _propertiesClone;	}    }    /**     * Implements JAXP's Transformer.setOutputProperty().     * Get an output property that is in effect for the transformation. The     * property specified may be a property that was set with      * setOutputProperty(), or it may be a property specified in the stylesheet.     *     * @param name The name of the property to set     * @param value The value to assign to the property     * @throws IllegalArgumentException Never, errors are ignored     */    public void setOutputProperty(String name, String value)	throws IllegalArgumentException     {	if (!validOutputProperty(name)) {	    ErrorMsg err = new ErrorMsg(ErrorMsg.JAXP_UNKNOWN_PROP_ERR, name);	    throw new IllegalArgumentException(err.toString());	}	_properties.setProperty(name, value);    }    /**     * Internal method to pass any properties to the translet prior to     * initiating the transformation     */    private void transferOutputProperties(AbstractTranslet translet)    {	// Return right now if no properties are set	if (_properties == null) return;	// Get a list of all the defined properties	Enumeration names = _properties.propertyNames();	while (names.hasMoreElements()) {	    // Note the use of get() instead of getProperty()	    String name  = (String) names.nextElement();	    String value = (String) _properties.get(name);	    // Ignore default properties	    if (value == null) continue;	    // Pass property value to translet - override previous setting	    if (name.equals(OutputKeys.ENCODING)) {		translet._encoding = value;	    }

⌨️ 快捷键说明

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